diff --git a/packages/react-native/Libraries/Blob/RCTFileReaderModule.mm b/packages/react-native/Libraries/Blob/RCTFileReaderModule.mm index cbb28dbfa83..02180144f28 100644 --- a/packages/react-native/Libraries/Blob/RCTFileReaderModule.mm +++ b/packages/react-native/Libraries/Blob/RCTFileReaderModule.mm @@ -24,11 +24,9 @@ RCT_EXPORT_MODULE(FileReaderModule) @synthesize moduleRegistry = _moduleRegistry; -RCT_EXPORT_METHOD(readAsText - : (NSDictionary *)blob encoding - : (NSString *)encoding resolve - : (RCTPromiseResolveBlock)resolve reject - : (RCTPromiseRejectBlock)reject) +RCT_EXPORT_METHOD( + readAsText : (NSDictionary *)blob encoding : (NSString *)encoding resolve : (RCTPromiseResolveBlock) + resolve reject : (RCTPromiseRejectBlock)reject) { RCTBlobManager *blobManager = [_moduleRegistry moduleForName:"BlobModule"]; dispatch_async(blobManager.methodQueue, ^{ @@ -56,10 +54,9 @@ RCT_EXPORT_METHOD(readAsText }); } -RCT_EXPORT_METHOD(readAsDataURL - : (NSDictionary *)blob resolve - : (RCTPromiseResolveBlock)resolve reject - : (RCTPromiseRejectBlock)reject) +RCT_EXPORT_METHOD( + readAsDataURL : (NSDictionary *)blob resolve : (RCTPromiseResolveBlock) + resolve reject : (RCTPromiseRejectBlock)reject) { RCTBlobManager *blobManager = [_moduleRegistry moduleForName:"BlobModule"]; dispatch_async(blobManager.methodQueue, ^{ diff --git a/packages/react-native/Libraries/FBLazyVector/FBLazyVector/FBLazyIterator.h b/packages/react-native/Libraries/FBLazyVector/FBLazyVector/FBLazyIterator.h index 2d4ae909f3b..65608d25da1 100644 --- a/packages/react-native/Libraries/FBLazyVector/FBLazyVector/FBLazyIterator.h +++ b/packages/react-native/Libraries/FBLazyVector/FBLazyVector/FBLazyIterator.h @@ -26,68 +26,81 @@ class LazyIterator { public: LazyIterator() = default; - LazyIterator(U vector, convert_type convert, size_type i) - : _v(vector), _i(i), _convert(std::move(convert)) {} + LazyIterator(U vector, convert_type convert, size_type i) : _v(vector), _i(i), _convert(std::move(convert)) {} - bool operator==(const LazyIterator& other) const { + bool operator==(const LazyIterator &other) const + { return _i == other._i && _v == other._v; } - bool operator<(const LazyIterator& b) const { + bool operator<(const LazyIterator &b) const + { return _i < b._i; } - value_type operator*() const { + value_type operator*() const + { return _convert(_v[_i]); } - std::unique_ptr operator->() const { + std::unique_ptr operator->() const + { return std::make_unique(*this); } - LazyIterator operator+(difference_type n) const { + LazyIterator operator+(difference_type n) const + { return LazyIterator(_v, _convert, _i + n); } - LazyIterator& operator+=(difference_type n) { + LazyIterator &operator+=(difference_type n) + { _i += n; return *this; } - LazyIterator& operator-=(difference_type n) { + LazyIterator &operator-=(difference_type n) + { _i -= n; return *this; } - LazyIterator operator-(difference_type n) const { + LazyIterator operator-(difference_type n) const + { return LazyIterator(_v, _i - n); } - difference_type operator-(const LazyIterator& a) const { + difference_type operator-(const LazyIterator &a) const + { return _i - a._i; } - LazyIterator& operator++() { + LazyIterator &operator++() + { return *this += 1; } - LazyIterator operator++(int) { + LazyIterator operator++(int) + { auto tmp = *this; ++*this; return tmp; } - LazyIterator& operator--() { + LazyIterator &operator--() + { return *this -= 1; } - LazyIterator operator--(int) { + LazyIterator operator--(int) + { auto tmp = *this; --*this; return tmp; } - value_type operator[](difference_type n) const { + value_type operator[](difference_type n) const + { return _convert(_v[_i + n]); } @@ -98,29 +111,32 @@ class LazyIterator { }; template -LazyIterator operator+( - typename LazyIterator::difference_type n, - const LazyIterator& i) { +LazyIterator operator+(typename LazyIterator::difference_type n, const LazyIterator &i) +{ return i + n; } template -bool operator!=(const LazyIterator& a, const LazyIterator& b) { +bool operator!=(const LazyIterator &a, const LazyIterator &b) +{ return !(a == b); } template -bool operator<=(const LazyIterator& a, const LazyIterator& b) { +bool operator<=(const LazyIterator &a, const LazyIterator &b) +{ return a < b || a == b; } template -bool operator>(const LazyIterator& a, const LazyIterator& b) { +bool operator>(const LazyIterator &a, const LazyIterator &b) +{ return b < a; } template -bool operator>=(const LazyIterator& a, const LazyIterator& b) { +bool operator>=(const LazyIterator &a, const LazyIterator &b) +{ return a > b || a == b; } diff --git a/packages/react-native/Libraries/FBLazyVector/FBLazyVector/FBLazyVector.h b/packages/react-native/Libraries/FBLazyVector/FBLazyVector/FBLazyVector.h index 46c2782bf9b..4d709056206 100644 --- a/packages/react-native/Libraries/FBLazyVector/FBLazyVector/FBLazyVector.h +++ b/packages/react-native/Libraries/FBLazyVector/FBLazyVector/FBLazyVector.h @@ -31,24 +31,28 @@ class LazyVector { using size_type = std::int32_t; using convert_type = std::function; - static LazyVector - fromUnsafeRawValue(U v, size_type size, convert_type convert) { + static LazyVector fromUnsafeRawValue(U v, size_type size, convert_type convert) + { return {v, size, convert}; } - U unsafeRawValue() const { + U unsafeRawValue() const + { return _v; } - bool empty() const { + bool empty() const + { return _size == 0; } - size_type size() const { + size_type size() const + { return _size; } - const_reference at(size_type pos) const { + const_reference at(size_type pos) const + { #ifndef _LIBCPP_NO_EXCEPTIONS if (!(pos < _size)) { throw std::out_of_range("out of range"); @@ -59,41 +63,47 @@ class LazyVector { return _convert(_v[pos]); } - const_reference operator[](size_type pos) const { + const_reference operator[](size_type pos) const + { assert(pos < _size); return _convert(_v[pos]); } - const_reference front() const { + const_reference front() const + { assert(_size); return (*this)[0]; } - const_reference back() const { + const_reference back() const + { assert(_size); return (*this)[_size - 1]; } - const_iterator begin() const { + const_iterator begin() const + { return const_iterator(_v, _convert, 0); } - const_iterator cbegin() const { + const_iterator cbegin() const + { return begin(); } - const_iterator end() const { + const_iterator end() const + { return const_iterator(_v, _convert, _size); } - const_iterator cend() const { + const_iterator cend() const + { return end(); } private: /** Wrapped vector */ - LazyVector(U vector, size_type size, convert_type convert) - : _v(vector), _size(size), _convert(convert) {} + LazyVector(U vector, size_type size, convert_type convert) : _v(vector), _size(size), _convert(convert) {} U _v; size_type _size; diff --git a/packages/react-native/Libraries/Image/RCTImageEditingManager.mm b/packages/react-native/Libraries/Image/RCTImageEditingManager.mm index 9fe7f2238d2..7f72f130217 100644 --- a/packages/react-native/Libraries/Image/RCTImageEditingManager.mm +++ b/packages/react-native/Libraries/Image/RCTImageEditingManager.mm @@ -38,11 +38,9 @@ RCT_EXPORT_MODULE() * be scaled down to `displaySize` rather than `size`. * All units are in px (not points). */ -RCT_EXPORT_METHOD(cropImage - : (NSURLRequest *)imageRequest cropData - : (JS::NativeImageEditor::Options &)cropData successCallback - : (RCTResponseSenderBlock)successCallback errorCallback - : (RCTResponseSenderBlock)errorCallback) +RCT_EXPORT_METHOD( + cropImage : (NSURLRequest *)imageRequest cropData : (JS::NativeImageEditor::Options &)cropData successCallback : ( + RCTResponseSenderBlock)successCallback errorCallback : (RCTResponseSenderBlock)errorCallback) { CGRect rect = { [RCTConvert CGPoint:@{ diff --git a/packages/react-native/Libraries/Image/RCTImageLoader.mm b/packages/react-native/Libraries/Image/RCTImageLoader.mm index 064497be1b4..9c2553d7ec5 100644 --- a/packages/react-native/Libraries/Image/RCTImageLoader.mm +++ b/packages/react-native/Libraries/Image/RCTImageLoader.mm @@ -331,9 +331,9 @@ static RCTImageLoaderCancellationBlock RCTLoadImageURLFromLoader( RCTImageLoaderPartialLoadBlock partialLoadHandler, RCTImageLoaderCompletionBlockWithMetadata completionHandler) { - if ([loadHandler respondsToSelector:@selector(loadImageForURL: - size:scale:resizeMode:progressHandler:partialLoadHandler - :completionHandlerWithMetadata:)]) { + if ([loadHandler + respondsToSelector:@selector + (loadImageForURL:size:scale:resizeMode:progressHandler:partialLoadHandler:completionHandlerWithMetadata:)]) { return [loadHandler loadImageForURL:imageURL size:size scale:scale @@ -410,17 +410,17 @@ static RCTImageLoaderCancellationBlock RCTLoadImageURLFromLoader( completionBlock:(RCTImageLoaderCompletionBlock)completionBlock { RCTImageURLLoaderRequest *request = [self loadImageWithURLRequest:imageURLRequest - size:size - scale:scale - clipped:clipped - resizeMode:resizeMode - priority:priority - attribution:{} - progressBlock:progressBlock - partialLoadBlock:partialLoadBlock - completionBlock:^(NSError *error, UIImage *image, id metadata) { - completionBlock(error, image); - }]; + size:size + scale:scale + clipped:clipped + resizeMode:resizeMode + priority:priority + attribution:{} + progressBlock:progressBlock + partialLoadBlock:partialLoadBlock + completionBlock:^(NSError *error, UIImage *image, id metadata) { + completionBlock(error, image); + }]; return ^{ [request cancel]; }; @@ -1229,10 +1229,8 @@ static RCTImageLoaderCancellationBlock RCTLoadImageURLFromLoader( return std::make_shared(params); } -RCT_EXPORT_METHOD(getSize - : (NSString *)uri resolve - : (RCTPromiseResolveBlock)resolve reject - : (RCTPromiseRejectBlock)reject) +RCT_EXPORT_METHOD( + getSize : (NSString *)uri resolve : (RCTPromiseResolveBlock)resolve reject : (RCTPromiseRejectBlock)reject) { NSURLRequest *request = [RCTConvert NSURLRequest:uri]; [self getImageSizeForURLRequest:request @@ -1248,11 +1246,9 @@ RCT_EXPORT_METHOD(getSize }]; } -RCT_EXPORT_METHOD(getSizeWithHeaders - : (NSString *)uri headers - : (NSDictionary *)headers resolve - : (RCTPromiseResolveBlock)resolve reject - : (RCTPromiseRejectBlock)reject) +RCT_EXPORT_METHOD( + getSizeWithHeaders : (NSString *)uri headers : (NSDictionary *)headers resolve : (RCTPromiseResolveBlock) + resolve reject : (RCTPromiseRejectBlock)reject) { NSURL *URL = [RCTConvert NSURL:uri]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL]; @@ -1269,20 +1265,15 @@ RCT_EXPORT_METHOD(getSizeWithHeaders }]; } -RCT_EXPORT_METHOD(prefetchImage - : (NSString *)uri resolve - : (RCTPromiseResolveBlock)resolve reject - : (RCTPromiseRejectBlock)reject) +RCT_EXPORT_METHOD( + prefetchImage : (NSString *)uri resolve : (RCTPromiseResolveBlock)resolve reject : (RCTPromiseRejectBlock)reject) { [self prefetchImageWithMetadata:uri queryRootName:nil rootTag:0 resolve:resolve reject:reject]; } -RCT_EXPORT_METHOD(prefetchImageWithMetadata - : (NSString *)uri queryRootName - : (NSString *)queryRootName rootTag - : (double)rootTag resolve - : (RCTPromiseResolveBlock)resolve reject - : (RCTPromiseRejectBlock)reject) +RCT_EXPORT_METHOD( + prefetchImageWithMetadata : (NSString *)uri queryRootName : (NSString *)queryRootName rootTag : (double) + rootTag resolve : (RCTPromiseResolveBlock)resolve reject : (RCTPromiseRejectBlock)reject) { NSURLRequest *request = [RCTConvert NSURLRequest:uri]; [self loadImageWithURLRequest:request @@ -1306,10 +1297,8 @@ RCT_EXPORT_METHOD(prefetchImageWithMetadata }]; } -RCT_EXPORT_METHOD(queryCache - : (NSArray *)uris resolve - : (RCTPromiseResolveBlock)resolve reject - : (RCTPromiseRejectBlock)reject) +RCT_EXPORT_METHOD( + queryCache : (NSArray *)uris resolve : (RCTPromiseResolveBlock)resolve reject : (RCTPromiseRejectBlock)reject) { resolve([self getImageCacheStatus:uris]); } diff --git a/packages/react-native/Libraries/Image/RCTImageStoreManager.mm b/packages/react-native/Libraries/Image/RCTImageStoreManager.mm index b28824556e0..f5f9a88b468 100644 --- a/packages/react-native/Libraries/Image/RCTImageStoreManager.mm +++ b/packages/react-native/Libraries/Image/RCTImageStoreManager.mm @@ -106,10 +106,9 @@ RCT_EXPORT_METHOD(hasImageForTag : (NSString *)imageTag callback : (RCTResponseS } // TODO (#5906496): Name could be more explicit - something like getBase64EncodedDataForTag:? -RCT_EXPORT_METHOD(getBase64ForTag - : (NSString *)imageTag successCallback - : (RCTResponseSenderBlock)successCallback errorCallback - : (RCTResponseSenderBlock)errorCallback) +RCT_EXPORT_METHOD( + getBase64ForTag : (NSString *)imageTag successCallback : (RCTResponseSenderBlock) + successCallback errorCallback : (RCTResponseSenderBlock)errorCallback) { NSData *imageData = _store[imageTag]; if (imageData == nullptr) { @@ -123,10 +122,9 @@ RCT_EXPORT_METHOD(getBase64ForTag }); } -RCT_EXPORT_METHOD(addImageFromBase64 - : (NSString *)base64String successCallback - : (RCTResponseSenderBlock)successCallback errorCallback - : (RCTResponseSenderBlock)errorCallback) +RCT_EXPORT_METHOD( + addImageFromBase64 : (NSString *)base64String successCallback : (RCTResponseSenderBlock) + successCallback errorCallback : (RCTResponseSenderBlock)errorCallback) { // Dispatching to a background thread to perform base64 decoding diff --git a/packages/react-native/Libraries/Image/RCTImageUtils.mm b/packages/react-native/Libraries/Image/RCTImageUtils.mm index 87e7083f877..d41a26f2112 100644 --- a/packages/react-native/Libraries/Image/RCTImageUtils.mm +++ b/packages/react-native/Libraries/Image/RCTImageUtils.mm @@ -101,12 +101,11 @@ CGRect RCTTargetRect(CGSize sourceSize, CGSize destSize, CGFloat destScale, RCTR sourceSize.height = destSize.height; sourceSize.width = sourceSize.height * aspect; } - return (CGRect){ - { - RCTFloorValue((destSize.width - sourceSize.width) / 2, destScale), - RCTFloorValue((destSize.height - sourceSize.height) / 2, destScale), - }, - RCTCeilSize(sourceSize, destScale)}; + return (CGRect){{ + RCTFloorValue((destSize.width - sourceSize.width) / 2, destScale), + RCTFloorValue((destSize.height - sourceSize.height) / 2, destScale), + }, + RCTCeilSize(sourceSize, destScale)}; case RCTResizeModeCover: @@ -115,17 +114,16 @@ CGRect RCTTargetRect(CGSize sourceSize, CGSize destSize, CGFloat destScale, RCTR sourceSize.height = destSize.height; sourceSize.width = sourceSize.height * aspect; destSize.width = destSize.height * targetAspect; - return (CGRect){ - {RCTFloorValue((destSize.width - sourceSize.width) / 2, destScale), 0}, RCTCeilSize(sourceSize, destScale)}; + return (CGRect){{RCTFloorValue((destSize.width - sourceSize.width) / 2, destScale), 0}, + RCTCeilSize(sourceSize, destScale)}; } else { // target is wider than content sourceSize.width = destSize.width; sourceSize.height = sourceSize.width / aspect; destSize.height = destSize.width / targetAspect; - return (CGRect){ - {0, RCTFloorValue((destSize.height - sourceSize.height) / 2, destScale)}, - RCTCeilSize(sourceSize, destScale)}; + return (CGRect){{0, RCTFloorValue((destSize.height - sourceSize.height) / 2, destScale)}, + RCTCeilSize(sourceSize, destScale)}; } case RCTResizeModeCenter: @@ -140,12 +138,11 @@ CGRect RCTTargetRect(CGSize sourceSize, CGSize destSize, CGFloat destScale, RCTR sourceSize.width = sourceSize.height * aspect; } - return (CGRect){ - { - RCTFloorValue((destSize.width - sourceSize.width) / 2, destScale), - RCTFloorValue((destSize.height - sourceSize.height) / 2, destScale), - }, - RCTCeilSize(sourceSize, destScale)}; + return (CGRect){{ + RCTFloorValue((destSize.width - sourceSize.width) / 2, destScale), + RCTFloorValue((destSize.height - sourceSize.height) / 2, destScale), + }, + RCTCeilSize(sourceSize, destScale)}; } } diff --git a/packages/react-native/Libraries/Image/RCTImageViewManager.mm b/packages/react-native/Libraries/Image/RCTImageViewManager.mm index 383fe4c81d5..74e1713b820 100644 --- a/packages/react-native/Libraries/Image/RCTImageViewManager.mm +++ b/packages/react-native/Libraries/Image/RCTImageViewManager.mm @@ -53,10 +53,9 @@ RCT_CUSTOM_VIEW_PROPERTY(tintColor, UIColor, RCTImageView) view.renderingMode = json ? UIImageRenderingModeAlwaysTemplate : defaultView.renderingMode; } -RCT_EXPORT_METHOD(getSize - : (NSURLRequest *)request successBlock - : (RCTResponseSenderBlock)successBlock errorBlock - : (RCTResponseErrorBlock)errorBlock) +RCT_EXPORT_METHOD( + getSize : (NSURLRequest *)request successBlock : (RCTResponseSenderBlock) + successBlock errorBlock : (RCTResponseErrorBlock)errorBlock) { [[self.bridge moduleForName:@"ImageLoader" lazilyLoadIfNecessary:YES] getImageSizeForURLRequest:request @@ -69,10 +68,9 @@ RCT_EXPORT_METHOD(getSize }]; } -RCT_EXPORT_METHOD(getSizeWithHeaders - : (RCTImageSource *)source resolve - : (RCTPromiseResolveBlock)resolve reject - : (RCTPromiseRejectBlock)reject) +RCT_EXPORT_METHOD( + getSizeWithHeaders : (RCTImageSource *)source resolve : (RCTPromiseResolveBlock) + resolve reject : (RCTPromiseRejectBlock)reject) { [[self.bridge moduleForName:@"ImageLoader" lazilyLoadIfNecessary:YES] getImageSizeForURLRequest:source.request @@ -85,10 +83,9 @@ RCT_EXPORT_METHOD(getSizeWithHeaders }]; } -RCT_EXPORT_METHOD(prefetchImage - : (NSURLRequest *)request resolve - : (RCTPromiseResolveBlock)resolve reject - : (RCTPromiseRejectBlock)reject) +RCT_EXPORT_METHOD( + prefetchImage : (NSURLRequest *)request resolve : (RCTPromiseResolveBlock)resolve reject : (RCTPromiseRejectBlock) + reject) { if (!request) { reject(@"E_INVALID_URI", @"Cannot prefetch an image for an empty URI", nil); @@ -107,10 +104,8 @@ RCT_EXPORT_METHOD(prefetchImage }]; } -RCT_EXPORT_METHOD(queryCache - : (NSArray *)requests resolve - : (RCTPromiseResolveBlock)resolve reject - : (RCTPromiseRejectBlock)reject) +RCT_EXPORT_METHOD( + queryCache : (NSArray *)requests resolve : (RCTPromiseResolveBlock)resolve reject : (RCTPromiseRejectBlock)reject) { resolve([[self.bridge moduleForName:@"ImageLoader"] getImageCacheStatus:requests]); } diff --git a/packages/react-native/Libraries/LinkingIOS/RCTLinkingManager.mm b/packages/react-native/Libraries/LinkingIOS/RCTLinkingManager.mm index bd4192b72ec..db689678d65 100644 --- a/packages/react-native/Libraries/LinkingIOS/RCTLinkingManager.mm +++ b/packages/react-native/Libraries/LinkingIOS/RCTLinkingManager.mm @@ -87,10 +87,8 @@ RCT_EXPORT_MODULE() [self sendEventWithName:@"url" body:notification.userInfo]; } -RCT_EXPORT_METHOD(openURL - : (NSURL *)URL resolve - : (RCTPromiseResolveBlock)resolve reject - : (RCTPromiseRejectBlock)reject) +RCT_EXPORT_METHOD( + openURL : (NSURL *)URL resolve : (RCTPromiseResolveBlock)resolve reject : (RCTPromiseRejectBlock)reject) { [RCTSharedApplication() openURL:URL options:@{} @@ -114,10 +112,8 @@ RCT_EXPORT_METHOD(openURL }]; } -RCT_EXPORT_METHOD(canOpenURL - : (NSURL *)URL resolve - : (RCTPromiseResolveBlock)resolve reject - : (__unused RCTPromiseRejectBlock)reject) +RCT_EXPORT_METHOD( + canOpenURL : (NSURL *)URL resolve : (RCTPromiseResolveBlock)resolve reject : (__unused RCTPromiseRejectBlock)reject) { if (RCTRunningInAppExtension()) { // Technically Today widgets can open urls, but supporting that would require @@ -181,11 +177,9 @@ RCT_EXPORT_METHOD(openSettings : (RCTPromiseResolveBlock)resolve reject : (__unu }]; } -RCT_EXPORT_METHOD(sendIntent - : (NSString *)action extras - : (NSArray *_Nullable)extras resolve - : (RCTPromiseResolveBlock)resolve reject - : (RCTPromiseRejectBlock)reject) +RCT_EXPORT_METHOD( + sendIntent : (NSString *)action extras : (NSArray *_Nullable)extras resolve : (RCTPromiseResolveBlock) + resolve reject : (RCTPromiseRejectBlock)reject) { RCTLogError(@"Not implemented: %@", NSStringFromSelector(_cmd)); } diff --git a/packages/react-native/Libraries/NativeAnimation/RCTNativeAnimatedModule.mm b/packages/react-native/Libraries/NativeAnimation/RCTNativeAnimatedModule.mm index 248a51ded68..9120e8c4754 100644 --- a/packages/react-native/Libraries/NativeAnimation/RCTNativeAnimatedModule.mm +++ b/packages/react-native/Libraries/NativeAnimation/RCTNativeAnimatedModule.mm @@ -118,11 +118,9 @@ RCT_EXPORT_METHOD(disconnectAnimatedNodes : (double)parentTag childTag : (double }]; } -RCT_EXPORT_METHOD(startAnimatingNode - : (double)animationId nodeTag - : (double)nodeTag config - : (NSDictionary *)config endCallback - : (RCTResponseSenderBlock)callBack) +RCT_EXPORT_METHOD( + startAnimatingNode : (double)animationId nodeTag : (double)nodeTag config : (NSDictionary *) + config endCallback : (RCTResponseSenderBlock)callBack) { [self addOperationBlock:^(RCTNativeAnimatedNodesManager *nodesManager) { [nodesManager startAnimatingNode:[NSNumber numberWithDouble:animationId] @@ -228,10 +226,9 @@ RCT_EXPORT_METHOD(stopListeningToAnimatedNodeValue : (double)tag) }]; } -RCT_EXPORT_METHOD(addAnimatedEventToView - : (double)viewTag eventName - : (nonnull NSString *)eventName eventMapping - : (JS::NativeAnimatedModule::EventMapping &)eventMapping) +RCT_EXPORT_METHOD( + addAnimatedEventToView : (double)viewTag eventName : (nonnull NSString *) + eventName eventMapping : (JS::NativeAnimatedModule::EventMapping &)eventMapping) { NSMutableDictionary *eventMappingDict = [NSMutableDictionary new]; eventMappingDict[@"nativeEventPath"] = RCTConvertVecToArray(eventMapping.nativeEventPath()); @@ -247,10 +244,9 @@ RCT_EXPORT_METHOD(addAnimatedEventToView }]; } -RCT_EXPORT_METHOD(removeAnimatedEventFromView - : (double)viewTag eventName - : (nonnull NSString *)eventName animatedNodeTag - : (double)animatedNodeTag) +RCT_EXPORT_METHOD( + removeAnimatedEventFromView : (double)viewTag eventName : (nonnull NSString *)eventName animatedNodeTag : (double) + animatedNodeTag) { [self addOperationBlock:^(RCTNativeAnimatedNodesManager *nodesManager) { [nodesManager removeAnimatedEventFromView:[NSNumber numberWithDouble:viewTag] diff --git a/packages/react-native/Libraries/NativeAnimation/RCTNativeAnimatedTurboModule.mm b/packages/react-native/Libraries/NativeAnimation/RCTNativeAnimatedTurboModule.mm index 000aa701865..a168bddff83 100644 --- a/packages/react-native/Libraries/NativeAnimation/RCTNativeAnimatedTurboModule.mm +++ b/packages/react-native/Libraries/NativeAnimation/RCTNativeAnimatedTurboModule.mm @@ -108,11 +108,9 @@ RCT_EXPORT_METHOD(disconnectAnimatedNodes : (double)parentTag childTag : (double }]; } -RCT_EXPORT_METHOD(startAnimatingNode - : (double)animationId nodeTag - : (double)nodeTag config - : (NSDictionary *)config endCallback - : (RCTResponseSenderBlock)callBack) +RCT_EXPORT_METHOD( + startAnimatingNode : (double)animationId nodeTag : (double)nodeTag config : (NSDictionary *) + config endCallback : (RCTResponseSenderBlock)callBack) { [self queueFlushedOperationBlock:^(RCTNativeAnimatedNodesManager *nodesManager) { [nodesManager startAnimatingNode:[NSNumber numberWithDouble:animationId] @@ -204,10 +202,9 @@ RCT_EXPORT_METHOD(stopListeningToAnimatedNodeValue : (double)tag) }]; } -RCT_EXPORT_METHOD(addAnimatedEventToView - : (double)viewTag eventName - : (nonnull NSString *)eventName eventMapping - : (JS::NativeAnimatedModule::EventMapping &)eventMapping) +RCT_EXPORT_METHOD( + addAnimatedEventToView : (double)viewTag eventName : (nonnull NSString *) + eventName eventMapping : (JS::NativeAnimatedModule::EventMapping &)eventMapping) { NSMutableDictionary *eventMappingDict = [NSMutableDictionary new]; eventMappingDict[@"nativeEventPath"] = RCTConvertVecToArray(eventMapping.nativeEventPath()); @@ -223,10 +220,9 @@ RCT_EXPORT_METHOD(addAnimatedEventToView }]; } -RCT_EXPORT_METHOD(removeAnimatedEventFromView - : (double)viewTag eventName - : (nonnull NSString *)eventName animatedNodeTag - : (double)animatedNodeTag) +RCT_EXPORT_METHOD( + removeAnimatedEventFromView : (double)viewTag eventName : (nonnull NSString *)eventName animatedNodeTag : (double) + animatedNodeTag) { [self queueOperationBlock:^(RCTNativeAnimatedNodesManager *nodesManager) { [nodesManager removeAnimatedEventFromView:[NSNumber numberWithDouble:viewTag] diff --git a/packages/react-native/Libraries/Network/RCTNetworking.mm b/packages/react-native/Libraries/Network/RCTNetworking.mm index e32419efa22..86e80e24cde 100644 --- a/packages/react-native/Libraries/Network/RCTNetworking.mm +++ b/packages/react-native/Libraries/Network/RCTNetworking.mm @@ -797,9 +797,9 @@ RCT_EXPORT_MODULE() #pragma mark - JS API -RCT_EXPORT_METHOD(sendRequest - : (JS::NativeNetworkingIOS::SpecSendRequestQuery &)query callback - : (RCTResponseSenderBlock)responseSender) +RCT_EXPORT_METHOD( + sendRequest : (JS::NativeNetworkingIOS::SpecSendRequestQuery &)query callback : (RCTResponseSenderBlock) + responseSender) { NSString *method = query.method(); NSString *url = query.url(); diff --git a/packages/react-native/Libraries/PushNotificationIOS/RCTPushNotificationManager.mm b/packages/react-native/Libraries/PushNotificationIOS/RCTPushNotificationManager.mm index 86f11c42f60..b113503efe5 100644 --- a/packages/react-native/Libraries/PushNotificationIOS/RCTPushNotificationManager.mm +++ b/packages/react-native/Libraries/PushNotificationIOS/RCTPushNotificationManager.mm @@ -327,10 +327,9 @@ RCT_EXPORT_METHOD(getApplicationIconBadgeNumber : (RCTResponseSenderBlock)callba callback(@[ @(RCTSharedApplication().applicationIconBadgeNumber) ]); } -RCT_EXPORT_METHOD(requestPermissions - : (JS::NativePushNotificationManagerIOS::SpecRequestPermissionsPermission &)permissions resolve - : (RCTPromiseResolveBlock)resolve reject - : (RCTPromiseRejectBlock)reject) +RCT_EXPORT_METHOD( + requestPermissions : (JS::NativePushNotificationManagerIOS::SpecRequestPermissionsPermission &) + permissions resolve : (RCTPromiseResolveBlock)resolve reject : (RCTPromiseRejectBlock)reject) { if (RCTRunningInAppExtension()) { reject( @@ -506,9 +505,8 @@ RCT_EXPORT_METHOD(cancelLocalNotifications : (NSDictionary *)use }]; } -RCT_EXPORT_METHOD(getInitialNotification - : (RCTPromiseResolveBlock)resolve reject - : (__unused RCTPromiseRejectBlock)reject) +RCT_EXPORT_METHOD( + getInitialNotification : (RCTPromiseResolveBlock)resolve reject : (__unused RCTPromiseRejectBlock)reject) { // The user actioned a local or remote notification to launch the app. Notification is represented by UNNotification. // Set this property in the implementation of diff --git a/packages/react-native/Libraries/Required/RCTRequired.h b/packages/react-native/Libraries/Required/RCTRequired.h index 169cf00fb2d..331b82a725a 100644 --- a/packages/react-native/Libraries/Required/RCTRequired.h +++ b/packages/react-native/Libraries/Required/RCTRequired.h @@ -44,22 +44,22 @@ struct RCTRequired { /// Pass-through constructor (allows for implicit conversion) for wrapped type /// T template - RCTREQUIRED_INLINE RCTRequired(Args&&... args) - : _t(std::forward(args)...) { + RCTREQUIRED_INLINE RCTRequired(Args &&...args) : _t(std::forward(args)...) + { static_assert( sizeof...(Args) > 0, "Required struct member not initialized. Expand assert trace to see where this was triggered."); } RCTREQUIRED_INLINE - RCTRequired(const RCTRequired&) = default; + RCTRequired(const RCTRequired &) = default; RCTREQUIRED_INLINE - RCTRequired(RCTRequired&&) = default; + RCTRequired(RCTRequired &&) = default; RCTREQUIRED_INLINE - RCTRequired& operator=(const RCTRequired&) = default; + RCTRequired &operator=(const RCTRequired &) = default; RCTREQUIRED_INLINE - RCTRequired& operator=(RCTRequired&&) = default; + RCTRequired &operator=(RCTRequired &&) = default; RCTREQUIRED_INLINE ~RCTRequired() = default; @@ -67,21 +67,25 @@ struct RCTRequired { /// Public accessor for private storage (Use when implicit conversion is /// impracticable) RCTREQUIRED_INLINE - const T& get() const { + const T &get() const + { return _t; } RCTREQUIRED_INLINE - T& get() { + T &get() + { return _t; } // Implicit conversion RCTREQUIRED_INLINE - operator T() const { + operator T() const + { return _t; } RCTREQUIRED_INLINE - operator T&() { + operator T &() + { return _t; } diff --git a/packages/react-native/Libraries/Text/Text/RCTTextShadowView.mm b/packages/react-native/Libraries/Text/Text/RCTTextShadowView.mm index 5184b6bf351..60de7af1370 100644 --- a/packages/react-native/Libraries/Text/Text/RCTTextShadowView.mm +++ b/packages/react-native/Libraries/Text/Text/RCTTextShadowView.mm @@ -443,15 +443,14 @@ static YGSize RCTTextShadowViewMeasure( size.width -= letterSpacing; } - size = (CGSize){ - MIN(RCTCeilPixelValue(size.width), maximumSize.width), MIN(RCTCeilPixelValue(size.height), maximumSize.height)}; + size = (CGSize){MIN(RCTCeilPixelValue(size.width), maximumSize.width), + MIN(RCTCeilPixelValue(size.height), maximumSize.height)}; // Adding epsilon value illuminates problems with converting values from // `double` to `float`, and then rounding them to pixel grid in Yoga. CGFloat epsilon = 0.001; - return (YGSize){ - RCTYogaFloatFromCoreGraphicsFloat(size.width + epsilon), - RCTYogaFloatFromCoreGraphicsFloat(size.height + epsilon)}; + return (YGSize){RCTYogaFloatFromCoreGraphicsFloat(size.width + epsilon), + RCTYogaFloatFromCoreGraphicsFloat(size.height + epsilon)}; } static float RCTTextShadowViewBaseline(YGNodeConstRef node, const float width, const float height) diff --git a/packages/react-native/Libraries/Text/TextInput/RCTBaseTextInputShadowView.mm b/packages/react-native/Libraries/Text/TextInput/RCTBaseTextInputShadowView.mm index 58fd2f71226..733e3acd251 100644 --- a/packages/react-native/Libraries/Text/TextInput/RCTBaseTextInputShadowView.mm +++ b/packages/react-native/Libraries/Text/TextInput/RCTBaseTextInputShadowView.mm @@ -285,9 +285,8 @@ [_layoutManager ensureLayoutForTextContainer:_textContainer]; CGSize size = [_layoutManager usedRectForTextContainer:_textContainer].size; - return (CGSize){ - MAX(minimumSize.width, MIN(RCTCeilPixelValue(size.width), maximumSize.width)), - MAX(minimumSize.height, MIN(RCTCeilPixelValue(size.height), maximumSize.height))}; + return (CGSize){MAX(minimumSize.width, MIN(RCTCeilPixelValue(size.width), maximumSize.width)), + MAX(minimumSize.height, MIN(RCTCeilPixelValue(size.height), maximumSize.height))}; } - (CGFloat)lastBaselineForSize:(CGSize)size @@ -348,8 +347,8 @@ static YGSize RCTBaseTextInputShadowViewMeasure( CGSize measuredSize = [shadowView sizeThatFitsMinimumSize:minimumSize maximumSize:maximumSize]; - return (YGSize){ - RCTYogaFloatFromCoreGraphicsFloat(measuredSize.width), RCTYogaFloatFromCoreGraphicsFloat(measuredSize.height)}; + return (YGSize){RCTYogaFloatFromCoreGraphicsFloat(measuredSize.width), + RCTYogaFloatFromCoreGraphicsFloat(measuredSize.height)}; } static float RCTTextInputShadowViewBaseline(YGNodeConstRef node, const float width, const float height) diff --git a/packages/react-native/Libraries/Text/TextInput/RCTBaseTextInputViewManager.mm b/packages/react-native/Libraries/Text/TextInput/RCTBaseTextInputViewManager.mm index 9db96aae92b..3503ccf4522 100644 --- a/packages/react-native/Libraries/Text/TextInput/RCTBaseTextInputViewManager.mm +++ b/packages/react-native/Libraries/Text/TextInput/RCTBaseTextInputViewManager.mm @@ -125,12 +125,9 @@ RCT_EXPORT_METHOD(blur : (nonnull NSNumber *)viewTag) }]; } -RCT_EXPORT_METHOD(setTextAndSelection - : (nonnull NSNumber *)viewTag mostRecentEventCount - : (NSInteger)mostRecentEventCount value - : (NSString *)value start - : (NSInteger)start end - : (NSInteger)end) +RCT_EXPORT_METHOD( + setTextAndSelection : (nonnull NSNumber *)viewTag mostRecentEventCount : (NSInteger) + mostRecentEventCount value : (NSString *)value start : (NSInteger)start end : (NSInteger)end) { [self.bridge.uiManager addUIBlock:^(RCTUIManager *uiManager, NSDictionary *viewRegistry) { RCTBaseTextInputView *view = (RCTBaseTextInputView *)viewRegistry[viewTag]; diff --git a/packages/react-native/Libraries/TypeSafety/RCTTypedModuleConstants.mm b/packages/react-native/Libraries/TypeSafety/RCTTypedModuleConstants.mm index b2f45da1cf9..f29de12de6b 100644 --- a/packages/react-native/Libraries/TypeSafety/RCTTypedModuleConstants.mm +++ b/packages/react-native/Libraries/TypeSafety/RCTTypedModuleConstants.mm @@ -27,10 +27,8 @@ // See subclassing notes in // https://developer.apple.com/documentation/foundation/nsdictionary#//apple_ref/occ/cl/NSDictionary -RCT_NOT_IMPLEMENTED(-(instancetype)initWithObjects - : (id _Nonnull const[])objects forKeys - : (id _Nonnull const[])keys count - : (NSUInteger)count) +RCT_NOT_IMPLEMENTED(-(instancetype)initWithObjects : (id _Nonnull const[]) + objects forKeys : (id _Nonnull const[])keys count : (NSUInteger)count) - (NSUInteger)count { diff --git a/packages/react-native/React/Base/RCTBridgeModule.h b/packages/react-native/React/Base/RCTBridgeModule.h index 1e60ff5b583..940e64f4dd0 100644 --- a/packages/react-native/React/Base/RCTBridgeModule.h +++ b/packages/react-native/React/Base/RCTBridgeModule.h @@ -295,10 +295,12 @@ RCT_EXTERN_C_END /** * Like RCT_EXTERN_MODULE, but allows setting a custom JavaScript name. */ -#define RCT_EXTERN_REMAP_MODULE(js_name, objc_name, objc_supername) \ - objc_name : objc_supername @end @interface objc_name(RCTExternModule) \ - @end \ - @implementation objc_name (RCTExternModule) \ +#define RCT_EXTERN_REMAP_MODULE(js_name, objc_name, objc_supername) \ + objc_name: \ + objc_supername @ \ + end @interface objc_name(RCTExternModule) \ + @end \ + @implementation objc_name (RCTExternModule) \ RCT_EXPORT_MODULE_NO_LOAD(js_name, objc_name) /** diff --git a/packages/react-native/React/Base/RCTConvert.mm b/packages/react-native/React/Base/RCTConvert.mm index 95a4bdc696d..f549b0d0bfd 100644 --- a/packages/react-native/React/Base/RCTConvert.mm +++ b/packages/react-native/React/Base/RCTConvert.mm @@ -857,7 +857,7 @@ static UIColor *RCTColorFromSemanticColorName(NSString *semanticColorName) RCTAssert([UIColor respondsToSelector:selector], @"RCTUIColor does not respond to a semantic color selector."); Class klass = [UIColor class]; IMP imp = [klass methodForSelector:selector]; - id (*getSemanticColorObject)(id, SEL) = (id(*)(id, SEL))imp; + id (*getSemanticColorObject)(id, SEL) = (id (*)(id, SEL))imp; id colorObject = getSemanticColorObject(klass, selector); if ([colorObject isKindOfClass:[UIColor class]]) { color = colorObject; @@ -1073,7 +1073,7 @@ NSArray *RCTConvertArrayValue(SEL type, id json) __block BOOL copy = NO; __block NSArray *values = json = [RCTConvert NSArray:json]; [json enumerateObjectsUsingBlock:^(id jsonValue, NSUInteger idx, __unused BOOL *stop) { - id value = ((id(*)(Class, SEL, id))objc_msgSend)([RCTConvert class], type, jsonValue); + id value = ((id (*)(Class, SEL, id))objc_msgSend)([RCTConvert class], type, jsonValue); if (copy) { if (value) { [(NSMutableArray *)values addObject:value]; diff --git a/packages/react-native/React/Base/RCTMockDef.h b/packages/react-native/React/Base/RCTMockDef.h index 38ee254ef7d..65e6d2d913b 100644 --- a/packages/react-native/React/Base/RCTMockDef.h +++ b/packages/react-native/React/Base/RCTMockDef.h @@ -44,12 +44,9 @@ */ #ifdef RCT_DEV -#define RCT_MOCK_DEF(context, api) \ - __typeof(__typeof(api)*) mockptr_##context##_##api = &api; -#define RCT_MOCK_REF(context, api) \ - extern __typeof(__typeof(api)*) mockptr_##context##_##api; -#define RCT_MOCK_SET(context, api, mockapi) \ - (mockptr_##context##_##api = &mockapi) +#define RCT_MOCK_DEF(context, api) __typeof(__typeof(api) *) mockptr_##context##_##api = &api; +#define RCT_MOCK_REF(context, api) extern __typeof(__typeof(api) *) mockptr_##context##_##api; +#define RCT_MOCK_SET(context, api, mockapi) (mockptr_##context##_##api = &mockapi) #define RCT_MOCK_RESET(context, api) (mockptr_##context##_##api = &api) #define RCT_MOCK_USE(context, api) (*mockptr_##context##_##api) #else diff --git a/packages/react-native/React/Base/RCTModuleMethod.mm b/packages/react-native/React/Base/RCTModuleMethod.mm index ba0693a4ca8..4dda9e0ff7c 100644 --- a/packages/react-native/React/Base/RCTModuleMethod.mm +++ b/packages/react-native/React/Base/RCTModuleMethod.mm @@ -256,15 +256,16 @@ RCT_EXTERN_C_END } #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{ \ @@ -345,8 +346,9 @@ 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]; }); } else { diff --git a/packages/react-native/React/Base/RCTUtils.mm b/packages/react-native/React/Base/RCTUtils.mm index f0404d55814..9936b96ffb8 100644 --- a/packages/react-native/React/Base/RCTUtils.mm +++ b/packages/react-native/React/Base/RCTUtils.mm @@ -146,7 +146,7 @@ static id __nullable _RCTJSONParse(NSString *__nullable jsonString, BOOL isMutab if (strchr("{[", c)) { static const int options = (1 << 2); // loose unicode SEL selector = isMutable ? 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; diff --git a/packages/react-native/React/CoreModules/RCTAccessibilityManager.mm b/packages/react-native/React/CoreModules/RCTAccessibilityManager.mm index c32a12d57a7..37e4228d283 100644 --- a/packages/react-native/React/CoreModules/RCTAccessibilityManager.mm +++ b/packages/react-native/React/CoreModules/RCTAccessibilityManager.mm @@ -274,9 +274,9 @@ RCT_EXPORT_MODULE() return _multipliers; } -RCT_EXPORT_METHOD(setAccessibilityContentSizeMultipliers - : (JS::NativeAccessibilityManager::SpecSetAccessibilityContentSizeMultipliersJSMultipliers &) - JSMultipliers) +RCT_EXPORT_METHOD( + setAccessibilityContentSizeMultipliers : ( + JS::NativeAccessibilityManager::SpecSetAccessibilityContentSizeMultipliersJSMultipliers &)JSMultipliers) { NSMutableDictionary *multipliers = [NSMutableDictionary new]; setMultipliers(multipliers, UIContentSizeCategoryExtraSmall, JSMultipliers.extraSmall()); @@ -321,9 +321,9 @@ RCT_EXPORT_METHOD(announceForAccessibility : (NSString *)announcement) UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, announcement); } -RCT_EXPORT_METHOD(announceForAccessibilityWithOptions - : (NSString *)announcement options - : (JS::NativeAccessibilityManager::SpecAnnounceForAccessibilityWithOptionsOptions &)options) +RCT_EXPORT_METHOD( + announceForAccessibilityWithOptions : (NSString *)announcement options : ( + JS::NativeAccessibilityManager::SpecAnnounceForAccessibilityWithOptionsOptions &)options) { NSMutableDictionary *attrsDictionary = [NSMutableDictionary new]; if (options.queue()) { @@ -346,44 +346,40 @@ RCT_EXPORT_METHOD(getMultiplier : (RCTResponseSenderBlock)callback) } } -RCT_EXPORT_METHOD(getCurrentBoldTextState - : (RCTResponseSenderBlock)onSuccess onError - : (__unused RCTResponseSenderBlock)onError) +RCT_EXPORT_METHOD( + getCurrentBoldTextState : (RCTResponseSenderBlock)onSuccess onError : (__unused RCTResponseSenderBlock)onError) { onSuccess(@[ @(_isBoldTextEnabled) ]); } -RCT_EXPORT_METHOD(getCurrentGrayscaleState - : (RCTResponseSenderBlock)onSuccess onError - : (__unused RCTResponseSenderBlock)onError) +RCT_EXPORT_METHOD( + getCurrentGrayscaleState : (RCTResponseSenderBlock)onSuccess onError : (__unused RCTResponseSenderBlock)onError) { onSuccess(@[ @(_isGrayscaleEnabled) ]); } -RCT_EXPORT_METHOD(getCurrentInvertColorsState - : (RCTResponseSenderBlock)onSuccess onError - : (__unused RCTResponseSenderBlock)onError) +RCT_EXPORT_METHOD( + getCurrentInvertColorsState : (RCTResponseSenderBlock)onSuccess onError : (__unused RCTResponseSenderBlock)onError) { onSuccess(@[ @(_isInvertColorsEnabled) ]); } -RCT_EXPORT_METHOD(getCurrentReduceMotionState - : (RCTResponseSenderBlock)onSuccess onError - : (__unused RCTResponseSenderBlock)onError) +RCT_EXPORT_METHOD( + getCurrentReduceMotionState : (RCTResponseSenderBlock)onSuccess onError : (__unused RCTResponseSenderBlock)onError) { onSuccess(@[ @(_isReduceMotionEnabled) ]); } -RCT_EXPORT_METHOD(getCurrentDarkerSystemColorsState - : (RCTResponseSenderBlock)onSuccess onError - : (__unused RCTResponseSenderBlock)onError) +RCT_EXPORT_METHOD( + getCurrentDarkerSystemColorsState : (RCTResponseSenderBlock)onSuccess onError : (__unused RCTResponseSenderBlock) + onError) { onSuccess(@[ @(_isDarkerSystemColorsEnabled) ]); } -RCT_EXPORT_METHOD(getCurrentPrefersCrossFadeTransitionsState - : (RCTResponseSenderBlock)onSuccess onError - : (__unused RCTResponseSenderBlock)onError) +RCT_EXPORT_METHOD( + getCurrentPrefersCrossFadeTransitionsState : (RCTResponseSenderBlock) + onSuccess onError : (__unused RCTResponseSenderBlock)onError) { if (@available(iOS 14.0, *)) { onSuccess(@[ @(UIAccessibilityPrefersCrossFadeTransitions()) ]); @@ -392,16 +388,15 @@ RCT_EXPORT_METHOD(getCurrentPrefersCrossFadeTransitionsState } } -RCT_EXPORT_METHOD(getCurrentReduceTransparencyState - : (RCTResponseSenderBlock)onSuccess onError - : (__unused RCTResponseSenderBlock)onError) +RCT_EXPORT_METHOD( + getCurrentReduceTransparencyState : (RCTResponseSenderBlock)onSuccess onError : (__unused RCTResponseSenderBlock) + onError) { onSuccess(@[ @(_isReduceTransparencyEnabled) ]); } -RCT_EXPORT_METHOD(getCurrentVoiceOverState - : (RCTResponseSenderBlock)onSuccess onError - : (__unused RCTResponseSenderBlock)onError) +RCT_EXPORT_METHOD( + getCurrentVoiceOverState : (RCTResponseSenderBlock)onSuccess onError : (__unused RCTResponseSenderBlock)onError) { onSuccess(@[ @(_isVoiceOverEnabled) ]); } diff --git a/packages/react-native/React/CoreModules/RCTActionSheetManager.mm b/packages/react-native/React/CoreModules/RCTActionSheetManager.mm index 2d630032f2e..6472cc44f0b 100644 --- a/packages/react-native/React/CoreModules/RCTActionSheetManager.mm +++ b/packages/react-native/React/CoreModules/RCTActionSheetManager.mm @@ -73,9 +73,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"); @@ -229,10 +229,10 @@ RCT_EXPORT_METHOD(dismissActionSheet) }); } -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"); diff --git a/packages/react-native/React/CoreModules/RCTDevLoadingView.mm b/packages/react-native/React/CoreModules/RCTDevLoadingView.mm index 3d866e91a40..0dd2a7f100c 100644 --- a/packages/react-native/React/CoreModules/RCTDevLoadingView.mm +++ b/packages/react-native/React/CoreModules/RCTDevLoadingView.mm @@ -156,10 +156,9 @@ RCT_EXPORT_MODULE() }); } -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]]; } diff --git a/packages/react-native/React/CoreModules/RCTDevToolsRuntimeSettingsModule.mm b/packages/react-native/React/CoreModules/RCTDevToolsRuntimeSettingsModule.mm index f7654940363..ba4e2559697 100644 --- a/packages/react-native/React/CoreModules/RCTDevToolsRuntimeSettingsModule.mm +++ b/packages/react-native/React/CoreModules/RCTDevToolsRuntimeSettingsModule.mm @@ -25,8 +25,8 @@ static Config _config; @implementation RCTDevToolsRuntimeSettingsModule RCT_EXPORT_MODULE(ReactDevToolsRuntimeSettingsModule) -RCT_EXPORT_METHOD(setReloadAndProfileConfig - : (JS::NativeReactDevToolsRuntimeSettingsModule::PartialReloadAndProfileConfig &)config) +RCT_EXPORT_METHOD( + setReloadAndProfileConfig : (JS::NativeReactDevToolsRuntimeSettingsModule::PartialReloadAndProfileConfig &)config) { if (config.shouldReloadAndProfile().has_value()) { _config.shouldReloadAndProfile = config.shouldReloadAndProfile().value(); diff --git a/packages/react-native/React/CoreModules/RCTExceptionsManager.mm b/packages/react-native/React/CoreModules/RCTExceptionsManager.mm index dea805fddb2..d49e49a029b 100644 --- a/packages/react-native/React/CoreModules/RCTExceptionsManager.mm +++ b/packages/react-native/React/CoreModules/RCTExceptionsManager.mm @@ -84,19 +84,17 @@ RCT_EXPORT_MODULE() } // TODO(T205456329): This method is deprecated in favour of reportException. Delete in v0.77 -RCT_EXPORT_METHOD(reportSoftException - : (NSString *)message stack - : (NSArray *)stack exceptionId - : (double)exceptionId) +RCT_EXPORT_METHOD( + reportSoftException : (NSString *)message stack : (NSArray *)stack exceptionId : (double) + exceptionId) { [self reportSoft:message stack:stack exceptionId:exceptionId extraDataAsJSON:nil]; } // TODO(T205456329): This method is deprecated in favour of reportException. Delete in v0.77 -RCT_EXPORT_METHOD(reportFatalException - : (NSString *)message stack - : (NSArray *)stack exceptionId - : (double)exceptionId) +RCT_EXPORT_METHOD( + reportFatalException : (NSString *)message stack : (NSArray *)stack exceptionId : (double) + exceptionId) { [self reportFatal:message stack:stack exceptionId:exceptionId extraDataAsJSON:nil]; } diff --git a/packages/react-native/React/CoreModules/RCTTiming.mm b/packages/react-native/React/CoreModules/RCTTiming.mm index 0b3630741c8..14ee7844c7f 100644 --- a/packages/react-native/React/CoreModules/RCTTiming.mm +++ b/packages/react-native/React/CoreModules/RCTTiming.mm @@ -353,11 +353,9 @@ RCT_EXPORT_MODULE() * calculating the timer's target time. We calculate this by passing in * Date.now() from JS and then subtracting that from the current time here. */ -RCT_EXPORT_METHOD(createTimer - : (double)callbackID duration - : (NSTimeInterval)jsDuration jsSchedulingTime - : (double)jsSchedulingTime repeats - : (BOOL)repeats) +RCT_EXPORT_METHOD( + createTimer : (double)callbackID duration : (NSTimeInterval)jsDuration jsSchedulingTime : (double) + jsSchedulingTime repeats : (BOOL)repeats) { NSNumber *callbackIdObjc = [NSNumber numberWithDouble:callbackID]; NSDate *schedulingTime = [RCTConvert NSDate:[NSNumber numberWithDouble:jsSchedulingTime]]; diff --git a/packages/react-native/React/CoreModules/RCTWebSocketModule.mm b/packages/react-native/React/CoreModules/RCTWebSocketModule.mm index 3fd7238911f..e29d76a76a2 100644 --- a/packages/react-native/React/CoreModules/RCTWebSocketModule.mm +++ b/packages/react-native/React/CoreModules/RCTWebSocketModule.mm @@ -62,11 +62,9 @@ RCT_EXPORT_MODULE() } } -RCT_EXPORT_METHOD(connect - : (NSURL *)URL protocols - : (NSArray *)protocols options - : (JS::NativeWebSocketModule::SpecConnectOptions &)options socketID - : (double)socketID) +RCT_EXPORT_METHOD( + connect : (NSURL *)URL protocols : (NSArray *)protocols options : (JS::NativeWebSocketModule::SpecConnectOptions &) + options socketID : (double)socketID) { NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL]; diff --git a/packages/react-native/React/CxxBridge/RCTCxxBridge.mm b/packages/react-native/React/CxxBridge/RCTCxxBridge.mm index 9ed885b3e1f..7a85fe7d582 100644 --- a/packages/react-native/React/CxxBridge/RCTCxxBridge.mm +++ b/packages/react-native/React/CxxBridge/RCTCxxBridge.mm @@ -179,7 +179,7 @@ static void registerPerformanceLoggerHooks(RCTPerformanceLogger *performanceLogg struct RCTInstanceCallback : public InstanceCallback { __weak RCTCxxBridge *bridge_; - RCTInstanceCallback(RCTCxxBridge *bridge) : bridge_(bridge){}; + RCTInstanceCallback(RCTCxxBridge *bridge) : bridge_(bridge) {}; void onBatchComplete() override { [bridge_ batchDidComplete]; @@ -1120,16 +1120,12 @@ struct RCTInstanceCallback : public InstanceCallback { }); } -RCT_NOT_IMPLEMENTED(-(instancetype)initWithDelegate - : (__unused id)delegate bundleURL - : (__unused NSURL *)bundleURL moduleProvider - : (__unused RCTBridgeModuleListProvider)block launchOptions - : (__unused NSDictionary *)launchOptions) +RCT_NOT_IMPLEMENTED(-(instancetype)initWithDelegate : (__unused id)delegate bundleURL : ( + __unused NSURL *)bundleURL moduleProvider : (__unused RCTBridgeModuleListProvider) + block launchOptions : (__unused NSDictionary *)launchOptions) -RCT_NOT_IMPLEMENTED(-(instancetype)initWithBundleURL - : (__unused NSURL *)bundleURL moduleProvider - : (__unused RCTBridgeModuleListProvider)block launchOptions - : (__unused NSDictionary *)launchOptions) +RCT_NOT_IMPLEMENTED(-(instancetype)initWithBundleURL : (__unused NSURL *)bundleURL moduleProvider : ( + __unused RCTBridgeModuleListProvider)block launchOptions : (__unused NSDictionary *)launchOptions) /** * Prevent super from calling setUp (that'd create another batchedBridge) diff --git a/packages/react-native/React/CxxBridge/RCTJSIExecutorRuntimeInstaller.h b/packages/react-native/React/CxxBridge/RCTJSIExecutorRuntimeInstaller.h index e59f7c54984..8515e6e8560 100644 --- a/packages/react-native/React/CxxBridge/RCTJSIExecutorRuntimeInstaller.h +++ b/packages/react-native/React/CxxBridge/RCTJSIExecutorRuntimeInstaller.h @@ -18,8 +18,7 @@ namespace facebook::react { * Apple platforms, such as console logging, performance metrics, etc. */ [[deprecated("This API will be removed along with the legacy architecture.")]] -JSIExecutor::RuntimeInstaller RCTJSIExecutorRuntimeInstaller( - JSIExecutor::RuntimeInstaller runtimeInstallerToWrap); +JSIExecutor::RuntimeInstaller RCTJSIExecutorRuntimeInstaller(JSIExecutor::RuntimeInstaller runtimeInstallerToWrap); } // namespace facebook::react diff --git a/packages/react-native/React/CxxBridge/RCTMessageThread.h b/packages/react-native/React/CxxBridge/RCTMessageThread.h index 0306a1fea3c..73d7605ca9d 100644 --- a/packages/react-native/React/CxxBridge/RCTMessageThread.h +++ b/packages/react-native/React/CxxBridge/RCTMessageThread.h @@ -16,18 +16,17 @@ namespace facebook::react { -class RCTMessageThread : public MessageQueueThread, - public std::enable_shared_from_this { +class RCTMessageThread : public MessageQueueThread, public std::enable_shared_from_this { public: - RCTMessageThread(NSRunLoop* runLoop, RCTJavaScriptCompleteBlock errorBlock); + RCTMessageThread(NSRunLoop *runLoop, RCTJavaScriptCompleteBlock errorBlock); ~RCTMessageThread() override; - void runOnQueue(std::function&& /*func*/) override; - void runOnQueueSync(std::function&& /*func*/) override; + void runOnQueue(std::function && /*func*/) override; + void runOnQueueSync(std::function && /*func*/) override; void quitSynchronous() override; - void setRunLoop(NSRunLoop* runLoop); + void setRunLoop(NSRunLoop *runLoop); private: - void tryFunc(const std::function& func); + void tryFunc(const std::function &func); void runAsync(std::function func); void runSync(std::function func); diff --git a/packages/react-native/React/CxxBridge/RCTObjcExecutor.h b/packages/react-native/React/CxxBridge/RCTObjcExecutor.h index bcb7530dce4..9074644fdfd 100644 --- a/packages/react-native/React/CxxBridge/RCTObjcExecutor.h +++ b/packages/react-native/React/CxxBridge/RCTObjcExecutor.h @@ -16,13 +16,10 @@ namespace facebook::react { -class [[deprecated( - "This API will be removed along with the legacy architecture.")]] RCTObjcExecutorFactory +class [[deprecated("This API will be removed along with the legacy architecture.")]] RCTObjcExecutorFactory : public JSExecutorFactory { public: - RCTObjcExecutorFactory( - id jse, - RCTJavaScriptCompleteBlock errorBlock); + RCTObjcExecutorFactory(id jse, RCTJavaScriptCompleteBlock errorBlock); std::unique_ptr createJSExecutor( std::shared_ptr delegate, std::shared_ptr jsQueue) override; diff --git a/packages/react-native/React/CxxLogUtils/RCTDefaultCxxLogFunction.h b/packages/react-native/React/CxxLogUtils/RCTDefaultCxxLogFunction.h index 53a22949b53..36a2abad242 100644 --- a/packages/react-native/React/CxxLogUtils/RCTDefaultCxxLogFunction.h +++ b/packages/react-native/React/CxxLogUtils/RCTDefaultCxxLogFunction.h @@ -11,6 +11,6 @@ namespace facebook::react { -void RCTDefaultCxxLogFunction(ReactNativeLogLevel level, const char* message); +void RCTDefaultCxxLogFunction(ReactNativeLogLevel level, const char *message); } // namespace facebook::react diff --git a/packages/react-native/React/CxxModule/RCTCxxUtils.mm b/packages/react-native/React/CxxModule/RCTCxxUtils.mm index f33ef557099..4c018e6fc96 100644 --- a/packages/react-native/React/CxxModule/RCTCxxUtils.mm +++ b/packages/react-native/React/CxxModule/RCTCxxUtils.mm @@ -28,11 +28,12 @@ createNativeModules(NSArray *modules, RCTBridge *bridge, const std::vector> nativeModules; for (RCTModuleData *moduleData in modules) { if ([moduleData.moduleClass isSubclassOfClass:[RCTCxxModule class]]) { - nativeModules.emplace_back(std::make_unique( - instance, - [moduleData.name UTF8String], - [moduleData] { return [(RCTCxxModule *)(moduleData.instance) createModule]; }, - std::make_shared(moduleData))); + nativeModules.emplace_back( + std::make_unique( + instance, + [moduleData.name UTF8String], + [moduleData] { return [(RCTCxxModule *)(moduleData.instance) createModule]; }, + std::make_shared(moduleData))); } else { nativeModules.emplace_back(std::make_unique(bridge, moduleData)); } diff --git a/packages/react-native/React/CxxModule/RCTNativeModule.h b/packages/react-native/React/CxxModule/RCTNativeModule.h index 103c662b1bc..3b08413e356 100644 --- a/packages/react-native/React/CxxModule/RCTNativeModule.h +++ b/packages/react-native/React/CxxModule/RCTNativeModule.h @@ -12,25 +12,21 @@ namespace facebook::react { -class [[deprecated( - "This API will be removed along with the legacy architecture.")]] RCTNativeModule +class [[deprecated("This API will be removed along with the legacy architecture.")]] RCTNativeModule : public NativeModule { public: - RCTNativeModule(RCTBridge* bridge, RCTModuleData* moduleData); + RCTNativeModule(RCTBridge *bridge, RCTModuleData *moduleData); std::string getName() override; std::string getSyncMethodName(unsigned int methodId) override; std::vector getMethods() override; folly::dynamic getConstants() override; - void invoke(unsigned int methodId, folly::dynamic&& params, int callId) - override; - MethodCallResult callSerializableNativeHook( - unsigned int reactMethodId, - folly::dynamic&& params) override; + void invoke(unsigned int methodId, folly::dynamic &¶ms, int callId) override; + MethodCallResult callSerializableNativeHook(unsigned int reactMethodId, folly::dynamic &¶ms) override; private: - __weak RCTBridge* m_bridge; - RCTModuleData* m_moduleData; + __weak RCTBridge *m_bridge; + RCTModuleData *m_moduleData; }; } // namespace facebook::react diff --git a/packages/react-native/React/Fabric/AppleEventBeat.h b/packages/react-native/React/Fabric/AppleEventBeat.h index f2f9ef4316a..256e0f0983a 100644 --- a/packages/react-native/React/Fabric/AppleEventBeat.h +++ b/packages/react-native/React/Fabric/AppleEventBeat.h @@ -25,13 +25,12 @@ class AppleEventBeat : public EventBeat, public RunLoopObserver::Delegate { AppleEventBeat( std::shared_ptr ownerBox, std::unique_ptr uiRunLoopObserver, - RuntimeScheduler& RuntimeScheduler); + RuntimeScheduler &RuntimeScheduler); #pragma mark - RunLoopObserver::Delegate - void activityDidChange( - const RunLoopObserver::Delegate* delegate, - RunLoopObserver::Activity activity) const noexcept override; + void activityDidChange(const RunLoopObserver::Delegate *delegate, RunLoopObserver::Activity activity) + const noexcept override; private: std::unique_ptr uiRunLoopObserver_; diff --git a/packages/react-native/React/Fabric/Mounting/RCTMountingTransactionObserverCoordinator.h b/packages/react-native/React/Fabric/Mounting/RCTMountingTransactionObserverCoordinator.h index 40ba1fd8214..6f11b31c28a 100644 --- a/packages/react-native/React/Fabric/Mounting/RCTMountingTransactionObserverCoordinator.h +++ b/packages/react-native/React/Fabric/Mounting/RCTMountingTransactionObserverCoordinator.h @@ -21,25 +21,22 @@ class RCTMountingTransactionObserverCoordinator final { * `componentViewDescriptor` does not listen the events. */ void registerViewComponentDescriptor( - const RCTComponentViewDescriptor& componentViewDescriptor, + const RCTComponentViewDescriptor &componentViewDescriptor, facebook::react::SurfaceId surfaceId); void unregisterViewComponentDescriptor( - const RCTComponentViewDescriptor& componentViewDescriptor, + const RCTComponentViewDescriptor &componentViewDescriptor, facebook::react::SurfaceId surfaceId); /* * To be called from `RCTMountingManager`. */ void notifyObserversMountingTransactionWillMount( - const facebook::react::MountingTransaction& transaction, - const facebook::react::SurfaceTelemetry& surfaceTelemetry) const; + const facebook::react::MountingTransaction &transaction, + const facebook::react::SurfaceTelemetry &surfaceTelemetry) const; void notifyObserversMountingTransactionDidMount( - const facebook::react::MountingTransaction& transaction, - const facebook::react::SurfaceTelemetry& surfaceTelemetry) const; + const facebook::react::MountingTransaction &transaction, + const facebook::react::SurfaceTelemetry &surfaceTelemetry) const; private: - std::unordered_map< - facebook::react::SurfaceId, - std::unordered_set> - registry_; + std::unordered_map> registry_; }; diff --git a/packages/react-native/React/Fabric/Utils/PlatformRunLoopObserver.h b/packages/react-native/React/Fabric/Utils/PlatformRunLoopObserver.h index 4f097aaac50..3faf9ec093f 100644 --- a/packages/react-native/React/Fabric/Utils/PlatformRunLoopObserver.h +++ b/packages/react-native/React/Fabric/Utils/PlatformRunLoopObserver.h @@ -20,10 +20,7 @@ namespace facebook::react { */ class PlatformRunLoopObserver : public RunLoopObserver { public: - PlatformRunLoopObserver( - RunLoopObserver::Activity activities, - RunLoopObserver::WeakOwner owner, - CFRunLoopRef runLoop); + PlatformRunLoopObserver(RunLoopObserver::Activity activities, RunLoopObserver::WeakOwner owner, CFRunLoopRef runLoop); ~PlatformRunLoopObserver(); @@ -43,13 +40,10 @@ class PlatformRunLoopObserver : public RunLoopObserver { */ class MainRunLoopObserver final : public PlatformRunLoopObserver { public: - MainRunLoopObserver( - RunLoopObserver::Activity activities, - RunLoopObserver::WeakOwner owner) - : PlatformRunLoopObserver( - activities, - std::move(owner), - CFRunLoopGetMain()) {} + MainRunLoopObserver(RunLoopObserver::Activity activities, RunLoopObserver::WeakOwner owner) + : PlatformRunLoopObserver(activities, std::move(owner), CFRunLoopGetMain()) + { + } }; } // namespace facebook::react diff --git a/packages/react-native/React/Fabric/Utils/RCTIdentifierPool.h b/packages/react-native/React/Fabric/Utils/RCTIdentifierPool.h index 89c984e90d9..ec5e849c812 100644 --- a/packages/react-native/React/Fabric/Utils/RCTIdentifierPool.h +++ b/packages/react-native/React/Fabric/Utils/RCTIdentifierPool.h @@ -14,11 +14,13 @@ namespace facebook::react { template class RCTIdentifierPool { public: - void enqueue(int index) { + void enqueue(int index) + { usage[index] = false; } - int dequeue() { + int dequeue() + { while (true) { if (!usage[lastIndex]) { usage[lastIndex] = true; @@ -28,7 +30,8 @@ class RCTIdentifierPool { } } - void reset() { + void reset() + { for (int i = 0; i < size; i++) { usage[i] = false; } diff --git a/packages/react-native/React/Inspector/RCTCxxInspectorPackagerConnectionDelegate.h b/packages/react-native/React/Inspector/RCTCxxInspectorPackagerConnectionDelegate.h index 56e5f51c161..2a680c34949 100644 --- a/packages/react-native/React/Inspector/RCTCxxInspectorPackagerConnectionDelegate.h +++ b/packages/react-native/React/Inspector/RCTCxxInspectorPackagerConnectionDelegate.h @@ -21,26 +21,23 @@ namespace facebook::react::jsinspector_modern { /** * Glue between C++ and Objective-C for InspectorPackagerConnectionDelegate. */ -class RCTCxxInspectorPackagerConnectionDelegate - : public InspectorPackagerConnectionDelegate { +class RCTCxxInspectorPackagerConnectionDelegate : public InspectorPackagerConnectionDelegate { class WebSocket : public IWebSocket { public: - WebSocket(RCTCxxInspectorWebSocketAdapter* adapter); + WebSocket(RCTCxxInspectorWebSocketAdapter *adapter); virtual void send(std::string_view message) override; virtual ~WebSocket() override; private: - RCTCxxInspectorWebSocketAdapter* const _adapter; + RCTCxxInspectorWebSocketAdapter *const _adapter; }; public: virtual std::unique_ptr connectWebSocket( - const std::string& url, + const std::string &url, std::weak_ptr delegate) override; - virtual void scheduleCallback( - std::function callback, - std::chrono::milliseconds delayMs) override; + virtual void scheduleCallback(std::function callback, std::chrono::milliseconds delayMs) override; }; } // namespace facebook::react::jsinspector_modern diff --git a/packages/react-native/React/Modules/RCTUIManager.mm b/packages/react-native/React/Modules/RCTUIManager.mm index 73b56282800..c3d1cf6d724 100644 --- a/packages/react-native/React/Modules/RCTUIManager.mm +++ b/packages/react-native/React/Modules/RCTUIManager.mm @@ -667,12 +667,11 @@ static NSDictionary *deviceOrientationEventBody(UIDeviceOrientation orientation) for (RCTShadowView *shadowView in affectedShadowViews) { reactTags[index] = shadowView.reactTag; RCTLayoutMetrics layoutMetrics = shadowView.layoutMetrics; - frameDataArray[index++] = (RCTFrameData){ - layoutMetrics.frame, - layoutMetrics.layoutDirection, - shadowView.isNewView, - shadowView.superview.isNewView, - layoutMetrics.displayType}; + frameDataArray[index++] = (RCTFrameData){layoutMetrics.frame, + layoutMetrics.layoutDirection, + shadowView.isNewView, + shadowView.superview.isNewView, + layoutMetrics.displayType}; } } @@ -944,13 +943,11 @@ static void RCTSetChildren( } } -RCT_EXPORT_METHOD(manageChildren - : (nonnull NSNumber *)containerTag moveFromIndices - : (NSArray *)moveFromIndices moveToIndices - : (NSArray *)moveToIndices addChildReactTags - : (NSArray *)addChildReactTags addAtIndices - : (NSArray *)addAtIndices removeAtIndices - : (NSArray *)removeAtIndices) +RCT_EXPORT_METHOD( + manageChildren : (nonnull NSNumber *)containerTag moveFromIndices : (NSArray *) + moveFromIndices moveToIndices : (NSArray *)moveToIndices addChildReactTags : (NSArray *) + addChildReactTags addAtIndices : (NSArray *) + addAtIndices removeAtIndices : (NSArray *)removeAtIndices) { [self _manageChildren:containerTag moveFromIndices:moveFromIndices @@ -1027,11 +1024,9 @@ RCT_EXPORT_METHOD(manageChildren } } -RCT_EXPORT_METHOD(createView - : (nonnull NSNumber *)reactTag viewName - : (NSString *)viewName rootTag - : (nonnull NSNumber *)rootTag props - : (NSDictionary *)props) +RCT_EXPORT_METHOD( + createView : (nonnull NSNumber *)reactTag viewName : (NSString *)viewName rootTag : (nonnull NSNumber *) + rootTag props : (NSDictionary *)props) { RCTComponentData *componentData = _componentDataByName[viewName]; if (componentData == nil) { @@ -1088,11 +1083,10 @@ RCT_EXPORT_METHOD(createView [self _shadowView:shadowView didReceiveUpdatedProps:[props allKeys]]; } -RCT_EXPORT_METHOD(updateView - : (nonnull NSNumber *)reactTag viewName - : (NSString *)viewName // not always reliable, use shadowView.viewName if available - props - : (NSDictionary *)props) +RCT_EXPORT_METHOD( + updateView : (nonnull NSNumber *)reactTag viewName : (NSString *) + viewName // not always reliable, use shadowView.viewName if available + props : (NSDictionary *)props) { RCTShadowView *shadowView = _shadowViewRegistry[reactTag]; RCTComponentData *componentData = _componentDataByName[shadowView.viewName ?: viewName]; @@ -1130,10 +1124,8 @@ RCT_EXPORT_METHOD(blur : (nonnull NSNumber *)reactTag) }]; } -RCT_EXPORT_METHOD(findSubviewIn - : (nonnull NSNumber *)reactTag atPoint - : (CGPoint)point callback - : (RCTResponseSenderBlock)callback) +RCT_EXPORT_METHOD( + findSubviewIn : (nonnull NSNumber *)reactTag atPoint : (CGPoint)point callback : (RCTResponseSenderBlock)callback) { [self addUIBlock:^(__unused RCTUIManager *uiManager, NSDictionary *viewRegistry) { UIView *view = viewRegistry[reactTag]; @@ -1154,10 +1146,9 @@ RCT_EXPORT_METHOD(findSubviewIn }]; } -RCT_EXPORT_METHOD(dispatchViewManagerCommand - : (nonnull NSNumber *)reactTag commandID - : (id /*(NSString or NSNumber) */)commandID commandArgs - : (NSArray *)commandArgs) +RCT_EXPORT_METHOD( + dispatchViewManagerCommand : (nonnull NSNumber *)reactTag commandID : (id /*(NSString or NSNumber) */) + commandID commandArgs : (NSArray *)commandArgs) { RCTShadowView *shadowView = _shadowViewRegistry[reactTag]; RCTComponentData *componentData = _componentDataByName[shadowView.viewName]; @@ -1420,10 +1411,9 @@ RCT_EXPORT_METHOD(measureInWindow : (nonnull NSNumber *)reactTag callback : (RCT * Returns if the shadow view provided has the `ancestor` shadow view as * an actual ancestor. */ -RCT_EXPORT_METHOD(viewIsDescendantOf - : (nonnull NSNumber *)reactTag ancestor - : (nonnull NSNumber *)ancestorReactTag callback - : (RCTResponseSenderBlock)callback) +RCT_EXPORT_METHOD( + viewIsDescendantOf : (nonnull NSNumber *)reactTag ancestor : (nonnull NSNumber *) + ancestorReactTag callback : (RCTResponseSenderBlock)callback) { RCTShadowView *shadowView = _shadowViewRegistry[reactTag]; RCTShadowView *ancestorShadowView = _shadowViewRegistry[ancestorReactTag]; @@ -1469,11 +1459,9 @@ static void RCTMeasureLayout(RCTShadowView *view, RCTShadowView *ancestor, RCTRe * anything on the main UI thread. Invokes supplied callback with (x, y, width, * height). */ -RCT_EXPORT_METHOD(measureLayout - : (nonnull NSNumber *)reactTag relativeTo - : (nonnull NSNumber *)ancestorReactTag errorCallback - : (__unused RCTResponseSenderBlock)errorCallback callback - : (RCTResponseSenderBlock)callback) +RCT_EXPORT_METHOD( + measureLayout : (nonnull NSNumber *)reactTag relativeTo : (nonnull NSNumber *)ancestorReactTag errorCallback : ( + __unused RCTResponseSenderBlock)errorCallback callback : (RCTResponseSenderBlock)callback) { RCTShadowView *shadowView = _shadowViewRegistry[reactTag]; RCTShadowView *ancestorShadowView = _shadowViewRegistry[ancestorReactTag]; @@ -1484,9 +1472,8 @@ RCT_EXPORT_METHOD(measureLayout * JS sets what *it* considers to be the responder. Later, scroll views can use * this in order to determine if scrolling is appropriate. */ -RCT_EXPORT_METHOD(setJSResponder - : (nonnull NSNumber *)reactTag blockNativeResponder - : (__unused BOOL)blockNativeResponder) +RCT_EXPORT_METHOD( + setJSResponder : (nonnull NSNumber *)reactTag blockNativeResponder : (__unused BOOL)blockNativeResponder) { [self addUIBlock:^(__unused RCTUIManager *uiManager, NSDictionary *viewRegistry) { _jsResponder = viewRegistry[reactTag]; @@ -1582,10 +1569,9 @@ RCT_EXPORT_BLOCKING_SYNCHRONOUS_METHOD(lazilyLoadView : (NSString *)name) }; } -RCT_EXPORT_METHOD(configureNextLayoutAnimation - : (NSDictionary *)config withCallback - : (RCTResponseSenderBlock)callback errorCallback - : (__unused RCTResponseSenderBlock)errorCallback) +RCT_EXPORT_METHOD( + configureNextLayoutAnimation : (NSDictionary *)config withCallback : (RCTResponseSenderBlock) + callback errorCallback : (__unused RCTResponseSenderBlock)errorCallback) { RCTLayoutAnimationGroup *layoutAnimationGroup = [[RCTLayoutAnimationGroup alloc] initWithConfig:config callback:callback]; diff --git a/packages/react-native/React/Profiler/RCTProfile.m b/packages/react-native/React/Profiler/RCTProfile.m index 47f7f6cfe71..04d6ac14ec9 100644 --- a/packages/react-native/React/Profiler/RCTProfile.m +++ b/packages/react-native/React/Profiler/RCTProfile.m @@ -471,12 +471,10 @@ void RCTProfileInit(RCTBridge *bridge) [orderedThreads enumerateObjectsUsingBlock:^(NSString *thread, NSUInteger idx, __unused BOOL *stop) { RCTProfileAddEvent( kProfileTraceEvents, - @"ph" - : @"M", // metadata event - @"name" - : @"thread_sort_index", @"tid" - : thread, @"args" - : + @"ph" : @"M", // metadata event + @"name" : @"thread_sort_index", + @"tid" : thread, + @"args" : @{@"sort_index" : @(-1000 + (NSInteger)idx)}); }]; }); @@ -582,14 +580,15 @@ void _RCTProfileEndEvent( } NSNumber *start = event[0]; - RCTProfileAddEvent(kProfileTraceEvents, @"tid" - : threadName, @"name" - : event[1], @"cat" - : category, @"ph" - : @"X", @"ts" - : start, @"dur" - : @(RCTProfileTimestamp(time).doubleValue - start.doubleValue), @"args" - : event[2], ); + RCTProfileAddEvent( + kProfileTraceEvents, + @"tid" : threadName, + @"name" : event[1], + @"cat" : category, + @"ph" : @"X", + @"ts" : start, + @"dur" : @(RCTProfileTimestamp(time).doubleValue - start.doubleValue), + @"args" : event[2], ); }); } @@ -636,14 +635,15 @@ void RCTProfileEndAsyncEvent(uint64_t tag, NSString *category, NSUInteger cookie if (event) { NSNumber *endTimestamp = RCTProfileTimestamp(time); - RCTProfileAddEvent(kProfileTraceEvents, @"tid" - : threadName, @"name" - : event[1], @"cat" - : category, @"ph" - : @"X", @"ts" - : event[0], @"dur" - : @(endTimestamp.doubleValue - [event[0] doubleValue]), @"args" - : event[2], ); + RCTProfileAddEvent( + kProfileTraceEvents, + @"tid" : threadName, + @"name" : event[1], + @"cat" : category, + @"ph" : @"X", + @"ts" : event[0], + @"dur" : @(endTimestamp.doubleValue - [event[0] doubleValue]), + @"args" : event[2], ); [RCTProfileOngoingEvents removeObjectForKey:@(cookie)]; } }); @@ -661,13 +661,14 @@ void RCTProfileImmediateEvent(uint64_t tag, NSString *name, NSTimeInterval time, NSString *threadName = RCTCurrentThreadName(); dispatch_async(RCTProfileGetQueue(), ^{ - RCTProfileAddEvent(kProfileTraceEvents, @"tid" - : threadName, @"name" - : name, @"ts" - : RCTProfileTimestamp(time), @"scope" - : @(scope), @"ph" - : @"i", @"args" - : RCTProfileGetMemoryUsage(), ); + RCTProfileAddEvent( + kProfileTraceEvents, + @"tid" : threadName, + @"name" : name, + @"ts" : RCTProfileTimestamp(time), + @"scope" : @(scope), + @"ph" : @"i", + @"args" : RCTProfileGetMemoryUsage(), ); }); } @@ -687,13 +688,14 @@ NSUInteger _RCTProfileBeginFlowEvent(void) NSString *threadName = RCTCurrentThreadName(); dispatch_async(RCTProfileGetQueue(), ^{ - RCTProfileAddEvent(kProfileTraceEvents, @"tid" - : threadName, @"name" - : @"flow", @"id" - : @(cookie), @"cat" - : @"flow", @"ph" - : @"s", @"ts" - : RCTProfileTimestamp(time), ); + RCTProfileAddEvent( + kProfileTraceEvents, + @"tid" : threadName, + @"name" : @"flow", + @"id" : @(cookie), + @"cat" : @"flow", + @"ph" : @"s", + @"ts" : RCTProfileTimestamp(time), ); }); return cookie; @@ -712,13 +714,14 @@ void _RCTProfileEndFlowEvent(NSUInteger cookie) NSString *threadName = RCTCurrentThreadName(); dispatch_async(RCTProfileGetQueue(), ^{ - RCTProfileAddEvent(kProfileTraceEvents, @"tid" - : threadName, @"name" - : @"flow", @"id" - : @(cookie), @"cat" - : @"flow", @"ph" - : @"f", @"ts" - : RCTProfileTimestamp(time), ); + RCTProfileAddEvent( + kProfileTraceEvents, + @"tid" : threadName, + @"name" : @"flow", + @"id" : @(cookie), + @"cat" : @"flow", + @"ph" : @"f", + @"ts" : RCTProfileTimestamp(time), ); }); } diff --git a/packages/react-native/React/Views/RCTActivityIndicatorViewManager.h b/packages/react-native/React/Views/RCTActivityIndicatorViewManager.h index 36fe6c323f7..79371b4f80f 100644 --- a/packages/react-native/React/Views/RCTActivityIndicatorViewManager.h +++ b/packages/react-native/React/Views/RCTActivityIndicatorViewManager.h @@ -10,7 +10,7 @@ #ifndef RCT_REMOVE_LEGACY_ARCH __attribute__((deprecated("This API will be removed along with the legacy architecture."))) -@interface RCTConvert (UIActivityIndicatorView) +@interface RCTConvert(UIActivityIndicatorView) + (UIActivityIndicatorViewStyle)UIActivityIndicatorViewStyle:(id)json; diff --git a/packages/react-native/React/Views/RCTBorderDrawing.m b/packages/react-native/React/Views/RCTBorderDrawing.m index 0b83bcb4e65..9755a2ae048 100644 --- a/packages/react-native/React/Views/RCTBorderDrawing.m +++ b/packages/react-native/React/Views/RCTBorderDrawing.m @@ -42,23 +42,22 @@ BOOL RCTBorderColorsAreEqual(RCTBorderColors borderColors) RCTCornerInsets RCTGetCornerInsets(RCTCornerRadii cornerRadii, UIEdgeInsets edgeInsets) { - return (RCTCornerInsets){ - { - MAX(0, cornerRadii.topLeftHorizontal - edgeInsets.left), - MAX(0, cornerRadii.topLeftVertical - edgeInsets.top), - }, - { - MAX(0, cornerRadii.topRightHorizontal - edgeInsets.right), - MAX(0, cornerRadii.topRightVertical - edgeInsets.top), - }, - { - MAX(0, cornerRadii.bottomLeftHorizontal - edgeInsets.left), - MAX(0, cornerRadii.bottomLeftVertical - edgeInsets.bottom), - }, - { - MAX(0, cornerRadii.bottomRightHorizontal - edgeInsets.right), - MAX(0, cornerRadii.bottomRightVertical - edgeInsets.bottom), - }}; + return (RCTCornerInsets){{ + MAX(0, cornerRadii.topLeftHorizontal - edgeInsets.left), + MAX(0, cornerRadii.topLeftVertical - edgeInsets.top), + }, + { + MAX(0, cornerRadii.topRightHorizontal - edgeInsets.right), + MAX(0, cornerRadii.topRightVertical - edgeInsets.top), + }, + { + MAX(0, cornerRadii.bottomLeftHorizontal - edgeInsets.left), + MAX(0, cornerRadii.bottomLeftVertical - edgeInsets.bottom), + }, + { + MAX(0, cornerRadii.bottomRightHorizontal - edgeInsets.right), + MAX(0, cornerRadii.bottomRightVertical - edgeInsets.bottom), + }}; } static UIEdgeInsets RCTRoundInsetsToPixel(UIEdgeInsets edgeInsets) @@ -240,11 +239,11 @@ static UIImage *RCTGetSolidBorderImage( (borderInsets.top + cornerInsets.topRight.height + borderInsets.bottom + cornerInsets.bottomLeft.height <= viewSize.height); - UIEdgeInsets edgeInsets = (UIEdgeInsets){ - borderInsets.top + MAX(cornerInsets.topLeft.height, cornerInsets.topRight.height), - borderInsets.left + MAX(cornerInsets.topLeft.width, cornerInsets.bottomLeft.width), - borderInsets.bottom + MAX(cornerInsets.bottomLeft.height, cornerInsets.bottomRight.height), - borderInsets.right + MAX(cornerInsets.bottomRight.width, cornerInsets.topRight.width)}; + UIEdgeInsets edgeInsets = + (UIEdgeInsets){borderInsets.top + MAX(cornerInsets.topLeft.height, cornerInsets.topRight.height), + borderInsets.left + MAX(cornerInsets.topLeft.width, cornerInsets.bottomLeft.width), + borderInsets.bottom + MAX(cornerInsets.bottomLeft.height, cornerInsets.bottomRight.height), + borderInsets.right + MAX(cornerInsets.bottomRight.width, cornerInsets.topRight.width)}; const CGSize size = makeStretchable ? (CGSize){ // 1pt for the middle stretchable area along each axis @@ -300,9 +299,8 @@ static UIImage *RCTGetSolidBorderImage( if (cornerInsets.bottomLeft.width > 0 && cornerInsets.bottomLeft.height > 0) { CGPoint points[2]; RCTEllipseGetIntersectionsWithLine( - (CGRect){ - {bottomLeft.x, bottomLeft.y - 2 * cornerInsets.bottomLeft.height}, - {2 * cornerInsets.bottomLeft.width, 2 * cornerInsets.bottomLeft.height}}, + (CGRect){{bottomLeft.x, bottomLeft.y - 2 * cornerInsets.bottomLeft.height}, + {2 * cornerInsets.bottomLeft.width, 2 * cornerInsets.bottomLeft.height}}, (CGPoint){0, size.height}, bottomLeft, points); @@ -315,9 +313,8 @@ static UIImage *RCTGetSolidBorderImage( if (cornerInsets.topRight.width > 0 && cornerInsets.topRight.height > 0) { CGPoint points[2]; RCTEllipseGetIntersectionsWithLine( - (CGRect){ - {topRight.x - 2 * cornerInsets.topRight.width, topRight.y}, - {2 * cornerInsets.topRight.width, 2 * cornerInsets.topRight.height}}, + (CGRect){{topRight.x - 2 * cornerInsets.topRight.width, topRight.y}, + {2 * cornerInsets.topRight.width, 2 * cornerInsets.topRight.height}}, (CGPoint){size.width, 0}, topRight, points); @@ -330,10 +327,9 @@ static UIImage *RCTGetSolidBorderImage( if (cornerInsets.bottomRight.width > 0 && cornerInsets.bottomRight.height > 0) { CGPoint points[2]; RCTEllipseGetIntersectionsWithLine( - (CGRect){ - {bottomRight.x - 2 * cornerInsets.bottomRight.width, - bottomRight.y - 2 * cornerInsets.bottomRight.height}, - {2 * cornerInsets.bottomRight.width, 2 * cornerInsets.bottomRight.height}}, + (CGRect){{bottomRight.x - 2 * cornerInsets.bottomRight.width, + bottomRight.y - 2 * cornerInsets.bottomRight.height}, + {2 * cornerInsets.bottomRight.width, 2 * cornerInsets.bottomRight.height}}, (CGPoint){size.width, size.height}, bottomRight, points); diff --git a/packages/react-native/React/Views/RCTConvert+CoreLocation.m b/packages/react-native/React/Views/RCTConvert+CoreLocation.m index a4d0516a28e..add97be1ede 100644 --- a/packages/react-native/React/Views/RCTConvert+CoreLocation.m +++ b/packages/react-native/React/Views/RCTConvert+CoreLocation.m @@ -15,8 +15,8 @@ RCT_CONVERTER(CLLocationDistance, CLLocationDistance, doubleValue); + (CLLocationCoordinate2D)CLLocationCoordinate2D:(id)json { json = [self NSDictionary:json]; - return (CLLocationCoordinate2D){ - [self CLLocationDegrees:json[@"latitude"]], [self CLLocationDegrees:json[@"longitude"]]}; + return (CLLocationCoordinate2D){[self CLLocationDegrees:json[@"latitude"]], + [self CLLocationDegrees:json[@"longitude"]]}; } @end diff --git a/packages/react-native/React/Views/RCTLayout.m b/packages/react-native/React/Views/RCTLayout.m index 0d16f955960..944b728684c 100644 --- a/packages/react-native/React/Views/RCTLayout.m +++ b/packages/react-native/React/Views/RCTLayout.m @@ -14,31 +14,27 @@ RCTLayoutMetrics RCTLayoutMetricsFromYogaNode(YGNodeRef yogaNode) { RCTLayoutMetrics layoutMetrics; - CGRect frame = (CGRect){ - (CGPoint){ - RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetLeft(yogaNode)), - RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetTop(yogaNode))}, - (CGSize){ - RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetWidth(yogaNode)), - RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetHeight(yogaNode))}}; + CGRect frame = (CGRect){(CGPoint){RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetLeft(yogaNode)), + RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetTop(yogaNode))}, + (CGSize){RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetWidth(yogaNode)), + RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetHeight(yogaNode))}}; - UIEdgeInsets padding = (UIEdgeInsets){ - RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetPadding(yogaNode, YGEdgeTop)), - RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetPadding(yogaNode, YGEdgeLeft)), - RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetPadding(yogaNode, YGEdgeBottom)), - RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetPadding(yogaNode, YGEdgeRight))}; + UIEdgeInsets padding = + (UIEdgeInsets){RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetPadding(yogaNode, YGEdgeTop)), + RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetPadding(yogaNode, YGEdgeLeft)), + RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetPadding(yogaNode, YGEdgeBottom)), + RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetPadding(yogaNode, YGEdgeRight))}; - UIEdgeInsets borderWidth = (UIEdgeInsets){ - RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetBorder(yogaNode, YGEdgeTop)), - RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetBorder(yogaNode, YGEdgeLeft)), - RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetBorder(yogaNode, YGEdgeBottom)), - RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetBorder(yogaNode, YGEdgeRight))}; + UIEdgeInsets borderWidth = + (UIEdgeInsets){RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetBorder(yogaNode, YGEdgeTop)), + RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetBorder(yogaNode, YGEdgeLeft)), + RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetBorder(yogaNode, YGEdgeBottom)), + RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetBorder(yogaNode, YGEdgeRight))}; - UIEdgeInsets compoundInsets = (UIEdgeInsets){ - borderWidth.top + padding.top, - borderWidth.left + padding.left, - borderWidth.bottom + padding.bottom, - borderWidth.right + padding.right}; + UIEdgeInsets compoundInsets = (UIEdgeInsets){borderWidth.top + padding.top, + borderWidth.left + padding.left, + borderWidth.bottom + padding.bottom, + borderWidth.right + padding.right}; CGRect bounds = (CGRect){CGPointZero, frame.size}; CGRect contentFrame = UIEdgeInsetsInsetRect(bounds, compoundInsets); diff --git a/packages/react-native/React/Views/RCTShadowView+Layout.m b/packages/react-native/React/Views/RCTShadowView+Layout.m index 6595f4e75a7..73301d468d2 100644 --- a/packages/react-native/React/Views/RCTShadowView+Layout.m +++ b/packages/react-native/React/Views/RCTShadowView+Layout.m @@ -18,21 +18,19 @@ - (UIEdgeInsets)paddingAsInsets { YGNodeRef yogaNode = self.yogaNode; - return (UIEdgeInsets){ - RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetPadding(yogaNode, YGEdgeTop)), - RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetPadding(yogaNode, YGEdgeLeft)), - RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetPadding(yogaNode, YGEdgeBottom)), - RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetPadding(yogaNode, YGEdgeRight))}; + return (UIEdgeInsets){RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetPadding(yogaNode, YGEdgeTop)), + RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetPadding(yogaNode, YGEdgeLeft)), + RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetPadding(yogaNode, YGEdgeBottom)), + RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetPadding(yogaNode, YGEdgeRight))}; } - (UIEdgeInsets)borderAsInsets { YGNodeRef yogaNode = self.yogaNode; - return (UIEdgeInsets){ - RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetBorder(yogaNode, YGEdgeTop)), - RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetBorder(yogaNode, YGEdgeLeft)), - RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetBorder(yogaNode, YGEdgeBottom)), - RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetBorder(yogaNode, YGEdgeRight))}; + return (UIEdgeInsets){RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetBorder(yogaNode, YGEdgeTop)), + RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetBorder(yogaNode, YGEdgeLeft)), + RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetBorder(yogaNode, YGEdgeBottom)), + RCTCoreGraphicsFloatFromYogaFloat(YGNodeLayoutGetBorder(yogaNode, YGEdgeRight))}; } - (UIEdgeInsets)compoundInsets @@ -40,11 +38,10 @@ UIEdgeInsets borderAsInsets = self.borderAsInsets; UIEdgeInsets paddingAsInsets = self.paddingAsInsets; - return (UIEdgeInsets){ - borderAsInsets.top + paddingAsInsets.top, - borderAsInsets.left + paddingAsInsets.left, - borderAsInsets.bottom + paddingAsInsets.bottom, - borderAsInsets.right + paddingAsInsets.right}; + return (UIEdgeInsets){borderAsInsets.top + paddingAsInsets.top, + borderAsInsets.left + paddingAsInsets.left, + borderAsInsets.bottom + paddingAsInsets.bottom, + borderAsInsets.right + paddingAsInsets.right}; } - (CGSize)availableSize diff --git a/packages/react-native/React/Views/RCTShadowView.m b/packages/react-native/React/Views/RCTShadowView.m index 098e1b4436f..a7a3d394848 100644 --- a/packages/react-native/React/Views/RCTShadowView.m +++ b/packages/react-native/React/Views/RCTShadowView.m @@ -294,9 +294,8 @@ static void RCTProcessMetaPropsBorder(const YGValue metaProps[META_PROP_COUNT], { YGNodeRef yogaNode = _yogaNode; - CGSize oldMinimumSize = (CGSize){ - RCTCoreGraphicsFloatFromYogaValue(YGNodeStyleGetMinWidth(yogaNode), 0.0), - RCTCoreGraphicsFloatFromYogaValue(YGNodeStyleGetMinHeight(yogaNode), 0.0)}; + CGSize oldMinimumSize = (CGSize){RCTCoreGraphicsFloatFromYogaValue(YGNodeStyleGetMinWidth(yogaNode), 0.0), + RCTCoreGraphicsFloatFromYogaValue(YGNodeStyleGetMinHeight(yogaNode), 0.0)}; if (!CGSizeEqualToSize(oldMinimumSize, minimumSize)) { YGNodeStyleSetMinWidth(yogaNode, RCTYogaFloatFromCoreGraphicsFloat(minimumSize.width)); diff --git a/packages/react-native/React/Views/ScrollView/RCTScrollView.m b/packages/react-native/React/Views/ScrollView/RCTScrollView.m index 691a11cc6a5..72c7c39e3c1 100644 --- a/packages/react-native/React/Views/ScrollView/RCTScrollView.m +++ b/packages/react-native/React/Views/ScrollView/RCTScrollView.m @@ -860,10 +860,8 @@ RCT_SCROLL_EVENT_HANDLER(scrollViewDidScrollToTop, onScrollToTop) @"targetContentOffset" : @{@"x" : @(targetContentOffset->x), @"y" : @(targetContentOffset->y)} }; RCT_SEND_SCROLL_EVENT(onScrollEndDrag, userData); - RCT_FORWARD_SCROLL_EVENT(scrollViewWillEndDragging - : scrollView withVelocity - : velocity targetContentOffset - : targetContentOffset); + RCT_FORWARD_SCROLL_EVENT( + scrollViewWillEndDragging : scrollView withVelocity : velocity targetContentOffset : targetContentOffset); } - (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate diff --git a/packages/react-native/React/Views/ScrollView/RCTScrollViewManager.h b/packages/react-native/React/Views/ScrollView/RCTScrollViewManager.h index e1df43aa922..bb5d7b0cea4 100644 --- a/packages/react-native/React/Views/ScrollView/RCTScrollViewManager.h +++ b/packages/react-native/React/Views/ScrollView/RCTScrollViewManager.h @@ -11,7 +11,7 @@ #ifndef RCT_REMOVE_LEGACY_ARCH __attribute__((deprecated("This API will be removed along with the legacy architecture."))) -@interface RCTConvert (UIScrollView) +@interface RCTConvert(UIScrollView) + (UIScrollViewKeyboardDismissMode)UIScrollViewKeyboardDismissMode:(id)json; diff --git a/packages/react-native/React/Views/ScrollView/RCTScrollViewManager.m b/packages/react-native/React/Views/ScrollView/RCTScrollViewManager.m index 0161a3a52e9..985771805c5 100644 --- a/packages/react-native/React/Views/ScrollView/RCTScrollViewManager.m +++ b/packages/react-native/React/Views/ScrollView/RCTScrollViewManager.m @@ -131,11 +131,8 @@ RCT_EXPORT_METHOD(getContentSize : (nonnull NSNumber *)reactTag callback : (RCTR }]; } -RCT_EXPORT_METHOD(scrollTo - : (nonnull NSNumber *)reactTag offsetX - : (CGFloat)x offsetY - : (CGFloat)y animated - : (BOOL)animated) +RCT_EXPORT_METHOD( + scrollTo : (nonnull NSNumber *)reactTag offsetX : (CGFloat)x offsetY : (CGFloat)y animated : (BOOL)animated) { [self.bridge.uiManager addUIBlock:^(__unused RCTUIManager *uiManager, NSDictionary *viewRegistry) { diff --git a/packages/react-native/ReactAndroid/src/main/jni/first-party/fbgloginit/fb/glog_init.h b/packages/react-native/ReactAndroid/src/main/jni/first-party/fbgloginit/fb/glog_init.h index f8258552ccb..4461e2aadb7 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/first-party/fbgloginit/fb/glog_init.h +++ b/packages/react-native/ReactAndroid/src/main/jni/first-party/fbgloginit/fb/glog_init.h @@ -11,6 +11,6 @@ namespace facebook::gloginit { -void initialize(const char* tag = "ReactNativeJNI"); +void initialize(const char *tag = "ReactNativeJNI"); } diff --git a/packages/react-native/ReactAndroid/src/main/jni/first-party/jni-hack/real/jni.h b/packages/react-native/ReactAndroid/src/main/jni/first-party/jni-hack/real/jni.h index 1eb30b6fedf..0d68ffb84da 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/first-party/jni-hack/real/jni.h +++ b/packages/react-native/ReactAndroid/src/main/jni/first-party/jni-hack/real/jni.h @@ -59,28 +59,28 @@ class _jfloatArray : public _jarray {}; class _jdoubleArray : public _jarray {}; class _jthrowable : public _jobject {}; -typedef _jobject* jobject; -typedef _jclass* jclass; -typedef _jstring* jstring; -typedef _jarray* jarray; -typedef _jobjectArray* jobjectArray; -typedef _jbooleanArray* jbooleanArray; -typedef _jbyteArray* jbyteArray; -typedef _jcharArray* jcharArray; -typedef _jshortArray* jshortArray; -typedef _jintArray* jintArray; -typedef _jlongArray* jlongArray; -typedef _jfloatArray* jfloatArray; -typedef _jdoubleArray* jdoubleArray; -typedef _jthrowable* jthrowable; -typedef _jobject* jweak; +typedef _jobject *jobject; +typedef _jclass *jclass; +typedef _jstring *jstring; +typedef _jarray *jarray; +typedef _jobjectArray *jobjectArray; +typedef _jbooleanArray *jbooleanArray; +typedef _jbyteArray *jbyteArray; +typedef _jcharArray *jcharArray; +typedef _jshortArray *jshortArray; +typedef _jintArray *jintArray; +typedef _jlongArray *jlongArray; +typedef _jfloatArray *jfloatArray; +typedef _jdoubleArray *jdoubleArray; +typedef _jthrowable *jthrowable; +typedef _jobject *jweak; #else /* not __cplusplus */ /* * Reference types, in C. */ -typedef void* jobject; +typedef void *jobject; typedef jobject jclass; typedef jobject jstring; typedef jobject jarray; @@ -99,10 +99,10 @@ typedef jobject jweak; #endif /* not __cplusplus */ struct _jfieldID; /* opaque structure */ -typedef struct _jfieldID* jfieldID; /* field IDs */ +typedef struct _jfieldID *jfieldID; /* field IDs */ struct _jmethodID; /* opaque structure */ -typedef struct _jmethodID* jmethodID; /* method IDs */ +typedef struct _jmethodID *jmethodID; /* method IDs */ struct JNIInvokeInterface; @@ -126,376 +126,300 @@ typedef enum jobjectRefType { } jobjectRefType; typedef struct { - const char* name; - const char* signature; - void* fnPtr; + const char *name; + const char *signature; + void *fnPtr; } JNINativeMethod; struct _JNIEnv; struct _JavaVM; -typedef const struct JNINativeInterface* C_JNIEnv; +typedef const struct JNINativeInterface *C_JNIEnv; #if defined(__cplusplus) typedef _JNIEnv JNIEnv; typedef _JavaVM JavaVM; #else -typedef const struct JNINativeInterface* JNIEnv; -typedef const struct JNIInvokeInterface* JavaVM; +typedef const struct JNINativeInterface *JNIEnv; +typedef const struct JNIInvokeInterface *JavaVM; #endif /* * Table of interface function pointers. */ struct JNINativeInterface { - void* reserved0; - void* reserved1; - void* reserved2; - void* reserved3; + void *reserved0; + void *reserved1; + void *reserved2; + void *reserved3; - jint (*GetVersion)(JNIEnv*); + jint (*GetVersion)(JNIEnv *); - jclass (*DefineClass)(JNIEnv*, const char*, jobject, const jbyte*, jsize); - jclass (*FindClass)(JNIEnv*, const char*); + jclass (*DefineClass)(JNIEnv *, const char *, jobject, const jbyte *, jsize); + jclass (*FindClass)(JNIEnv *, const char *); - jmethodID (*FromReflectedMethod)(JNIEnv*, jobject); - jfieldID (*FromReflectedField)(JNIEnv*, jobject); + jmethodID (*FromReflectedMethod)(JNIEnv *, jobject); + jfieldID (*FromReflectedField)(JNIEnv *, jobject); /* spec doesn't show jboolean parameter */ - jobject (*ToReflectedMethod)(JNIEnv*, jclass, jmethodID, jboolean); + jobject (*ToReflectedMethod)(JNIEnv *, jclass, jmethodID, jboolean); - jclass (*GetSuperclass)(JNIEnv*, jclass); - jboolean (*IsAssignableFrom)(JNIEnv*, jclass, jclass); + jclass (*GetSuperclass)(JNIEnv *, jclass); + jboolean (*IsAssignableFrom)(JNIEnv *, jclass, jclass); /* spec doesn't show jboolean parameter */ - jobject (*ToReflectedField)(JNIEnv*, jclass, jfieldID, jboolean); + jobject (*ToReflectedField)(JNIEnv *, jclass, jfieldID, jboolean); - jint (*Throw)(JNIEnv*, jthrowable); - jint (*ThrowNew)(JNIEnv*, jclass, const char*); - jthrowable (*ExceptionOccurred)(JNIEnv*); - void (*ExceptionDescribe)(JNIEnv*); - void (*ExceptionClear)(JNIEnv*); - void (*FatalError)(JNIEnv*, const char*); + jint (*Throw)(JNIEnv *, jthrowable); + jint (*ThrowNew)(JNIEnv *, jclass, const char *); + jthrowable (*ExceptionOccurred)(JNIEnv *); + void (*ExceptionDescribe)(JNIEnv *); + void (*ExceptionClear)(JNIEnv *); + void (*FatalError)(JNIEnv *, const char *); - jint (*PushLocalFrame)(JNIEnv*, jint); - jobject (*PopLocalFrame)(JNIEnv*, jobject); + jint (*PushLocalFrame)(JNIEnv *, jint); + jobject (*PopLocalFrame)(JNIEnv *, jobject); - jobject (*NewGlobalRef)(JNIEnv*, jobject); - void (*DeleteGlobalRef)(JNIEnv*, jobject); - void (*DeleteLocalRef)(JNIEnv*, jobject); - jboolean (*IsSameObject)(JNIEnv*, jobject, jobject); + jobject (*NewGlobalRef)(JNIEnv *, jobject); + void (*DeleteGlobalRef)(JNIEnv *, jobject); + void (*DeleteLocalRef)(JNIEnv *, jobject); + jboolean (*IsSameObject)(JNIEnv *, jobject, jobject); - jobject (*NewLocalRef)(JNIEnv*, jobject); - jint (*EnsureLocalCapacity)(JNIEnv*, jint); + jobject (*NewLocalRef)(JNIEnv *, jobject); + jint (*EnsureLocalCapacity)(JNIEnv *, jint); - jobject (*AllocObject)(JNIEnv*, jclass); - jobject (*NewObject)(JNIEnv*, jclass, jmethodID, ...); - jobject (*NewObjectV)(JNIEnv*, jclass, jmethodID, va_list); - jobject (*NewObjectA)(JNIEnv*, jclass, jmethodID, jvalue*); + jobject (*AllocObject)(JNIEnv *, jclass); + jobject (*NewObject)(JNIEnv *, jclass, jmethodID, ...); + jobject (*NewObjectV)(JNIEnv *, jclass, jmethodID, va_list); + jobject (*NewObjectA)(JNIEnv *, jclass, jmethodID, jvalue *); - jclass (*GetObjectClass)(JNIEnv*, jobject); - jboolean (*IsInstanceOf)(JNIEnv*, jobject, jclass); - jmethodID (*GetMethodID)(JNIEnv*, jclass, const char*, const char*); + jclass (*GetObjectClass)(JNIEnv *, jobject); + jboolean (*IsInstanceOf)(JNIEnv *, jobject, jclass); + jmethodID (*GetMethodID)(JNIEnv *, jclass, const char *, const char *); - jobject (*CallObjectMethod)(JNIEnv*, jobject, jmethodID, ...); - jobject (*CallObjectMethodV)(JNIEnv*, jobject, jmethodID, va_list); - jobject (*CallObjectMethodA)(JNIEnv*, jobject, jmethodID, jvalue*); - jboolean (*CallBooleanMethod)(JNIEnv*, jobject, jmethodID, ...); - jboolean (*CallBooleanMethodV)(JNIEnv*, jobject, jmethodID, va_list); - jboolean (*CallBooleanMethodA)(JNIEnv*, jobject, jmethodID, jvalue*); - jbyte (*CallByteMethod)(JNIEnv*, jobject, jmethodID, ...); - jbyte (*CallByteMethodV)(JNIEnv*, jobject, jmethodID, va_list); - jbyte (*CallByteMethodA)(JNIEnv*, jobject, jmethodID, jvalue*); - jchar (*CallCharMethod)(JNIEnv*, jobject, jmethodID, ...); - jchar (*CallCharMethodV)(JNIEnv*, jobject, jmethodID, va_list); - jchar (*CallCharMethodA)(JNIEnv*, jobject, jmethodID, jvalue*); - jshort (*CallShortMethod)(JNIEnv*, jobject, jmethodID, ...); - jshort (*CallShortMethodV)(JNIEnv*, jobject, jmethodID, va_list); - jshort (*CallShortMethodA)(JNIEnv*, jobject, jmethodID, jvalue*); - jint (*CallIntMethod)(JNIEnv*, jobject, jmethodID, ...); - jint (*CallIntMethodV)(JNIEnv*, jobject, jmethodID, va_list); - jint (*CallIntMethodA)(JNIEnv*, jobject, jmethodID, jvalue*); - jlong (*CallLongMethod)(JNIEnv*, jobject, jmethodID, ...); - jlong (*CallLongMethodV)(JNIEnv*, jobject, jmethodID, va_list); - jlong (*CallLongMethodA)(JNIEnv*, jobject, jmethodID, jvalue*); - jfloat (*CallFloatMethod)(JNIEnv*, jobject, jmethodID, ...); - jfloat (*CallFloatMethodV)(JNIEnv*, jobject, jmethodID, va_list); - jfloat (*CallFloatMethodA)(JNIEnv*, jobject, jmethodID, jvalue*); - jdouble (*CallDoubleMethod)(JNIEnv*, jobject, jmethodID, ...); - jdouble (*CallDoubleMethodV)(JNIEnv*, jobject, jmethodID, va_list); - jdouble (*CallDoubleMethodA)(JNIEnv*, jobject, jmethodID, jvalue*); - void (*CallVoidMethod)(JNIEnv*, jobject, jmethodID, ...); - void (*CallVoidMethodV)(JNIEnv*, jobject, jmethodID, va_list); - void (*CallVoidMethodA)(JNIEnv*, jobject, jmethodID, jvalue*); + jobject (*CallObjectMethod)(JNIEnv *, jobject, jmethodID, ...); + jobject (*CallObjectMethodV)(JNIEnv *, jobject, jmethodID, va_list); + jobject (*CallObjectMethodA)(JNIEnv *, jobject, jmethodID, jvalue *); + jboolean (*CallBooleanMethod)(JNIEnv *, jobject, jmethodID, ...); + jboolean (*CallBooleanMethodV)(JNIEnv *, jobject, jmethodID, va_list); + jboolean (*CallBooleanMethodA)(JNIEnv *, jobject, jmethodID, jvalue *); + jbyte (*CallByteMethod)(JNIEnv *, jobject, jmethodID, ...); + jbyte (*CallByteMethodV)(JNIEnv *, jobject, jmethodID, va_list); + jbyte (*CallByteMethodA)(JNIEnv *, jobject, jmethodID, jvalue *); + jchar (*CallCharMethod)(JNIEnv *, jobject, jmethodID, ...); + jchar (*CallCharMethodV)(JNIEnv *, jobject, jmethodID, va_list); + jchar (*CallCharMethodA)(JNIEnv *, jobject, jmethodID, jvalue *); + jshort (*CallShortMethod)(JNIEnv *, jobject, jmethodID, ...); + jshort (*CallShortMethodV)(JNIEnv *, jobject, jmethodID, va_list); + jshort (*CallShortMethodA)(JNIEnv *, jobject, jmethodID, jvalue *); + jint (*CallIntMethod)(JNIEnv *, jobject, jmethodID, ...); + jint (*CallIntMethodV)(JNIEnv *, jobject, jmethodID, va_list); + jint (*CallIntMethodA)(JNIEnv *, jobject, jmethodID, jvalue *); + jlong (*CallLongMethod)(JNIEnv *, jobject, jmethodID, ...); + jlong (*CallLongMethodV)(JNIEnv *, jobject, jmethodID, va_list); + jlong (*CallLongMethodA)(JNIEnv *, jobject, jmethodID, jvalue *); + jfloat (*CallFloatMethod)(JNIEnv *, jobject, jmethodID, ...); + jfloat (*CallFloatMethodV)(JNIEnv *, jobject, jmethodID, va_list); + jfloat (*CallFloatMethodA)(JNIEnv *, jobject, jmethodID, jvalue *); + jdouble (*CallDoubleMethod)(JNIEnv *, jobject, jmethodID, ...); + jdouble (*CallDoubleMethodV)(JNIEnv *, jobject, jmethodID, va_list); + jdouble (*CallDoubleMethodA)(JNIEnv *, jobject, jmethodID, jvalue *); + void (*CallVoidMethod)(JNIEnv *, jobject, jmethodID, ...); + void (*CallVoidMethodV)(JNIEnv *, jobject, jmethodID, va_list); + void (*CallVoidMethodA)(JNIEnv *, jobject, jmethodID, jvalue *); - jobject ( - *CallNonvirtualObjectMethod)(JNIEnv*, jobject, jclass, jmethodID, ...); - jobject (*CallNonvirtualObjectMethodV)( - JNIEnv*, - jobject, - jclass, - jmethodID, - va_list); - jobject (*CallNonvirtualObjectMethodA)( - JNIEnv*, - jobject, - jclass, - jmethodID, - jvalue*); - jboolean ( - *CallNonvirtualBooleanMethod)(JNIEnv*, jobject, jclass, jmethodID, ...); - jboolean (*CallNonvirtualBooleanMethodV)( - JNIEnv*, - jobject, - jclass, - jmethodID, - va_list); - jboolean (*CallNonvirtualBooleanMethodA)( - JNIEnv*, - jobject, - jclass, - jmethodID, - jvalue*); - jbyte (*CallNonvirtualByteMethod)(JNIEnv*, jobject, jclass, jmethodID, ...); - jbyte ( - *CallNonvirtualByteMethodV)(JNIEnv*, jobject, jclass, jmethodID, va_list); - jbyte ( - *CallNonvirtualByteMethodA)(JNIEnv*, jobject, jclass, jmethodID, jvalue*); - jchar (*CallNonvirtualCharMethod)(JNIEnv*, jobject, jclass, jmethodID, ...); - jchar ( - *CallNonvirtualCharMethodV)(JNIEnv*, jobject, jclass, jmethodID, va_list); - jchar ( - *CallNonvirtualCharMethodA)(JNIEnv*, jobject, jclass, jmethodID, jvalue*); - jshort (*CallNonvirtualShortMethod)(JNIEnv*, jobject, jclass, jmethodID, ...); - jshort (*CallNonvirtualShortMethodV)( - JNIEnv*, - jobject, - jclass, - jmethodID, - va_list); - jshort (*CallNonvirtualShortMethodA)( - JNIEnv*, - jobject, - jclass, - jmethodID, - jvalue*); - jint (*CallNonvirtualIntMethod)(JNIEnv*, jobject, jclass, jmethodID, ...); - jint ( - *CallNonvirtualIntMethodV)(JNIEnv*, jobject, jclass, jmethodID, va_list); - jint ( - *CallNonvirtualIntMethodA)(JNIEnv*, jobject, jclass, jmethodID, jvalue*); - jlong (*CallNonvirtualLongMethod)(JNIEnv*, jobject, jclass, jmethodID, ...); - jlong ( - *CallNonvirtualLongMethodV)(JNIEnv*, jobject, jclass, jmethodID, va_list); - jlong ( - *CallNonvirtualLongMethodA)(JNIEnv*, jobject, jclass, jmethodID, jvalue*); - jfloat (*CallNonvirtualFloatMethod)(JNIEnv*, jobject, jclass, jmethodID, ...); - jfloat (*CallNonvirtualFloatMethodV)( - JNIEnv*, - jobject, - jclass, - jmethodID, - va_list); - jfloat (*CallNonvirtualFloatMethodA)( - JNIEnv*, - jobject, - jclass, - jmethodID, - jvalue*); - jdouble ( - *CallNonvirtualDoubleMethod)(JNIEnv*, jobject, jclass, jmethodID, ...); - jdouble (*CallNonvirtualDoubleMethodV)( - JNIEnv*, - jobject, - jclass, - jmethodID, - va_list); - jdouble (*CallNonvirtualDoubleMethodA)( - JNIEnv*, - jobject, - jclass, - jmethodID, - jvalue*); - void (*CallNonvirtualVoidMethod)(JNIEnv*, jobject, jclass, jmethodID, ...); - void ( - *CallNonvirtualVoidMethodV)(JNIEnv*, jobject, jclass, jmethodID, va_list); - void ( - *CallNonvirtualVoidMethodA)(JNIEnv*, jobject, jclass, jmethodID, jvalue*); + jobject (*CallNonvirtualObjectMethod)(JNIEnv *, jobject, jclass, jmethodID, ...); + jobject (*CallNonvirtualObjectMethodV)(JNIEnv *, jobject, jclass, jmethodID, va_list); + jobject (*CallNonvirtualObjectMethodA)(JNIEnv *, jobject, jclass, jmethodID, jvalue *); + jboolean (*CallNonvirtualBooleanMethod)(JNIEnv *, jobject, jclass, jmethodID, ...); + jboolean (*CallNonvirtualBooleanMethodV)(JNIEnv *, jobject, jclass, jmethodID, va_list); + jboolean (*CallNonvirtualBooleanMethodA)(JNIEnv *, jobject, jclass, jmethodID, jvalue *); + jbyte (*CallNonvirtualByteMethod)(JNIEnv *, jobject, jclass, jmethodID, ...); + jbyte (*CallNonvirtualByteMethodV)(JNIEnv *, jobject, jclass, jmethodID, va_list); + jbyte (*CallNonvirtualByteMethodA)(JNIEnv *, jobject, jclass, jmethodID, jvalue *); + jchar (*CallNonvirtualCharMethod)(JNIEnv *, jobject, jclass, jmethodID, ...); + jchar (*CallNonvirtualCharMethodV)(JNIEnv *, jobject, jclass, jmethodID, va_list); + jchar (*CallNonvirtualCharMethodA)(JNIEnv *, jobject, jclass, jmethodID, jvalue *); + jshort (*CallNonvirtualShortMethod)(JNIEnv *, jobject, jclass, jmethodID, ...); + jshort (*CallNonvirtualShortMethodV)(JNIEnv *, jobject, jclass, jmethodID, va_list); + jshort (*CallNonvirtualShortMethodA)(JNIEnv *, jobject, jclass, jmethodID, jvalue *); + jint (*CallNonvirtualIntMethod)(JNIEnv *, jobject, jclass, jmethodID, ...); + jint (*CallNonvirtualIntMethodV)(JNIEnv *, jobject, jclass, jmethodID, va_list); + jint (*CallNonvirtualIntMethodA)(JNIEnv *, jobject, jclass, jmethodID, jvalue *); + jlong (*CallNonvirtualLongMethod)(JNIEnv *, jobject, jclass, jmethodID, ...); + jlong (*CallNonvirtualLongMethodV)(JNIEnv *, jobject, jclass, jmethodID, va_list); + jlong (*CallNonvirtualLongMethodA)(JNIEnv *, jobject, jclass, jmethodID, jvalue *); + jfloat (*CallNonvirtualFloatMethod)(JNIEnv *, jobject, jclass, jmethodID, ...); + jfloat (*CallNonvirtualFloatMethodV)(JNIEnv *, jobject, jclass, jmethodID, va_list); + jfloat (*CallNonvirtualFloatMethodA)(JNIEnv *, jobject, jclass, jmethodID, jvalue *); + jdouble (*CallNonvirtualDoubleMethod)(JNIEnv *, jobject, jclass, jmethodID, ...); + jdouble (*CallNonvirtualDoubleMethodV)(JNIEnv *, jobject, jclass, jmethodID, va_list); + jdouble (*CallNonvirtualDoubleMethodA)(JNIEnv *, jobject, jclass, jmethodID, jvalue *); + void (*CallNonvirtualVoidMethod)(JNIEnv *, jobject, jclass, jmethodID, ...); + void (*CallNonvirtualVoidMethodV)(JNIEnv *, jobject, jclass, jmethodID, va_list); + void (*CallNonvirtualVoidMethodA)(JNIEnv *, jobject, jclass, jmethodID, jvalue *); - jfieldID (*GetFieldID)(JNIEnv*, jclass, const char*, const char*); + jfieldID (*GetFieldID)(JNIEnv *, jclass, const char *, const char *); - jobject (*GetObjectField)(JNIEnv*, jobject, jfieldID); - jboolean (*GetBooleanField)(JNIEnv*, jobject, jfieldID); - jbyte (*GetByteField)(JNIEnv*, jobject, jfieldID); - jchar (*GetCharField)(JNIEnv*, jobject, jfieldID); - jshort (*GetShortField)(JNIEnv*, jobject, jfieldID); - jint (*GetIntField)(JNIEnv*, jobject, jfieldID); - jlong (*GetLongField)(JNIEnv*, jobject, jfieldID); - jfloat (*GetFloatField)(JNIEnv*, jobject, jfieldID); - jdouble (*GetDoubleField)(JNIEnv*, jobject, jfieldID); + jobject (*GetObjectField)(JNIEnv *, jobject, jfieldID); + jboolean (*GetBooleanField)(JNIEnv *, jobject, jfieldID); + jbyte (*GetByteField)(JNIEnv *, jobject, jfieldID); + jchar (*GetCharField)(JNIEnv *, jobject, jfieldID); + jshort (*GetShortField)(JNIEnv *, jobject, jfieldID); + jint (*GetIntField)(JNIEnv *, jobject, jfieldID); + jlong (*GetLongField)(JNIEnv *, jobject, jfieldID); + jfloat (*GetFloatField)(JNIEnv *, jobject, jfieldID); + jdouble (*GetDoubleField)(JNIEnv *, jobject, jfieldID); - void (*SetObjectField)(JNIEnv*, jobject, jfieldID, jobject); - void (*SetBooleanField)(JNIEnv*, jobject, jfieldID, jboolean); - void (*SetByteField)(JNIEnv*, jobject, jfieldID, jbyte); - void (*SetCharField)(JNIEnv*, jobject, jfieldID, jchar); - void (*SetShortField)(JNIEnv*, jobject, jfieldID, jshort); - void (*SetIntField)(JNIEnv*, jobject, jfieldID, jint); - void (*SetLongField)(JNIEnv*, jobject, jfieldID, jlong); - void (*SetFloatField)(JNIEnv*, jobject, jfieldID, jfloat); - void (*SetDoubleField)(JNIEnv*, jobject, jfieldID, jdouble); + void (*SetObjectField)(JNIEnv *, jobject, jfieldID, jobject); + void (*SetBooleanField)(JNIEnv *, jobject, jfieldID, jboolean); + void (*SetByteField)(JNIEnv *, jobject, jfieldID, jbyte); + void (*SetCharField)(JNIEnv *, jobject, jfieldID, jchar); + void (*SetShortField)(JNIEnv *, jobject, jfieldID, jshort); + void (*SetIntField)(JNIEnv *, jobject, jfieldID, jint); + void (*SetLongField)(JNIEnv *, jobject, jfieldID, jlong); + void (*SetFloatField)(JNIEnv *, jobject, jfieldID, jfloat); + void (*SetDoubleField)(JNIEnv *, jobject, jfieldID, jdouble); - jmethodID (*GetStaticMethodID)(JNIEnv*, jclass, const char*, const char*); + jmethodID (*GetStaticMethodID)(JNIEnv *, jclass, const char *, const char *); - jobject (*CallStaticObjectMethod)(JNIEnv*, jclass, jmethodID, ...); - jobject (*CallStaticObjectMethodV)(JNIEnv*, jclass, jmethodID, va_list); - jobject (*CallStaticObjectMethodA)(JNIEnv*, jclass, jmethodID, jvalue*); - jboolean (*CallStaticBooleanMethod)(JNIEnv*, jclass, jmethodID, ...); - jboolean (*CallStaticBooleanMethodV)(JNIEnv*, jclass, jmethodID, va_list); - jboolean (*CallStaticBooleanMethodA)(JNIEnv*, jclass, jmethodID, jvalue*); - jbyte (*CallStaticByteMethod)(JNIEnv*, jclass, jmethodID, ...); - jbyte (*CallStaticByteMethodV)(JNIEnv*, jclass, jmethodID, va_list); - jbyte (*CallStaticByteMethodA)(JNIEnv*, jclass, jmethodID, jvalue*); - jchar (*CallStaticCharMethod)(JNIEnv*, jclass, jmethodID, ...); - jchar (*CallStaticCharMethodV)(JNIEnv*, jclass, jmethodID, va_list); - jchar (*CallStaticCharMethodA)(JNIEnv*, jclass, jmethodID, jvalue*); - jshort (*CallStaticShortMethod)(JNIEnv*, jclass, jmethodID, ...); - jshort (*CallStaticShortMethodV)(JNIEnv*, jclass, jmethodID, va_list); - jshort (*CallStaticShortMethodA)(JNIEnv*, jclass, jmethodID, jvalue*); - jint (*CallStaticIntMethod)(JNIEnv*, jclass, jmethodID, ...); - jint (*CallStaticIntMethodV)(JNIEnv*, jclass, jmethodID, va_list); - jint (*CallStaticIntMethodA)(JNIEnv*, jclass, jmethodID, jvalue*); - jlong (*CallStaticLongMethod)(JNIEnv*, jclass, jmethodID, ...); - jlong (*CallStaticLongMethodV)(JNIEnv*, jclass, jmethodID, va_list); - jlong (*CallStaticLongMethodA)(JNIEnv*, jclass, jmethodID, jvalue*); - jfloat (*CallStaticFloatMethod)(JNIEnv*, jclass, jmethodID, ...); - jfloat (*CallStaticFloatMethodV)(JNIEnv*, jclass, jmethodID, va_list); - jfloat (*CallStaticFloatMethodA)(JNIEnv*, jclass, jmethodID, jvalue*); - jdouble (*CallStaticDoubleMethod)(JNIEnv*, jclass, jmethodID, ...); - jdouble (*CallStaticDoubleMethodV)(JNIEnv*, jclass, jmethodID, va_list); - jdouble (*CallStaticDoubleMethodA)(JNIEnv*, jclass, jmethodID, jvalue*); - void (*CallStaticVoidMethod)(JNIEnv*, jclass, jmethodID, ...); - void (*CallStaticVoidMethodV)(JNIEnv*, jclass, jmethodID, va_list); - void (*CallStaticVoidMethodA)(JNIEnv*, jclass, jmethodID, jvalue*); + jobject (*CallStaticObjectMethod)(JNIEnv *, jclass, jmethodID, ...); + jobject (*CallStaticObjectMethodV)(JNIEnv *, jclass, jmethodID, va_list); + jobject (*CallStaticObjectMethodA)(JNIEnv *, jclass, jmethodID, jvalue *); + jboolean (*CallStaticBooleanMethod)(JNIEnv *, jclass, jmethodID, ...); + jboolean (*CallStaticBooleanMethodV)(JNIEnv *, jclass, jmethodID, va_list); + jboolean (*CallStaticBooleanMethodA)(JNIEnv *, jclass, jmethodID, jvalue *); + jbyte (*CallStaticByteMethod)(JNIEnv *, jclass, jmethodID, ...); + jbyte (*CallStaticByteMethodV)(JNIEnv *, jclass, jmethodID, va_list); + jbyte (*CallStaticByteMethodA)(JNIEnv *, jclass, jmethodID, jvalue *); + jchar (*CallStaticCharMethod)(JNIEnv *, jclass, jmethodID, ...); + jchar (*CallStaticCharMethodV)(JNIEnv *, jclass, jmethodID, va_list); + jchar (*CallStaticCharMethodA)(JNIEnv *, jclass, jmethodID, jvalue *); + jshort (*CallStaticShortMethod)(JNIEnv *, jclass, jmethodID, ...); + jshort (*CallStaticShortMethodV)(JNIEnv *, jclass, jmethodID, va_list); + jshort (*CallStaticShortMethodA)(JNIEnv *, jclass, jmethodID, jvalue *); + jint (*CallStaticIntMethod)(JNIEnv *, jclass, jmethodID, ...); + jint (*CallStaticIntMethodV)(JNIEnv *, jclass, jmethodID, va_list); + jint (*CallStaticIntMethodA)(JNIEnv *, jclass, jmethodID, jvalue *); + jlong (*CallStaticLongMethod)(JNIEnv *, jclass, jmethodID, ...); + jlong (*CallStaticLongMethodV)(JNIEnv *, jclass, jmethodID, va_list); + jlong (*CallStaticLongMethodA)(JNIEnv *, jclass, jmethodID, jvalue *); + jfloat (*CallStaticFloatMethod)(JNIEnv *, jclass, jmethodID, ...); + jfloat (*CallStaticFloatMethodV)(JNIEnv *, jclass, jmethodID, va_list); + jfloat (*CallStaticFloatMethodA)(JNIEnv *, jclass, jmethodID, jvalue *); + jdouble (*CallStaticDoubleMethod)(JNIEnv *, jclass, jmethodID, ...); + jdouble (*CallStaticDoubleMethodV)(JNIEnv *, jclass, jmethodID, va_list); + jdouble (*CallStaticDoubleMethodA)(JNIEnv *, jclass, jmethodID, jvalue *); + void (*CallStaticVoidMethod)(JNIEnv *, jclass, jmethodID, ...); + void (*CallStaticVoidMethodV)(JNIEnv *, jclass, jmethodID, va_list); + void (*CallStaticVoidMethodA)(JNIEnv *, jclass, jmethodID, jvalue *); - jfieldID (*GetStaticFieldID)(JNIEnv*, jclass, const char*, const char*); + jfieldID (*GetStaticFieldID)(JNIEnv *, jclass, const char *, const char *); - jobject (*GetStaticObjectField)(JNIEnv*, jclass, jfieldID); - jboolean (*GetStaticBooleanField)(JNIEnv*, jclass, jfieldID); - jbyte (*GetStaticByteField)(JNIEnv*, jclass, jfieldID); - jchar (*GetStaticCharField)(JNIEnv*, jclass, jfieldID); - jshort (*GetStaticShortField)(JNIEnv*, jclass, jfieldID); - jint (*GetStaticIntField)(JNIEnv*, jclass, jfieldID); - jlong (*GetStaticLongField)(JNIEnv*, jclass, jfieldID); - jfloat (*GetStaticFloatField)(JNIEnv*, jclass, jfieldID); - jdouble (*GetStaticDoubleField)(JNIEnv*, jclass, jfieldID); + jobject (*GetStaticObjectField)(JNIEnv *, jclass, jfieldID); + jboolean (*GetStaticBooleanField)(JNIEnv *, jclass, jfieldID); + jbyte (*GetStaticByteField)(JNIEnv *, jclass, jfieldID); + jchar (*GetStaticCharField)(JNIEnv *, jclass, jfieldID); + jshort (*GetStaticShortField)(JNIEnv *, jclass, jfieldID); + jint (*GetStaticIntField)(JNIEnv *, jclass, jfieldID); + jlong (*GetStaticLongField)(JNIEnv *, jclass, jfieldID); + jfloat (*GetStaticFloatField)(JNIEnv *, jclass, jfieldID); + jdouble (*GetStaticDoubleField)(JNIEnv *, jclass, jfieldID); - void (*SetStaticObjectField)(JNIEnv*, jclass, jfieldID, jobject); - void (*SetStaticBooleanField)(JNIEnv*, jclass, jfieldID, jboolean); - void (*SetStaticByteField)(JNIEnv*, jclass, jfieldID, jbyte); - void (*SetStaticCharField)(JNIEnv*, jclass, jfieldID, jchar); - void (*SetStaticShortField)(JNIEnv*, jclass, jfieldID, jshort); - void (*SetStaticIntField)(JNIEnv*, jclass, jfieldID, jint); - void (*SetStaticLongField)(JNIEnv*, jclass, jfieldID, jlong); - void (*SetStaticFloatField)(JNIEnv*, jclass, jfieldID, jfloat); - void (*SetStaticDoubleField)(JNIEnv*, jclass, jfieldID, jdouble); + void (*SetStaticObjectField)(JNIEnv *, jclass, jfieldID, jobject); + void (*SetStaticBooleanField)(JNIEnv *, jclass, jfieldID, jboolean); + void (*SetStaticByteField)(JNIEnv *, jclass, jfieldID, jbyte); + void (*SetStaticCharField)(JNIEnv *, jclass, jfieldID, jchar); + void (*SetStaticShortField)(JNIEnv *, jclass, jfieldID, jshort); + void (*SetStaticIntField)(JNIEnv *, jclass, jfieldID, jint); + void (*SetStaticLongField)(JNIEnv *, jclass, jfieldID, jlong); + void (*SetStaticFloatField)(JNIEnv *, jclass, jfieldID, jfloat); + void (*SetStaticDoubleField)(JNIEnv *, jclass, jfieldID, jdouble); - jstring (*NewString)(JNIEnv*, const jchar*, jsize); - jsize (*GetStringLength)(JNIEnv*, jstring); - const jchar* (*GetStringChars)(JNIEnv*, jstring, jboolean*); - void (*ReleaseStringChars)(JNIEnv*, jstring, const jchar*); - jstring (*NewStringUTF)(JNIEnv*, const char*); - jsize (*GetStringUTFLength)(JNIEnv*, jstring); + jstring (*NewString)(JNIEnv *, const jchar *, jsize); + jsize (*GetStringLength)(JNIEnv *, jstring); + const jchar *(*GetStringChars)(JNIEnv *, jstring, jboolean *); + void (*ReleaseStringChars)(JNIEnv *, jstring, const jchar *); + jstring (*NewStringUTF)(JNIEnv *, const char *); + jsize (*GetStringUTFLength)(JNIEnv *, jstring); /* JNI spec says this returns const jbyte*, but that's inconsistent */ - const char* (*GetStringUTFChars)(JNIEnv*, jstring, jboolean*); - void (*ReleaseStringUTFChars)(JNIEnv*, jstring, const char*); - jsize (*GetArrayLength)(JNIEnv*, jarray); - jobjectArray (*NewObjectArray)(JNIEnv*, jsize, jclass, jobject); - jobject (*GetObjectArrayElement)(JNIEnv*, jobjectArray, jsize); - void (*SetObjectArrayElement)(JNIEnv*, jobjectArray, jsize, jobject); + const char *(*GetStringUTFChars)(JNIEnv *, jstring, jboolean *); + void (*ReleaseStringUTFChars)(JNIEnv *, jstring, const char *); + jsize (*GetArrayLength)(JNIEnv *, jarray); + jobjectArray (*NewObjectArray)(JNIEnv *, jsize, jclass, jobject); + jobject (*GetObjectArrayElement)(JNIEnv *, jobjectArray, jsize); + void (*SetObjectArrayElement)(JNIEnv *, jobjectArray, jsize, jobject); - jbooleanArray (*NewBooleanArray)(JNIEnv*, jsize); - jbyteArray (*NewByteArray)(JNIEnv*, jsize); - jcharArray (*NewCharArray)(JNIEnv*, jsize); - jshortArray (*NewShortArray)(JNIEnv*, jsize); - jintArray (*NewIntArray)(JNIEnv*, jsize); - jlongArray (*NewLongArray)(JNIEnv*, jsize); - jfloatArray (*NewFloatArray)(JNIEnv*, jsize); - jdoubleArray (*NewDoubleArray)(JNIEnv*, jsize); + jbooleanArray (*NewBooleanArray)(JNIEnv *, jsize); + jbyteArray (*NewByteArray)(JNIEnv *, jsize); + jcharArray (*NewCharArray)(JNIEnv *, jsize); + jshortArray (*NewShortArray)(JNIEnv *, jsize); + jintArray (*NewIntArray)(JNIEnv *, jsize); + jlongArray (*NewLongArray)(JNIEnv *, jsize); + jfloatArray (*NewFloatArray)(JNIEnv *, jsize); + jdoubleArray (*NewDoubleArray)(JNIEnv *, jsize); - jboolean* (*GetBooleanArrayElements)(JNIEnv*, jbooleanArray, jboolean*); - jbyte* (*GetByteArrayElements)(JNIEnv*, jbyteArray, jboolean*); - jchar* (*GetCharArrayElements)(JNIEnv*, jcharArray, jboolean*); - jshort* (*GetShortArrayElements)(JNIEnv*, jshortArray, jboolean*); - jint* (*GetIntArrayElements)(JNIEnv*, jintArray, jboolean*); - jlong* (*GetLongArrayElements)(JNIEnv*, jlongArray, jboolean*); - jfloat* (*GetFloatArrayElements)(JNIEnv*, jfloatArray, jboolean*); - jdouble* (*GetDoubleArrayElements)(JNIEnv*, jdoubleArray, jboolean*); + jboolean *(*GetBooleanArrayElements)(JNIEnv *, jbooleanArray, jboolean *); + jbyte *(*GetByteArrayElements)(JNIEnv *, jbyteArray, jboolean *); + jchar *(*GetCharArrayElements)(JNIEnv *, jcharArray, jboolean *); + jshort *(*GetShortArrayElements)(JNIEnv *, jshortArray, jboolean *); + jint *(*GetIntArrayElements)(JNIEnv *, jintArray, jboolean *); + jlong *(*GetLongArrayElements)(JNIEnv *, jlongArray, jboolean *); + jfloat *(*GetFloatArrayElements)(JNIEnv *, jfloatArray, jboolean *); + jdouble *(*GetDoubleArrayElements)(JNIEnv *, jdoubleArray, jboolean *); - void (*ReleaseBooleanArrayElements)(JNIEnv*, jbooleanArray, jboolean*, jint); - void (*ReleaseByteArrayElements)(JNIEnv*, jbyteArray, jbyte*, jint); - void (*ReleaseCharArrayElements)(JNIEnv*, jcharArray, jchar*, jint); - void (*ReleaseShortArrayElements)(JNIEnv*, jshortArray, jshort*, jint); - void (*ReleaseIntArrayElements)(JNIEnv*, jintArray, jint*, jint); - void (*ReleaseLongArrayElements)(JNIEnv*, jlongArray, jlong*, jint); - void (*ReleaseFloatArrayElements)(JNIEnv*, jfloatArray, jfloat*, jint); - void (*ReleaseDoubleArrayElements)(JNIEnv*, jdoubleArray, jdouble*, jint); + void (*ReleaseBooleanArrayElements)(JNIEnv *, jbooleanArray, jboolean *, jint); + void (*ReleaseByteArrayElements)(JNIEnv *, jbyteArray, jbyte *, jint); + void (*ReleaseCharArrayElements)(JNIEnv *, jcharArray, jchar *, jint); + void (*ReleaseShortArrayElements)(JNIEnv *, jshortArray, jshort *, jint); + void (*ReleaseIntArrayElements)(JNIEnv *, jintArray, jint *, jint); + void (*ReleaseLongArrayElements)(JNIEnv *, jlongArray, jlong *, jint); + void (*ReleaseFloatArrayElements)(JNIEnv *, jfloatArray, jfloat *, jint); + void (*ReleaseDoubleArrayElements)(JNIEnv *, jdoubleArray, jdouble *, jint); - void ( - *GetBooleanArrayRegion)(JNIEnv*, jbooleanArray, jsize, jsize, jboolean*); - void (*GetByteArrayRegion)(JNIEnv*, jbyteArray, jsize, jsize, jbyte*); - void (*GetCharArrayRegion)(JNIEnv*, jcharArray, jsize, jsize, jchar*); - void (*GetShortArrayRegion)(JNIEnv*, jshortArray, jsize, jsize, jshort*); - void (*GetIntArrayRegion)(JNIEnv*, jintArray, jsize, jsize, jint*); - void (*GetLongArrayRegion)(JNIEnv*, jlongArray, jsize, jsize, jlong*); - void (*GetFloatArrayRegion)(JNIEnv*, jfloatArray, jsize, jsize, jfloat*); - void (*GetDoubleArrayRegion)(JNIEnv*, jdoubleArray, jsize, jsize, jdouble*); + void (*GetBooleanArrayRegion)(JNIEnv *, jbooleanArray, jsize, jsize, jboolean *); + void (*GetByteArrayRegion)(JNIEnv *, jbyteArray, jsize, jsize, jbyte *); + void (*GetCharArrayRegion)(JNIEnv *, jcharArray, jsize, jsize, jchar *); + void (*GetShortArrayRegion)(JNIEnv *, jshortArray, jsize, jsize, jshort *); + void (*GetIntArrayRegion)(JNIEnv *, jintArray, jsize, jsize, jint *); + void (*GetLongArrayRegion)(JNIEnv *, jlongArray, jsize, jsize, jlong *); + void (*GetFloatArrayRegion)(JNIEnv *, jfloatArray, jsize, jsize, jfloat *); + void (*GetDoubleArrayRegion)(JNIEnv *, jdoubleArray, jsize, jsize, jdouble *); /* spec shows these without const; some jni.h do, some don't */ - void (*SetBooleanArrayRegion)( - JNIEnv*, - jbooleanArray, - jsize, - jsize, - const jboolean*); - void (*SetByteArrayRegion)(JNIEnv*, jbyteArray, jsize, jsize, const jbyte*); - void (*SetCharArrayRegion)(JNIEnv*, jcharArray, jsize, jsize, const jchar*); - void ( - *SetShortArrayRegion)(JNIEnv*, jshortArray, jsize, jsize, const jshort*); - void (*SetIntArrayRegion)(JNIEnv*, jintArray, jsize, jsize, const jint*); - void (*SetLongArrayRegion)(JNIEnv*, jlongArray, jsize, jsize, const jlong*); - void ( - *SetFloatArrayRegion)(JNIEnv*, jfloatArray, jsize, jsize, const jfloat*); - void (*SetDoubleArrayRegion)( - JNIEnv*, - jdoubleArray, - jsize, - jsize, - const jdouble*); + void (*SetBooleanArrayRegion)(JNIEnv *, jbooleanArray, jsize, jsize, const jboolean *); + void (*SetByteArrayRegion)(JNIEnv *, jbyteArray, jsize, jsize, const jbyte *); + void (*SetCharArrayRegion)(JNIEnv *, jcharArray, jsize, jsize, const jchar *); + void (*SetShortArrayRegion)(JNIEnv *, jshortArray, jsize, jsize, const jshort *); + void (*SetIntArrayRegion)(JNIEnv *, jintArray, jsize, jsize, const jint *); + void (*SetLongArrayRegion)(JNIEnv *, jlongArray, jsize, jsize, const jlong *); + void (*SetFloatArrayRegion)(JNIEnv *, jfloatArray, jsize, jsize, const jfloat *); + void (*SetDoubleArrayRegion)(JNIEnv *, jdoubleArray, jsize, jsize, const jdouble *); - jint (*RegisterNatives)(JNIEnv*, jclass, const JNINativeMethod*, jint); - jint (*UnregisterNatives)(JNIEnv*, jclass); - jint (*MonitorEnter)(JNIEnv*, jobject); - jint (*MonitorExit)(JNIEnv*, jobject); - jint (*GetJavaVM)(JNIEnv*, JavaVM**); + jint (*RegisterNatives)(JNIEnv *, jclass, const JNINativeMethod *, jint); + jint (*UnregisterNatives)(JNIEnv *, jclass); + jint (*MonitorEnter)(JNIEnv *, jobject); + jint (*MonitorExit)(JNIEnv *, jobject); + jint (*GetJavaVM)(JNIEnv *, JavaVM **); - void (*GetStringRegion)(JNIEnv*, jstring, jsize, jsize, jchar*); - void (*GetStringUTFRegion)(JNIEnv*, jstring, jsize, jsize, char*); + void (*GetStringRegion)(JNIEnv *, jstring, jsize, jsize, jchar *); + void (*GetStringUTFRegion)(JNIEnv *, jstring, jsize, jsize, char *); - void* (*GetPrimitiveArrayCritical)(JNIEnv*, jarray, jboolean*); - void (*ReleasePrimitiveArrayCritical)(JNIEnv*, jarray, void*, jint); + void *(*GetPrimitiveArrayCritical)(JNIEnv *, jarray, jboolean *); + void (*ReleasePrimitiveArrayCritical)(JNIEnv *, jarray, void *, jint); - const jchar* (*GetStringCritical)(JNIEnv*, jstring, jboolean*); - void (*ReleaseStringCritical)(JNIEnv*, jstring, const jchar*); + const jchar *(*GetStringCritical)(JNIEnv *, jstring, jboolean *); + void (*ReleaseStringCritical)(JNIEnv *, jstring, const jchar *); - jweak (*NewWeakGlobalRef)(JNIEnv*, jobject); - void (*DeleteWeakGlobalRef)(JNIEnv*, jweak); + jweak (*NewWeakGlobalRef)(JNIEnv *, jobject); + void (*DeleteWeakGlobalRef)(JNIEnv *, jweak); - jboolean (*ExceptionCheck)(JNIEnv*); + jboolean (*ExceptionCheck)(JNIEnv *); - jobject (*NewDirectByteBuffer)(JNIEnv*, void*, jlong); - void* (*GetDirectBufferAddress)(JNIEnv*, jobject); - jlong (*GetDirectBufferCapacity)(JNIEnv*, jobject); + jobject (*NewDirectByteBuffer)(JNIEnv *, void *, jlong); + void *(*GetDirectBufferAddress)(JNIEnv *, jobject); + jlong (*GetDirectBufferCapacity)(JNIEnv *, jobject); /* added in JNI 1.6 */ - jobjectRefType (*GetObjectRefType)(JNIEnv*, jobject); + jobjectRefType (*GetObjectRefType)(JNIEnv *, jobject); }; /* @@ -506,111 +430,132 @@ struct JNINativeInterface { */ struct _JNIEnv { /* do not rename this; it does not seem to be entirely opaque */ - const struct JNINativeInterface* functions; + const struct JNINativeInterface *functions; #if defined(__cplusplus) - jint GetVersion() { + jint GetVersion() + { return functions->GetVersion(this); } - jclass DefineClass( - const char* name, - jobject loader, - const jbyte* buf, - jsize bufLen) { + jclass DefineClass(const char *name, jobject loader, const jbyte *buf, jsize bufLen) + { return functions->DefineClass(this, name, loader, buf, bufLen); } - jclass FindClass(const char* name) { + jclass FindClass(const char *name) + { return functions->FindClass(this, name); } - jmethodID FromReflectedMethod(jobject method) { + jmethodID FromReflectedMethod(jobject method) + { return functions->FromReflectedMethod(this, method); } - jfieldID FromReflectedField(jobject field) { + jfieldID FromReflectedField(jobject field) + { return functions->FromReflectedField(this, field); } - jobject ToReflectedMethod(jclass cls, jmethodID methodID, jboolean isStatic) { + jobject ToReflectedMethod(jclass cls, jmethodID methodID, jboolean isStatic) + { return functions->ToReflectedMethod(this, cls, methodID, isStatic); } - jclass GetSuperclass(jclass clazz) { + jclass GetSuperclass(jclass clazz) + { return functions->GetSuperclass(this, clazz); } - jboolean IsAssignableFrom(jclass clazz1, jclass clazz2) { + jboolean IsAssignableFrom(jclass clazz1, jclass clazz2) + { return functions->IsAssignableFrom(this, clazz1, clazz2); } - jobject ToReflectedField(jclass cls, jfieldID fieldID, jboolean isStatic) { + jobject ToReflectedField(jclass cls, jfieldID fieldID, jboolean isStatic) + { return functions->ToReflectedField(this, cls, fieldID, isStatic); } - jint Throw(jthrowable obj) { + jint Throw(jthrowable obj) + { return functions->Throw(this, obj); } - jint ThrowNew(jclass clazz, const char* message) { + jint ThrowNew(jclass clazz, const char *message) + { return functions->ThrowNew(this, clazz, message); } - jthrowable ExceptionOccurred() { + jthrowable ExceptionOccurred() + { return functions->ExceptionOccurred(this); } - void ExceptionDescribe() { + void ExceptionDescribe() + { functions->ExceptionDescribe(this); } - void ExceptionClear() { + void ExceptionClear() + { functions->ExceptionClear(this); } - void FatalError(const char* msg) { + void FatalError(const char *msg) + { functions->FatalError(this, msg); } - jint PushLocalFrame(jint capacity) { + jint PushLocalFrame(jint capacity) + { return functions->PushLocalFrame(this, capacity); } - jobject PopLocalFrame(jobject result) { + jobject PopLocalFrame(jobject result) + { return functions->PopLocalFrame(this, result); } - jobject NewGlobalRef(jobject obj) { + jobject NewGlobalRef(jobject obj) + { return functions->NewGlobalRef(this, obj); } - void DeleteGlobalRef(jobject globalRef) { + void DeleteGlobalRef(jobject globalRef) + { functions->DeleteGlobalRef(this, globalRef); } - void DeleteLocalRef(jobject localRef) { + void DeleteLocalRef(jobject localRef) + { functions->DeleteLocalRef(this, localRef); } - jboolean IsSameObject(jobject ref1, jobject ref2) { + jboolean IsSameObject(jobject ref1, jobject ref2) + { return functions->IsSameObject(this, ref1, ref2); } - jobject NewLocalRef(jobject ref) { + jobject NewLocalRef(jobject ref) + { return functions->NewLocalRef(this, ref); } - jint EnsureLocalCapacity(jint capacity) { + jint EnsureLocalCapacity(jint capacity) + { return functions->EnsureLocalCapacity(this, capacity); } - jobject AllocObject(jclass clazz) { + jobject AllocObject(jclass clazz) + { return functions->AllocObject(this, clazz); } - jobject NewObject(jclass clazz, jmethodID methodID, ...) { + jobject NewObject(jclass clazz, jmethodID methodID, ...) + { va_list args; va_start(args, methodID); jobject result = functions->NewObjectV(this, clazz, methodID, args); @@ -618,28 +563,34 @@ struct _JNIEnv { return result; } - jobject NewObjectV(jclass clazz, jmethodID methodID, va_list args) { + jobject NewObjectV(jclass clazz, jmethodID methodID, va_list args) + { return functions->NewObjectV(this, clazz, methodID, args); } - jobject NewObjectA(jclass clazz, jmethodID methodID, jvalue* args) { + jobject NewObjectA(jclass clazz, jmethodID methodID, jvalue *args) + { return functions->NewObjectA(this, clazz, methodID, args); } - jclass GetObjectClass(jobject obj) { + jclass GetObjectClass(jobject obj) + { return functions->GetObjectClass(this, obj); } - jboolean IsInstanceOf(jobject obj, jclass clazz) { + jboolean IsInstanceOf(jobject obj, jclass clazz) + { return functions->IsInstanceOf(this, obj, clazz); } - jmethodID GetMethodID(jclass clazz, const char* name, const char* sig) { + jmethodID GetMethodID(jclass clazz, const char *name, const char *sig) + { return functions->GetMethodID(this, clazz, name, sig); } #define CALL_TYPE_METHOD(_jtype, _jname) \ - _jtype Call##_jname##Method(jobject obj, jmethodID methodID, ...) { \ + _jtype Call##_jname##Method(jobject obj, jmethodID methodID, ...) \ + { \ _jtype result; \ va_list args; \ va_start(args, methodID); \ @@ -647,15 +598,15 @@ struct _JNIEnv { va_end(args); \ return result; \ } -#define CALL_TYPE_METHODV(_jtype, _jname) \ - _jtype Call##_jname##MethodV( \ - jobject obj, jmethodID methodID, va_list args) { \ - return functions->Call##_jname##MethodV(this, obj, methodID, args); \ +#define CALL_TYPE_METHODV(_jtype, _jname) \ + _jtype Call##_jname##MethodV(jobject obj, jmethodID methodID, va_list args) \ + { \ + return functions->Call##_jname##MethodV(this, obj, methodID, args); \ } -#define CALL_TYPE_METHODA(_jtype, _jname) \ - _jtype Call##_jname##MethodA( \ - jobject obj, jmethodID methodID, jvalue* args) { \ - return functions->Call##_jname##MethodA(this, obj, methodID, args); \ +#define CALL_TYPE_METHODA(_jtype, _jname) \ + _jtype Call##_jname##MethodA(jobject obj, jmethodID methodID, jvalue *args) \ + { \ + return functions->Call##_jname##MethodA(this, obj, methodID, args); \ } #define CALL_TYPE(_jtype, _jname) \ @@ -673,41 +624,41 @@ struct _JNIEnv { CALL_TYPE(jfloat, Float) CALL_TYPE(jdouble, Double) - void CallVoidMethod(jobject obj, jmethodID methodID, ...) { + void CallVoidMethod(jobject obj, jmethodID methodID, ...) + { va_list args; va_start(args, methodID); functions->CallVoidMethodV(this, obj, methodID, args); va_end(args); } - void CallVoidMethodV(jobject obj, jmethodID methodID, va_list args) { + void CallVoidMethodV(jobject obj, jmethodID methodID, va_list args) + { functions->CallVoidMethodV(this, obj, methodID, args); } - void CallVoidMethodA(jobject obj, jmethodID methodID, jvalue* args) { + void CallVoidMethodA(jobject obj, jmethodID methodID, jvalue *args) + { functions->CallVoidMethodA(this, obj, methodID, args); } -#define CALL_NONVIRT_TYPE_METHOD(_jtype, _jname) \ - _jtype CallNonvirtual##_jname##Method( \ - jobject obj, jclass clazz, jmethodID methodID, ...) { \ - _jtype result; \ - va_list args; \ - va_start(args, methodID); \ - result = functions->CallNonvirtual##_jname##MethodV( \ - this, obj, clazz, methodID, args); \ - va_end(args); \ - return result; \ +#define CALL_NONVIRT_TYPE_METHOD(_jtype, _jname) \ + _jtype CallNonvirtual##_jname##Method(jobject obj, jclass clazz, jmethodID methodID, ...) \ + { \ + _jtype result; \ + va_list args; \ + va_start(args, methodID); \ + result = functions->CallNonvirtual##_jname##MethodV(this, obj, clazz, methodID, args); \ + va_end(args); \ + return result; \ } -#define CALL_NONVIRT_TYPE_METHODV(_jtype, _jname) \ - _jtype CallNonvirtual##_jname##MethodV( \ - jobject obj, jclass clazz, jmethodID methodID, va_list args) { \ - return functions->CallNonvirtual##_jname##MethodV( \ - this, obj, clazz, methodID, args); \ +#define CALL_NONVIRT_TYPE_METHODV(_jtype, _jname) \ + _jtype CallNonvirtual##_jname##MethodV(jobject obj, jclass clazz, jmethodID methodID, va_list args) \ + { \ + return functions->CallNonvirtual##_jname##MethodV(this, obj, clazz, methodID, args); \ } -#define CALL_NONVIRT_TYPE_METHODA(_jtype, _jname) \ - _jtype CallNonvirtual##_jname##MethodA( \ - jobject obj, jclass clazz, jmethodID methodID, jvalue* args) { \ - return functions->CallNonvirtual##_jname##MethodA( \ - this, obj, clazz, methodID, args); \ +#define CALL_NONVIRT_TYPE_METHODA(_jtype, _jname) \ + _jtype CallNonvirtual##_jname##MethodA(jobject obj, jclass clazz, jmethodID methodID, jvalue *args) \ + { \ + return functions->CallNonvirtual##_jname##MethodA(this, obj, clazz, methodID, args); \ } #define CALL_NONVIRT_TYPE(_jtype, _jname) \ @@ -725,113 +676,125 @@ struct _JNIEnv { CALL_NONVIRT_TYPE(jfloat, Float) CALL_NONVIRT_TYPE(jdouble, Double) - void - CallNonvirtualVoidMethod(jobject obj, jclass clazz, jmethodID methodID, ...) { + void CallNonvirtualVoidMethod(jobject obj, jclass clazz, jmethodID methodID, ...) + { va_list args; va_start(args, methodID); functions->CallNonvirtualVoidMethodV(this, obj, clazz, methodID, args); va_end(args); } - void CallNonvirtualVoidMethodV( - jobject obj, - jclass clazz, - jmethodID methodID, - va_list args) { + void CallNonvirtualVoidMethodV(jobject obj, jclass clazz, jmethodID methodID, va_list args) + { functions->CallNonvirtualVoidMethodV(this, obj, clazz, methodID, args); } - void CallNonvirtualVoidMethodA( - jobject obj, - jclass clazz, - jmethodID methodID, - jvalue* args) { + void CallNonvirtualVoidMethodA(jobject obj, jclass clazz, jmethodID methodID, jvalue *args) + { functions->CallNonvirtualVoidMethodA(this, obj, clazz, methodID, args); } - jfieldID GetFieldID(jclass clazz, const char* name, const char* sig) { + jfieldID GetFieldID(jclass clazz, const char *name, const char *sig) + { return functions->GetFieldID(this, clazz, name, sig); } - jobject GetObjectField(jobject obj, jfieldID fieldID) { + jobject GetObjectField(jobject obj, jfieldID fieldID) + { return functions->GetObjectField(this, obj, fieldID); } - jboolean GetBooleanField(jobject obj, jfieldID fieldID) { + jboolean GetBooleanField(jobject obj, jfieldID fieldID) + { return functions->GetBooleanField(this, obj, fieldID); } - jbyte GetByteField(jobject obj, jfieldID fieldID) { + jbyte GetByteField(jobject obj, jfieldID fieldID) + { return functions->GetByteField(this, obj, fieldID); } - jchar GetCharField(jobject obj, jfieldID fieldID) { + jchar GetCharField(jobject obj, jfieldID fieldID) + { return functions->GetCharField(this, obj, fieldID); } - jshort GetShortField(jobject obj, jfieldID fieldID) { + jshort GetShortField(jobject obj, jfieldID fieldID) + { return functions->GetShortField(this, obj, fieldID); } - jint GetIntField(jobject obj, jfieldID fieldID) { + jint GetIntField(jobject obj, jfieldID fieldID) + { return functions->GetIntField(this, obj, fieldID); } - jlong GetLongField(jobject obj, jfieldID fieldID) { + jlong GetLongField(jobject obj, jfieldID fieldID) + { return functions->GetLongField(this, obj, fieldID); } - jfloat GetFloatField(jobject obj, jfieldID fieldID) { + jfloat GetFloatField(jobject obj, jfieldID fieldID) + { return functions->GetFloatField(this, obj, fieldID); } - jdouble GetDoubleField(jobject obj, jfieldID fieldID) { + jdouble GetDoubleField(jobject obj, jfieldID fieldID) + { return functions->GetDoubleField(this, obj, fieldID); } - void SetObjectField(jobject obj, jfieldID fieldID, jobject value) { + void SetObjectField(jobject obj, jfieldID fieldID, jobject value) + { functions->SetObjectField(this, obj, fieldID, value); } - void SetBooleanField(jobject obj, jfieldID fieldID, jboolean value) { + void SetBooleanField(jobject obj, jfieldID fieldID, jboolean value) + { functions->SetBooleanField(this, obj, fieldID, value); } - void SetByteField(jobject obj, jfieldID fieldID, jbyte value) { + void SetByteField(jobject obj, jfieldID fieldID, jbyte value) + { functions->SetByteField(this, obj, fieldID, value); } - void SetCharField(jobject obj, jfieldID fieldID, jchar value) { + void SetCharField(jobject obj, jfieldID fieldID, jchar value) + { functions->SetCharField(this, obj, fieldID, value); } - void SetShortField(jobject obj, jfieldID fieldID, jshort value) { + void SetShortField(jobject obj, jfieldID fieldID, jshort value) + { functions->SetShortField(this, obj, fieldID, value); } - void SetIntField(jobject obj, jfieldID fieldID, jint value) { + void SetIntField(jobject obj, jfieldID fieldID, jint value) + { functions->SetIntField(this, obj, fieldID, value); } - void SetLongField(jobject obj, jfieldID fieldID, jlong value) { + void SetLongField(jobject obj, jfieldID fieldID, jlong value) + { functions->SetLongField(this, obj, fieldID, value); } - void SetFloatField(jobject obj, jfieldID fieldID, jfloat value) { + void SetFloatField(jobject obj, jfieldID fieldID, jfloat value) + { functions->SetFloatField(this, obj, fieldID, value); } - void SetDoubleField(jobject obj, jfieldID fieldID, jdouble value) { + void SetDoubleField(jobject obj, jfieldID fieldID, jdouble value) + { functions->SetDoubleField(this, obj, fieldID, value); } - jmethodID GetStaticMethodID(jclass clazz, const char* name, const char* sig) { + jmethodID GetStaticMethodID(jclass clazz, const char *name, const char *sig) + { return functions->GetStaticMethodID(this, clazz, name, sig); } -#define CALL_STATIC_TYPE_METHOD(_jtype, _jname) \ - _jtype CallStatic##_jname##Method(jclass clazz, jmethodID methodID, ...) { \ - _jtype result; \ - va_list args; \ - va_start(args, methodID); \ - result = \ - functions->CallStatic##_jname##MethodV(this, clazz, methodID, args); \ - va_end(args); \ - return result; \ +#define CALL_STATIC_TYPE_METHOD(_jtype, _jname) \ + _jtype CallStatic##_jname##Method(jclass clazz, jmethodID methodID, ...) \ + { \ + _jtype result; \ + va_list args; \ + va_start(args, methodID); \ + result = functions->CallStatic##_jname##MethodV(this, clazz, methodID, args); \ + va_end(args); \ + return result; \ } -#define CALL_STATIC_TYPE_METHODV(_jtype, _jname) \ - _jtype CallStatic##_jname##MethodV( \ - jclass clazz, jmethodID methodID, va_list args) { \ - return functions->CallStatic##_jname##MethodV( \ - this, clazz, methodID, args); \ +#define CALL_STATIC_TYPE_METHODV(_jtype, _jname) \ + _jtype CallStatic##_jname##MethodV(jclass clazz, jmethodID methodID, va_list args) \ + { \ + return functions->CallStatic##_jname##MethodV(this, clazz, methodID, args); \ } -#define CALL_STATIC_TYPE_METHODA(_jtype, _jname) \ - _jtype CallStatic##_jname##MethodA( \ - jclass clazz, jmethodID methodID, jvalue* args) { \ - return functions->CallStatic##_jname##MethodA( \ - this, clazz, methodID, args); \ +#define CALL_STATIC_TYPE_METHODA(_jtype, _jname) \ + _jtype CallStatic##_jname##MethodA(jclass clazz, jmethodID methodID, jvalue *args) \ + { \ + return functions->CallStatic##_jname##MethodA(this, clazz, methodID, args); \ } #define CALL_STATIC_TYPE(_jtype, _jname) \ @@ -849,369 +812,414 @@ struct _JNIEnv { CALL_STATIC_TYPE(jfloat, Float) CALL_STATIC_TYPE(jdouble, Double) - void CallStaticVoidMethod(jclass clazz, jmethodID methodID, ...) { + void CallStaticVoidMethod(jclass clazz, jmethodID methodID, ...) + { va_list args; va_start(args, methodID); functions->CallStaticVoidMethodV(this, clazz, methodID, args); va_end(args); } - void CallStaticVoidMethodV(jclass clazz, jmethodID methodID, va_list args) { + void CallStaticVoidMethodV(jclass clazz, jmethodID methodID, va_list args) + { functions->CallStaticVoidMethodV(this, clazz, methodID, args); } - void CallStaticVoidMethodA(jclass clazz, jmethodID methodID, jvalue* args) { + void CallStaticVoidMethodA(jclass clazz, jmethodID methodID, jvalue *args) + { functions->CallStaticVoidMethodA(this, clazz, methodID, args); } - jfieldID GetStaticFieldID(jclass clazz, const char* name, const char* sig) { + jfieldID GetStaticFieldID(jclass clazz, const char *name, const char *sig) + { return functions->GetStaticFieldID(this, clazz, name, sig); } - jobject GetStaticObjectField(jclass clazz, jfieldID fieldID) { + jobject GetStaticObjectField(jclass clazz, jfieldID fieldID) + { return functions->GetStaticObjectField(this, clazz, fieldID); } - jboolean GetStaticBooleanField(jclass clazz, jfieldID fieldID) { + jboolean GetStaticBooleanField(jclass clazz, jfieldID fieldID) + { return functions->GetStaticBooleanField(this, clazz, fieldID); } - jbyte GetStaticByteField(jclass clazz, jfieldID fieldID) { + jbyte GetStaticByteField(jclass clazz, jfieldID fieldID) + { return functions->GetStaticByteField(this, clazz, fieldID); } - jchar GetStaticCharField(jclass clazz, jfieldID fieldID) { + jchar GetStaticCharField(jclass clazz, jfieldID fieldID) + { return functions->GetStaticCharField(this, clazz, fieldID); } - jshort GetStaticShortField(jclass clazz, jfieldID fieldID) { + jshort GetStaticShortField(jclass clazz, jfieldID fieldID) + { return functions->GetStaticShortField(this, clazz, fieldID); } - jint GetStaticIntField(jclass clazz, jfieldID fieldID) { + jint GetStaticIntField(jclass clazz, jfieldID fieldID) + { return functions->GetStaticIntField(this, clazz, fieldID); } - jlong GetStaticLongField(jclass clazz, jfieldID fieldID) { + jlong GetStaticLongField(jclass clazz, jfieldID fieldID) + { return functions->GetStaticLongField(this, clazz, fieldID); } - jfloat GetStaticFloatField(jclass clazz, jfieldID fieldID) { + jfloat GetStaticFloatField(jclass clazz, jfieldID fieldID) + { return functions->GetStaticFloatField(this, clazz, fieldID); } - jdouble GetStaticDoubleField(jclass clazz, jfieldID fieldID) { + jdouble GetStaticDoubleField(jclass clazz, jfieldID fieldID) + { return functions->GetStaticDoubleField(this, clazz, fieldID); } - void SetStaticObjectField(jclass clazz, jfieldID fieldID, jobject value) { + void SetStaticObjectField(jclass clazz, jfieldID fieldID, jobject value) + { functions->SetStaticObjectField(this, clazz, fieldID, value); } - void SetStaticBooleanField(jclass clazz, jfieldID fieldID, jboolean value) { + void SetStaticBooleanField(jclass clazz, jfieldID fieldID, jboolean value) + { functions->SetStaticBooleanField(this, clazz, fieldID, value); } - void SetStaticByteField(jclass clazz, jfieldID fieldID, jbyte value) { + void SetStaticByteField(jclass clazz, jfieldID fieldID, jbyte value) + { functions->SetStaticByteField(this, clazz, fieldID, value); } - void SetStaticCharField(jclass clazz, jfieldID fieldID, jchar value) { + void SetStaticCharField(jclass clazz, jfieldID fieldID, jchar value) + { functions->SetStaticCharField(this, clazz, fieldID, value); } - void SetStaticShortField(jclass clazz, jfieldID fieldID, jshort value) { + void SetStaticShortField(jclass clazz, jfieldID fieldID, jshort value) + { functions->SetStaticShortField(this, clazz, fieldID, value); } - void SetStaticIntField(jclass clazz, jfieldID fieldID, jint value) { + void SetStaticIntField(jclass clazz, jfieldID fieldID, jint value) + { functions->SetStaticIntField(this, clazz, fieldID, value); } - void SetStaticLongField(jclass clazz, jfieldID fieldID, jlong value) { + void SetStaticLongField(jclass clazz, jfieldID fieldID, jlong value) + { functions->SetStaticLongField(this, clazz, fieldID, value); } - void SetStaticFloatField(jclass clazz, jfieldID fieldID, jfloat value) { + void SetStaticFloatField(jclass clazz, jfieldID fieldID, jfloat value) + { functions->SetStaticFloatField(this, clazz, fieldID, value); } - void SetStaticDoubleField(jclass clazz, jfieldID fieldID, jdouble value) { + void SetStaticDoubleField(jclass clazz, jfieldID fieldID, jdouble value) + { functions->SetStaticDoubleField(this, clazz, fieldID, value); } - jstring NewString(const jchar* unicodeChars, jsize len) { + jstring NewString(const jchar *unicodeChars, jsize len) + { return functions->NewString(this, unicodeChars, len); } - jsize GetStringLength(jstring string) { + jsize GetStringLength(jstring string) + { return functions->GetStringLength(this, string); } - const jchar* GetStringChars(jstring string, jboolean* isCopy) { + const jchar *GetStringChars(jstring string, jboolean *isCopy) + { return functions->GetStringChars(this, string, isCopy); } - void ReleaseStringChars(jstring string, const jchar* chars) { + void ReleaseStringChars(jstring string, const jchar *chars) + { functions->ReleaseStringChars(this, string, chars); } - jstring NewStringUTF(const char* bytes) { + jstring NewStringUTF(const char *bytes) + { return functions->NewStringUTF(this, bytes); } - jsize GetStringUTFLength(jstring string) { + jsize GetStringUTFLength(jstring string) + { return functions->GetStringUTFLength(this, string); } - const char* GetStringUTFChars(jstring string, jboolean* isCopy) { + const char *GetStringUTFChars(jstring string, jboolean *isCopy) + { return functions->GetStringUTFChars(this, string, isCopy); } - void ReleaseStringUTFChars(jstring string, const char* utf) { + void ReleaseStringUTFChars(jstring string, const char *utf) + { functions->ReleaseStringUTFChars(this, string, utf); } - jsize GetArrayLength(jarray array) { + jsize GetArrayLength(jarray array) + { return functions->GetArrayLength(this, array); } - jobjectArray - NewObjectArray(jsize length, jclass elementClass, jobject initialElement) { - return functions->NewObjectArray( - this, length, elementClass, initialElement); + jobjectArray NewObjectArray(jsize length, jclass elementClass, jobject initialElement) + { + return functions->NewObjectArray(this, length, elementClass, initialElement); } - jobject GetObjectArrayElement(jobjectArray array, jsize index) { + jobject GetObjectArrayElement(jobjectArray array, jsize index) + { return functions->GetObjectArrayElement(this, array, index); } - void SetObjectArrayElement(jobjectArray array, jsize index, jobject value) { + void SetObjectArrayElement(jobjectArray array, jsize index, jobject value) + { functions->SetObjectArrayElement(this, array, index, value); } - jbooleanArray NewBooleanArray(jsize length) { + jbooleanArray NewBooleanArray(jsize length) + { return functions->NewBooleanArray(this, length); } - jbyteArray NewByteArray(jsize length) { + jbyteArray NewByteArray(jsize length) + { return functions->NewByteArray(this, length); } - jcharArray NewCharArray(jsize length) { + jcharArray NewCharArray(jsize length) + { return functions->NewCharArray(this, length); } - jshortArray NewShortArray(jsize length) { + jshortArray NewShortArray(jsize length) + { return functions->NewShortArray(this, length); } - jintArray NewIntArray(jsize length) { + jintArray NewIntArray(jsize length) + { return functions->NewIntArray(this, length); } - jlongArray NewLongArray(jsize length) { + jlongArray NewLongArray(jsize length) + { return functions->NewLongArray(this, length); } - jfloatArray NewFloatArray(jsize length) { + jfloatArray NewFloatArray(jsize length) + { return functions->NewFloatArray(this, length); } - jdoubleArray NewDoubleArray(jsize length) { + jdoubleArray NewDoubleArray(jsize length) + { return functions->NewDoubleArray(this, length); } - jboolean* GetBooleanArrayElements(jbooleanArray array, jboolean* isCopy) { + jboolean *GetBooleanArrayElements(jbooleanArray array, jboolean *isCopy) + { return functions->GetBooleanArrayElements(this, array, isCopy); } - jbyte* GetByteArrayElements(jbyteArray array, jboolean* isCopy) { + jbyte *GetByteArrayElements(jbyteArray array, jboolean *isCopy) + { return functions->GetByteArrayElements(this, array, isCopy); } - jchar* GetCharArrayElements(jcharArray array, jboolean* isCopy) { + jchar *GetCharArrayElements(jcharArray array, jboolean *isCopy) + { return functions->GetCharArrayElements(this, array, isCopy); } - jshort* GetShortArrayElements(jshortArray array, jboolean* isCopy) { + jshort *GetShortArrayElements(jshortArray array, jboolean *isCopy) + { return functions->GetShortArrayElements(this, array, isCopy); } - jint* GetIntArrayElements(jintArray array, jboolean* isCopy) { + jint *GetIntArrayElements(jintArray array, jboolean *isCopy) + { return functions->GetIntArrayElements(this, array, isCopy); } - jlong* GetLongArrayElements(jlongArray array, jboolean* isCopy) { + jlong *GetLongArrayElements(jlongArray array, jboolean *isCopy) + { return functions->GetLongArrayElements(this, array, isCopy); } - jfloat* GetFloatArrayElements(jfloatArray array, jboolean* isCopy) { + jfloat *GetFloatArrayElements(jfloatArray array, jboolean *isCopy) + { return functions->GetFloatArrayElements(this, array, isCopy); } - jdouble* GetDoubleArrayElements(jdoubleArray array, jboolean* isCopy) { + jdouble *GetDoubleArrayElements(jdoubleArray array, jboolean *isCopy) + { return functions->GetDoubleArrayElements(this, array, isCopy); } - void - ReleaseBooleanArrayElements(jbooleanArray array, jboolean* elems, jint mode) { + void ReleaseBooleanArrayElements(jbooleanArray array, jboolean *elems, jint mode) + { functions->ReleaseBooleanArrayElements(this, array, elems, mode); } - void ReleaseByteArrayElements(jbyteArray array, jbyte* elems, jint mode) { + void ReleaseByteArrayElements(jbyteArray array, jbyte *elems, jint mode) + { functions->ReleaseByteArrayElements(this, array, elems, mode); } - void ReleaseCharArrayElements(jcharArray array, jchar* elems, jint mode) { + void ReleaseCharArrayElements(jcharArray array, jchar *elems, jint mode) + { functions->ReleaseCharArrayElements(this, array, elems, mode); } - void ReleaseShortArrayElements(jshortArray array, jshort* elems, jint mode) { + void ReleaseShortArrayElements(jshortArray array, jshort *elems, jint mode) + { functions->ReleaseShortArrayElements(this, array, elems, mode); } - void ReleaseIntArrayElements(jintArray array, jint* elems, jint mode) { + void ReleaseIntArrayElements(jintArray array, jint *elems, jint mode) + { functions->ReleaseIntArrayElements(this, array, elems, mode); } - void ReleaseLongArrayElements(jlongArray array, jlong* elems, jint mode) { + void ReleaseLongArrayElements(jlongArray array, jlong *elems, jint mode) + { functions->ReleaseLongArrayElements(this, array, elems, mode); } - void ReleaseFloatArrayElements(jfloatArray array, jfloat* elems, jint mode) { + void ReleaseFloatArrayElements(jfloatArray array, jfloat *elems, jint mode) + { functions->ReleaseFloatArrayElements(this, array, elems, mode); } - void - ReleaseDoubleArrayElements(jdoubleArray array, jdouble* elems, jint mode) { + void ReleaseDoubleArrayElements(jdoubleArray array, jdouble *elems, jint mode) + { functions->ReleaseDoubleArrayElements(this, array, elems, mode); } - void GetBooleanArrayRegion( - jbooleanArray array, - jsize start, - jsize len, - jboolean* buf) { + void GetBooleanArrayRegion(jbooleanArray array, jsize start, jsize len, jboolean *buf) + { functions->GetBooleanArrayRegion(this, array, start, len, buf); } - void - GetByteArrayRegion(jbyteArray array, jsize start, jsize len, jbyte* buf) { + void GetByteArrayRegion(jbyteArray array, jsize start, jsize len, jbyte *buf) + { functions->GetByteArrayRegion(this, array, start, len, buf); } - void - GetCharArrayRegion(jcharArray array, jsize start, jsize len, jchar* buf) { + void GetCharArrayRegion(jcharArray array, jsize start, jsize len, jchar *buf) + { functions->GetCharArrayRegion(this, array, start, len, buf); } - void - GetShortArrayRegion(jshortArray array, jsize start, jsize len, jshort* buf) { + void GetShortArrayRegion(jshortArray array, jsize start, jsize len, jshort *buf) + { functions->GetShortArrayRegion(this, array, start, len, buf); } - void GetIntArrayRegion(jintArray array, jsize start, jsize len, jint* buf) { + void GetIntArrayRegion(jintArray array, jsize start, jsize len, jint *buf) + { functions->GetIntArrayRegion(this, array, start, len, buf); } - void - GetLongArrayRegion(jlongArray array, jsize start, jsize len, jlong* buf) { + void GetLongArrayRegion(jlongArray array, jsize start, jsize len, jlong *buf) + { functions->GetLongArrayRegion(this, array, start, len, buf); } - void - GetFloatArrayRegion(jfloatArray array, jsize start, jsize len, jfloat* buf) { + void GetFloatArrayRegion(jfloatArray array, jsize start, jsize len, jfloat *buf) + { functions->GetFloatArrayRegion(this, array, start, len, buf); } - void GetDoubleArrayRegion( - jdoubleArray array, - jsize start, - jsize len, - jdouble* buf) { + void GetDoubleArrayRegion(jdoubleArray array, jsize start, jsize len, jdouble *buf) + { functions->GetDoubleArrayRegion(this, array, start, len, buf); } - void SetBooleanArrayRegion( - jbooleanArray array, - jsize start, - jsize len, - const jboolean* buf) { + void SetBooleanArrayRegion(jbooleanArray array, jsize start, jsize len, const jboolean *buf) + { functions->SetBooleanArrayRegion(this, array, start, len, buf); } - void SetByteArrayRegion( - jbyteArray array, - jsize start, - jsize len, - const jbyte* buf) { + void SetByteArrayRegion(jbyteArray array, jsize start, jsize len, const jbyte *buf) + { functions->SetByteArrayRegion(this, array, start, len, buf); } - void SetCharArrayRegion( - jcharArray array, - jsize start, - jsize len, - const jchar* buf) { + void SetCharArrayRegion(jcharArray array, jsize start, jsize len, const jchar *buf) + { functions->SetCharArrayRegion(this, array, start, len, buf); } - void SetShortArrayRegion( - jshortArray array, - jsize start, - jsize len, - const jshort* buf) { + void SetShortArrayRegion(jshortArray array, jsize start, jsize len, const jshort *buf) + { functions->SetShortArrayRegion(this, array, start, len, buf); } - void - SetIntArrayRegion(jintArray array, jsize start, jsize len, const jint* buf) { + void SetIntArrayRegion(jintArray array, jsize start, jsize len, const jint *buf) + { functions->SetIntArrayRegion(this, array, start, len, buf); } - void SetLongArrayRegion( - jlongArray array, - jsize start, - jsize len, - const jlong* buf) { + void SetLongArrayRegion(jlongArray array, jsize start, jsize len, const jlong *buf) + { functions->SetLongArrayRegion(this, array, start, len, buf); } - void SetFloatArrayRegion( - jfloatArray array, - jsize start, - jsize len, - const jfloat* buf) { + void SetFloatArrayRegion(jfloatArray array, jsize start, jsize len, const jfloat *buf) + { functions->SetFloatArrayRegion(this, array, start, len, buf); } - void SetDoubleArrayRegion( - jdoubleArray array, - jsize start, - jsize len, - const jdouble* buf) { + void SetDoubleArrayRegion(jdoubleArray array, jsize start, jsize len, const jdouble *buf) + { functions->SetDoubleArrayRegion(this, array, start, len, buf); } - jint - RegisterNatives(jclass clazz, const JNINativeMethod* methods, jint nMethods) { + jint RegisterNatives(jclass clazz, const JNINativeMethod *methods, jint nMethods) + { return functions->RegisterNatives(this, clazz, methods, nMethods); } - jint UnregisterNatives(jclass clazz) { + jint UnregisterNatives(jclass clazz) + { return functions->UnregisterNatives(this, clazz); } - jint MonitorEnter(jobject obj) { + jint MonitorEnter(jobject obj) + { return functions->MonitorEnter(this, obj); } - jint MonitorExit(jobject obj) { + jint MonitorExit(jobject obj) + { return functions->MonitorExit(this, obj); } - jint GetJavaVM(JavaVM** vm) { + jint GetJavaVM(JavaVM **vm) + { return functions->GetJavaVM(this, vm); } - void GetStringRegion(jstring str, jsize start, jsize len, jchar* buf) { + void GetStringRegion(jstring str, jsize start, jsize len, jchar *buf) + { functions->GetStringRegion(this, str, start, len, buf); } - void GetStringUTFRegion(jstring str, jsize start, jsize len, char* buf) { + void GetStringUTFRegion(jstring str, jsize start, jsize len, char *buf) + { return functions->GetStringUTFRegion(this, str, start, len, buf); } - void* GetPrimitiveArrayCritical(jarray array, jboolean* isCopy) { + void *GetPrimitiveArrayCritical(jarray array, jboolean *isCopy) + { return functions->GetPrimitiveArrayCritical(this, array, isCopy); } - void ReleasePrimitiveArrayCritical(jarray array, void* carray, jint mode) { + void ReleasePrimitiveArrayCritical(jarray array, void *carray, jint mode) + { functions->ReleasePrimitiveArrayCritical(this, array, carray, mode); } - const jchar* GetStringCritical(jstring string, jboolean* isCopy) { + const jchar *GetStringCritical(jstring string, jboolean *isCopy) + { return functions->GetStringCritical(this, string, isCopy); } - void ReleaseStringCritical(jstring string, const jchar* carray) { + void ReleaseStringCritical(jstring string, const jchar *carray) + { functions->ReleaseStringCritical(this, string, carray); } - jweak NewWeakGlobalRef(jobject obj) { + jweak NewWeakGlobalRef(jobject obj) + { return functions->NewWeakGlobalRef(this, obj); } - void DeleteWeakGlobalRef(jweak obj) { + void DeleteWeakGlobalRef(jweak obj) + { functions->DeleteWeakGlobalRef(this, obj); } - jboolean ExceptionCheck() { + jboolean ExceptionCheck() + { return functions->ExceptionCheck(this); } - jobject NewDirectByteBuffer(void* address, jlong capacity) { + jobject NewDirectByteBuffer(void *address, jlong capacity) + { return functions->NewDirectByteBuffer(this, address, capacity); } - void* GetDirectBufferAddress(jobject buf) { + void *GetDirectBufferAddress(jobject buf) + { return functions->GetDirectBufferAddress(this, buf); } - jlong GetDirectBufferCapacity(jobject buf) { + jlong GetDirectBufferCapacity(jobject buf) + { return functions->GetDirectBufferCapacity(this, buf); } /* added in JNI 1.6 */ - jobjectRefType GetObjectRefType(jobject obj) { + jobjectRefType GetObjectRefType(jobject obj) + { return functions->GetObjectRefType(this, obj); } #endif /*__cplusplus*/ @@ -1221,37 +1229,42 @@ struct _JNIEnv { * JNI invocation interface. */ struct JNIInvokeInterface { - void* reserved0; - void* reserved1; - void* reserved2; + void *reserved0; + void *reserved1; + void *reserved2; - jint (*DestroyJavaVM)(JavaVM*); - jint (*AttachCurrentThread)(JavaVM*, JNIEnv**, void*); - jint (*DetachCurrentThread)(JavaVM*); - jint (*GetEnv)(JavaVM*, void**, jint); - jint (*AttachCurrentThreadAsDaemon)(JavaVM*, JNIEnv**, void*); + jint (*DestroyJavaVM)(JavaVM *); + jint (*AttachCurrentThread)(JavaVM *, JNIEnv **, void *); + jint (*DetachCurrentThread)(JavaVM *); + jint (*GetEnv)(JavaVM *, void **, jint); + jint (*AttachCurrentThreadAsDaemon)(JavaVM *, JNIEnv **, void *); }; /* * C++ version. */ struct _JavaVM { - const struct JNIInvokeInterface* functions; + const struct JNIInvokeInterface *functions; #if defined(__cplusplus) - jint DestroyJavaVM() { + jint DestroyJavaVM() + { return functions->DestroyJavaVM(this); } - jint AttachCurrentThread(JNIEnv** p_env, void* thr_args) { + jint AttachCurrentThread(JNIEnv **p_env, void *thr_args) + { return functions->AttachCurrentThread(this, p_env, thr_args); } - jint DetachCurrentThread() { + jint DetachCurrentThread() + { return functions->DetachCurrentThread(this); } - jint GetEnv(void** env, jint version) { + jint GetEnv(void **env, jint version) + { return functions->GetEnv(this, env, version); } - jint AttachCurrentThreadAsDaemon(JNIEnv** p_env, void* thr_args) { + jint AttachCurrentThreadAsDaemon(JNIEnv **p_env, void *thr_args) + { return functions->AttachCurrentThreadAsDaemon(this, p_env, thr_args); } #endif /*__cplusplus*/ @@ -1259,7 +1272,7 @@ struct _JavaVM { struct JavaVMAttachArgs { jint version; /* must be >= JNI_VERSION_1_2 */ - const char* name; /* NULL or name of thread as modified UTF-8 str */ + const char *name; /* NULL or name of thread as modified UTF-8 str */ jobject group; /* global ref of a ThreadGroup object, or NULL */ }; typedef struct JavaVMAttachArgs JavaVMAttachArgs; @@ -1269,15 +1282,15 @@ typedef struct JavaVMAttachArgs JavaVMAttachArgs; * longer supported.) */ typedef struct JavaVMOption { - const char* optionString; - void* extraInfo; + const char *optionString; + void *extraInfo; } JavaVMOption; typedef struct JavaVMInitArgs { jint version; /* use JNI_VERSION_1_2 or later */ jint nOptions; - JavaVMOption* options; + JavaVMOption *options; jboolean ignoreUnrecognized; } JavaVMInitArgs; @@ -1289,9 +1302,9 @@ extern "C" { * * Note these are the only symbols exported for JNI by the VM. */ -jint JNI_GetDefaultJavaVMInitArgs(void*); -jint JNI_CreateJavaVM(JavaVM**, JNIEnv**, void*); -jint JNI_GetCreatedJavaVMs(JavaVM**, jsize, jsize*); +jint JNI_GetDefaultJavaVMInitArgs(void *); +jint JNI_CreateJavaVM(JavaVM **, JNIEnv **, void *); +jint JNI_GetCreatedJavaVMs(JavaVM **, jsize, jsize *); #define JNIIMPORT #define JNIEXPORT __attribute__((visibility("default"))) @@ -1301,8 +1314,8 @@ jint JNI_GetCreatedJavaVMs(JavaVM**, jsize, jsize*); * Prototypes for functions exported by loadable shared libs. These are * called by JNI, not provided by JNI. */ -JNIEXPORT jint JNI_OnLoad(JavaVM* vm, void* reserved); -JNIEXPORT void JNI_OnUnload(JavaVM* vm, void* reserved); +JNIEXPORT jint JNI_OnLoad(JavaVM *vm, void *reserved); +JNIEXPORT void JNI_OnUnload(JavaVM *vm, void *reserved); #ifdef __cplusplus } diff --git a/packages/react-native/ReactAndroid/src/main/jni/first-party/jni-lib-merge/jni_lib_merge.h b/packages/react-native/ReactAndroid/src/main/jni/first-party/jni-lib-merge/jni_lib_merge.h index 0b8122d7c19..6adb0d390bf 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/first-party/jni-lib-merge/jni_lib_merge.h +++ b/packages/react-native/ReactAndroid/src/main/jni/first-party/jni-lib-merge/jni_lib_merge.h @@ -13,8 +13,7 @@ #ifdef JNI_MERGE_PRINT_ONLOAD #ifdef __ANDROID__ #include -#define JNI_MERGE_PRINT(...) \ - __android_log_print(ANDROID_LOG_DEBUG, "jni_lib_merge", __VA_ARGS__) +#define JNI_MERGE_PRINT(...) __android_log_print(ANDROID_LOG_DEBUG, "jni_lib_merge", __VA_ARGS__) #else #include #define JNI_MERGE_PRINT(...) fprintf(stderr, __VA_ARGS__); @@ -38,70 +37,69 @@ #endif struct pre_merge_jni_library { - const char* name; - int (*onload_func)(JNIEnv*, jclass); + const char *name; + int (*onload_func)(JNIEnv *, jclass); }; #ifdef __cplusplus extern "C" { #endif -JNIEXPORT jint JNICALL JNI_OnLoad_Weak(JavaVM* vm, void* reserved); +JNIEXPORT jint JNICALL JNI_OnLoad_Weak(JavaVM *vm, void *reserved); #ifdef __cplusplus } #endif -#define JNI_OnLoad \ - /* Need to make JNI_OnLoad weak, which requires splitting it into */ \ - /* a declaration and definition, which is a little risky. */ \ - /* Hopefully they didn't use 'extern "C"'. */ \ - JNI_OnLoad_Weak(JavaVM* vm, void* reserved) __attribute__((weak)); \ - \ - /* We rename the declared JNI_OnLoad to this so we can call it */ \ - /* from either our weak JNI_OnLoad or our merge-friendly init function. */ \ - static jint pre_merge_original_JNI_OnLoad(JavaVM* vm, void* reserved); \ - \ - /* Merge-friendly wrapper for the original JNI_OnLoad, called by JNI. */ \ - /* Return non-zero to indicate failure. */ \ - static inline jint pre_merge_jni_library_wrapper_for_JNI_OnLoad( \ - JNIEnv* env, jclass clazz) { \ - (void)clazz; \ - JNI_MERGE_PRINT("In JNI_OnLoad wrapper for %s", ORIGINAL_SONAME); \ - /* Note: relying on SoLoader's synchronization for thread-safety. */ \ - static char already_loaded = 0; \ - if (already_loaded) { \ - return 0; \ - } \ - already_loaded = 1; \ - JavaVM* vm; \ - jint ret = JNI_MERGE_GET_JAVA_VM(env, vm); \ - if (ret < 0) { \ - /* Exception already thrown. */ \ - return -1; \ - } \ - JNI_MERGE_PRINT("Calling original JNI_OnLoad for %s", ORIGINAL_SONAME); \ - ret = pre_merge_original_JNI_OnLoad(vm, NULL); \ - if (!(ret == JNI_VERSION_1_2 || ret == JNI_VERSION_1_4 || \ - ret == JNI_VERSION_1_6)) { \ - return -1; \ - } \ - return 0; \ - } \ - \ - jint JNI_OnLoad_Weak(JavaVM* vm, void* reserved) { \ - /* This path will be taken if we're not merged. */ \ - /* Just call the original JNI_OnLoad. */ \ - JNI_MERGE_PRINT( \ - "Calling original (unmerged) JNI_OnLoad for %s", ORIGINAL_SONAME); \ - return pre_merge_original_JNI_OnLoad(vm, reserved); \ - } \ - \ - /* Register our name and wrapper in the proper section. */ \ - static struct pre_merge_jni_library pre_merge_jni_library_register_object \ - ATTRIBUTE_RETAIN __attribute__((__section__("pre_merge_jni_libraries"))) \ - __attribute__((no_sanitize("address"))) __attribute__((__used__)) = { \ - .name = ORIGINAL_SONAME, \ - .onload_func = pre_merge_jni_library_wrapper_for_JNI_OnLoad, \ - }; \ - \ - /* Re-start the JNI_OnLoad prototype to capture the body. */ \ +#define JNI_OnLoad \ + /* Need to make JNI_OnLoad weak, which requires splitting it into */ \ + /* a declaration and definition, which is a little risky. */ \ + /* Hopefully they didn't use 'extern "C"'. */ \ + JNI_OnLoad_Weak(JavaVM *vm, void *reserved) __attribute__((weak)); \ + \ + /* We rename the declared JNI_OnLoad to this so we can call it */ \ + /* from either our weak JNI_OnLoad or our merge-friendly init function. */ \ + static jint pre_merge_original_JNI_OnLoad(JavaVM *vm, void *reserved); \ + \ + /* Merge-friendly wrapper for the original JNI_OnLoad, called by JNI. */ \ + /* Return non-zero to indicate failure. */ \ + static inline jint pre_merge_jni_library_wrapper_for_JNI_OnLoad(JNIEnv *env, jclass clazz) \ + { \ + (void)clazz; \ + JNI_MERGE_PRINT("In JNI_OnLoad wrapper for %s", ORIGINAL_SONAME); \ + /* Note: relying on SoLoader's synchronization for thread-safety. */ \ + static char already_loaded = 0; \ + if (already_loaded) { \ + return 0; \ + } \ + already_loaded = 1; \ + JavaVM *vm; \ + jint ret = JNI_MERGE_GET_JAVA_VM(env, vm); \ + if (ret < 0) { \ + /* Exception already thrown. */ \ + return -1; \ + } \ + JNI_MERGE_PRINT("Calling original JNI_OnLoad for %s", ORIGINAL_SONAME); \ + ret = pre_merge_original_JNI_OnLoad(vm, NULL); \ + if (!(ret == JNI_VERSION_1_2 || ret == JNI_VERSION_1_4 || ret == JNI_VERSION_1_6)) { \ + return -1; \ + } \ + return 0; \ + } \ + \ + jint JNI_OnLoad_Weak(JavaVM *vm, void *reserved) \ + { \ + /* This path will be taken if we're not merged. */ \ + /* Just call the original JNI_OnLoad. */ \ + JNI_MERGE_PRINT("Calling original (unmerged) JNI_OnLoad for %s", ORIGINAL_SONAME); \ + return pre_merge_original_JNI_OnLoad(vm, reserved); \ + } \ + \ + /* Register our name and wrapper in the proper section. */ \ + static struct pre_merge_jni_library pre_merge_jni_library_register_object ATTRIBUTE_RETAIN \ + __attribute__((__section__("pre_merge_jni_libraries"))) __attribute__((no_sanitize("address"))) \ + __attribute__((__used__)) = { \ + .name = ORIGINAL_SONAME, \ + .onload_func = pre_merge_jni_library_wrapper_for_JNI_OnLoad, \ + }; \ + \ + /* Re-start the JNI_OnLoad prototype to capture the body. */ \ static jint pre_merge_original_JNI_OnLoad diff --git a/packages/react-native/ReactAndroid/src/main/jni/first-party/yogajni/jni/YGJNIVanilla.cpp b/packages/react-native/ReactAndroid/src/main/jni/first-party/yogajni/jni/YGJNIVanilla.cpp index e164c96c38b..c5fdd8c7913 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/first-party/yogajni/jni/YGJNIVanilla.cpp +++ b/packages/react-native/ReactAndroid/src/main/jni/first-party/yogajni/jni/YGJNIVanilla.cpp @@ -454,8 +454,9 @@ static void jni_YGNodeCopyStyleJNI( #define YG_NODE_JNI_STYLE_EDGE_UNIT_PROP(name) \ static jlong jni_YGNodeStyleGet##name##JNI( \ JNIEnv* /*env*/, jobject /*obj*/, jlong nativePointer, jint edge) { \ - return YogaValue::asJavaLong(YGNodeStyleGet##name( \ - _jlong2YGNodeRef(nativePointer), static_cast(edge))); \ + return YogaValue::asJavaLong( \ + YGNodeStyleGet##name( \ + _jlong2YGNodeRef(nativePointer), static_cast(edge))); \ } \ \ static void jni_YGNodeStyleSet##name##JNI( \ diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/devsupport/JCxxInspectorPackagerConnection.h b/packages/react-native/ReactAndroid/src/main/jni/react/devsupport/JCxxInspectorPackagerConnection.h index 79793b75114..26d29aac4a0 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/devsupport/JCxxInspectorPackagerConnection.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/devsupport/JCxxInspectorPackagerConnection.h @@ -20,11 +20,9 @@ namespace facebook::react::jsinspector_modern { * A hybrid Java/C++ class that exposes an instance of * InspectorPackagerConnection to Java. */ -class JCxxInspectorPackagerConnection - : public jni::HybridClass { +class JCxxInspectorPackagerConnection : public jni::HybridClass { public: - constexpr static auto kJavaDescriptor = - "Lcom/facebook/react/devsupport/CxxInspectorPackagerConnection;"; + constexpr static auto kJavaDescriptor = "Lcom/facebook/react/devsupport/CxxInspectorPackagerConnection;"; static void registerNatives(); @@ -32,7 +30,7 @@ class JCxxInspectorPackagerConnection void connect(); void closeQuietly(); - void sendEventToAllConnections(const std::string& event); + void sendEventToAllConnections(const std::string &event); private: friend HybridBase; @@ -43,16 +41,16 @@ class JCxxInspectorPackagerConnection * Private constructor since this class can only be created from Java. */ JCxxInspectorPackagerConnection( - const std::string& url, - const std::string& deviceName, - const std::string& packageName, + const std::string &url, + const std::string &deviceName, + const std::string &packageName, jni::alias_ref delegate); static jni::local_ref initHybrid( jni::alias_ref /*unused*/, - const std::string& url, - const std::string& deviceName, - const std::string& packageName, + const std::string &url, + const std::string &deviceName, + const std::string &packageName, jni::alias_ref delegate); /** diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/devsupport/JCxxInspectorPackagerConnectionDelegateImpl.h b/packages/react-native/ReactAndroid/src/main/jni/react/devsupport/JCxxInspectorPackagerConnectionDelegateImpl.h index 087c5ecb579..7ce5c5899d6 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/devsupport/JCxxInspectorPackagerConnectionDelegateImpl.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/devsupport/JCxxInspectorPackagerConnectionDelegateImpl.h @@ -28,39 +28,31 @@ namespace facebook::react::jsinspector_modern { struct JCxxInspectorPackagerConnectionDelegateImpl : public jni::JavaClass { public: - static auto constexpr kJavaDescriptor = - "Lcom/facebook/react/devsupport/CxxInspectorPackagerConnection$DelegateImpl;"; + static auto constexpr kJavaDescriptor = "Lcom/facebook/react/devsupport/CxxInspectorPackagerConnection$DelegateImpl;"; std::unique_ptr wrapInUniquePtr(); // InspectorPackagerConnectionDelegate methods (mirrored) - std::unique_ptr connectWebSocket( - const std::string& url, - std::weak_ptr delegate); + std::unique_ptr connectWebSocket(const std::string &url, std::weak_ptr delegate); - void scheduleCallback( - std::function callback, - std::chrono::milliseconds delayMs); + void scheduleCallback(std::function callback, std::chrono::milliseconds delayMs); private: class RefWrapper; }; -class JCxxInspectorPackagerConnectionDelegateImpl::RefWrapper - : public InspectorPackagerConnectionDelegate { +class JCxxInspectorPackagerConnectionDelegateImpl::RefWrapper : public InspectorPackagerConnectionDelegate { public: explicit RefWrapper(jni::alias_ref jDelegate); // InspectorPackagerConnectionDelegate methods virtual std::unique_ptr connectWebSocket( - const std::string& url, + const std::string &url, std::weak_ptr delegate) override; - virtual void scheduleCallback( - std::function callback, - std::chrono::milliseconds delayMs) override; + virtual void scheduleCallback(std::function callback, std::chrono::milliseconds delayMs) override; private: jni::global_ref jDelegate_; diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/devsupport/JCxxInspectorPackagerConnectionWebSocket.h b/packages/react-native/ReactAndroid/src/main/jni/react/devsupport/JCxxInspectorPackagerConnectionWebSocket.h index d73b360fb8a..6d75450f88a 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/devsupport/JCxxInspectorPackagerConnectionWebSocket.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/devsupport/JCxxInspectorPackagerConnectionWebSocket.h @@ -22,11 +22,9 @@ namespace facebook::react::jsinspector_modern { * usable IWebSocket instance from this object, call * wrapInUniquePtr(). */ -class JCxxInspectorPackagerConnectionWebSocket - : public jni::JavaClass { +class JCxxInspectorPackagerConnectionWebSocket : public jni::JavaClass { public: - static auto constexpr kJavaDescriptor = - "Lcom/facebook/react/devsupport/CxxInspectorPackagerConnection$IWebSocket;"; + static auto constexpr kJavaDescriptor = "Lcom/facebook/react/devsupport/CxxInspectorPackagerConnection$IWebSocket;"; ~JCxxInspectorPackagerConnectionWebSocket(); diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/devsupport/JCxxInspectorPackagerConnectionWebSocketDelegate.h b/packages/react-native/ReactAndroid/src/main/jni/react/devsupport/JCxxInspectorPackagerConnectionWebSocketDelegate.h index 0335f7a2de9..3fc7c0caa68 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/devsupport/JCxxInspectorPackagerConnectionWebSocketDelegate.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/devsupport/JCxxInspectorPackagerConnectionWebSocketDelegate.h @@ -20,17 +20,14 @@ namespace facebook::react::jsinspector_modern { * IWebSocketDelegate to Java. */ class JCxxInspectorPackagerConnectionWebSocketDelegate - : public jni::HybridClass< - JCxxInspectorPackagerConnectionWebSocketDelegate> { + : public jni::HybridClass { public: static auto constexpr kJavaDescriptor = "Lcom/facebook/react/devsupport/CxxInspectorPackagerConnection$WebSocketDelegate;"; - void didFailWithError( - jni::alias_ref posixCode, - const std::string& error); + void didFailWithError(jni::alias_ref posixCode, const std::string &error); - void didReceiveMessage(const std::string& message); + void didReceiveMessage(const std::string &message); void didOpen(); @@ -38,8 +35,7 @@ class JCxxInspectorPackagerConnectionWebSocketDelegate static void registerNatives(); - JCxxInspectorPackagerConnectionWebSocketDelegate( - std::weak_ptr cxxDelegate); + JCxxInspectorPackagerConnectionWebSocketDelegate(std::weak_ptr cxxDelegate); private: friend HybridBase; diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/devsupport/JInspectorFlags.h b/packages/react-native/ReactAndroid/src/main/jni/react/devsupport/JInspectorFlags.h index 0874ccf3ac3..4541665e2ca 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/devsupport/JInspectorFlags.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/devsupport/JInspectorFlags.h @@ -16,8 +16,7 @@ namespace facebook::react::jsinspector_modern { */ class JInspectorFlags : public jni::JavaClass { public: - static constexpr auto kJavaDescriptor = - "Lcom/facebook/react/devsupport/InspectorFlags;"; + static constexpr auto kJavaDescriptor = "Lcom/facebook/react/devsupport/InspectorFlags;"; static bool getFuseboxEnabled(jni::alias_ref /*unused*/); static bool getIsProfilingBuild(jni::alias_ref /*unused*/); diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/devsupport/JInspectorNetworkReporter.h b/packages/react-native/ReactAndroid/src/main/jni/react/devsupport/JInspectorNetworkReporter.h index 95f9dd6a2e2..3d50c5b044f 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/devsupport/JInspectorNetworkReporter.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/devsupport/JInspectorNetworkReporter.h @@ -11,11 +11,9 @@ namespace facebook::react::jsinspector_modern { -class JInspectorNetworkReporter - : public jni::HybridClass { +class JInspectorNetworkReporter : public jni::HybridClass { public: - static constexpr auto kJavaDescriptor = - "Lcom/facebook/react/modules/network/InspectorNetworkReporter;"; + static constexpr auto kJavaDescriptor = "Lcom/facebook/react/modules/network/InspectorNetworkReporter;"; static jboolean isDebuggingEnabled(jni::alias_ref /*unused*/); @@ -41,20 +39,14 @@ class JInspectorNetworkReporter jni::alias_ref> responseHeaders, jlong encodedDataLength); - static void reportDataReceivedImpl( - jni::alias_ref /*unused*/, - jni::alias_ref requestId, - jint dataLength); + static void + reportDataReceivedImpl(jni::alias_ref /*unused*/, jni::alias_ref requestId, jint dataLength); - static void reportResponseEnd( - jni::alias_ref /*unused*/, - jni::alias_ref requestId, - jlong encodedDataLength); + static void + reportResponseEnd(jni::alias_ref /*unused*/, jni::alias_ref requestId, jlong encodedDataLength); - static void reportRequestFailed( - jni::alias_ref /*unused*/, - jni::alias_ref requestId, - jboolean cancelled); + static void + reportRequestFailed(jni::alias_ref /*unused*/, jni::alias_ref requestId, jboolean cancelled); static void maybeStoreResponseBodyImpl( jni::alias_ref /*unused*/, diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/fabric/AndroidEventBeat.h b/packages/react-native/ReactAndroid/src/main/jni/react/fabric/AndroidEventBeat.h index b093a7cf841..8f5a2ce92d0 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/fabric/AndroidEventBeat.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/fabric/AndroidEventBeat.h @@ -13,13 +13,12 @@ namespace facebook::react { -class AndroidEventBeat final : public EventBeat, - public EventBeatManagerObserver { +class AndroidEventBeat final : public EventBeat, public EventBeatManagerObserver { public: AndroidEventBeat( std::shared_ptr ownerBox, - EventBeatManager* eventBeatManager, - RuntimeScheduler& runtimeScheduler, + EventBeatManager *eventBeatManager, + RuntimeScheduler &runtimeScheduler, jni::global_ref javaUIManager); ~AndroidEventBeat() override; @@ -29,7 +28,7 @@ class AndroidEventBeat final : public EventBeat, void request() const override; private: - EventBeatManager* eventBeatManager_; + EventBeatManager *eventBeatManager_; jni::global_ref javaUIManager_; }; diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/fabric/ComponentFactory.h b/packages/react-native/ReactAndroid/src/main/jni/react/fabric/ComponentFactory.h index c87780f3f96..e6b72a28173 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/fabric/ComponentFactory.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/fabric/ComponentFactory.h @@ -17,16 +17,14 @@ class Instance; class ComponentFactory : public jni::HybridClass { public: - constexpr static const char* const kJavaDescriptor = - "Lcom/facebook/react/fabric/ComponentFactory;"; + constexpr static const char *const kJavaDescriptor = "Lcom/facebook/react/fabric/ComponentFactory;"; static void registerNatives(); ComponentRegistryFactory buildRegistryFunction; private: - static jni::local_ref initHybrid( - jni::alias_ref /*unused*/); + static jni::local_ref initHybrid(jni::alias_ref /*unused*/); }; } // namespace facebook::react diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/fabric/CoreComponentsRegistry.cpp b/packages/react-native/ReactAndroid/src/main/jni/react/fabric/CoreComponentsRegistry.cpp index 940f0cd6573..6df5502d223 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/fabric/CoreComponentsRegistry.cpp +++ b/packages/react-native/ReactAndroid/src/main/jni/react/fabric/CoreComponentsRegistry.cpp @@ -39,14 +39,18 @@ sharedProviderRegistry() { void addCoreComponents( std::shared_ptr providerRegistry) { - providerRegistry->add(concreteComponentDescriptorProvider< - AndroidProgressBarComponentDescriptor>()); - providerRegistry->add(concreteComponentDescriptorProvider< - AndroidSwipeRefreshLayoutComponentDescriptor>()); - providerRegistry->add(concreteComponentDescriptorProvider< - ActivityIndicatorViewComponentDescriptor>()); - providerRegistry->add(concreteComponentDescriptorProvider< - AndroidTextInputComponentDescriptor>()); + providerRegistry->add( + concreteComponentDescriptorProvider< + AndroidProgressBarComponentDescriptor>()); + providerRegistry->add( + concreteComponentDescriptorProvider< + AndroidSwipeRefreshLayoutComponentDescriptor>()); + providerRegistry->add( + concreteComponentDescriptorProvider< + ActivityIndicatorViewComponentDescriptor>()); + providerRegistry->add( + concreteComponentDescriptorProvider< + AndroidTextInputComponentDescriptor>()); providerRegistry->add( concreteComponentDescriptorProvider()); providerRegistry->add( @@ -68,16 +72,20 @@ void addCoreComponents( AndroidHorizontalScrollContentViewComponentDescriptor>()); providerRegistry->add( concreteComponentDescriptorProvider()); - providerRegistry->add(concreteComponentDescriptorProvider< - AndroidDrawerLayoutComponentDescriptor>()); - providerRegistry->add(concreteComponentDescriptorProvider< - DebuggingOverlayComponentDescriptor>()); - providerRegistry->add(concreteComponentDescriptorProvider< - LayoutConformanceComponentDescriptor>()); + providerRegistry->add( + concreteComponentDescriptorProvider< + AndroidDrawerLayoutComponentDescriptor>()); + providerRegistry->add( + concreteComponentDescriptorProvider< + DebuggingOverlayComponentDescriptor>()); + providerRegistry->add( + concreteComponentDescriptorProvider< + LayoutConformanceComponentDescriptor>()); providerRegistry->add( concreteComponentDescriptorProvider()); - providerRegistry->add(concreteComponentDescriptorProvider< - VirtualViewExperimentalComponentDescriptor>()); + providerRegistry->add( + concreteComponentDescriptorProvider< + VirtualViewExperimentalComponentDescriptor>()); } } // namespace facebook::react::CoreComponentsRegistry diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/fabric/CoreComponentsRegistry.h b/packages/react-native/ReactAndroid/src/main/jni/react/fabric/CoreComponentsRegistry.h index da6653c86bc..36eec9bbae7 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/fabric/CoreComponentsRegistry.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/fabric/CoreComponentsRegistry.h @@ -11,10 +11,8 @@ namespace facebook::react::CoreComponentsRegistry { -std::shared_ptr -sharedProviderRegistry(); +std::shared_ptr sharedProviderRegistry(); -void addCoreComponents( - std::shared_ptr registry); +void addCoreComponents(std::shared_ptr registry); } // namespace facebook::react::CoreComponentsRegistry diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/fabric/EventBeatManager.h b/packages/react-native/ReactAndroid/src/main/jni/react/fabric/EventBeatManager.h index 78059248060..d056cc9feca 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/fabric/EventBeatManager.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/fabric/EventBeatManager.h @@ -27,8 +27,7 @@ class EventBeatManagerObserver { class EventBeatManager : public jni::HybridClass { public: - constexpr static const char* const kJavaDescriptor = - "Lcom/facebook/react/fabric/events/EventBeatManager;"; + constexpr static const char *const kJavaDescriptor = "Lcom/facebook/react/fabric/events/EventBeatManager;"; static void registerNatives(); @@ -37,8 +36,8 @@ class EventBeatManager : public jni::HybridClass { * `EventBeatManager` does not own/retain observers; observers must overlive * the manager or be properly removed before deallocation. */ - void addObserver(const EventBeatManagerObserver& observer) const; - void removeObserver(const EventBeatManagerObserver& observer) const; + void addObserver(const EventBeatManagerObserver &observer) const; + void removeObserver(const EventBeatManagerObserver &observer) const; private: /* @@ -46,8 +45,7 @@ class EventBeatManager : public jni::HybridClass { */ void tick(); - mutable std::unordered_set - observers_{}; // Protected by `mutex_` + mutable std::unordered_set observers_{}; // Protected by `mutex_` mutable std::mutex mutex_; diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/fabric/EventEmitterWrapper.h b/packages/react-native/ReactAndroid/src/main/jni/react/fabric/EventEmitterWrapper.h index e2b79938e04..20bed32f575 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/fabric/EventEmitterWrapper.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/fabric/EventEmitterWrapper.h @@ -17,19 +17,17 @@ class Instance; class EventEmitterWrapper : public jni::HybridClass { public: - constexpr static const char* const kJavaDescriptor = - "Lcom/facebook/react/fabric/events/EventEmitterWrapper;"; + constexpr static const char *const kJavaDescriptor = "Lcom/facebook/react/fabric/events/EventEmitterWrapper;"; static void registerNatives(); - EventEmitterWrapper(SharedEventEmitter eventEmitter) - : eventEmitter(std::move(eventEmitter)){}; + EventEmitterWrapper(SharedEventEmitter eventEmitter) : eventEmitter(std::move(eventEmitter)) {}; SharedEventEmitter eventEmitter; - void dispatchEvent(std::string eventName, NativeMap* payload, int category); - void dispatchEventSynchronously(std::string eventName, NativeMap* params); - void dispatchUniqueEvent(std::string eventName, NativeMap* payload); + void dispatchEvent(std::string eventName, NativeMap *payload, int category); + void dispatchEventSynchronously(std::string eventName, NativeMap *params); + void dispatchUniqueEvent(std::string eventName, NativeMap *payload); }; } // namespace facebook::react diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/fabric/FabricMountingManager.cpp b/packages/react-native/ReactAndroid/src/main/jni/react/fabric/FabricMountingManager.cpp index 54b7f76572d..a8196314710 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/fabric/FabricMountingManager.cpp +++ b/packages/react-native/ReactAndroid/src/main/jni/react/fabric/FabricMountingManager.cpp @@ -286,9 +286,10 @@ inline void writeMountItemPreamble( if (numItems == 1) { buffer.writeInt(mountItemType); } else { - buffer.writeIntArray(std::array{ - mountItemType | CppMountItem::Type::Multiple, - static_cast(numItems)}); + buffer.writeIntArray( + std::array{ + mountItemType | CppMountItem::Type::Multiple, + static_cast(numItems)}); } } @@ -319,11 +320,12 @@ inline void writeCreateMountItem( auto javaEventEmitter = EventEmitterWrapper::newObjectCxxArgs( mountItem.newChildShadowView.eventEmitter); - buffer.writeObjectsArray(std::array{ - componentName.get(), - props.get(), - javaStateWrapper != nullptr ? javaStateWrapper.get() : nullptr, - javaEventEmitter.get()}); + buffer.writeObjectsArray( + std::array{ + componentName.get(), + props.get(), + javaStateWrapper != nullptr ? javaStateWrapper.get() : nullptr, + javaEventEmitter.get()}); } inline void writeDeleteMountItem( @@ -335,15 +337,21 @@ inline void writeDeleteMountItem( inline void writeInsertMountItem( InstructionBuffer& buffer, const CppMountItem& mountItem) { - buffer.writeIntArray(std::array{ - mountItem.newChildShadowView.tag, mountItem.parentTag, mountItem.index}); + buffer.writeIntArray( + std::array{ + mountItem.newChildShadowView.tag, + mountItem.parentTag, + mountItem.index}); } inline void writeRemoveMountItem( InstructionBuffer& buffer, const CppMountItem& mountItem) { - buffer.writeIntArray(std::array{ - mountItem.oldChildShadowView.tag, mountItem.parentTag, mountItem.index}); + buffer.writeIntArray( + std::array{ + mountItem.oldChildShadowView.tag, + mountItem.parentTag, + mountItem.index}); } inline void writeUpdatePropsMountItem( @@ -387,15 +395,16 @@ inline void writeUpdateLayoutMountItem( int w = round(scale(frame.size.width, pointScaleFactor)); int h = round(scale(frame.size.height, pointScaleFactor)); - buffer.writeIntArray(std::array{ - mountItem.newChildShadowView.tag, - mountItem.parentTag, - x, - y, - w, - h, - toInt(layoutMetrics.displayType), - toInt(layoutMetrics.layoutDirection)}); + buffer.writeIntArray( + std::array{ + mountItem.newChildShadowView.tag, + mountItem.parentTag, + x, + y, + w, + h, + toInt(layoutMetrics.displayType), + toInt(layoutMetrics.layoutDirection)}); } inline void writeUpdateEventEmitterMountItem( @@ -421,12 +430,13 @@ inline void writeUpdatePaddingMountItem( int insetRight = floor(scale(contentInsets.right, pointScaleFactor)); int insetBottom = floor(scale(contentInsets.bottom, pointScaleFactor)); - buffer.writeIntArray(std::array{ - mountItem.newChildShadowView.tag, - insetLeft, - insetTop, - insetRight, - insetBottom}); + buffer.writeIntArray( + std::array{ + mountItem.newChildShadowView.tag, + insetLeft, + insetTop, + insetRight, + insetBottom}); } inline void writeUpdateOverflowInsetMountItem( @@ -442,12 +452,13 @@ inline void writeUpdateOverflowInsetMountItem( int overflowInsetBottom = round(scale(overflowInset.bottom, pointScaleFactor)); - buffer.writeIntArray(std::array{ - mountItem.newChildShadowView.tag, - overflowInsetLeft, - overflowInsetTop, - overflowInsetRight, - overflowInsetBottom}); + buffer.writeIntArray( + std::array{ + mountItem.newChildShadowView.tag, + overflowInsetLeft, + overflowInsetTop, + overflowInsetRight, + overflowInsetBottom}); } } // namespace @@ -520,8 +531,9 @@ void FabricMountingManager::executeMount( } case ShadowViewMutation::Remove: { if (!isVirtual) { - cppCommonMountItems.push_back(CppMountItem::RemoveMountItem( - parentTag, oldChildShadowView, index)); + cppCommonMountItems.push_back( + CppMountItem::RemoveMountItem( + parentTag, oldChildShadowView, index)); } break; } @@ -544,8 +556,9 @@ void FabricMountingManager::executeMount( if (oldChildShadowView.props != newChildShadowView.props) { (maintainMutationOrder ? cppCommonMountItems : cppUpdatePropsMountItems) - .push_back(CppMountItem::UpdatePropsMountItem( - oldChildShadowView, newChildShadowView)); + .push_back( + CppMountItem::UpdatePropsMountItem( + oldChildShadowView, newChildShadowView)); } if (oldChildShadowView.state != newChildShadowView.state) { (maintainMutationOrder ? cppCommonMountItems @@ -570,8 +583,9 @@ void FabricMountingManager::executeMount( newChildShadowView.layoutMetrics) { (maintainMutationOrder ? cppCommonMountItems : cppUpdateLayoutMountItems) - .push_back(CppMountItem::UpdateLayoutMountItem( - mutation.newChildShadowView, parentTag)); + .push_back( + CppMountItem::UpdateLayoutMountItem( + mutation.newChildShadowView, parentTag)); } // OverflowInset: This is the values indicating boundaries including @@ -582,8 +596,9 @@ void FabricMountingManager::executeMount( newChildShadowView.layoutMetrics.overflowInset)) { (maintainMutationOrder ? cppCommonMountItems : cppUpdateOverflowInsetMountItems) - .push_back(CppMountItem::UpdateOverflowInsetMountItem( - newChildShadowView)); + .push_back( + CppMountItem::UpdateOverflowInsetMountItem( + newChildShadowView)); } } @@ -591,16 +606,18 @@ void FabricMountingManager::executeMount( newChildShadowView.eventEmitter) { (maintainMutationOrder ? cppCommonMountItems : cppUpdatePropsMountItems) - .push_back(CppMountItem::UpdateEventEmitterMountItem( - mutation.newChildShadowView)); + .push_back( + CppMountItem::UpdateEventEmitterMountItem( + mutation.newChildShadowView)); } break; } case ShadowViewMutation::Insert: { if (!isVirtual) { // Insert item - cppCommonMountItems.push_back(CppMountItem::InsertMountItem( - parentTag, newChildShadowView, index)); + cppCommonMountItems.push_back( + CppMountItem::InsertMountItem( + parentTag, newChildShadowView, index)); bool shouldCreateView = !allocatedViewTags.contains(newChildShadowView.tag); @@ -612,16 +629,18 @@ void FabricMountingManager::executeMount( } (maintainMutationOrder ? cppCommonMountItems : cppUpdatePropsMountItems) - .push_back(CppMountItem::UpdatePropsMountItem( - {}, newChildShadowView)); + .push_back( + CppMountItem::UpdatePropsMountItem( + {}, newChildShadowView)); } else { if (shouldCreateView) { LOG(ERROR) << "Emitting insert for unallocated view " << newChildShadowView.tag; (maintainMutationOrder ? cppCommonMountItems : cppUpdatePropsMountItems) - .push_back(CppMountItem::UpdatePropsMountItem( - {}, newChildShadowView)); + .push_back( + CppMountItem::UpdatePropsMountItem( + {}, newChildShadowView)); } } @@ -648,8 +667,9 @@ void FabricMountingManager::executeMount( // Layout (maintainMutationOrder ? cppCommonMountItems : cppUpdateLayoutMountItems) - .push_back(CppMountItem::UpdateLayoutMountItem( - newChildShadowView, parentTag)); + .push_back( + CppMountItem::UpdateLayoutMountItem( + newChildShadowView, parentTag)); // OverflowInset: This is the values indicating boundaries including // children of the current view. The layout of current view may not @@ -659,8 +679,9 @@ void FabricMountingManager::executeMount( EdgeInsets::ZERO) { (maintainMutationOrder ? cppCommonMountItems : cppUpdateOverflowInsetMountItems) - .push_back(CppMountItem::UpdateOverflowInsetMountItem( - newChildShadowView)); + .push_back( + CppMountItem::UpdateOverflowInsetMountItem( + newChildShadowView)); } } @@ -669,8 +690,9 @@ void FabricMountingManager::executeMount( // it in when preallocating views (maintainMutationOrder ? cppCommonMountItems : cppUpdateEventEmitterMountItems) - .push_back(CppMountItem::UpdateEventEmitterMountItem( - mutation.newChildShadowView)); + .push_back( + CppMountItem::UpdateEventEmitterMountItem( + mutation.newChildShadowView)); break; } @@ -1010,8 +1032,9 @@ void FabricMountingManager::dispatchCommand( ->getMethod( "dispatchCommand"); auto command = jni::make_jstring(commandName); - auto argsArray = jni::adopt_local(reinterpret_cast( - ReadableNativeArray::newObjectCxxArgs(args).release())); + auto argsArray = jni::adopt_local( + reinterpret_cast( + ReadableNativeArray::newObjectCxxArgs(args).release())); dispatchCommand( javaUIManager_, shadowView.surfaceId, diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/fabric/FabricMountingManager.h b/packages/react-native/ReactAndroid/src/main/jni/react/fabric/FabricMountingManager.h index 3ae20c2370f..9fd87538d16 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/fabric/FabricMountingManager.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/fabric/FabricMountingManager.h @@ -22,18 +22,17 @@ struct ShadowView; class FabricMountingManager final { public: - FabricMountingManager( - jni::global_ref& javaUIManager); - FabricMountingManager(const FabricMountingManager&) = delete; + FabricMountingManager(jni::global_ref &javaUIManager); + FabricMountingManager(const FabricMountingManager &) = delete; ~FabricMountingManager(); void onSurfaceStart(SurfaceId surfaceId); void onSurfaceStop(SurfaceId surfaceId); - void maybePreallocateShadowNode(const ShadowNode& shadowNode); + void maybePreallocateShadowNode(const ShadowNode &shadowNode); - void destroyUnmountedShadowNode(const ShadowNodeFamily& family); + void destroyUnmountedShadowNode(const ShadowNodeFamily &family); /* * Drains preallocatedViewsQueue_ by calling preallocateShadowView on each @@ -41,29 +40,19 @@ class FabricMountingManager final { */ void drainPreallocateViewsQueue(); - void executeMount(const MountingTransaction& transaction); + void executeMount(const MountingTransaction &transaction); - void dispatchCommand( - const ShadowView& shadowView, - const std::string& commandName, - const folly::dynamic& args); + void dispatchCommand(const ShadowView &shadowView, const std::string &commandName, const folly::dynamic &args); - void sendAccessibilityEvent( - const ShadowView& shadowView, - const std::string& eventType); + void sendAccessibilityEvent(const ShadowView &shadowView, const std::string &eventType); - void setIsJSResponder( - const ShadowView& shadowView, - bool isJSResponder, - bool blockNativeResponder); + void setIsJSResponder(const ShadowView &shadowView, bool isJSResponder, bool blockNativeResponder); void onAnimationStarted(); void onAllAnimationsComplete(); - void synchronouslyUpdateViewOnUIThread( - Tag viewTag, - const folly::dynamic& props); + void synchronouslyUpdateViewOnUIThread(Tag viewTag, const folly::dynamic &props); private: bool isOnMainThread(); @@ -82,15 +71,14 @@ class FabricMountingManager final { */ std::vector preallocatedViewsQueue_{}; - std::unordered_map> - allocatedViewRegistry_{}; + std::unordered_map> allocatedViewRegistry_{}; std::recursive_mutex allocatedViewsMutex_; /* * Calls FabricUIManager.preallocateView() on the Java side if view needs to * be preallocated. */ - void preallocateShadowView(const ShadowView& shadowView); + void preallocateShadowView(const ShadowView &shadowView); }; } // namespace facebook::react diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/fabric/FabricUIManagerBinding.h b/packages/react-native/ReactAndroid/src/main/jni/react/fabric/FabricUIManagerBinding.h index 39e724038c6..29adfde41ce 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/fabric/FabricUIManagerBinding.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/fabric/FabricUIManagerBinding.h @@ -37,8 +37,7 @@ class FabricUIManagerBinding : public jni::HybridClass, public SchedulerDelegate, public LayoutAnimationStatusDelegate { public: - constexpr static const char* const kJavaDescriptor = - "Lcom/facebook/react/fabric/FabricUIManagerBinding;"; + constexpr static const char *const kJavaDescriptor = "Lcom/facebook/react/fabric/FabricUIManagerBinding;"; static void registerNatives(); @@ -65,18 +64,15 @@ class FabricUIManagerBinding : public jni::HybridClass, jni::alias_ref runtimeExecutorHolder, jni::alias_ref runtimeSchedulerHolder, jni::alias_ref javaUIManager, - EventBeatManager* eventBeatManager, - ComponentFactory* componentsRegistry); + EventBeatManager *eventBeatManager, + ComponentFactory *componentsRegistry); - void startSurface( - jint surfaceId, - jni::alias_ref moduleName, - NativeMap* initialProps); + void startSurface(jint surfaceId, jni::alias_ref moduleName, NativeMap *initialProps); void startSurfaceWithConstraints( jint surfaceId, jni::alias_ref moduleName, - NativeMap* initialProps, + NativeMap *initialProps, jfloat minWidth, jfloat maxWidth, jfloat minHeight, @@ -90,44 +86,31 @@ class FabricUIManagerBinding : public jni::HybridClass, void startSurfaceWithSurfaceHandler( jint surfaceId, - jni::alias_ref - surfaceHandlerBinding, + jni::alias_ref surfaceHandlerBinding, jboolean isMountable); - void stopSurfaceWithSurfaceHandler( - jni::alias_ref surfaceHandler); + void stopSurfaceWithSurfaceHandler(jni::alias_ref surfaceHandler); - void schedulerDidFinishTransaction( - const std::shared_ptr& mountingCoordinator) - override; + void schedulerDidFinishTransaction(const std::shared_ptr &mountingCoordinator) override; void schedulerShouldRenderTransactions( - const std::shared_ptr& mountingCoordinator) - override; + const std::shared_ptr &mountingCoordinator) override; - void schedulerDidRequestPreliminaryViewAllocation( - const ShadowNode& shadowNode) override; + void schedulerDidRequestPreliminaryViewAllocation(const ShadowNode &shadowNode) override; void schedulerDidDispatchCommand( - const ShadowView& shadowView, - const std::string& commandName, - const folly::dynamic& args) override; + const ShadowView &shadowView, + const std::string &commandName, + const folly::dynamic &args) override; - void schedulerDidSendAccessibilityEvent( - const ShadowView& shadowView, - const std::string& eventType) override; + void schedulerDidSendAccessibilityEvent(const ShadowView &shadowView, const std::string &eventType) override; - void schedulerDidSetIsJSResponder( - const ShadowView& shadowView, - bool isJSResponder, - bool blockNativeResponder) override; + void schedulerDidSetIsJSResponder(const ShadowView &shadowView, bool isJSResponder, bool blockNativeResponder) + override; - void schedulerShouldSynchronouslyUpdateViewOnUIThread( - Tag tag, - const folly::dynamic& props) override; + void schedulerShouldSynchronouslyUpdateViewOnUIThread(Tag tag, const folly::dynamic &props) override; - void schedulerDidUpdateShadowTree( - const std::unordered_map& tagToProps) override; + void schedulerDidUpdateShadowTree(const std::unordered_map &tagToProps) override; void setPixelDensity(float pointScaleFactor); @@ -137,8 +120,7 @@ class FabricUIManagerBinding : public jni::HybridClass, void reportMount(SurfaceId surfaceId); - jint - findNextFocusableElement(jint parentTag, jint focusedTag, jint direction); + jint findNextFocusableElement(jint parentTag, jint focusedTag, jint direction); jintArray getRelativeAncestorList(jint rootTag, jint childTag); @@ -149,8 +131,7 @@ class FabricUIManagerBinding : public jni::HybridClass, std::shared_ptr mountingManager_; std::shared_ptr scheduler_; - std::shared_ptr getMountingManager( - const char* locationHint); + std::shared_ptr getMountingManager(const char *locationHint); // LayoutAnimations void onAnimationStarted() override; @@ -161,14 +142,9 @@ class FabricUIManagerBinding : public jni::HybridClass, // Roots not created through ReactSurface (non-bridgeless) will store their // SurfaceHandler here, for other roots we keep a weak reference to the Java // owner - std::unordered_map< - SurfaceId, - std::variant< - SurfaceHandler, - jni::weak_ref>> + std::unordered_map>> surfaceHandlerRegistry_{}; - std::shared_mutex - surfaceHandlerRegistryMutex_; // Protects `surfaceHandlerRegistry_`. + std::shared_mutex surfaceHandlerRegistryMutex_; // Protects `surfaceHandlerRegistry_`. // Track pending transactions, one per surfaceId std::mutex pendingTransactionsMutex_; diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/fabric/FocusOrderingHelper.h b/packages/react-native/ReactAndroid/src/main/jni/react/fabric/FocusOrderingHelper.h index cd15298685c..802ba169978 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/fabric/FocusOrderingHelper.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/fabric/FocusOrderingHelper.h @@ -22,17 +22,17 @@ enum class FocusDirection { class FocusOrderingHelper { public: static void traverseAndUpdateNextFocusableElement( - const std::shared_ptr& parentShadowNode, - const std::shared_ptr& focusedShadowNode, - const std::shared_ptr& currNode, + const std::shared_ptr &parentShadowNode, + const std::shared_ptr &focusedShadowNode, + const std::shared_ptr &currNode, FocusDirection focusDirection, - const UIManager& uimanager, + const UIManager &uimanager, Rect sourceRect, - std::optional& nextRect, - std::shared_ptr& nextNode); + std::optional &nextRect, + std::shared_ptr &nextNode); static std::shared_ptr findShadowNodeByTagRecursively( - const std::shared_ptr& parentShadowNode, + const std::shared_ptr &parentShadowNode, Tag tag); static std::optional resolveFocusDirection(int direction); diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/fabric/JFabricUIManager.h b/packages/react-native/ReactAndroid/src/main/jni/react/fabric/JFabricUIManager.h index c19701fe871..16e3bf8fb20 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/fabric/JFabricUIManager.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/fabric/JFabricUIManager.h @@ -15,10 +15,9 @@ class FabricUIManagerBinding; class JFabricUIManager : public jni::JavaClass { public: - static constexpr auto kJavaDescriptor = - "Lcom/facebook/react/fabric/FabricUIManager;"; + static constexpr auto kJavaDescriptor = "Lcom/facebook/react/fabric/FabricUIManager;"; - FabricUIManagerBinding* getBinding(); + FabricUIManagerBinding *getBinding(); }; } // namespace facebook::react diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/fabric/MountItem.h b/packages/react-native/ReactAndroid/src/main/jni/react/fabric/MountItem.h index ad115be9161..3384e4df3b4 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/fabric/MountItem.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/fabric/MountItem.h @@ -13,39 +13,31 @@ namespace facebook::react { struct JMountItem : public jni::JavaClass { - static constexpr auto kJavaDescriptor = - "Lcom/facebook/react/fabric/mounting/mountitems/MountItem;"; + static constexpr auto kJavaDescriptor = "Lcom/facebook/react/fabric/mounting/mountitems/MountItem;"; }; struct CppMountItem final { #pragma mark - Designated Initializers - static CppMountItem CreateMountItem(const ShadowView& shadowView); + static CppMountItem CreateMountItem(const ShadowView &shadowView); - static CppMountItem DeleteMountItem(const ShadowView& shadowView); + static CppMountItem DeleteMountItem(const ShadowView &shadowView); - static CppMountItem - InsertMountItem(Tag parentTag, const ShadowView& shadowView, int index); + static CppMountItem InsertMountItem(Tag parentTag, const ShadowView &shadowView, int index); - static CppMountItem - RemoveMountItem(Tag parentTag, const ShadowView& shadowView, int index); + static CppMountItem RemoveMountItem(Tag parentTag, const ShadowView &shadowView, int index); - static CppMountItem UpdatePropsMountItem( - const ShadowView& oldShadowView, - const ShadowView& newShadowView); + static CppMountItem UpdatePropsMountItem(const ShadowView &oldShadowView, const ShadowView &newShadowView); - static CppMountItem UpdateStateMountItem(const ShadowView& shadowView); + static CppMountItem UpdateStateMountItem(const ShadowView &shadowView); - static CppMountItem UpdateLayoutMountItem( - const ShadowView& shadowView, - Tag parentTag); + static CppMountItem UpdateLayoutMountItem(const ShadowView &shadowView, Tag parentTag); - static CppMountItem UpdateEventEmitterMountItem(const ShadowView& shadowView); + static CppMountItem UpdateEventEmitterMountItem(const ShadowView &shadowView); - static CppMountItem UpdatePaddingMountItem(const ShadowView& shadowView); + static CppMountItem UpdatePaddingMountItem(const ShadowView &shadowView); - static CppMountItem UpdateOverflowInsetMountItem( - const ShadowView& shadowView); + static CppMountItem UpdateOverflowInsetMountItem(const ShadowView &shadowView); #pragma mark - Type diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/fabric/StateWrapperImpl.h b/packages/react-native/ReactAndroid/src/main/jni/react/fabric/StateWrapperImpl.h index b15f65b0314..0fd1de93b43 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/fabric/StateWrapperImpl.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/fabric/StateWrapperImpl.h @@ -18,17 +18,15 @@ class Instance; class StateWrapperImpl : public jni::HybridClass { public: - constexpr static const char* const kJavaDescriptor = - "Lcom/facebook/react/fabric/StateWrapperImpl;"; - constexpr static auto StateWrapperImplJavaDescriptor = - "com/facebook/react/fabric/StateWrapperImpl"; + constexpr static const char *const kJavaDescriptor = "Lcom/facebook/react/fabric/StateWrapperImpl;"; + constexpr static auto StateWrapperImplJavaDescriptor = "com/facebook/react/fabric/StateWrapperImpl"; static void registerNatives(); jni::local_ref getStateMapBufferDataImpl(); jni::local_ref getStateDataImpl(); jni::local_ref getStateDataReferenceImpl(); - void updateStateImpl(NativeMap* map); + void updateStateImpl(NativeMap *map); void setState(std::shared_ptr state); std::shared_ptr getState() const; diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/fabric/SurfaceHandlerBinding.h b/packages/react-native/ReactAndroid/src/main/jni/react/fabric/SurfaceHandlerBinding.h index 3e6f9f61d6c..fe687d148ab 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/fabric/SurfaceHandlerBinding.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/fabric/SurfaceHandlerBinding.h @@ -17,12 +17,11 @@ namespace facebook::react { class SurfaceHandlerBinding : public jni::HybridClass { public: - constexpr static const char* const kJavaDescriptor = - "Lcom/facebook/react/fabric/SurfaceHandlerBinding;"; + constexpr static const char *const kJavaDescriptor = "Lcom/facebook/react/fabric/SurfaceHandlerBinding;"; static void registerNatives(); - SurfaceHandlerBinding(SurfaceId surfaceId, const std::string& moduleName); + SurfaceHandlerBinding(SurfaceId surfaceId, const std::string &moduleName); void setDisplayMode(jint mode); @@ -43,17 +42,14 @@ class SurfaceHandlerBinding : public jni::HybridClass { jfloat pixelDensity, jfloat fontScale); - void setProps(NativeMap* props); + void setProps(NativeMap *props); - const SurfaceHandler& getSurfaceHandler(); + const SurfaceHandler &getSurfaceHandler(); private: const SurfaceHandler surfaceHandler_; - static void initHybrid( - jni::alias_ref jobj, - jint surfaceId, - jni::alias_ref moduleName); + static void initHybrid(jni::alias_ref jobj, jint surfaceId, jni::alias_ref moduleName); }; } // namespace facebook::react diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/hermes/instrumentation/HermesMemoryDumper.h b/packages/react-native/ReactAndroid/src/main/jni/react/hermes/instrumentation/HermesMemoryDumper.h index b1bd30874b5..16a7f7b034c 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/hermes/instrumentation/HermesMemoryDumper.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/hermes/instrumentation/HermesMemoryDumper.h @@ -16,30 +16,29 @@ namespace jni = ::facebook::jni; class HermesMemoryDumper : public jni::JavaClass { public: - constexpr static auto kJavaDescriptor = - "Lcom/facebook/hermes/instrumentation/HermesMemoryDumper;"; + constexpr static auto kJavaDescriptor = "Lcom/facebook/hermes/instrumentation/HermesMemoryDumper;"; - bool shouldSaveSnapshot() { - static auto shouldSaveSnapshotMethod = - javaClassStatic()->getMethod("shouldSaveSnapshot"); + bool shouldSaveSnapshot() + { + static auto shouldSaveSnapshotMethod = javaClassStatic()->getMethod("shouldSaveSnapshot"); return shouldSaveSnapshotMethod(self()); } - std::string getInternalStorage() { - static auto getInternalStorageMethod = - javaClassStatic()->getMethod("getInternalStorage"); + std::string getInternalStorage() + { + static auto getInternalStorageMethod = javaClassStatic()->getMethod("getInternalStorage"); return getInternalStorageMethod(self())->toStdString(); } - std::string getId() { - static auto getInternalStorageMethod = - javaClassStatic()->getMethod("getId"); + std::string getId() + { + static auto getInternalStorageMethod = javaClassStatic()->getMethod("getId"); return getInternalStorageMethod(self())->toStdString(); } - void setMetaData(std::string crashId) { - static auto getIdMethod = - javaClassStatic()->getMethod("setMetaData"); + void setMetaData(std::string crashId) + { + static auto getIdMethod = javaClassStatic()->getMethod("setMetaData"); getIdMethod(self(), crashId); } }; diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/hermes/instrumentation/HermesSamplingProfiler.h b/packages/react-native/ReactAndroid/src/main/jni/react/hermes/instrumentation/HermesSamplingProfiler.h index 4cfb0e8fc34..3b06dcf26dd 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/hermes/instrumentation/HermesSamplingProfiler.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/hermes/instrumentation/HermesSamplingProfiler.h @@ -17,13 +17,10 @@ namespace jni = ::facebook::jni; class HermesSamplingProfiler : public jni::JavaClass { public: - constexpr static auto kJavaDescriptor = - "Lcom/facebook/hermes/instrumentation/HermesSamplingProfiler;"; + constexpr static auto kJavaDescriptor = "Lcom/facebook/hermes/instrumentation/HermesSamplingProfiler;"; static void enable(jni::alias_ref /*unused*/); static void disable(jni::alias_ref /*unused*/); - static void dumpSampledTraceToFile( - jni::alias_ref /*unused*/, - const std::string& filename); + static void dumpSampledTraceToFile(jni::alias_ref /*unused*/, const std::string &filename); static void registerNatives(); diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/hermes/reactexecutor/OnLoad.cpp b/packages/react-native/ReactAndroid/src/main/jni/react/hermes/reactexecutor/OnLoad.cpp index 92e97d0694b..53d76082651 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/hermes/reactexecutor/OnLoad.cpp +++ b/packages/react-native/ReactAndroid/src/main/jni/react/hermes/reactexecutor/OnLoad.cpp @@ -45,7 +45,8 @@ static void installBindings(jsi::Runtime& runtime) { } class [[deprecated( - "This API will be removed along with the legacy architecture.")]] HermesExecutorHolder + "This API will be removed along with the legacy architecture.")]] +HermesExecutorHolder : public jni::HybridClass { public: static constexpr auto kJavaDescriptor = diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/jni/CatalystInstanceImpl.cpp b/packages/react-native/ReactAndroid/src/main/jni/react/jni/CatalystInstanceImpl.cpp index a9515165a13..cc618247533 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/jni/CatalystInstanceImpl.cpp +++ b/packages/react-native/ReactAndroid/src/main/jni/react/jni/CatalystInstanceImpl.cpp @@ -46,8 +46,8 @@ namespace facebook::react { namespace { class [[deprecated( - "This API will be removed along with the legacy architecture.")]] InstanceCallbackImpl - : public InstanceCallback { + "This API will be removed along with the legacy architecture.")]] +InstanceCallbackImpl : public InstanceCallback { public: explicit InstanceCallbackImpl(alias_ref jobj) : jobj_(make_global(jobj)) {} @@ -380,8 +380,8 @@ CatalystInstanceImpl::getNativeMethodCallInvokerHolder() { std::shared_ptr decoratedNativeMethodCallInvoker = instance_->getDecoratedNativeMethodCallInvoker(nativeMethodCallInvoker); - nativeMethodCallInvokerHolder_ = - jni::make_global(NativeMethodCallInvokerHolder::newObjectCxxArgs( + nativeMethodCallInvokerHolder_ = jni::make_global( + NativeMethodCallInvokerHolder::newObjectCxxArgs( decoratedNativeMethodCallInvoker)); } diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/jni/CatalystInstanceImpl.h b/packages/react-native/ReactAndroid/src/main/jni/react/jni/CatalystInstanceImpl.h index 327c5e4583e..2993161ac7a 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/jni/CatalystInstanceImpl.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/jni/CatalystInstanceImpl.h @@ -29,26 +29,22 @@ class Instance; class JavaScriptExecutorHolder; class NativeArray; -struct [[deprecated( - "This API will be removed along with the legacy architecture.")]] JInstanceCallback +struct [[deprecated("This API will be removed along with the legacy architecture.")]] JInstanceCallback : public jni::JavaClass { - static constexpr auto kJavaDescriptor = - "Lcom/facebook/react/bridge/CatalystInstanceImpl$InstanceCallback;"; + static constexpr auto kJavaDescriptor = "Lcom/facebook/react/bridge/CatalystInstanceImpl$InstanceCallback;"; }; -class [[deprecated( - "This API will be removed along with the legacy architecture.")]] CatalystInstanceImpl +class [[deprecated("This API will be removed along with the legacy architecture.")]] CatalystInstanceImpl : public jni::HybridClass { public: - static constexpr auto kJavaDescriptor = - "Lcom/facebook/react/bridge/CatalystInstanceImpl;"; + static constexpr auto kJavaDescriptor = "Lcom/facebook/react/bridge/CatalystInstanceImpl;"; - static jni::local_ref initHybrid( - jni::alias_ref /*unused*/); + static jni::local_ref initHybrid(jni::alias_ref /*unused*/); static void registerNatives(); - std::shared_ptr getInstance() { + std::shared_ptr getInstance() + { return instance_; } @@ -60,53 +56,40 @@ class [[deprecated( void initializeBridge( jni::alias_ref callback, // This executor is actually a factory holder. - JavaScriptExecutorHolder* jseh, + JavaScriptExecutorHolder *jseh, jni::alias_ref jsQueue, jni::alias_ref nativeModulesQueue, - jni::alias_ref< - jni::JCollection::javaobject> - javaModules, - jni::alias_ref::javaobject> - cxxModules, - jni::alias_ref - inspectorTarget); + jni::alias_ref::javaobject> javaModules, + jni::alias_ref::javaobject> cxxModules, + jni::alias_ref inspectorTarget); void extendNativeModules( - jni::alias_ref::javaobject> javaModules, - jni::alias_ref::javaobject> - cxxModules); + jni::alias_ref::javaobject> javaModules, + jni::alias_ref::javaobject> cxxModules); /** * Sets the source URL of the underlying bridge without loading any JS code. */ - void jniSetSourceURL(const std::string& sourceURL); + void jniSetSourceURL(const std::string &sourceURL); /** * Registers the file path of an additional JS segment by its ID. * */ - void jniRegisterSegment(int segmentId, const std::string& path); + void jniRegisterSegment(int segmentId, const std::string &path); void jniLoadScriptFromAssets( jni::alias_ref assetManager, - const std::string& assetURL, + const std::string &assetURL, bool loadSynchronously); - void jniLoadScriptFromFile( - const std::string& fileName, - const std::string& sourceURL, - bool loadSynchronously); - void jniCallJSFunction( - std::string module, - std::string method, - NativeArray* arguments); - void jniCallJSCallback(jint callbackId, NativeArray* arguments); + void jniLoadScriptFromFile(const std::string &fileName, const std::string &sourceURL, bool loadSynchronously); + void jniCallJSFunction(std::string module, std::string method, NativeArray *arguments); + void jniCallJSCallback(jint callbackId, NativeArray *arguments); jni::alias_ref getJSCallInvokerHolder(); - jni::alias_ref - getNativeMethodCallInvokerHolder(); + jni::alias_ref getNativeMethodCallInvokerHolder(); jni::alias_ref getRuntimeExecutor(); jni::alias_ref getRuntimeScheduler(); - void setGlobalVariable(std::string propName, std::string&& jsonValue); + void setGlobalVariable(std::string propName, std::string &&jsonValue); jlong getJavaScriptContext(); void handleMemoryPressure(int pressureLevel); @@ -125,8 +108,7 @@ class [[deprecated( std::shared_ptr moduleRegistry_; std::shared_ptr moduleMessageQueue_; jni::global_ref jsCallInvokerHolder_; - jni::global_ref - nativeMethodCallInvokerHolder_; + jni::global_ref nativeMethodCallInvokerHolder_; jni::global_ref runtimeExecutor_; jni::global_ref runtimeScheduler_; }; diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/jni/CxxModuleWrapper.h b/packages/react-native/ReactAndroid/src/main/jni/react/jni/CxxModuleWrapper.h index 80747e18f8d..70c9f3bc843 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/jni/CxxModuleWrapper.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/jni/CxxModuleWrapper.h @@ -11,26 +11,25 @@ namespace facebook::react { -class CxxModuleWrapper - : public jni::HybridClass { +class CxxModuleWrapper : public jni::HybridClass { public: - constexpr static const char* const kJavaDescriptor = - "Lcom/facebook/react/bridge/CxxModuleWrapper;"; + constexpr static const char *const kJavaDescriptor = "Lcom/facebook/react/bridge/CxxModuleWrapper;"; - std::string getName() override { + std::string getName() override + { return module_->getName(); } // This steals ownership of the underlying module for use by the C++ bridge - std::unique_ptr getModule() override { + std::unique_ptr getModule() override + { return std::move(module_); } protected: friend HybridBase; - explicit CxxModuleWrapper(std::unique_ptr module) - : module_(std::move(module)) {} + explicit CxxModuleWrapper(std::unique_ptr module) : module_(std::move(module)) {} std::unique_ptr module_; }; diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/jni/CxxModuleWrapperBase.h b/packages/react-native/ReactAndroid/src/main/jni/react/jni/CxxModuleWrapperBase.h index dc1954f1ba3..4cc38e86a39 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/jni/CxxModuleWrapperBase.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/jni/CxxModuleWrapperBase.h @@ -16,23 +16,20 @@ namespace facebook::react { struct JNativeModule : jni::JavaClass { - constexpr static const char* const kJavaDescriptor = - "Lcom/facebook/react/bridge/NativeModule;"; + constexpr static const char *const kJavaDescriptor = "Lcom/facebook/react/bridge/NativeModule;"; }; /** * The C++ part of a CxxModuleWrapper is not a unique class, but it * must extend this base class. */ -class CxxModuleWrapperBase - : public jni::HybridClass { +class CxxModuleWrapperBase : public jni::HybridClass { public: - constexpr static const char* const kJavaDescriptor = - "Lcom/facebook/react/bridge/CxxModuleWrapperBase;"; + constexpr static const char *const kJavaDescriptor = "Lcom/facebook/react/bridge/CxxModuleWrapperBase;"; - static void registerNatives() { - registerHybrid( - {makeNativeMethod("getName", CxxModuleWrapperBase::getName)}); + static void registerNatives() + { + registerHybrid({makeNativeMethod("getName", CxxModuleWrapperBase::getName)}); } // JNI method diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/jni/InspectorNetworkRequestListener.h b/packages/react-native/ReactAndroid/src/main/jni/react/jni/InspectorNetworkRequestListener.h index 48745a0dba5..8bf97abce2a 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/jni/InspectorNetworkRequestListener.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/jni/InspectorNetworkRequestListener.h @@ -15,17 +15,13 @@ namespace facebook::react { -class InspectorNetworkRequestListener - : public jni::HybridClass { +class InspectorNetworkRequestListener : public jni::HybridClass { public: - static constexpr auto kJavaDescriptor = - "Lcom/facebook/react/devsupport/inspector/InspectorNetworkRequestListener;"; + static constexpr auto kJavaDescriptor = "Lcom/facebook/react/devsupport/inspector/InspectorNetworkRequestListener;"; static void registerNatives(); - void onHeaders( - jint httpStatusCode, - jni::alias_ref> headers); + void onHeaders(jint httpStatusCode, jni::alias_ref> headers); void onData(jni::alias_ref data); void onError(jni::alias_ref message); void onCompletion(); @@ -34,11 +30,9 @@ class InspectorNetworkRequestListener friend HybridBase; InspectorNetworkRequestListener( - jsinspector_modern::ScopedExecutor< - jsinspector_modern::NetworkRequestListener> executor); + jsinspector_modern::ScopedExecutor executor); - jsinspector_modern::ScopedExecutor - executor_; + jsinspector_modern::ScopedExecutor executor_; }; } // namespace facebook::react diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/jni/JCallback.h b/packages/react-native/ReactAndroid/src/main/jni/react/jni/JCallback.h index f052c2cd83d..bde467d4a7e 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/jni/JCallback.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/jni/JCallback.h @@ -19,16 +19,15 @@ namespace facebook::react { class Instance; struct JCallback : public jni::JavaClass { - constexpr static auto kJavaDescriptor = - "Lcom/facebook/react/bridge/Callback;"; + constexpr static auto kJavaDescriptor = "Lcom/facebook/react/bridge/Callback;"; }; class JCxxCallbackImpl : public jni::HybridClass { public: - constexpr static auto kJavaDescriptor = - "Lcom/facebook/react/bridge/CxxCallbackImpl;"; + constexpr static auto kJavaDescriptor = "Lcom/facebook/react/bridge/CxxCallbackImpl;"; - static void registerNatives() { + static void registerNatives() + { registerHybrid({ makeNativeMethod("nativeInvoke", JCxxCallbackImpl::invoke), }); @@ -40,7 +39,8 @@ class JCxxCallbackImpl : public jni::HybridClass { using Callback = std::function; JCxxCallbackImpl(Callback callback) : callback_(std::move(callback)) {} - void invoke(NativeArray* arguments) { + void invoke(NativeArray *arguments) + { callback_(arguments->consume()); } diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/jni/JDynamicNative.cpp b/packages/react-native/ReactAndroid/src/main/jni/react/jni/JDynamicNative.cpp index 49df6e43f49..a6c1b52a077 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/jni/JDynamicNative.cpp +++ b/packages/react-native/ReactAndroid/src/main/jni/react/jni/JDynamicNative.cpp @@ -34,13 +34,16 @@ jdouble JDynamicNative::asDouble() { } jni::local_ref JDynamicNative::asArray() { - return jni::adopt_local(reinterpret_cast( - ReadableNativeArray::newObjectCxxArgs(payload_).release())); + return jni::adopt_local( + reinterpret_cast( + ReadableNativeArray::newObjectCxxArgs(payload_).release())); } jni::local_ref JDynamicNative::asMap() { - return jni::adopt_local(reinterpret_cast( - ReadableNativeMap::createWithContents(std::move(payload_)).release())); + return jni::adopt_local( + reinterpret_cast( + ReadableNativeMap::createWithContents(std::move(payload_)) + .release())); } } // namespace facebook::react diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/jni/JDynamicNative.h b/packages/react-native/ReactAndroid/src/main/jni/react/jni/JDynamicNative.h index 8b05243fc22..1ba0d485c0b 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/jni/JDynamicNative.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/jni/JDynamicNative.h @@ -23,12 +23,12 @@ struct JDynamic : public jni::JavaClass { class JDynamicNative : public jni::HybridClass { public: - constexpr static auto kJavaDescriptor = - "Lcom/facebook/react/bridge/DynamicNative;"; + constexpr static auto kJavaDescriptor = "Lcom/facebook/react/bridge/DynamicNative;"; JDynamicNative(folly::dynamic payload) : payload_(std::move(payload)) {} - static void registerNatives() { + static void registerNatives() + { javaClassStatic()->registerNatives( {makeNativeMethod("isNullNative", JDynamicNative::isNullNative), makeNativeMethod("getTypeNative", JDynamicNative::getTypeNative), diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/jni/JMessageQueueThread.h b/packages/react-native/ReactAndroid/src/main/jni/react/jni/JMessageQueueThread.h index 716e58b0a7b..cd506810351 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/jni/JMessageQueueThread.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/jni/JMessageQueueThread.h @@ -16,8 +16,7 @@ namespace facebook::react { class JavaMessageQueueThread : public jni::JavaClass { public: - static constexpr auto kJavaDescriptor = - "Lcom/facebook/react/bridge/queue/MessageQueueThread;"; + static constexpr auto kJavaDescriptor = "Lcom/facebook/react/bridge/queue/MessageQueueThread;"; }; class JMessageQueueThread : public MessageQueueThread { @@ -27,14 +26,14 @@ class JMessageQueueThread : public MessageQueueThread { /** * Enqueues the given function to run on this MessageQueueThread. */ - void runOnQueue(std::function&& runnable) override; + void runOnQueue(std::function &&runnable) override; /** * Synchronously executes the given function to run on this * MessageQueueThread, waiting until it completes. Can be called from any * thread, but will block if not called on this MessageQueueThread. */ - void runOnQueueSync(std::function&& runnable) override; + void runOnQueueSync(std::function &&runnable) override; /** * Synchronously quits the current MessageQueueThread. Can be called from any diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/jni/JReactCxxErrorHandler.h b/packages/react-native/ReactAndroid/src/main/jni/react/jni/JReactCxxErrorHandler.h index e54dbde8338..b50a0580ae2 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/jni/JReactCxxErrorHandler.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/jni/JReactCxxErrorHandler.h @@ -14,8 +14,7 @@ namespace facebook::react { class JReactCxxErrorHandler : public jni::JavaClass { public: - static constexpr const char* kJavaDescriptor = - "Lcom/facebook/react/bridge/ReactCxxErrorHandler;"; + static constexpr const char *kJavaDescriptor = "Lcom/facebook/react/bridge/ReactCxxErrorHandler;"; static void handleError(std::string message); }; diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/jni/JReactMarker.h b/packages/react-native/ReactAndroid/src/main/jni/react/jni/JReactMarker.h index aab4af4d8c3..2f621482328 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/jni/JReactMarker.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/jni/JReactMarker.h @@ -16,30 +16,18 @@ namespace facebook::react { class JReactMarker : public facebook::jni::JavaClass { public: - static constexpr auto kJavaDescriptor = - "Lcom/facebook/react/bridge/ReactMarker;"; + static constexpr auto kJavaDescriptor = "Lcom/facebook/react/bridge/ReactMarker;"; static void registerNatives(); static void setLogPerfMarkerIfNeeded(); private: - static void logMarker(const std::string& marker); - static void logMarker(const std::string& marker, const std::string& tag); - static void - logMarker(const std::string& marker, const std::string& tag, int instanceKey); - static void logPerfMarker( - ReactMarker::ReactMarkerId markerId, - const char* tag); - static void logPerfMarkerBridgeless( - ReactMarker::ReactMarkerId markerId, - const char* tag); - static void logPerfMarkerWithInstanceKey( - ReactMarker::ReactMarkerId markerId, - const char* tag, - int instanceKey); - static void nativeLogMarker( - jni::alias_ref /* unused */, - const std::string& markerNameStr, - jlong markerTime); + static void logMarker(const std::string &marker); + static void logMarker(const std::string &marker, const std::string &tag); + static void logMarker(const std::string &marker, const std::string &tag, int instanceKey); + static void logPerfMarker(ReactMarker::ReactMarkerId markerId, const char *tag); + static void logPerfMarkerBridgeless(ReactMarker::ReactMarkerId markerId, const char *tag); + static void logPerfMarkerWithInstanceKey(ReactMarker::ReactMarkerId markerId, const char *tag, int instanceKey); + static void nativeLogMarker(jni::alias_ref /* unused */, const std::string &markerNameStr, jlong markerTime); }; } // namespace facebook::react diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/jni/JReactSoftExceptionLogger.h b/packages/react-native/ReactAndroid/src/main/jni/react/jni/JReactSoftExceptionLogger.h index c8ea6e1d442..29342660799 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/jni/JReactSoftExceptionLogger.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/jni/JReactSoftExceptionLogger.h @@ -12,15 +12,11 @@ namespace facebook::react { -class JReactSoftExceptionLogger - : public jni::JavaClass { +class JReactSoftExceptionLogger : public jni::JavaClass { public: - static constexpr const char* kJavaDescriptor = - "Lcom/facebook/react/bridge/ReactSoftExceptionLogger;"; + static constexpr const char *kJavaDescriptor = "Lcom/facebook/react/bridge/ReactSoftExceptionLogger;"; - static void logNoThrowSoftExceptionWithMessage( - std::string tag, - std::string message); + static void logNoThrowSoftExceptionWithMessage(std::string tag, std::string message); }; } // namespace facebook::react diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/jni/JRuntimeExecutor.h b/packages/react-native/ReactAndroid/src/main/jni/react/jni/JRuntimeExecutor.h index b614ad1a1fe..9caffec9c43 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/jni/JRuntimeExecutor.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/jni/JRuntimeExecutor.h @@ -14,8 +14,7 @@ namespace facebook::react { class JRuntimeExecutor : public jni::HybridClass { public: - static auto constexpr kJavaDescriptor = - "Lcom/facebook/react/bridge/RuntimeExecutor;"; + static auto constexpr kJavaDescriptor = "Lcom/facebook/react/bridge/RuntimeExecutor;"; RuntimeExecutor get(); diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/jni/JRuntimeScheduler.h b/packages/react-native/ReactAndroid/src/main/jni/react/jni/JRuntimeScheduler.h index 6220ccedda3..69537d43f01 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/jni/JRuntimeScheduler.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/jni/JRuntimeScheduler.h @@ -14,8 +14,7 @@ namespace facebook::react { class JRuntimeScheduler : public jni::HybridClass { public: - static auto constexpr kJavaDescriptor = - "Lcom/facebook/react/bridge/RuntimeScheduler;"; + static auto constexpr kJavaDescriptor = "Lcom/facebook/react/bridge/RuntimeScheduler;"; std::weak_ptr get(); diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/jni/JSLoader.cpp b/packages/react-native/ReactAndroid/src/main/jni/react/jni/JSLoader.cpp index ca575dedd6d..15be4c408bc 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/jni/JSLoader.cpp +++ b/packages/react-native/ReactAndroid/src/main/jni/react/jni/JSLoader.cpp @@ -19,7 +19,7 @@ namespace facebook::react { class AssetManagerString : public JSBigString { public: - AssetManagerString(AAsset* asset) : asset_(asset){}; + AssetManagerString(AAsset* asset) : asset_(asset) {}; ~AssetManagerString() override { AAsset_close(asset_); diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/jni/JSLoader.h b/packages/react-native/ReactAndroid/src/main/jni/react/jni/JSLoader.h index 1d18db4722f..4c0135bfe20 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/jni/JSLoader.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/jni/JSLoader.h @@ -22,11 +22,8 @@ struct JAssetManager : jni::JavaClass { /** * Helper method for loading JS script from android asset */ -AAssetManager* extractAssetManager( - jni::alias_ref assetManager); +AAssetManager *extractAssetManager(jni::alias_ref assetManager); -std::unique_ptr loadScriptFromAssets( - AAssetManager* assetManager, - const std::string& assetName); +std::unique_ptr loadScriptFromAssets(AAssetManager *assetManager, const std::string &assetName); } // namespace facebook::react diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/jni/JSLogging.h b/packages/react-native/ReactAndroid/src/main/jni/react/jni/JSLogging.h index 423e5896b64..2217203f141 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/jni/JSLogging.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/jni/JSLogging.h @@ -11,6 +11,6 @@ namespace facebook::react { -void reactAndroidLoggingHook(const std::string& message, unsigned int logLevel); +void reactAndroidLoggingHook(const std::string &message, unsigned int logLevel); } // namespace facebook::react diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/jni/JWeakRefUtils.h b/packages/react-native/ReactAndroid/src/main/jni/react/jni/JWeakRefUtils.h index 6674afb9cfb..66db613fb2b 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/jni/JWeakRefUtils.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/jni/JWeakRefUtils.h @@ -15,8 +15,8 @@ namespace facebook::react { * Helper for constructing a JWeakReference. \see JWeakReference.h in fbjni. */ template -inline jni::local_ref> makeJWeakReference( - jni::alias_ref ref) { +inline jni::local_ref> makeJWeakReference(jni::alias_ref ref) +{ return jni::JWeakReference::newInstance(ref); } diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/jni/JavaModuleWrapper.h b/packages/react-native/ReactAndroid/src/main/jni/react/jni/JavaModuleWrapper.h index ca751e6b8ad..2239ee57980 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/jni/JavaModuleWrapper.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/jni/JavaModuleWrapper.h @@ -20,11 +20,9 @@ namespace facebook::react { class Instance; class MessageQueueThread; -struct [[deprecated( - "This API will be removed along with the legacy architecture.")]] JMethodDescriptor +struct [[deprecated("This API will be removed along with the legacy architecture.")]] JMethodDescriptor : public jni::JavaClass { - static constexpr auto kJavaDescriptor = - "Lcom/facebook/react/bridge/JavaModuleWrapper$MethodDescriptor;"; + static constexpr auto kJavaDescriptor = "Lcom/facebook/react/bridge/JavaModuleWrapper$MethodDescriptor;"; jni::local_ref getMethod() const; std::string getSignature() const; @@ -32,39 +30,33 @@ struct [[deprecated( std::string getType() const; }; -struct [[deprecated( - "This API will be removed along with the legacy architecture.")]] JavaModuleWrapper +struct [[deprecated("This API will be removed along with the legacy architecture.")]] JavaModuleWrapper : jni::JavaClass { - static constexpr auto kJavaDescriptor = - "Lcom/facebook/react/bridge/JavaModuleWrapper;"; + static constexpr auto kJavaDescriptor = "Lcom/facebook/react/bridge/JavaModuleWrapper;"; - jni::local_ref getModule() { + jni::local_ref getModule() + { // This is the call which causes a lazy Java module to actually be // created. - static auto getModule = - javaClassStatic()->getMethod( - "getModule"); + static auto getModule = javaClassStatic()->getMethod("getModule"); return getModule(self()); } - std::string getName() const { + std::string getName() const + { static auto getName = javaClassStatic()->getMethod("getName"); return getName(self())->toStdString(); } - jni::local_ref::javaobject> - getMethodDescriptors() { + jni::local_ref::javaobject> getMethodDescriptors() + { static auto getMethods = - getClass() - ->getMethod< - jni::JList::javaobject()>( - "getMethodDescriptors"); + getClass()->getMethod::javaobject()>("getMethodDescriptors"); return getMethods(self()); } }; -class [[deprecated( - "This API will be removed along with the legacy architecture.")]] JavaNativeModule +class [[deprecated("This API will be removed along with the legacy architecture.")]] JavaNativeModule : public NativeModule { public: JavaNativeModule( @@ -73,17 +65,16 @@ class [[deprecated( std::shared_ptr messageQueueThread) : instance_(std::move(instance)), wrapper_(make_global(wrapper)), - messageQueueThread_(std::move(messageQueueThread)) {} + messageQueueThread_(std::move(messageQueueThread)) + { + } std::string getName() override; std::string getSyncMethodName(unsigned int reactMethodId) override; folly::dynamic getConstants() override; std::vector getMethods() override; - void invoke(unsigned int reactMethodId, folly::dynamic&& params, int callId) - override; - MethodCallResult callSerializableNativeHook( - unsigned int reactMethodId, - folly::dynamic&& params) override; + void invoke(unsigned int reactMethodId, folly::dynamic &¶ms, int callId) override; + MethodCallResult callSerializableNativeHook(unsigned int reactMethodId, folly::dynamic &¶ms) override; private: std::weak_ptr instance_; diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/jni/JavaScriptExecutorHolder.h b/packages/react-native/ReactAndroid/src/main/jni/react/jni/JavaScriptExecutorHolder.h index 5849b42cf5c..d144398244f 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/jni/JavaScriptExecutorHolder.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/jni/JavaScriptExecutorHolder.h @@ -14,20 +14,18 @@ namespace facebook::react { -class [[deprecated( - "This API will be removed along with the legacy architecture.")]] JavaScriptExecutorHolder +class [[deprecated("This API will be removed along with the legacy architecture.")]] JavaScriptExecutorHolder : public jni::HybridClass { public: - static constexpr auto kJavaDescriptor = - "Lcom/facebook/react/bridge/JavaScriptExecutor;"; + static constexpr auto kJavaDescriptor = "Lcom/facebook/react/bridge/JavaScriptExecutor;"; - std::shared_ptr getExecutorFactory() { + std::shared_ptr getExecutorFactory() + { return mExecutorFactory; } protected: - JavaScriptExecutorHolder(std::shared_ptr factory) - : mExecutorFactory(factory) {} + JavaScriptExecutorHolder(std::shared_ptr factory) : mExecutorFactory(factory) {} private: std::shared_ptr mExecutorFactory; diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/jni/JniJSModulesUnbundle.h b/packages/react-native/ReactAndroid/src/main/jni/react/jni/JniJSModulesUnbundle.h index 57a7a04aebf..3c246e47d5e 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/jni/JniJSModulesUnbundle.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/jni/JniJSModulesUnbundle.h @@ -16,31 +16,24 @@ namespace facebook::react { -class [[deprecated( - "This API will be removed along with the legacy architecture.")]] JniJSModulesUnbundle +class [[deprecated("This API will be removed along with the legacy architecture.")]] JniJSModulesUnbundle : public JSModulesUnbundle { /** * This implementation reads modules as single file from the assets of an apk. */ public: JniJSModulesUnbundle() = default; - JniJSModulesUnbundle( - AAssetManager* assetManager, - std::string moduleDirectory); - JniJSModulesUnbundle(JniJSModulesUnbundle&& other) = delete; - JniJSModulesUnbundle& operator=(JSModulesUnbundle&& other) = delete; + JniJSModulesUnbundle(AAssetManager *assetManager, std::string moduleDirectory); + JniJSModulesUnbundle(JniJSModulesUnbundle &&other) = delete; + JniJSModulesUnbundle &operator=(JSModulesUnbundle &&other) = delete; - static std::unique_ptr fromEntryFile( - AAssetManager* assetManager, - const std::string& entryFile); + static std::unique_ptr fromEntryFile(AAssetManager *assetManager, const std::string &entryFile); - static bool isUnbundle( - AAssetManager* assetManager, - const std::string& assetName); + static bool isUnbundle(AAssetManager *assetManager, const std::string &assetName); virtual Module getModule(uint32_t moduleId) const override; private: - AAssetManager* m_assetManager = nullptr; + AAssetManager *m_assetManager = nullptr; std::string m_moduleDirectory; }; diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/jni/MethodInvoker.h b/packages/react-native/ReactAndroid/src/main/jni/react/jni/MethodInvoker.h index b2f8b8cc0d4..bdefb6a068f 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/jni/MethodInvoker.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/jni/MethodInvoker.h @@ -19,27 +19,24 @@ namespace facebook::react { class Instance; -struct [[deprecated( - "This API will be removed along with the legacy architecture.")]] JReflectMethod +struct [[deprecated("This API will be removed along with the legacy architecture.")]] JReflectMethod : public jni::JavaClass { static constexpr auto kJavaDescriptor = "Ljava/lang/reflect/Method;"; - jmethodID getMethodID() { + jmethodID getMethodID() + { auto id = jni::Environment::current()->FromReflectedMethod(self()); jni::throwPendingJniExceptionAsCppException(); return id; } }; -struct [[deprecated( - "This API will be removed along with the legacy architecture.")]] JBaseJavaModule +struct [[deprecated("This API will be removed along with the legacy architecture.")]] JBaseJavaModule : public jni::JavaClass { - static constexpr auto kJavaDescriptor = - "Lcom/facebook/react/bridge/BaseJavaModule;"; + static constexpr auto kJavaDescriptor = "Lcom/facebook/react/bridge/BaseJavaModule;"; }; -class [[deprecated( - "This API will be removed along with the legacy architecture.")]] MethodInvoker { +class [[deprecated("This API will be removed along with the legacy architecture.")]] MethodInvoker { public: MethodInvoker( jni::alias_ref method, @@ -49,13 +46,14 @@ class [[deprecated( bool isSync); MethodCallResult invoke( - std::weak_ptr& instance, + std::weak_ptr &instance, jni::alias_ref module, - const folly::dynamic& params); + const folly::dynamic ¶ms); std::string getMethodName() const; - bool isSyncHook() const { + bool isSyncHook() const + { return isSync_; } diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/jni/ModuleRegistryBuilder.cpp b/packages/react-native/ReactAndroid/src/main/jni/react/jni/ModuleRegistryBuilder.cpp index c6e5bb385f4..3b08f442bcb 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/jni/ModuleRegistryBuilder.cpp +++ b/packages/react-native/ReactAndroid/src/main/jni/react/jni/ModuleRegistryBuilder.cpp @@ -52,18 +52,20 @@ std::vector> buildNativeModuleList( std::vector> modules; if (javaModules) { for (const auto& jm : *javaModules) { - modules.emplace_back(std::make_unique( - winstance, jm, moduleMessageQueue)); + modules.emplace_back( + std::make_unique( + winstance, jm, moduleMessageQueue)); } } if (cxxModules) { for (const auto& cm : *cxxModules) { std::string moduleName = cm->getName(); - modules.emplace_back(std::make_unique( - winstance, - moduleName, - cm->getProvider(moduleName), - moduleMessageQueue)); + modules.emplace_back( + std::make_unique( + winstance, + moduleName, + cm->getProvider(moduleName), + moduleMessageQueue)); } } return modules; diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/jni/ModuleRegistryBuilder.h b/packages/react-native/ReactAndroid/src/main/jni/react/jni/ModuleRegistryBuilder.h index 6b46cc00151..ebc905ba633 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/jni/ModuleRegistryBuilder.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/jni/ModuleRegistryBuilder.h @@ -20,25 +20,20 @@ namespace facebook::react { class MessageQueueThread; -class [[deprecated( - "This API will be removed along with the legacy architecture.")]] ModuleHolder +class [[deprecated("This API will be removed along with the legacy architecture.")]] ModuleHolder : public jni::JavaClass { public: - static auto constexpr kJavaDescriptor = - "Lcom/facebook/react/bridge/ModuleHolder;"; + static auto constexpr kJavaDescriptor = "Lcom/facebook/react/bridge/ModuleHolder;"; std::string getName() const; - xplat::module::CxxModule::Provider getProvider( - const std::string& moduleName) const; + xplat::module::CxxModule::Provider getProvider(const std::string &moduleName) const; }; [[deprecated("This API will be removed along with the legacy architecture.")]] std::vector> buildNativeModuleList( std::weak_ptr winstance, - jni::alias_ref::javaobject> - javaModules, - jni::alias_ref::javaobject> - cxxModules, + jni::alias_ref::javaobject> javaModules, + jni::alias_ref::javaobject> cxxModules, std::shared_ptr moduleMessageQueue); } // namespace facebook::react diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/jni/NativeArray.h b/packages/react-native/ReactAndroid/src/main/jni/react/jni/NativeArray.h index 738738437b0..792dee8b21d 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/jni/NativeArray.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/jni/NativeArray.h @@ -16,12 +16,12 @@ namespace facebook::react { class NativeArray : public jni::HybridClass { public: - static auto constexpr* kJavaDescriptor = - "Lcom/facebook/react/bridge/NativeArray;"; + static auto constexpr *kJavaDescriptor = "Lcom/facebook/react/bridge/NativeArray;"; jni::local_ref toString(); - const folly::dynamic& getArray() const { + const folly::dynamic &getArray() const + { return array_; } @@ -39,16 +39,16 @@ class NativeArray : public jni::HybridClass { friend HybridBase; template - explicit NativeArray(Dyn&& array) - : isConsumed(false), array_(std::forward(array)) { + explicit NativeArray(Dyn &&array) : isConsumed(false), array_(std::forward(array)) + { assertInternalType(); } void assertInternalType(); void throwIfConsumed(); - NativeArray(const NativeArray&) = delete; - NativeArray& operator=(const NativeArray&) = delete; + NativeArray(const NativeArray &) = delete; + NativeArray &operator=(const NativeArray &) = delete; }; } // namespace facebook::react diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/jni/NativeCommon.h b/packages/react-native/ReactAndroid/src/main/jni/react/jni/NativeCommon.h index b3b7bc0f45a..8f79c5db679 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/jni/NativeCommon.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/jni/NativeCommon.h @@ -17,21 +17,20 @@ namespace facebook::react { struct ReadableType : public jni::JavaClass { - static auto constexpr kJavaDescriptor = - "Lcom/facebook/react/bridge/ReadableType;"; + static auto constexpr kJavaDescriptor = "Lcom/facebook/react/bridge/ReadableType;"; static jni::local_ref getType(folly::dynamic::Type type); }; namespace exceptions { -extern const char* gUnexpectedNativeTypeExceptionClass; +extern const char *gUnexpectedNativeTypeExceptionClass; template -void throwIfObjectAlreadyConsumed(const T& t, const char* msg) { +void throwIfObjectAlreadyConsumed(const T &t, const char *msg) +{ if (t->isConsumed) { - jni::throwNewJavaException( - "com/facebook/react/bridge/ObjectAlreadyConsumedException", msg); + jni::throwNewJavaException("com/facebook/react/bridge/ObjectAlreadyConsumedException", msg); } } diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/jni/NativeMap.h b/packages/react-native/ReactAndroid/src/main/jni/react/jni/NativeMap.h index a451c41aa16..2a4e513029d 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/jni/NativeMap.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/jni/NativeMap.h @@ -16,8 +16,7 @@ namespace facebook::react { class NativeMap : public jni::HybridClass { public: - static auto constexpr kJavaDescriptor = - "Lcom/facebook/react/bridge/NativeMap;"; + static auto constexpr kJavaDescriptor = "Lcom/facebook/react/bridge/NativeMap;"; jni::local_ref toString(); @@ -35,13 +34,14 @@ class NativeMap : public jni::HybridClass { friend HybridBase; template - explicit NativeMap(Dyn&& map) - : isConsumed(false), map_(std::forward(map)) {} + explicit NativeMap(Dyn &&map) : isConsumed(false), map_(std::forward(map)) + { + } void throwIfConsumed(); - NativeMap(const NativeMap&) = delete; - NativeMap& operator=(const NativeMap&) = delete; + NativeMap(const NativeMap &) = delete; + NativeMap &operator=(const NativeMap &) = delete; }; } // namespace facebook::react diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/jni/ReactInstanceManagerInspectorTarget.h b/packages/react-native/ReactAndroid/src/main/jni/react/jni/ReactInstanceManagerInspectorTarget.h index 3161651e9a2..aa80f639707 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/jni/ReactInstanceManagerInspectorTarget.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/jni/ReactInstanceManagerInspectorTarget.h @@ -16,9 +16,8 @@ namespace facebook::react { -class ReactInstanceManagerInspectorTarget - : public jni::HybridClass, - public jsinspector_modern::HostTargetDelegate { +class ReactInstanceManagerInspectorTarget : public jni::HybridClass, + public jsinspector_modern::HostTargetDelegate { private: struct TargetDelegate : public facebook::jni::JavaClass { static constexpr auto kJavaDescriptor = @@ -26,47 +25,38 @@ class ReactInstanceManagerInspectorTarget jni::local_ref> getMetadata() const; void onReload() const; - void onSetPausedInDebuggerMessage( - const OverlaySetPausedInDebuggerMessageRequest& request) const; + void onSetPausedInDebuggerMessage(const OverlaySetPausedInDebuggerMessageRequest &request) const; void loadNetworkResource( - const std::string& url, - jni::local_ref listener) - const; + const std::string &url, + jni::local_ref listener) const; }; public: - static constexpr auto kJavaDescriptor = - "Lcom/facebook/react/bridge/ReactInstanceManagerInspectorTarget;"; + static constexpr auto kJavaDescriptor = "Lcom/facebook/react/bridge/ReactInstanceManagerInspectorTarget;"; - ReactInstanceManagerInspectorTarget( - const ReactInstanceManagerInspectorTarget&) = delete; - ReactInstanceManagerInspectorTarget& operator=( - const ReactInstanceManagerInspectorTarget&) = delete; + ReactInstanceManagerInspectorTarget(const ReactInstanceManagerInspectorTarget &) = delete; + ReactInstanceManagerInspectorTarget &operator=(const ReactInstanceManagerInspectorTarget &) = delete; ~ReactInstanceManagerInspectorTarget() override; static jni::local_ref initHybrid( jni::alias_ref jobj, jni::alias_ref javaExecutor, - jni::alias_ref< - ReactInstanceManagerInspectorTarget::TargetDelegate::javaobject> - delegate); + jni::alias_ref delegate); void sendDebuggerResumeCommand(); static void registerNatives(); - jsinspector_modern::HostTarget* getInspectorTarget(); + jsinspector_modern::HostTarget *getInspectorTarget(); // HostTargetDelegate methods jsinspector_modern::HostTargetMetadata getMetadata() override; - void onReload(const PageReloadRequest& request) override; - void onSetPausedInDebuggerMessage( - const OverlaySetPausedInDebuggerMessageRequest& /*request*/) override; + void onReload(const PageReloadRequest &request) override; + void onSetPausedInDebuggerMessage(const OverlaySetPausedInDebuggerMessageRequest & /*request*/) override; void loadNetworkResource( - const jsinspector_modern::LoadNetworkResourceRequest& params, - jsinspector_modern::ScopedExecutor< - jsinspector_modern::NetworkRequestListener> executor) override; + const jsinspector_modern::LoadNetworkResourceRequest ¶ms, + jsinspector_modern::ScopedExecutor executor) override; private: friend HybridBase; @@ -74,11 +64,9 @@ class ReactInstanceManagerInspectorTarget ReactInstanceManagerInspectorTarget( jni::alias_ref jobj, jni::alias_ref javaExecutor, - jni::alias_ref - delegate); + jni::alias_ref delegate); - jni::global_ref - delegate_; + jni::global_ref delegate_; jsinspector_modern::VoidExecutor inspectorExecutor_; std::shared_ptr inspectorTarget_; std::optional inspectorPageId_; diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/jni/ReadableNativeArray.h b/packages/react-native/ReactAndroid/src/main/jni/react/jni/ReadableNativeArray.h index 1ab3243ad12..0129c066165 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/jni/ReadableNativeArray.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/jni/ReadableNativeArray.h @@ -15,22 +15,20 @@ namespace facebook::react { struct ReadableArray : jni::JavaClass { - static auto constexpr kJavaDescriptor = - "Lcom/facebook/react/bridge/ReadableArray;"; + static auto constexpr kJavaDescriptor = "Lcom/facebook/react/bridge/ReadableArray;"; }; -class ReadableNativeArray - : public jni::HybridClass { +class ReadableNativeArray : public jni::HybridClass { protected: friend HybridBase; template - explicit ReadableNativeArray(Dyn&& array) - : HybridBase(std::forward(array)) {} + explicit ReadableNativeArray(Dyn &&array) : HybridBase(std::forward(array)) + { + } public: - static constexpr const char* kJavaDescriptor = - "Lcom/facebook/react/bridge/ReadableNativeArray;"; + static constexpr const char *kJavaDescriptor = "Lcom/facebook/react/bridge/ReadableNativeArray;"; static void mapException(std::exception_ptr ex); static void registerNatives(); diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/jni/ReadableNativeMap.h b/packages/react-native/ReactAndroid/src/main/jni/react/jni/ReadableNativeMap.h index 16ff720b4c0..b2818cb48ab 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/jni/ReadableNativeMap.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/jni/ReadableNativeMap.h @@ -21,24 +21,19 @@ namespace facebook::react { struct WritableNativeMap; struct ReadableMap : jni::JavaClass { - static auto constexpr kJavaDescriptor = - "Lcom/facebook/react/bridge/ReadableMap;"; + static auto constexpr kJavaDescriptor = "Lcom/facebook/react/bridge/ReadableMap;"; }; -void addDynamicToJArray( - jni::local_ref> jarray, - jint index, - const folly::dynamic& dyn); +void addDynamicToJArray(jni::local_ref> jarray, jint index, const folly::dynamic &dyn); struct ReadableNativeMap : jni::HybridClass { - static auto constexpr kJavaDescriptor = - "Lcom/facebook/react/bridge/ReadableNativeMap;"; + static auto constexpr kJavaDescriptor = "Lcom/facebook/react/bridge/ReadableNativeMap;"; jni::local_ref> importKeys(); jni::local_ref> importValues(); jni::local_ref> importTypes(); std::optional keys_; - static jni::local_ref createWithContents(folly::dynamic&& map); + static jni::local_ref createWithContents(folly::dynamic &&map); static void mapException(std::exception_ptr ex); static void registerNatives(); diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/jni/SafeReleaseJniRef.h b/packages/react-native/ReactAndroid/src/main/jni/react/jni/SafeReleaseJniRef.h index af1eb84fa3c..635725a2e3b 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/jni/SafeReleaseJniRef.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/jni/SafeReleaseJniRef.h @@ -37,43 +37,51 @@ class SafeReleaseJniRef { public: SafeReleaseJniRef() = default; /* explicit */ SafeReleaseJniRef(RefT ref) : ref_(std::move(ref)) {} - SafeReleaseJniRef(const SafeReleaseJniRef& other) = default; - SafeReleaseJniRef(SafeReleaseJniRef&& other) = default; - SafeReleaseJniRef& operator=(const SafeReleaseJniRef& other) = default; - SafeReleaseJniRef& operator=(SafeReleaseJniRef&& other) = default; + SafeReleaseJniRef(const SafeReleaseJniRef &other) = default; + SafeReleaseJniRef(SafeReleaseJniRef &&other) = default; + SafeReleaseJniRef &operator=(const SafeReleaseJniRef &other) = default; + SafeReleaseJniRef &operator=(SafeReleaseJniRef &&other) = default; - ~SafeReleaseJniRef() { + ~SafeReleaseJniRef() + { if (ref_) { ensureThreadDurationJNIEnvAttached(); ref_.reset(); } } - operator bool() const noexcept { + operator bool() const noexcept + { return (bool)ref_; } - T& operator*() noexcept { + T &operator*() noexcept + { return *ref_; } - T* operator->() noexcept { + T *operator->() noexcept + { return &*ref_; } - const T& operator*() const noexcept { + const T &operator*() const noexcept + { return *ref_; } - const T* operator->() const noexcept { + const T *operator->() const noexcept + { return &*ref_; } - operator RefT() const { + operator RefT() const + { return ref_; } - RefT::javaobject get() const { + RefT::javaobject get() const + { return ref_.get(); } diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/jni/TransformHelper.h b/packages/react-native/ReactAndroid/src/main/jni/react/jni/TransformHelper.h index 342a8ee1100..cbb7e639bb1 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/jni/TransformHelper.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/jni/TransformHelper.h @@ -13,8 +13,7 @@ namespace facebook::react { class TransformHelper : public jni::JavaClass { public: - static auto constexpr* kJavaDescriptor = - "Lcom/facebook/react/uimanager/TransformHelper;"; + static auto constexpr *kJavaDescriptor = "Lcom/facebook/react/uimanager/TransformHelper;"; static void registerNatives(); }; diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/jni/WritableNativeArray.h b/packages/react-native/ReactAndroid/src/main/jni/react/jni/WritableNativeArray.h index b40eb5916fb..0554e1ea134 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/jni/WritableNativeArray.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/jni/WritableNativeArray.h @@ -18,17 +18,14 @@ namespace facebook::react { struct ReadableNativeMap; struct WritableArray : jni::JavaClass { - static auto constexpr kJavaDescriptor = - "Lcom/facebook/react/bridge/WritableArray;"; + static auto constexpr kJavaDescriptor = "Lcom/facebook/react/bridge/WritableArray;"; }; -struct WritableNativeArray - : public jni::HybridClass { - static constexpr const char* kJavaDescriptor = - "Lcom/facebook/react/bridge/WritableNativeArray;"; +struct WritableNativeArray : public jni::HybridClass { + static constexpr const char *kJavaDescriptor = "Lcom/facebook/react/bridge/WritableNativeArray;"; WritableNativeArray(); - WritableNativeArray(folly::dynamic&& val); + WritableNativeArray(folly::dynamic &&val); static void initHybrid(jni::alias_ref jobj); @@ -38,8 +35,8 @@ struct WritableNativeArray void pushInt(jint value); void pushLong(jlong value); void pushString(jstring value); - void pushNativeArray(ReadableNativeArray* otherArray); - void pushNativeMap(ReadableNativeMap* map); + void pushNativeArray(ReadableNativeArray *otherArray); + void pushNativeMap(ReadableNativeMap *map); static void registerNatives(); }; diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/jni/WritableNativeMap.h b/packages/react-native/ReactAndroid/src/main/jni/react/jni/WritableNativeMap.h index bb2ca9fbf5f..d1179982414 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/jni/WritableNativeMap.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/jni/WritableNativeMap.h @@ -17,17 +17,14 @@ namespace facebook::react { struct WritableMap : jni::JavaClass { - static auto constexpr kJavaDescriptor = - "Lcom/facebook/react/bridge/WritableMap;"; + static auto constexpr kJavaDescriptor = "Lcom/facebook/react/bridge/WritableMap;"; }; -struct WritableNativeMap - : jni::HybridClass { - static auto constexpr kJavaDescriptor = - "Lcom/facebook/react/bridge/WritableNativeMap;"; +struct WritableNativeMap : jni::HybridClass { + static auto constexpr kJavaDescriptor = "Lcom/facebook/react/bridge/WritableNativeMap;"; WritableNativeMap(); - WritableNativeMap(folly::dynamic&& val); + WritableNativeMap(folly::dynamic &&val); static void initHybrid(jni::alias_ref jobj); @@ -37,9 +34,9 @@ struct WritableNativeMap void putInt(std::string key, int val); void putLong(std::string key, jlong val); void putString(std::string key, jni::alias_ref val); - void putNativeArray(std::string key, ReadableNativeArray* otherArray); - void putNativeMap(std::string key, ReadableNativeMap* otherMap); - void mergeNativeMap(ReadableNativeMap* other); + void putNativeArray(std::string key, ReadableNativeArray *otherArray); + void putNativeMap(std::string key, ReadableNativeMap *otherMap); + void mergeNativeMap(ReadableNativeMap *other); static void registerNatives(); diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/mapbuffer/react/common/mapbuffer/JReadableMapBuffer.h b/packages/react-native/ReactAndroid/src/main/jni/react/mapbuffer/react/common/mapbuffer/JReadableMapBuffer.h index 0ccc90d6aa6..aed8d355ad1 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/mapbuffer/react/common/mapbuffer/JReadableMapBuffer.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/mapbuffer/react/common/mapbuffer/JReadableMapBuffer.h @@ -17,13 +17,11 @@ namespace facebook::react { class JReadableMapBuffer : public jni::HybridClass { public: - static auto constexpr kJavaDescriptor = - "Lcom/facebook/react/common/mapbuffer/ReadableMapBuffer;"; + static auto constexpr kJavaDescriptor = "Lcom/facebook/react/common/mapbuffer/ReadableMapBuffer;"; - static jni::local_ref createWithContents( - MapBuffer&& map); + static jni::local_ref createWithContents(MapBuffer &&map); - explicit JReadableMapBuffer(MapBuffer&& map); + explicit JReadableMapBuffer(MapBuffer &&map); std::vector data() const; diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/mapbuffer/react/common/mapbuffer/JWritableMapBuffer.h b/packages/react-native/ReactAndroid/src/main/jni/react/mapbuffer/react/common/mapbuffer/JWritableMapBuffer.h index e076b28385b..4cd0df3ef32 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/mapbuffer/react/common/mapbuffer/JWritableMapBuffer.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/mapbuffer/react/common/mapbuffer/JWritableMapBuffer.h @@ -14,8 +14,7 @@ namespace facebook::react { class JWritableMapBuffer : public jni::JavaClass { public: - static auto constexpr kJavaDescriptor = - "Lcom/facebook/react/common/mapbuffer/WritableMapBuffer;"; + static auto constexpr kJavaDescriptor = "Lcom/facebook/react/common/mapbuffer/WritableMapBuffer;"; MapBuffer getMapBuffer(); }; diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/newarchdefaults/DefaultComponentsRegistry.h b/packages/react-native/ReactAndroid/src/main/jni/react/newarchdefaults/DefaultComponentsRegistry.h index a5a77b4e61a..b432b1a5371 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/newarchdefaults/DefaultComponentsRegistry.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/newarchdefaults/DefaultComponentsRegistry.h @@ -15,26 +15,20 @@ namespace facebook::react { -class DefaultComponentsRegistry - : public facebook::jni::JavaClass { +class DefaultComponentsRegistry : public facebook::jni::JavaClass { public: - constexpr static auto kJavaDescriptor = - "Lcom/facebook/react/defaults/DefaultComponentsRegistry;"; + constexpr static auto kJavaDescriptor = "Lcom/facebook/react/defaults/DefaultComponentsRegistry;"; static void registerNatives(); - static std::function)> + static std::function)> registerComponentDescriptorsFromEntryPoint; - static std::function)> + static std::function)> registerCodegenComponentDescriptorsFromEntryPoint; private: - static void setRegistryRunction( - jni::alias_ref /*unused*/, - ComponentFactory* delegate); + static void setRegistryRunction(jni::alias_ref /*unused*/, ComponentFactory *delegate); }; } // namespace facebook::react diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/newarchdefaults/DefaultTurboModuleManagerDelegate.h b/packages/react-native/ReactAndroid/src/main/jni/react/newarchdefaults/DefaultTurboModuleManagerDelegate.h index 0a8af0d35d2..c8f87d39ce9 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/newarchdefaults/DefaultTurboModuleManagerDelegate.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/newarchdefaults/DefaultTurboModuleManagerDelegate.h @@ -17,36 +17,27 @@ namespace facebook::react { -class DefaultTurboModuleManagerDelegate : public jni::HybridClass< - DefaultTurboModuleManagerDelegate, - TurboModuleManagerDelegate> { +class DefaultTurboModuleManagerDelegate + : public jni::HybridClass { public: - static constexpr auto kJavaDescriptor = - "Lcom/facebook/react/defaults/DefaultTurboModuleManagerDelegate;"; + static constexpr auto kJavaDescriptor = "Lcom/facebook/react/defaults/DefaultTurboModuleManagerDelegate;"; static jni::local_ref initHybrid( jni::alias_ref /*unused*/, - jni::alias_ref::javaobject> /*cxxReactPackages*/); + jni::alias_ref::javaobject> /*cxxReactPackages*/); static void registerNatives(); - static std::function( - const std::string&, - const std::shared_ptr&)> + static std::function(const std::string &, const std::shared_ptr &)> cxxModuleProvider; - static std::function( - const std::string&, - const JavaTurboModule::InitParams&)> + static std::function(const std::string &, const JavaTurboModule::InitParams &)> javaModuleProvider; - std::shared_ptr getTurboModule( - const std::string& name, - const std::shared_ptr& jsInvoker) override; - std::shared_ptr getTurboModule( - const std::string& name, - const JavaTurboModule::InitParams& params) override; + std::shared_ptr getTurboModule(const std::string &name, const std::shared_ptr &jsInvoker) + override; + std::shared_ptr getTurboModule(const std::string &name, const JavaTurboModule::InitParams ¶ms) + override; private: friend HybridBase; @@ -55,8 +46,7 @@ class DefaultTurboModuleManagerDelegate : public jni::HybridClass< std::vector> cxxReactPackages_; DefaultTurboModuleManagerDelegate( - jni::alias_ref::javaobject> - cxxReactPackage); + jni::alias_ref::javaobject> cxxReactPackage); }; } // namespace facebook::react diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/reactnativeblob/BlobCollector.h b/packages/react-native/ReactAndroid/src/main/jni/react/reactnativeblob/BlobCollector.h index 63202bcef05..440e725e28d 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/reactnativeblob/BlobCollector.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/reactnativeblob/BlobCollector.h @@ -12,21 +12,17 @@ namespace facebook::react { -class BlobCollector : public jni::HybridClass, - public jsi::HostObject { +class BlobCollector : public jni::HybridClass, public jsi::HostObject { public: BlobCollector(jni::global_ref blobModule, std::string blobId); ~BlobCollector(); size_t getBlobLength(); - static constexpr auto kJavaDescriptor = - "Lcom/facebook/react/modules/blob/BlobCollector;"; + static constexpr auto kJavaDescriptor = "Lcom/facebook/react/modules/blob/BlobCollector;"; - static void nativeInstall( - jni::alias_ref /*unused*/, - jni::alias_ref blobModule, - jlong jsContextNativePointer); + static void + nativeInstall(jni::alias_ref /*unused*/, jni::alias_ref blobModule, jlong jsContextNativePointer); static void registerNatives(); diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/reactperflogger/reactperflogger/JNativeModulePerfLogger.h b/packages/react-native/ReactAndroid/src/main/jni/react/reactperflogger/reactperflogger/JNativeModulePerfLogger.h index 3081409afd8..c530ce57b5c 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/reactperflogger/reactperflogger/JNativeModulePerfLogger.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/reactperflogger/reactperflogger/JNativeModulePerfLogger.h @@ -13,11 +13,9 @@ namespace facebook::react { -class JNativeModulePerfLogger - : public jni::HybridClass { +class JNativeModulePerfLogger : public jni::HybridClass { public: - static auto constexpr kJavaDescriptor = - "Lcom/facebook/react/reactperflogger/NativeModulePerfLogger;"; + static auto constexpr kJavaDescriptor = "Lcom/facebook/react/reactperflogger/NativeModulePerfLogger;"; virtual std::unique_ptr get() = 0; diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/runtime/cxxreactpackage/ReactCommon/CxxReactPackage.h b/packages/react-native/ReactAndroid/src/main/jni/react/runtime/cxxreactpackage/ReactCommon/CxxReactPackage.h index cdf1a86a7f4..30adda5ed13 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/runtime/cxxreactpackage/ReactCommon/CxxReactPackage.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/runtime/cxxreactpackage/ReactCommon/CxxReactPackage.h @@ -17,12 +17,11 @@ class CallInvoker; class CxxReactPackage : public jni::HybridClass { public: - static auto constexpr kJavaDescriptor = - "Lcom/facebook/react/runtime/cxxreactpackage/CxxReactPackage;"; + static auto constexpr kJavaDescriptor = "Lcom/facebook/react/runtime/cxxreactpackage/CxxReactPackage;"; virtual std::shared_ptr getModule( - const std::string& name, - const std::shared_ptr& jsInvoker) = 0; + const std::string &name, + const std::shared_ptr &jsInvoker) = 0; private: friend HybridBase; diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/runtime/hermes/jni/JHermesInstance.h b/packages/react-native/ReactAndroid/src/main/jni/react/runtime/hermes/jni/JHermesInstance.h index eb732d881be..53b0b36c7c3 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/runtime/hermes/jni/JHermesInstance.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/runtime/hermes/jni/JHermesInstance.h @@ -19,23 +19,17 @@ namespace facebook::react { -class JHermesInstance - : public jni::HybridClass { +class JHermesInstance : public jni::HybridClass { public: - static constexpr auto kJavaDescriptor = - "Lcom/facebook/react/runtime/hermes/HermesInstance;"; + static constexpr auto kJavaDescriptor = "Lcom/facebook/react/runtime/hermes/HermesInstance;"; - static jni::local_ref initHybrid( - jni::alias_ref /* unused */, - bool allocInOldGenBeforeTTI); + static jni::local_ref initHybrid(jni::alias_ref /* unused */, bool allocInOldGenBeforeTTI); static void registerNatives(); - JHermesInstance(bool allocInOldGenBeforeTTI) - : allocInOldGenBeforeTTI_(allocInOldGenBeforeTTI){}; + JHermesInstance(bool allocInOldGenBeforeTTI) : allocInOldGenBeforeTTI_(allocInOldGenBeforeTTI) {}; - std::unique_ptr createJSRuntime( - std::shared_ptr msgQueueThread) noexcept; + std::unique_ptr createJSRuntime(std::shared_ptr msgQueueThread) noexcept; ~JHermesInstance() {} diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/runtime/jni/JBindingsInstaller.h b/packages/react-native/ReactAndroid/src/main/jni/react/runtime/jni/JBindingsInstaller.h index b0d8d1f581a..f6af0cebfb3 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/runtime/jni/JBindingsInstaller.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/runtime/jni/JBindingsInstaller.h @@ -15,11 +15,9 @@ namespace facebook::react { -class JBindingsInstaller : public jni::HybridClass, - public BindingsInstaller { +class JBindingsInstaller : public jni::HybridClass, public BindingsInstaller { public: - static constexpr auto kJavaDescriptor = - "Lcom/facebook/react/runtime/BindingsInstaller;"; + static constexpr auto kJavaDescriptor = "Lcom/facebook/react/runtime/BindingsInstaller;"; ~JBindingsInstaller() {} diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/runtime/jni/JJSRuntimeFactory.h b/packages/react-native/ReactAndroid/src/main/jni/react/runtime/jni/JJSRuntimeFactory.h index 03c312cd378..5c8e4603ccc 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/runtime/jni/JJSRuntimeFactory.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/runtime/jni/JJSRuntimeFactory.h @@ -13,11 +13,9 @@ namespace facebook::react { -class JJSRuntimeFactory : public jni::HybridClass, - public JSRuntimeFactory { +class JJSRuntimeFactory : public jni::HybridClass, public JSRuntimeFactory { public: - static auto constexpr kJavaDescriptor = - "Lcom/facebook/react/runtime/JSRuntimeFactory;"; + static auto constexpr kJavaDescriptor = "Lcom/facebook/react/runtime/JSRuntimeFactory;"; private: friend HybridBase; diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/runtime/jni/JJSTimerExecutor.h b/packages/react-native/ReactAndroid/src/main/jni/react/runtime/jni/JJSTimerExecutor.h index a3b89ebb6f6..b34b7fec883 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/runtime/jni/JJSTimerExecutor.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/runtime/jni/JJSTimerExecutor.h @@ -17,8 +17,7 @@ namespace facebook::react { class JJSTimerExecutor : public jni::HybridClass { public: - constexpr static auto kJavaDescriptor = - "Lcom/facebook/react/runtime/JSTimerExecutor;"; + constexpr static auto kJavaDescriptor = "Lcom/facebook/react/runtime/JSTimerExecutor;"; static void registerNatives(); @@ -26,7 +25,7 @@ class JJSTimerExecutor : public jni::HybridClass { void setTimerManager(std::weak_ptr timerManager); - void callTimers(WritableNativeArray* timerIDs); + void callTimers(WritableNativeArray *timerIDs); private: JJSTimerExecutor() = default; diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/runtime/jni/JJavaTimerManager.h b/packages/react-native/ReactAndroid/src/main/jni/react/runtime/jni/JJavaTimerManager.h index e576a1f892a..29f2c8cd7a2 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/runtime/jni/JJavaTimerManager.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/runtime/jni/JJavaTimerManager.h @@ -15,8 +15,7 @@ namespace facebook::react { struct JJavaTimerManager : jni::JavaClass { - static auto constexpr kJavaDescriptor = - "Lcom/facebook/react/modules/core/JavaTimerManager;"; + static auto constexpr kJavaDescriptor = "Lcom/facebook/react/modules/core/JavaTimerManager;"; void createTimer(uint32_t timerID, double duration, bool repeat); diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/runtime/jni/JReactExceptionManager.h b/packages/react-native/ReactAndroid/src/main/jni/react/runtime/jni/JReactExceptionManager.h index 8ab06a236bf..c86547a3240 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/runtime/jni/JReactExceptionManager.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/runtime/jni/JReactExceptionManager.h @@ -13,15 +13,11 @@ namespace facebook::react { -class JReactExceptionManager - : public facebook::jni::JavaClass { +class JReactExceptionManager : public facebook::jni::JavaClass { public: - static auto constexpr kJavaDescriptor = - "Lcom/facebook/react/interfaces/exceptionmanager/ReactJsExceptionHandler;"; + static auto constexpr kJavaDescriptor = "Lcom/facebook/react/interfaces/exceptionmanager/ReactJsExceptionHandler;"; - void reportJsException( - jsi::Runtime& runtime, - const JsErrorHandler::ProcessedError& error); + void reportJsException(jsi::Runtime &runtime, const JsErrorHandler::ProcessedError &error); }; } // namespace facebook::react diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/runtime/jni/JReactHostInspectorTarget.h b/packages/react-native/ReactAndroid/src/main/jni/react/runtime/jni/JReactHostInspectorTarget.h index b4eb4940227..4eddce6825a 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/runtime/jni/JReactHostInspectorTarget.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/runtime/jni/JReactHostInspectorTarget.h @@ -16,61 +16,49 @@ namespace facebook::react { struct JTaskInterface : public jni::JavaClass { - static constexpr auto kJavaDescriptor = - "Lcom/facebook/react/interfaces/TaskInterface;"; + static constexpr auto kJavaDescriptor = "Lcom/facebook/react/interfaces/TaskInterface;"; }; struct JTracingState : public jni::JavaClass { - static constexpr auto kJavaDescriptor = - "Lcom/facebook/react/devsupport/TracingState;"; + static constexpr auto kJavaDescriptor = "Lcom/facebook/react/devsupport/TracingState;"; }; struct JReactHostImpl : public jni::JavaClass { - static constexpr auto kJavaDescriptor = - "Lcom/facebook/react/runtime/ReactHostImpl;"; + static constexpr auto kJavaDescriptor = "Lcom/facebook/react/runtime/ReactHostImpl;"; - jni::local_ref reload(const std::string& reason) { - static auto method = - javaClassStatic()->getMethod( - "reload"); + jni::local_ref reload(const std::string &reason) + { + static auto method = javaClassStatic()->getMethod("reload"); return method(self(), reason); } - void setPausedInDebuggerMessage(std::optional message) { - static auto method = - javaClassStatic()->getMethod)>( - "setPausedInDebuggerMessage"); + void setPausedInDebuggerMessage(std::optional message) + { + static auto method = javaClassStatic()->getMethod)>("setPausedInDebuggerMessage"); method(self(), message ? jni::make_jstring(*message) : nullptr); } - jni::local_ref> getHostMetadata() const { - static auto method = - javaClassStatic() - ->getMethod>()>( - "getHostMetadata"); + jni::local_ref> getHostMetadata() const + { + static auto method = javaClassStatic()->getMethod>()>("getHostMetadata"); return method(self()); } - void loadNetworkResource( - const std::string& url, - jni::local_ref listener) - const { - auto method = - javaClassStatic() - ->getMethod, - jni::local_ref)>( - "loadNetworkResource"); + void loadNetworkResource(const std::string &url, jni::local_ref listener) + const + { + auto method = javaClassStatic() + ->getMethod, jni::local_ref)>( + "loadNetworkResource"); return method(self(), jni::make_jstring(url), listener); } }; -class JReactHostInspectorTarget - : public jni::HybridClass, - public jsinspector_modern::HostTargetDelegate { +class JReactHostInspectorTarget : public jni::HybridClass, + public jsinspector_modern::HostTargetDelegate { public: - static constexpr auto kJavaDescriptor = - "Lcom/facebook/react/runtime/ReactHostInspectorTarget;"; + static constexpr auto kJavaDescriptor = "Lcom/facebook/react/runtime/ReactHostInspectorTarget;"; ~JReactHostInspectorTarget() override; @@ -109,17 +97,15 @@ class JReactHostInspectorTarget */ void stopAndDiscardBackgroundTrace(); - jsinspector_modern::HostTarget* getInspectorTarget(); + jsinspector_modern::HostTarget *getInspectorTarget(); // HostTargetDelegate methods jsinspector_modern::HostTargetMetadata getMetadata() override; - void onReload(const PageReloadRequest& request) override; - void onSetPausedInDebuggerMessage( - const OverlaySetPausedInDebuggerMessageRequest& request) override; + void onReload(const PageReloadRequest &request) override; + void onSetPausedInDebuggerMessage(const OverlaySetPausedInDebuggerMessageRequest &request) override; void loadNetworkResource( - const jsinspector_modern::LoadNetworkResourceRequest& params, - jsinspector_modern::ScopedExecutor< - jsinspector_modern::NetworkRequestListener> executor) override; + const jsinspector_modern::LoadNetworkResourceRequest ¶ms, + jsinspector_modern::ScopedExecutor executor) override; std::optional unstable_getTraceRecordingThatWillBeEmittedOnInitialization() override; @@ -147,14 +133,12 @@ class JReactHostInspectorTarget * CDP session is created. Once emitted, the value will be cleared from this * instance. */ - void stashTraceRecordingState( - jsinspector_modern::tracing::TraceRecordingState&& state); + void stashTraceRecordingState(jsinspector_modern::tracing::TraceRecordingState &&state); /** * Previously recorded trace recording state that will be emitted when * CDP session is created. */ - std::optional - stashedTraceRecordingState_; + std::optional stashedTraceRecordingState_; friend HybridBase; }; diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/runtime/jni/JReactInstance.cpp b/packages/react-native/ReactAndroid/src/main/jni/react/runtime/jni/JReactInstance.cpp index f0b5e62826a..5d123a5d1b8 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/runtime/jni/JReactInstance.cpp +++ b/packages/react-native/ReactAndroid/src/main/jni/react/runtime/jni/JReactInstance.cpp @@ -95,8 +95,8 @@ JReactInstance::JReactInstance( auto nativeMethodCallInvoker = std::make_unique( sharedNativeMessageQueueThread); - nativeMethodCallInvokerHolder_ = - jni::make_global(NativeMethodCallInvokerHolder::newObjectCxxArgs( + nativeMethodCallInvokerHolder_ = jni::make_global( + NativeMethodCallInvokerHolder::newObjectCxxArgs( std::move(nativeMethodCallInvoker))); // Storing this here to make sure the Java reference doesn't get destroyed diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/runtime/jni/JReactInstance.h b/packages/react-native/ReactAndroid/src/main/jni/react/runtime/jni/JReactInstance.h index 1274cad4f2b..d58e52722b7 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/runtime/jni/JReactInstance.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/runtime/jni/JReactInstance.h @@ -33,45 +33,33 @@ namespace facebook::react { class JReactInstance : public jni::HybridClass { public: - constexpr static auto kJavaDescriptor = - "Lcom/facebook/react/runtime/ReactInstance;"; + constexpr static auto kJavaDescriptor = "Lcom/facebook/react/runtime/ReactInstance;"; static jni::local_ref initHybrid( jni::alias_ref /*unused*/, jni::alias_ref jsRuntimeFactory, jni::alias_ref jsMessageQueueThread, - jni::alias_ref - nativeMessageQueueThread, + jni::alias_ref nativeMessageQueueThread, jni::alias_ref javaTimerManager, jni::alias_ref jsTimerExecutor, jni::alias_ref jReactExceptionManager, jni::alias_ref jBindingsInstaller, bool isProfiling, - jni::alias_ref - jReactHostInspectorTarget); + jni::alias_ref jReactHostInspectorTarget); static void registerNatives(); - void loadJSBundleFromAssets( - jni::alias_ref assetManager, - const std::string& assetURL); + void loadJSBundleFromAssets(jni::alias_ref assetManager, const std::string &assetURL); - void loadJSBundleFromFile( - const std::string& fileName, - const std::string& sourceURL); + void loadJSBundleFromFile(const std::string &fileName, const std::string &sourceURL); - void callFunctionOnModule( - const std::string& moduleName, - const std::string& methodName, - NativeArray* args); + void callFunctionOnModule(const std::string &moduleName, const std::string &methodName, NativeArray *args); - jni::alias_ref - getUnbufferedRuntimeExecutor() noexcept; - jni::alias_ref - getBufferedRuntimeExecutor() noexcept; + jni::alias_ref getUnbufferedRuntimeExecutor() noexcept; + jni::alias_ref getBufferedRuntimeExecutor() noexcept; jni::alias_ref getRuntimeScheduler() noexcept; - void registerSegment(int segmentId, const std::string& segmentPath) noexcept; + void registerSegment(int segmentId, const std::string &segmentPath) noexcept; void handleMemoryPressureJs(jint level); @@ -83,27 +71,23 @@ class JReactInstance : public jni::HybridClass { explicit JReactInstance( jni::alias_ref jsRuntimeFactory, jni::alias_ref jsMessageQueueThread, - jni::alias_ref - nativeMessageQueueThread, + jni::alias_ref nativeMessageQueueThread, jni::alias_ref javaTimerManager, jni::alias_ref jsTimerExecutor, jni::alias_ref jReactExceptionManager, jni::alias_ref jBindingsInstaller, bool isProfiling, - jni::alias_ref - jReactHostInspectorTarget) noexcept; + jni::alias_ref jReactHostInspectorTarget) noexcept; jni::alias_ref getJSCallInvokerHolder(); - jni::alias_ref - getNativeMethodCallInvokerHolder(); + jni::alias_ref getNativeMethodCallInvokerHolder(); std::unique_ptr instance_; jni::global_ref unbufferedRuntimeExecutor_; jni::global_ref bufferedRuntimeExecutor_; jni::global_ref runtimeScheduler_; jni::global_ref jsCallInvokerHolder_; - jni::global_ref - nativeMethodCallInvokerHolder_; + jni::global_ref nativeMethodCallInvokerHolder_; jni::global_ref jReactExceptionManager_; jni::global_ref jBindingsInstaller_; diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/runtime/jni/JavaTimerRegistry.h b/packages/react-native/ReactAndroid/src/main/jni/react/runtime/jni/JavaTimerRegistry.h index 06670e141b4..e87a8fc873a 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/runtime/jni/JavaTimerRegistry.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/runtime/jni/JavaTimerRegistry.h @@ -22,8 +22,7 @@ namespace facebook::react { */ class JavaTimerRegistry : public PlatformTimerRegistry { public: - JavaTimerRegistry( - jni::global_ref javaTimerManager); + JavaTimerRegistry(jni::global_ref javaTimerManager); #pragma mark - PlatformTimerRegistry diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/turbomodule/ReactCommon/BindingsInstallerHolder.h b/packages/react-native/ReactAndroid/src/main/jni/react/turbomodule/ReactCommon/BindingsInstallerHolder.h index 417255c0889..1ca58bba439 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/turbomodule/ReactCommon/BindingsInstallerHolder.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/turbomodule/ReactCommon/BindingsInstallerHolder.h @@ -13,25 +13,18 @@ namespace facebook::react { -class BindingsInstallerHolder - : public jni::HybridClass { +class BindingsInstallerHolder : public jni::HybridClass { public: - static auto constexpr kJavaDescriptor = - "Lcom/facebook/react/turbomodule/core/interfaces/BindingsInstallerHolder;"; - using BindingsInstallFunc = std::function& callInvoker)>; + static auto constexpr kJavaDescriptor = "Lcom/facebook/react/turbomodule/core/interfaces/BindingsInstallerHolder;"; + using BindingsInstallFunc = + std::function &callInvoker)>; - void installBindings( - jsi::Runtime& runtime, - const std::shared_ptr& callInvoker); + void installBindings(jsi::Runtime &runtime, const std::shared_ptr &callInvoker); private: BindingsInstallerHolder(BindingsInstallFunc bindingsInstaller); - [[deprecated( - "Use 'BindingsInstallerHolder([](Runtime, CallInvoker) { ... })' instead")]] - BindingsInstallerHolder( - std::function oldBindingsInstaller); + [[deprecated("Use 'BindingsInstallerHolder([](Runtime, CallInvoker) { ... })' instead")]] + BindingsInstallerHolder(std::function oldBindingsInstaller); private: friend HybridBase; diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/turbomodule/ReactCommon/CallInvokerHolder.h b/packages/react-native/ReactAndroid/src/main/jni/react/turbomodule/ReactCommon/CallInvokerHolder.h index 6561f9cc5dd..ca1fd0ff3e3 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/turbomodule/ReactCommon/CallInvokerHolder.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/turbomodule/ReactCommon/CallInvokerHolder.h @@ -15,10 +15,10 @@ namespace facebook::react { class CallInvokerHolder : public jni::HybridClass { public: - static auto constexpr kJavaDescriptor = - "Lcom/facebook/react/turbomodule/core/CallInvokerHolderImpl;"; + static auto constexpr kJavaDescriptor = "Lcom/facebook/react/turbomodule/core/CallInvokerHolderImpl;"; - std::shared_ptr getCallInvoker() { + std::shared_ptr getCallInvoker() + { return callInvoker_; } diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/turbomodule/ReactCommon/NativeMethodCallInvokerHolder.h b/packages/react-native/ReactAndroid/src/main/jni/react/turbomodule/ReactCommon/NativeMethodCallInvokerHolder.h index cc5a2e3637f..b6f9b1aed4c 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/turbomodule/ReactCommon/NativeMethodCallInvokerHolder.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/turbomodule/ReactCommon/NativeMethodCallInvokerHolder.h @@ -13,20 +13,18 @@ namespace facebook::react { -class NativeMethodCallInvokerHolder - : public jni::HybridClass { +class NativeMethodCallInvokerHolder : public jni::HybridClass { public: - static auto constexpr kJavaDescriptor = - "Lcom/facebook/react/turbomodule/core/NativeMethodCallInvokerHolderImpl;"; + static auto constexpr kJavaDescriptor = "Lcom/facebook/react/turbomodule/core/NativeMethodCallInvokerHolderImpl;"; - std::shared_ptr getNativeMethodCallInvoker() { + std::shared_ptr getNativeMethodCallInvoker() + { return nativeMethodCallInvoker_; } private: friend HybridBase; - NativeMethodCallInvokerHolder( - std::shared_ptr nativeMethodCallInvoker); + NativeMethodCallInvokerHolder(std::shared_ptr nativeMethodCallInvoker); std::shared_ptr nativeMethodCallInvoker_; }; diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/turbomodule/ReactCommon/TurboModuleManager.h b/packages/react-native/ReactAndroid/src/main/jni/react/turbomodule/ReactCommon/TurboModuleManager.h index 5b0b82729b4..296c2c2b040 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/turbomodule/ReactCommon/TurboModuleManager.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/turbomodule/ReactCommon/TurboModuleManager.h @@ -24,14 +24,12 @@ namespace facebook::react { class TurboModuleManager : public jni::HybridClass { public: - static auto constexpr kJavaDescriptor = - "Lcom/facebook/react/internal/turbomodule/core/TurboModuleManager;"; + static auto constexpr kJavaDescriptor = "Lcom/facebook/react/internal/turbomodule/core/TurboModuleManager;"; static jni::local_ref initHybrid( jni::alias_ref /* unused */, jni::alias_ref runtimeExecutor, jni::alias_ref jsCallInvokerHolder, - jni::alias_ref - nativeMethodCallInvokerHolder, + jni::alias_ref nativeMethodCallInvokerHolder, jni::alias_ref delegate); static void registerNatives(); @@ -42,8 +40,7 @@ class TurboModuleManager : public jni::HybridClass { std::shared_ptr nativeMethodCallInvoker_; jni::global_ref delegate_; - using ModuleCache = - std::unordered_map>; + using ModuleCache = std::unordered_map>; /** * TODO(T48018690): @@ -60,23 +57,16 @@ class TurboModuleManager : public jni::HybridClass { std::shared_ptr nativeMethodCallInvoker, jni::alias_ref delegate); - static void installJSIBindings( - jni::alias_ref javaPart, - bool shouldCreateLegacyModules); + static void installJSIBindings(jni::alias_ref javaPart, bool shouldCreateLegacyModules); static TurboModuleProviderFunctionType createTurboModuleProvider( jni::alias_ref javaPart, - jsi::Runtime* runtime); - std::shared_ptr getTurboModule( - jni::alias_ref javaPart, - const std::string& name, - jsi::Runtime& runtime); + jsi::Runtime *runtime); + std::shared_ptr + getTurboModule(jni::alias_ref javaPart, const std::string &name, jsi::Runtime &runtime); - static TurboModuleProviderFunctionType createLegacyModuleProvider( - jni::alias_ref javaPart); - std::shared_ptr getLegacyModule( - jni::alias_ref javaPart, - const std::string& name); + static TurboModuleProviderFunctionType createLegacyModuleProvider(jni::alias_ref javaPart); + std::shared_ptr getLegacyModule(jni::alias_ref javaPart, const std::string &name); }; } // namespace facebook::react diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/turbomodule/ReactCommon/TurboModuleManagerDelegate.h b/packages/react-native/ReactAndroid/src/main/jni/react/turbomodule/ReactCommon/TurboModuleManagerDelegate.h index 0c387004da3..ce7ac58fa36 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/turbomodule/ReactCommon/TurboModuleManagerDelegate.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/turbomodule/ReactCommon/TurboModuleManagerDelegate.h @@ -15,18 +15,16 @@ namespace facebook::react { -class TurboModuleManagerDelegate - : public jni::HybridClass { +class TurboModuleManagerDelegate : public jni::HybridClass { public: - static auto constexpr kJavaDescriptor = - "Lcom/facebook/react/internal/turbomodule/core/TurboModuleManagerDelegate;"; + static auto constexpr kJavaDescriptor = "Lcom/facebook/react/internal/turbomodule/core/TurboModuleManagerDelegate;"; virtual std::shared_ptr getTurboModule( - const std::string& name, - const JavaTurboModule::InitParams& params) = 0; + const std::string &name, + const JavaTurboModule::InitParams ¶ms) = 0; virtual std::shared_ptr getTurboModule( - const std::string& name, - const std::shared_ptr& jsInvoker) = 0; + const std::string &name, + const std::shared_ptr &jsInvoker) = 0; private: friend HybridBase; diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/uimanager/ComponentNameResolverBinding.h b/packages/react-native/ReactAndroid/src/main/jni/react/uimanager/ComponentNameResolverBinding.h index fb0b9f7cb38..71599f269b9 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/uimanager/ComponentNameResolverBinding.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/uimanager/ComponentNameResolverBinding.h @@ -12,11 +12,9 @@ namespace facebook::react { -class ComponentNameResolverBinding - : public facebook::jni::JavaClass { +class ComponentNameResolverBinding : public facebook::jni::JavaClass { public: - static auto constexpr kJavaDescriptor = - "Lcom/facebook/react/uimanager/ComponentNameResolverBinding;"; + static auto constexpr kJavaDescriptor = "Lcom/facebook/react/uimanager/ComponentNameResolverBinding;"; static void install( jni::alias_ref /* unused */, diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/uimanager/UIConstantsProviderBinding.h b/packages/react-native/ReactAndroid/src/main/jni/react/uimanager/UIConstantsProviderBinding.h index aa01a342ec0..27222d4f48c 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/uimanager/UIConstantsProviderBinding.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/uimanager/UIConstantsProviderBinding.h @@ -13,33 +13,28 @@ namespace facebook::react { -class DefaultEventTypesProvider - : public jni::JavaClass { +class DefaultEventTypesProvider : public jni::JavaClass { public: - static constexpr const char* kJavaDescriptor = + static constexpr const char *kJavaDescriptor = "Lcom/facebook/react/uimanager/UIConstantsProviderBinding$DefaultEventTypesProvider;"; - folly::dynamic getDefaultEventTypes() const { + folly::dynamic getDefaultEventTypes() const + { static auto method = - javaClassStatic() - ->getMethod()>( - "getDefaultEventTypes"); + javaClassStatic()->getMethod()>("getDefaultEventTypes"); return method(self())->cthis()->consume(); } }; -class ConstantsForViewManagerProvider - : public jni::JavaClass { +class ConstantsForViewManagerProvider : public jni::JavaClass { public: - static constexpr const char* kJavaDescriptor = + static constexpr const char *kJavaDescriptor = "Lcom/facebook/react/uimanager/UIConstantsProviderBinding$ConstantsForViewManagerProvider;"; - folly::dynamic getConstantsForViewManager( - const std::string& viewManagerName) const { - static auto method = - javaClassStatic() - ->getMethod( - const std::string&)>("getConstantsForViewManager"); + folly::dynamic getConstantsForViewManager(const std::string &viewManagerName) const + { + static auto method = javaClassStatic()->getMethod(const std::string &)>( + "getConstantsForViewManager"); auto result = method(self(), viewManagerName); if (result == nullptr) { return nullptr; @@ -50,31 +45,25 @@ class ConstantsForViewManagerProvider class ConstantsProvider : public jni::JavaClass { public: - static constexpr const char* kJavaDescriptor = + static constexpr const char *kJavaDescriptor = "Lcom/facebook/react/uimanager/UIConstantsProviderBinding$ConstantsProvider;"; - folly::dynamic getConstants() const { - static auto method = - javaClassStatic() - ->getMethod()>( - "getConstants"); + folly::dynamic getConstants() const + { + static auto method = javaClassStatic()->getMethod()>("getConstants"); return method(self())->cthis()->consume(); } }; -class UIConstantsProviderBinding - : public jni::JavaClass { +class UIConstantsProviderBinding : public jni::JavaClass { public: - static auto constexpr kJavaDescriptor = - "Lcom/facebook/react/uimanager/UIConstantsProviderBinding;"; + static auto constexpr kJavaDescriptor = "Lcom/facebook/react/uimanager/UIConstantsProviderBinding;"; static void install( jni::alias_ref /* unused */, jni::alias_ref runtimeExecutor, - jni::alias_ref - defaultExportableEventTypesProvider, - jni::alias_ref - constantsForViewManagerProvider, + jni::alias_ref defaultExportableEventTypesProvider, + jni::alias_ref constantsForViewManagerProvider, jni::alias_ref constantsProvider); static void registerNatives(); diff --git a/packages/react-native/ReactCommon/callinvoker/ReactCommon/CallInvoker.h b/packages/react-native/ReactCommon/callinvoker/ReactCommon/CallInvoker.h index 91a8b4ee591..452493c27e3 100644 --- a/packages/react-native/ReactCommon/callinvoker/ReactCommon/CallInvoker.h +++ b/packages/react-native/ReactCommon/callinvoker/ReactCommon/CallInvoker.h @@ -18,7 +18,7 @@ class Runtime; namespace facebook::react { -using CallFunc = std::function; +using CallFunc = std::function; /** * An interface for a generic native-to-JS call invoker. See BridgeJSCallInvoker @@ -26,23 +26,24 @@ using CallFunc = std::function; */ class CallInvoker { public: - virtual void invokeAsync(CallFunc&& func) noexcept = 0; - virtual void invokeAsync( - SchedulerPriority /*priority*/, - CallFunc&& func) noexcept { + virtual void invokeAsync(CallFunc &&func) noexcept = 0; + virtual void invokeAsync(SchedulerPriority /*priority*/, CallFunc &&func) noexcept + { // When call with priority is not implemented, fall back to a regular async // execution invokeAsync(std::move(func)); } - virtual void invokeSync(CallFunc&& func) = 0; + virtual void invokeSync(CallFunc &&func) = 0; // Backward compatibility only, prefer the CallFunc methods instead - virtual void invokeAsync(std::function&& func) noexcept { - invokeAsync([func = std::move(func)](jsi::Runtime&) { func(); }); + virtual void invokeAsync(std::function &&func) noexcept + { + invokeAsync([func = std::move(func)](jsi::Runtime &) { func(); }); } - virtual void invokeSync(std::function&& func) { - invokeSync([func = std::move(func)](jsi::Runtime&) { func(); }); + virtual void invokeSync(std::function &&func) + { + invokeSync([func = std::move(func)](jsi::Runtime &) { func(); }); } virtual ~CallInvoker() = default; @@ -52,12 +53,8 @@ using NativeMethodCallFunc = std::function; class NativeMethodCallInvoker { public: - virtual void invokeAsync( - const std::string& methodName, - NativeMethodCallFunc&& func) noexcept = 0; - virtual void invokeSync( - const std::string& methodName, - NativeMethodCallFunc&& func) = 0; + virtual void invokeAsync(const std::string &methodName, NativeMethodCallFunc &&func) noexcept = 0; + virtual void invokeSync(const std::string &methodName, NativeMethodCallFunc &&func) = 0; virtual ~NativeMethodCallInvoker() = default; }; diff --git a/packages/react-native/ReactCommon/callinvoker/ReactCommon/tests/TestCallInvoker.h b/packages/react-native/ReactCommon/callinvoker/ReactCommon/tests/TestCallInvoker.h index 98807df7cc9..17ef56e5164 100644 --- a/packages/react-native/ReactCommon/callinvoker/ReactCommon/tests/TestCallInvoker.h +++ b/packages/react-native/ReactCommon/callinvoker/ReactCommon/tests/TestCallInvoker.h @@ -15,18 +15,20 @@ namespace facebook::react { class TestCallInvoker : public CallInvoker { public: - explicit TestCallInvoker(facebook::jsi::Runtime& runtime) - : runtime_(runtime) {} + explicit TestCallInvoker(facebook::jsi::Runtime &runtime) : runtime_(runtime) {} - void invokeAsync(CallFunc&& func) noexcept override { + void invokeAsync(CallFunc &&func) noexcept override + { queue_.push_back(std::move(func)); } - void invokeSync(CallFunc&& func) override { + void invokeSync(CallFunc &&func) override + { func(runtime_); } - void flushQueue() { + void flushQueue() + { while (!queue_.empty()) { queue_.front()(runtime_); queue_.pop_front(); @@ -34,12 +36,13 @@ class TestCallInvoker : public CallInvoker { } } - size_t queueSize() { + size_t queueSize() + { return queue_.size(); } private: - facebook::jsi::Runtime& runtime_; + facebook::jsi::Runtime &runtime_; std::list queue_{}; }; diff --git a/packages/react-native/ReactCommon/cxxreact/CxxModule.h b/packages/react-native/ReactCommon/cxxreact/CxxModule.h index 59c7d637a95..6582fd40dd8 100644 --- a/packages/react-native/ReactCommon/cxxreact/CxxModule.h +++ b/packages/react-native/ReactCommon/cxxreact/CxxModule.h @@ -69,110 +69,85 @@ class CxxModule { std::function syncFunc; - const char* getType() { + const char *getType() + { assert(func || syncFunc); return func ? (isPromise ? "promise" : "async") : "sync"; } // std::function/lambda ctors - Method(std::string aname, std::function&& afunc) + Method(std::string aname, std::function &&afunc) + : name(std::move(aname)), callbacks(0), isPromise(false), func(std::bind(std::move(afunc))) + { + } + + Method(std::string aname, std::function &&afunc) : name(std::move(aname)), callbacks(0), isPromise(false), - func(std::bind(std::move(afunc))) {} + func(std::bind(std::move(afunc), std::placeholders::_1)) + { + } - Method(std::string aname, std::function&& afunc) - : name(std::move(aname)), - callbacks(0), - isPromise(false), - func(std::bind(std::move(afunc), std::placeholders::_1)) {} - - Method( - std::string aname, - std::function&& afunc) + Method(std::string aname, std::function &&afunc) : name(std::move(aname)), callbacks(1), isPromise(false), - func(std::bind( - std::move(afunc), - std::placeholders::_1, - std::placeholders::_2)) {} + func(std::bind(std::move(afunc), std::placeholders::_1, std::placeholders::_2)) + { + } - Method( - std::string aname, - std::function&& afunc) - : name(std::move(aname)), - callbacks(2), - isPromise(true), - func(std::move(afunc)) {} + Method(std::string aname, std::function &&afunc) + : name(std::move(aname)), callbacks(2), isPromise(true), func(std::move(afunc)) + { + } - Method( - std::string aname, - std::function&& afunc, - AsyncTagType /*unused*/) - : name(std::move(aname)), - callbacks(2), - isPromise(false), - func(std::move(afunc)) {} + Method(std::string aname, std::function &&afunc, AsyncTagType /*unused*/) + : name(std::move(aname)), callbacks(2), isPromise(false), func(std::move(afunc)) + { + } // method pointer ctors template - Method(std::string aname, T* t, void (T::*method)()) - : name(std::move(aname)), - callbacks(0), - isPromise(false), - func(std::bind(method, t)) {} + Method(std::string aname, T *t, void (T::*method)()) + : name(std::move(aname)), callbacks(0), isPromise(false), func(std::bind(method, t)) + { + } template - Method(std::string aname, T* t, void (T::*method)(folly::dynamic)) - : name(std::move(aname)), - callbacks(0), - isPromise(false), - func(std::bind(method, t, std::placeholders::_1)) {} + Method(std::string aname, T *t, void (T::*method)(folly::dynamic)) + : name(std::move(aname)), callbacks(0), isPromise(false), func(std::bind(method, t, std::placeholders::_1)) + { + } template - Method(std::string aname, T* t, void (T::*method)(folly::dynamic, Callback)) + Method(std::string aname, T *t, void (T::*method)(folly::dynamic, Callback)) : name(std::move(aname)), callbacks(1), isPromise(false), - func(std::bind( - method, - t, - std::placeholders::_1, - std::placeholders::_2)) {} + func(std::bind(method, t, std::placeholders::_1, std::placeholders::_2)) + { + } template - Method( - std::string aname, - T* t, - void (T::*method)(folly::dynamic, Callback, Callback)) + Method(std::string aname, T *t, void (T::*method)(folly::dynamic, Callback, Callback)) : name(std::move(aname)), callbacks(2), isPromise(true), - func(std::bind( - method, - t, - std::placeholders::_1, - std::placeholders::_2, - std::placeholders::_3)) {} + func(std::bind(method, t, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)) + { + } template - Method( - std::string aname, - T* t, - void (T::*method)(folly::dynamic, Callback, Callback), - AsyncTagType /*unused*/) + Method(std::string aname, T *t, void (T::*method)(folly::dynamic, Callback, Callback), AsyncTagType /*unused*/) : name(std::move(aname)), callbacks(2), isPromise(false), - func(std::bind( - method, - t, - std::placeholders::_1, - std::placeholders::_2, - std::placeholders::_3)) {} + func(std::bind(method, t, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)) + { + } // sync std::function/lambda ctors @@ -180,25 +155,18 @@ class CxxModule { // I am not sure if this is a runtime/compiler bug, or a // limitation I do not understand. - Method( - std::string aname, - std::function&& afunc, - SyncTagType /*unused*/) + Method(std::string aname, std::function &&afunc, SyncTagType /*unused*/) : name(std::move(aname)), callbacks(0), isPromise(false), - syncFunc([afunc = std::move(afunc)](const folly::dynamic&) { - return afunc(); - }) {} + syncFunc([afunc = std::move(afunc)](const folly::dynamic &) { return afunc(); }) + { + } - Method( - std::string aname, - std::function&& afunc, - SyncTagType /*unused*/) - : name(std::move(aname)), - callbacks(0), - isPromise(false), - syncFunc(std::move(afunc)) {} + Method(std::string aname, std::function &&afunc, SyncTagType /*unused*/) + : name(std::move(aname)), callbacks(0), isPromise(false), syncFunc(std::move(afunc)) + { + } }; /** @@ -217,7 +185,8 @@ class CxxModule { * Each entry in the map will be exported as a property to JS. The * key is the property name, and the value can be anything. */ - virtual auto getConstants() -> std::map { + virtual auto getConstants() -> std::map + { return {}; }; @@ -229,7 +198,8 @@ class CxxModule { /** * Called during the construction of CxxNativeModule. */ - void setInstance(std::weak_ptr instance) { + void setInstance(std::weak_ptr instance) + { instance_ = instance; } @@ -239,7 +209,8 @@ class CxxModule { * such as `callJSFunction`, allowing them to communicate back to JS outside * of the regular callbacks. */ - std::weak_ptr getInstance() { + std::weak_ptr getInstance() + { return instance_; } diff --git a/packages/react-native/ReactCommon/cxxreact/CxxNativeModule.h b/packages/react-native/ReactCommon/cxxreact/CxxNativeModule.h index e06c89387a3..7b42f6d9f89 100644 --- a/packages/react-native/ReactCommon/cxxreact/CxxNativeModule.h +++ b/packages/react-native/ReactCommon/cxxreact/CxxNativeModule.h @@ -24,12 +24,9 @@ class MessageQueueThread; typedef void (*WarnOnUsageLogger)(std::string message); [[deprecated("This API will be removed along with the legacy architecture.")]] -std::function makeCallback( - std::weak_ptr instance, - const folly::dynamic& callbackId); +std::function makeCallback(std::weak_ptr instance, const folly::dynamic &callbackId); -class RN_EXPORT [[deprecated( - "This API will be removed along with the legacy architecture.")]] CxxNativeModule +class RN_EXPORT [[deprecated("This API will be removed along with the legacy architecture.")]] CxxNativeModule : public NativeModule { public: CxxNativeModule( @@ -37,20 +34,16 @@ class RN_EXPORT [[deprecated( std::string name, xplat::module::CxxModule::Provider provider, std::shared_ptr messageQueueThread) - : instance_(instance), - name_(std::move(name)), - provider_(provider), - messageQueueThread_(messageQueueThread) {} + : instance_(instance), name_(std::move(name)), provider_(provider), messageQueueThread_(messageQueueThread) + { + } std::string getName() override; std::string getSyncMethodName(unsigned int methodId) override; std::vector getMethods() override; folly::dynamic getConstants() override; - void invoke(unsigned int reactMethodId, folly::dynamic&& params, int callId) - override; - MethodCallResult callSerializableNativeHook( - unsigned int hookId, - folly::dynamic&& args) override; + void invoke(unsigned int reactMethodId, folly::dynamic &¶ms, int callId) override; + MethodCallResult callSerializableNativeHook(unsigned int hookId, folly::dynamic &&args) override; static void setShouldWarnOnUse(bool value); @@ -63,9 +56,7 @@ class RN_EXPORT [[deprecated( std::shared_ptr messageQueueThread_; std::unique_ptr module_; std::vector methods_; - void emitWarnIfWarnOnUsage( - const std::string& method_name, - const std::string& module_name); + void emitWarnIfWarnOnUsage(const std::string &method_name, const std::string &module_name); static bool shouldWarnOnUse_; }; diff --git a/packages/react-native/ReactCommon/cxxreact/ErrorUtils.h b/packages/react-native/ReactCommon/cxxreact/ErrorUtils.h index bb08c4894a0..5d9d5db3682 100644 --- a/packages/react-native/ReactCommon/cxxreact/ErrorUtils.h +++ b/packages/react-native/ReactCommon/cxxreact/ErrorUtils.h @@ -11,8 +11,8 @@ namespace facebook::react { -inline static void -handleJSError(jsi::Runtime& runtime, const jsi::JSError& error, bool isFatal) { +inline static void handleJSError(jsi::Runtime &runtime, const jsi::JSError &error, bool isFatal) +{ auto errorUtils = runtime.global().getProperty(runtime, "ErrorUtils"); if (errorUtils.isUndefined() || !errorUtils.isObject() || !errorUtils.getObject(runtime).hasProperty(runtime, "reportFatalError") || @@ -29,13 +29,11 @@ handleJSError(jsi::Runtime& runtime, const jsi::JSError& error, bool isFatal) { // TODO(janzer): Rewrite this function to return the processed error // instead of just reporting it through the native module if (isFatal) { - auto func = errorUtils.asObject(runtime).getPropertyAsFunction( - runtime, "reportFatalError"); + auto func = errorUtils.asObject(runtime).getPropertyAsFunction(runtime, "reportFatalError"); func.call(runtime, error.value()); } else { - auto func = errorUtils.asObject(runtime).getPropertyAsFunction( - runtime, "reportError"); + auto func = errorUtils.asObject(runtime).getPropertyAsFunction(runtime, "reportError"); func.call(runtime, error.value()); } diff --git a/packages/react-native/ReactCommon/cxxreact/Instance.h b/packages/react-native/ReactCommon/cxxreact/Instance.h index dd4fe7ee9e1..501810e69ad 100644 --- a/packages/react-native/ReactCommon/cxxreact/Instance.h +++ b/packages/react-native/ReactCommon/cxxreact/Instance.h @@ -34,16 +34,14 @@ class MessageQueueThread; class ModuleRegistry; class RAMBundleRegistry; -struct [[deprecated( - "This API will be removed along with the legacy architecture.")]] InstanceCallback { +struct [[deprecated("This API will be removed along with the legacy architecture.")]] InstanceCallback { virtual ~InstanceCallback() = default; virtual void onBatchComplete() {} virtual void incrementPendingJSCalls() {} virtual void decrementPendingJSCalls() {} }; -class RN_EXPORT [[deprecated( - "This API will be removed along with the legacy architecture.")]] Instance +class RN_EXPORT [[deprecated("This API will be removed along with the legacy architecture.")]] Instance : private jsinspector_modern::InstanceTargetDelegate { public: ~Instance() override; @@ -52,46 +50,33 @@ class RN_EXPORT [[deprecated( std::shared_ptr jsef, std::shared_ptr jsQueue, std::shared_ptr moduleRegistry, - jsinspector_modern::HostTarget* inspectorTarget = nullptr); + jsinspector_modern::HostTarget *inspectorTarget = nullptr); void initializeRuntime(); void setSourceURL(std::string sourceURL); - void loadScriptFromString( - std::unique_ptr string, - std::string sourceURL, - bool loadSynchronously); - void loadRAMBundleFromString( - std::unique_ptr script, - const std::string& sourceURL); - void loadRAMBundleFromFile( - const std::string& sourcePath, - const std::string& sourceURL, - bool loadSynchronously); + void loadScriptFromString(std::unique_ptr string, std::string sourceURL, bool loadSynchronously); + void loadRAMBundleFromString(std::unique_ptr script, const std::string &sourceURL); + void loadRAMBundleFromFile(const std::string &sourcePath, const std::string &sourceURL, bool loadSynchronously); void loadRAMBundle( std::unique_ptr bundleRegistry, std::unique_ptr startupScript, std::string startupScriptSourceURL, bool loadSynchronously); bool supportsProfiling(); - void setGlobalVariable( - std::string propName, - std::unique_ptr jsonValue); - void* getJavaScriptContext(); + void setGlobalVariable(std::string propName, std::unique_ptr jsonValue); + void *getJavaScriptContext(); bool isInspectable(); bool isBatchActive(); - void callJSFunction( - std::string&& module, - std::string&& method, - folly::dynamic&& params); - void callJSCallback(uint64_t callbackId, folly::dynamic&& params); + void callJSFunction(std::string &&module, std::string &&method, folly::dynamic &¶ms); + void callJSCallback(uint64_t callbackId, folly::dynamic &¶ms); // This method is experimental, and may be modified or removed. - void registerBundle(uint32_t bundleId, const std::string& bundlePath); + void registerBundle(uint32_t bundleId, const std::string &bundlePath); - const ModuleRegistry& getModuleRegistry() const; - ModuleRegistry& getModuleRegistry(); + const ModuleRegistry &getModuleRegistry() const; + ModuleRegistry &getModuleRegistry(); void handleMemoryPressure(int pressureLevel); @@ -146,7 +131,7 @@ class RN_EXPORT [[deprecated( void unregisterFromInspector(); private: - void callNativeModules(folly::dynamic&& calls, bool isEndOfBatch); + void callNativeModules(folly::dynamic &&calls, bool isEndOfBatch); void loadBundle( std::unique_ptr bundleRegistry, std::unique_ptr startupScript, @@ -171,21 +156,19 @@ class RN_EXPORT [[deprecated( bool m_shouldBuffer = true; std::list m_workBuffer; - void scheduleAsync(CallFunc&& work) noexcept; + void scheduleAsync(CallFunc &&work) noexcept; public: - void setNativeToJsBridgeAndFlushCalls( - std::weak_ptr nativeToJsBridge); - void invokeAsync(CallFunc&& work) noexcept override; - void invokeSync(CallFunc&& work) override; + void setNativeToJsBridgeAndFlushCalls(std::weak_ptr nativeToJsBridge); + void invokeAsync(CallFunc &&work) noexcept override; + void invokeSync(CallFunc &&work) override; }; - std::shared_ptr jsCallInvoker_ = - std::make_shared(); + std::shared_ptr jsCallInvoker_ = std::make_shared(); - jsinspector_modern::HostTarget* parentInspectorTarget_{nullptr}; - jsinspector_modern::InstanceTarget* inspectorTarget_{nullptr}; - jsinspector_modern::RuntimeTarget* runtimeInspectorTarget_{nullptr}; + jsinspector_modern::HostTarget *parentInspectorTarget_{nullptr}; + jsinspector_modern::InstanceTarget *inspectorTarget_{nullptr}; + jsinspector_modern::RuntimeTarget *runtimeInspectorTarget_{nullptr}; }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/cxxreact/JSBigString.cpp b/packages/react-native/ReactCommon/cxxreact/JSBigString.cpp index ea4116d0fdf..8f12a8a680a 100644 --- a/packages/react-native/ReactCommon/cxxreact/JSBigString.cpp +++ b/packages/react-native/ReactCommon/cxxreact/JSBigString.cpp @@ -98,7 +98,7 @@ std::unique_ptr JSBigFileString::fromPath( throw std::runtime_error(message.c_str()); } - struct stat fileInfo {}; + struct stat fileInfo{}; int res = ::fstat(fd, &fileInfo); if (res == -1) { diff --git a/packages/react-native/ReactCommon/cxxreact/JSBigString.h b/packages/react-native/ReactCommon/cxxreact/JSBigString.h index 6d79184de7f..6e3030043a7 100644 --- a/packages/react-native/ReactCommon/cxxreact/JSBigString.h +++ b/packages/react-native/ReactCommon/cxxreact/JSBigString.h @@ -32,15 +32,15 @@ class JSBigString { JSBigString() = default; // Not copyable - JSBigString(const JSBigString&) = delete; - JSBigString& operator=(const JSBigString&) = delete; + JSBigString(const JSBigString &) = delete; + JSBigString &operator=(const JSBigString &) = delete; virtual ~JSBigString() = default; virtual bool isAscii() const = 0; // This needs to be a \0 terminated string - virtual const char* c_str() const = 0; + virtual const char *c_str() const = 0; // Length of the c_str without the NULL byte. virtual size_t size() const = 0; @@ -50,18 +50,20 @@ class JSBigString { // instance. class JSBigStdString : public JSBigString { public: - JSBigStdString(std::string str, bool isAscii = false) - : m_isAscii(isAscii), m_str(std::move(str)) {} + JSBigStdString(std::string str, bool isAscii = false) : m_isAscii(isAscii), m_str(std::move(str)) {} - bool isAscii() const override { + bool isAscii() const override + { return m_isAscii; } - const char* c_str() const override { + const char *c_str() const override + { return m_str.c_str(); } - size_t size() const override { + size_t size() const override + { return m_str.size(); } @@ -76,34 +78,40 @@ class JSBigStdString : public JSBigString { // file. class RN_EXPORT JSBigBufferString : public JSBigString { public: - JSBigBufferString(size_t size) : m_data(new char[size + 1]), m_size(size) { + JSBigBufferString(size_t size) : m_data(new char[size + 1]), m_size(size) + { // Guarantee nul-termination. The caller is responsible for // filling in the rest of m_data. m_data[m_size] = '\0'; } - ~JSBigBufferString() override { + ~JSBigBufferString() override + { delete[] m_data; } - bool isAscii() const override { + bool isAscii() const override + { return true; } - const char* c_str() const override { + const char *c_str() const override + { return m_data; } - size_t size() const override { + size_t size() const override + { return m_size; } - char* data() { + char *data() + { return m_data; } private: - char* m_data; + char *m_data; size_t m_size; }; @@ -113,24 +121,24 @@ class RN_EXPORT JSBigFileString : public JSBigString { JSBigFileString(int fd, size_t size, off_t offset = 0); ~JSBigFileString() override; - bool isAscii() const override { + bool isAscii() const override + { return true; } - const char* c_str() const override; + const char *c_str() const override; size_t size() const override; int fd() const; - static std::unique_ptr fromPath( - const std::string& sourceURL); + static std::unique_ptr fromPath(const std::string &sourceURL); private: int m_fd; // The file descriptor being mmapped size_t m_size; // The size of the mmapped region mutable off_t m_pageOff; // The offset in the mmapped region to the data. off_t m_mapOff; // The offset in the file to the mmapped region. - mutable const char* m_data; // Pointer to the mmapped region. + mutable const char *m_data; // Pointer to the mmapped region. }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/cxxreact/JSBundleType.h b/packages/react-native/ReactCommon/cxxreact/JSBundleType.h index c88add2cb0c..08cb4d4974f 100644 --- a/packages/react-native/ReactCommon/cxxreact/JSBundleType.h +++ b/packages/react-native/ReactCommon/cxxreact/JSBundleType.h @@ -41,7 +41,8 @@ struct FOLLY_PACK_ATTR Magic32 { }; struct FOLLY_PACK_ATTR BundleHeader { - BundleHeader() { + BundleHeader() + { std::memset(this, 0, sizeof(BundleHeader)); } @@ -57,17 +58,17 @@ FOLLY_PACK_POP * Takes the first 8 bytes of a bundle, and returns a tag describing the * bundle's format. */ -RN_EXPORT ScriptTag parseTypeFromHeader(const BundleHeader& header); +RN_EXPORT ScriptTag parseTypeFromHeader(const BundleHeader &header); /** * Convert an `ScriptTag` enum into a string, useful for emitting in errors * and diagnostic messages. */ -RN_EXPORT const char* stringForScriptTag(const ScriptTag& tag); +RN_EXPORT const char *stringForScriptTag(const ScriptTag &tag); /** * Check whether a given bundle is hermesc-generated bytecode */ -RN_EXPORT bool isHermesBytecodeBundle(const BundleHeader& header); +RN_EXPORT bool isHermesBytecodeBundle(const BundleHeader &header); } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/cxxreact/JSExecutor.h b/packages/react-native/ReactCommon/cxxreact/JSExecutor.h index a6a66fbc644..e6959416834 100644 --- a/packages/react-native/ReactCommon/cxxreact/JSExecutor.h +++ b/packages/react-native/ReactCommon/cxxreact/JSExecutor.h @@ -31,26 +31,21 @@ class RAMBundleRegistry; // This interface describes the delegate interface required by // Executor implementations to call from JS into native code. -class [[deprecated( - "This API will be removed along with the legacy architecture.")]] ExecutorDelegate { +class [[deprecated("This API will be removed along with the legacy architecture.")]] ExecutorDelegate { public: virtual ~ExecutorDelegate() = default; virtual std::shared_ptr getModuleRegistry() = 0; - virtual void callNativeModules( - JSExecutor& executor, - folly::dynamic&& calls, - bool isEndOfBatch) = 0; + virtual void callNativeModules(JSExecutor &executor, folly::dynamic &&calls, bool isEndOfBatch) = 0; virtual MethodCallResult callSerializableNativeHook( - JSExecutor& executor, + JSExecutor &executor, unsigned int moduleId, unsigned int methodId, - folly::dynamic&& args) = 0; + folly::dynamic &&args) = 0; }; -class [[deprecated( - "This API will be removed along with the legacy architecture.")]] JSExecutorFactory { +class [[deprecated("This API will be removed along with the legacy architecture.")]] JSExecutorFactory { public: virtual std::unique_ptr createJSExecutor( std::shared_ptr delegate, @@ -58,8 +53,7 @@ class [[deprecated( virtual ~JSExecutorFactory() = default; }; -class RN_EXPORT [[deprecated( - "This API will be removed along with the legacy architecture.")]] JSExecutor { +class RN_EXPORT [[deprecated("This API will be removed along with the legacy architecture.")]] JSExecutor { public: /** * Prepares the JS runtime for React Native by installing global variables. @@ -69,24 +63,19 @@ class RN_EXPORT [[deprecated( /** * Execute an application script bundle in the JS context. */ - virtual void loadBundle( - std::unique_ptr script, - std::string sourceURL) = 0; + virtual void loadBundle(std::unique_ptr script, std::string sourceURL) = 0; #ifndef RCT_REMOVE_LEGACY_ARCH /** * Add an application "RAM" bundle registry */ - virtual void setBundleRegistry( - std::unique_ptr bundleRegistry) = 0; + virtual void setBundleRegistry(std::unique_ptr bundleRegistry) = 0; #endif // RCT_REMOVE_LEGACY_ARCH /** * Register a file path for an additional "RAM" bundle */ - virtual void registerBundle( - uint32_t bundleId, - const std::string& bundlePath) = 0; + virtual void registerBundle(uint32_t bundleId, const std::string &bundlePath) = 0; /** * Executes BatchedBridge.callFunctionReturnFlushedQueue with the module ID, @@ -94,10 +83,8 @@ class RN_EXPORT [[deprecated( * responsible for using Bridge->callNativeModules to invoke any necessary * native modules methods. */ - virtual void callFunction( - const std::string& moduleId, - const std::string& methodId, - const folly::dynamic& arguments) = 0; + virtual void + callFunction(const std::string &moduleId, const std::string &methodId, const folly::dynamic &arguments) = 0; /** * Executes BatchedBridge.invokeCallbackAndReturnFlushedQueue with the cbID, @@ -105,15 +92,12 @@ class RN_EXPORT [[deprecated( * executor is responsible for using Bridge->callNativeModules to invoke any * necessary native modules methods. */ - virtual void invokeCallback( - double callbackId, - const folly::dynamic& arguments) = 0; + virtual void invokeCallback(double callbackId, const folly::dynamic &arguments) = 0; - virtual void setGlobalVariable( - std::string propName, - std::unique_ptr jsonValue) = 0; + virtual void setGlobalVariable(std::string propName, std::unique_ptr jsonValue) = 0; - virtual void* getJavaScriptContext() { + virtual void *getJavaScriptContext() + { return nullptr; } @@ -122,7 +106,8 @@ class RN_EXPORT [[deprecated( * Chrome remote debugging protocol. If true, the executor should also * override the \c createAgentDelegate method. */ - virtual bool isInspectable() { + virtual bool isInspectable() + { return false; } @@ -140,24 +125,21 @@ class RN_EXPORT [[deprecated( virtual void flush() {} - static std::string getSyntheticBundlePath( - uint32_t bundleId, - const std::string& bundlePath); + static std::string getSyntheticBundlePath(uint32_t bundleId, const std::string &bundlePath); /** * Get a reference to the \c RuntimeTargetDelegate owned (or implemented) by * this executor. This reference must remain valid for the duration of the * executor's lifetime. */ - virtual jsinspector_modern::RuntimeTargetDelegate& getRuntimeTargetDelegate(); + virtual jsinspector_modern::RuntimeTargetDelegate &getRuntimeTargetDelegate(); private: /** * Initialized by \c getRuntimeTargetDelegate if not overridden, and then * never changes. */ - std::optional - runtimeTargetDelegate_; + std::optional runtimeTargetDelegate_; }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/cxxreact/JSIndexedRAMBundle.h b/packages/react-native/ReactCommon/cxxreact/JSIndexedRAMBundle.h index 477185884d3..715d8535884 100644 --- a/packages/react-native/ReactCommon/cxxreact/JSIndexedRAMBundle.h +++ b/packages/react-native/ReactCommon/cxxreact/JSIndexedRAMBundle.h @@ -23,15 +23,13 @@ namespace facebook::react { -class RN_EXPORT [[deprecated( - "This API will be removed along with the legacy architecture.")]] JSIndexedRAMBundle +class RN_EXPORT [[deprecated("This API will be removed along with the legacy architecture.")]] JSIndexedRAMBundle : public JSModulesUnbundle { public: - static std::function(std::string)> - buildFactory(); + static std::function(std::string)> buildFactory(); // Throws std::runtime_error on failure. - explicit JSIndexedRAMBundle(const char* sourcePath); + explicit JSIndexedRAMBundle(const char *sourcePath); JSIndexedRAMBundle(std::unique_ptr script); // Throws std::runtime_error on failure. @@ -44,29 +42,24 @@ class RN_EXPORT [[deprecated( uint32_t offset; uint32_t length; }; - static_assert( - sizeof(ModuleData) == 8, - "ModuleData must not have any padding and use sizes matching input files"); + static_assert(sizeof(ModuleData) == 8, "ModuleData must not have any padding and use sizes matching input files"); struct ModuleTable { size_t numEntries; std::unique_ptr data; - ModuleTable() : numEntries(0){}; + ModuleTable() : numEntries(0) {}; ModuleTable(size_t entries) - : numEntries(entries), - data(std::unique_ptr(new ModuleData[numEntries])){}; - size_t byteLength() const { + : numEntries(entries), data(std::unique_ptr(new ModuleData[numEntries])) {}; + size_t byteLength() const + { return numEntries * sizeof(ModuleData); } }; void init(); std::string getModuleCode(uint32_t id) const; - void readBundle(char* buffer, std::streamsize bytes) const; - void readBundle( - char* buffer, - std::streamsize bytes, - std::istream::pos_type position) const; + void readBundle(char *buffer, std::streamsize bytes) const; + void readBundle(char *buffer, std::streamsize bytes, std::istream::pos_type position) const; mutable std::unique_ptr m_bundle; ModuleTable m_table; diff --git a/packages/react-native/ReactCommon/cxxreact/JSModulesUnbundle.h b/packages/react-native/ReactCommon/cxxreact/JSModulesUnbundle.h index 69aebe6cafa..7abea636d56 100644 --- a/packages/react-native/ReactCommon/cxxreact/JSModulesUnbundle.h +++ b/packages/react-native/ReactCommon/cxxreact/JSModulesUnbundle.h @@ -15,8 +15,7 @@ namespace facebook::react { -class [[deprecated( - "This API will be removed along with the legacy architecture.")]] JSModulesUnbundle { +class [[deprecated("This API will be removed along with the legacy architecture.")]] JSModulesUnbundle { /** * Represents the set of JavaScript modules that the application consists of. * The source code of each module can be retrieved by module ID. @@ -29,8 +28,9 @@ class [[deprecated( public: using std::out_of_range::out_of_range; explicit ModuleNotFound(uint32_t moduleId) - : std::out_of_range::out_of_range( - "Module not found: " + std::to_string(moduleId)) {} + : std::out_of_range::out_of_range("Module not found: " + std::to_string(moduleId)) + { + } }; struct Module { std::string name; @@ -41,7 +41,7 @@ class [[deprecated( virtual Module getModule(uint32_t moduleId) const = 0; private: - JSModulesUnbundle(const JSModulesUnbundle&) = delete; + JSModulesUnbundle(const JSModulesUnbundle &) = delete; }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/cxxreact/JsArgumentHelpers-inl.h b/packages/react-native/ReactCommon/cxxreact/JsArgumentHelpers-inl.h index 3814e3df320..6795c3335d8 100644 --- a/packages/react-native/ReactCommon/cxxreact/JsArgumentHelpers-inl.h +++ b/packages/react-native/ReactCommon/cxxreact/JsArgumentHelpers-inl.h @@ -14,79 +14,72 @@ namespace xplat { namespace detail { -inline std::string toStringHelper() { +inline std::string toStringHelper() +{ return ""; } template -inline std::string toStringHelper(const T& value, const Rest&... rest) { +inline std::string toStringHelper(const T &value, const Rest &...rest) +{ return std::to_string(value) + toStringHelper(rest...); } template -inline std::string toStringHelper(const char* value, const Rest&... rest) { +inline std::string toStringHelper(const char *value, const Rest &...rest) +{ return std::string(value) + toStringHelper(rest...); } template -R jsArg1(const folly::dynamic& arg, M asFoo, const T&... desc) { +R jsArg1(const folly::dynamic &arg, M asFoo, const T &...desc) +{ try { return (arg.*asFoo)(); - } catch (const folly::TypeError& ex) { + } catch (const folly::TypeError &ex) { + throw JsArgumentException("Error converting JavaScript arg " + toStringHelper(desc...) + " to C++: " + ex.what()); + } catch (const std::range_error &ex) { throw JsArgumentException( - "Error converting JavaScript arg " + toStringHelper(desc...) + - " to C++: " + ex.what()); - } catch (const std::range_error& ex) { - throw JsArgumentException( - "Could not convert argument " + toStringHelper(desc...) + - " to required type: " + ex.what()); + "Could not convert argument " + toStringHelper(desc...) + " to required type: " + ex.what()); } } } // namespace detail template -R jsArg( - const folly::dynamic& arg, - R (folly::dynamic::*asFoo)() const, - const T&... desc) { +R jsArg(const folly::dynamic &arg, R (folly::dynamic::*asFoo)() const, const T &...desc) +{ return detail::jsArg1(arg, asFoo, desc...); } template -R jsArg( - const folly::dynamic& arg, - R (folly::dynamic::*asFoo)() const&, - const T&... desc) { +R jsArg(const folly::dynamic &arg, R (folly::dynamic::*asFoo)() const &, const T &...desc) +{ return detail::jsArg1(arg, asFoo, desc...); } template // NOLINTNEXTLINE (T62192316) -typename detail::is_dynamic::type& jsArgAsDynamic(T&& args, size_t n) { +typename detail::is_dynamic::type &jsArgAsDynamic(T &&args, size_t n) +{ try { return args[n]; - } catch (const std::out_of_range& ex) { + } catch (const std::out_of_range &ex) { // Use 1-base counting for argument description. throw JsArgumentException( - "JavaScript provided " + std::to_string(args.size()) + - " arguments for C++ method which references at least " + + "JavaScript provided " + std::to_string(args.size()) + " arguments for C++ method which references at least " + std::to_string(n + 1) + " arguments: " + ex.what()); } } template -R jsArgN( - const folly::dynamic& args, - size_t n, - R (folly::dynamic::*asFoo)() const) { +R jsArgN(const folly::dynamic &args, size_t n, R (folly::dynamic::*asFoo)() const) +{ return jsArg(jsArgAsDynamic(args, n), asFoo, n); } template -R jsArgN( - const folly::dynamic& args, - size_t n, - R (folly::dynamic::*asFoo)() const&) { +R jsArgN(const folly::dynamic &args, size_t n, R (folly::dynamic::*asFoo)() const &) +{ return jsArg(jsArgAsDynamic(args, n), asFoo, n); } @@ -95,31 +88,30 @@ namespace detail { // This is a helper for jsArgAsArray and jsArgAsObject. template -typename detail::is_dynamic::type& jsArgAsType( - T&& args, - size_t n, - const char* required, - bool (folly::dynamic::*isFoo)() const) { - T& ret = jsArgAsDynamic(args, n); +typename detail::is_dynamic::type & +jsArgAsType(T &&args, size_t n, const char *required, bool (folly::dynamic::*isFoo)() const) +{ + T &ret = jsArgAsDynamic(args, n); if ((ret.*isFoo)()) { return ret; } // Use 1-base counting for argument description. throw JsArgumentException( - "Argument " + std::to_string(n + 1) + " of type " + ret.typeName() + - " is not required type " + required); + "Argument " + std::to_string(n + 1) + " of type " + ret.typeName() + " is not required type " + required); } } // end namespace detail template -typename detail::is_dynamic::type& jsArgAsArray(T&& args, size_t n) { +typename detail::is_dynamic::type &jsArgAsArray(T &&args, size_t n) +{ return detail::jsArgAsType(args, n, "Array", &folly::dynamic::isArray); } template -typename detail::is_dynamic::type& jsArgAsObject(T&& args, size_t n) { +typename detail::is_dynamic::type &jsArgAsObject(T &&args, size_t n) +{ return detail::jsArgAsType(args, n, "Object", &folly::dynamic::isObject); } diff --git a/packages/react-native/ReactCommon/cxxreact/JsArgumentHelpers.h b/packages/react-native/ReactCommon/cxxreact/JsArgumentHelpers.h index cf5343cb3e7..9f6c1963de4 100644 --- a/packages/react-native/ReactCommon/cxxreact/JsArgumentHelpers.h +++ b/packages/react-native/ReactCommon/cxxreact/JsArgumentHelpers.h @@ -24,7 +24,7 @@ namespace facebook::xplat { class JsArgumentException : public std::logic_error { public: - JsArgumentException(const std::string& msg) : std::logic_error(msg) {} + JsArgumentException(const std::string &msg) : std::logic_error(msg) {} }; // This extracts a single argument by calling the given method pointer on it. @@ -34,15 +34,9 @@ class JsArgumentException : public std::logic_error { // overload accepts ref-qualified member functions. template -R jsArg( - const folly::dynamic& arg, - R (folly::dynamic::*asFoo)() const, - const T&... desc); +R jsArg(const folly::dynamic &arg, R (folly::dynamic::*asFoo)() const, const T &...desc); template -R jsArg( - const folly::dynamic& arg, - R (folly::dynamic::*asFoo)() const&, - const T&... desc); +R jsArg(const folly::dynamic &arg, R (folly::dynamic::*asFoo)() const &, const T &...desc); // This is like jsArg, but a operates on a dynamic representing an array of // arguments. The argument n is used both to index the array and build the @@ -50,15 +44,9 @@ R jsArg( // used by the type-specific methods following. template -R jsArgN( - const folly::dynamic& args, - size_t n, - R (folly::dynamic::*asFoo)() const); +R jsArgN(const folly::dynamic &args, size_t n, R (folly::dynamic::*asFoo)() const); template -R jsArgN( - const folly::dynamic& args, - size_t n, - R (folly::dynamic::*asFoo)() const&); +R jsArgN(const folly::dynamic &args, size_t n, R (folly::dynamic::*asFoo)() const &); namespace detail { @@ -68,8 +56,7 @@ namespace detail { // only for types compatible with folly::dynamic. template struct is_dynamic { - using type = typename std:: - enable_if::value, T>::type; + using type = typename std::enable_if::value, T>::type; }; } // end namespace detail @@ -79,41 +66,45 @@ struct is_dynamic { // Extract the n'th arg from the given dynamic, as a dynamic. Throws a // JsArgumentException if there is no n'th arg in the input. template -typename detail::is_dynamic::type& jsArgAsDynamic(T&& args, size_t n); +typename detail::is_dynamic::type &jsArgAsDynamic(T &&args, size_t n); // Extract the n'th arg from the given dynamic, as a dynamic Array. Throws a // JsArgumentException if there is no n'th arg in the input, or it is not an // Array. template -typename detail::is_dynamic::type& jsArgAsArray(T&& args, size_t n); +typename detail::is_dynamic::type &jsArgAsArray(T &&args, size_t n); // Extract the n'th arg from the given dynamic, as a dynamic Object. Throws a // JsArgumentException if there is no n'th arg in the input, or it is not an // Object. template -typename detail::is_dynamic::type& jsArgAsObject(T&& args, size_t n); +typename detail::is_dynamic::type &jsArgAsObject(T &&args, size_t n); // Extract the n'th arg from the given dynamic, as a bool. Throws a // JsArgumentException if this fails for some reason. -inline bool jsArgAsBool(const folly::dynamic& args, size_t n) { +inline bool jsArgAsBool(const folly::dynamic &args, size_t n) +{ return jsArgN(args, n, &folly::dynamic::asBool); } // Extract the n'th arg from the given dynamic, as an integer. Throws a // JsArgumentException if this fails for some reason. -inline int64_t jsArgAsInt(const folly::dynamic& args, size_t n) { +inline int64_t jsArgAsInt(const folly::dynamic &args, size_t n) +{ return jsArgN(args, n, &folly::dynamic::asInt); } // Extract the n'th arg from the given dynamic, as a double. Throws a // JsArgumentException if this fails for some reason. -inline double jsArgAsDouble(const folly::dynamic& args, size_t n) { +inline double jsArgAsDouble(const folly::dynamic &args, size_t n) +{ return jsArgN(args, n, &folly::dynamic::asDouble); } // Extract the n'th arg from the given dynamic, as a string. Throws a // JsArgumentException if this fails for some reason. -inline std::string jsArgAsString(const folly::dynamic& args, size_t n) { +inline std::string jsArgAsString(const folly::dynamic &args, size_t n) +{ return jsArgN(args, n, &folly::dynamic::asString); } diff --git a/packages/react-native/ReactCommon/cxxreact/MessageQueueThread.h b/packages/react-native/ReactCommon/cxxreact/MessageQueueThread.h index 4c31f881a7d..724f7f7516d 100644 --- a/packages/react-native/ReactCommon/cxxreact/MessageQueueThread.h +++ b/packages/react-native/ReactCommon/cxxreact/MessageQueueThread.h @@ -14,10 +14,10 @@ namespace facebook::react { class MessageQueueThread { public: virtual ~MessageQueueThread() = default; - virtual void runOnQueue(std::function&&) = 0; + virtual void runOnQueue(std::function &&) = 0; // runOnQueueSync and quitSynchronous are dangerous. They should only be // used for initialization and cleanup. - virtual void runOnQueueSync(std::function&&) = 0; + virtual void runOnQueueSync(std::function &&) = 0; // Once quitSynchronous() returns, no further work should run on the queue. virtual void quitSynchronous() = 0; }; diff --git a/packages/react-native/ReactCommon/cxxreact/MethodCall.h b/packages/react-native/ReactCommon/cxxreact/MethodCall.h index af0ab2bf310..bf2aa8eb556 100644 --- a/packages/react-native/ReactCommon/cxxreact/MethodCall.h +++ b/packages/react-native/ReactCommon/cxxreact/MethodCall.h @@ -17,23 +17,21 @@ namespace facebook::react { -struct [[deprecated( - "This API will be removed along with the legacy architecture.")]] MethodCall { +struct [[deprecated("This API will be removed along with the legacy architecture.")]] MethodCall { int moduleId; int methodId; folly::dynamic arguments; int callId; - MethodCall(int mod, int meth, folly::dynamic&& args, int cid) - : moduleId(mod), - methodId(meth), - arguments(std::move(args)), - callId(cid) {} + MethodCall(int mod, int meth, folly::dynamic &&args, int cid) + : moduleId(mod), methodId(meth), arguments(std::move(args)), callId(cid) + { + } }; /// \throws std::invalid_argument [[deprecated("This API will be removed along with the legacy architecture.")]] -std::vector parseMethodCalls(folly::dynamic&& jsonData); +std::vector parseMethodCalls(folly::dynamic &&jsonData); } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/cxxreact/ModuleRegistry.h b/packages/react-native/ReactCommon/cxxreact/ModuleRegistry.h index a5e88f37622..831a69e62bb 100644 --- a/packages/react-native/ReactCommon/cxxreact/ModuleRegistry.h +++ b/packages/react-native/ReactCommon/cxxreact/ModuleRegistry.h @@ -25,14 +25,12 @@ namespace facebook::react { class NativeModule; -struct [[deprecated( - "This API will be removed along with the legacy architecture.")]] ModuleConfig { +struct [[deprecated("This API will be removed along with the legacy architecture.")]] ModuleConfig { size_t index; folly::dynamic config; }; -class RN_EXPORT [[deprecated( - "This API will be removed along with the legacy architecture.")]] ModuleRegistry { +class RN_EXPORT [[deprecated("This API will be removed along with the legacy architecture.")]] ModuleRegistry { public: // not implemented: // onBatchComplete: see @@ -41,31 +39,20 @@ class RN_EXPORT [[deprecated( // notifyCatalystInstanceInitialized: this is really only used by view-related // code notifyCatalystInstanceDestroy: use RAII instead - using ModuleNotFoundCallback = std::function; + using ModuleNotFoundCallback = std::function; - ModuleRegistry( - std::vector> modules, - ModuleNotFoundCallback callback = nullptr); + ModuleRegistry(std::vector> modules, ModuleNotFoundCallback callback = nullptr); void registerModules(std::vector> modules); std::vector moduleNames(); - std::optional getConfig(const std::string& name); + std::optional getConfig(const std::string &name); - void callNativeMethod( - unsigned int moduleId, - unsigned int methodId, - folly::dynamic&& params, - int callId); - MethodCallResult callSerializableNativeHook( - unsigned int moduleId, - unsigned int methodId, - folly::dynamic&& params); + void callNativeMethod(unsigned int moduleId, unsigned int methodId, folly::dynamic &¶ms, int callId); + MethodCallResult callSerializableNativeHook(unsigned int moduleId, unsigned int methodId, folly::dynamic &¶ms); std::string getModuleName(unsigned int moduleId); - std::string getModuleSyncMethodName( - unsigned int moduleId, - unsigned int methodId); + std::string getModuleSyncMethodName(unsigned int moduleId, unsigned int methodId); private: // This is always populated diff --git a/packages/react-native/ReactCommon/cxxreact/MoveWrapper.h b/packages/react-native/ReactCommon/cxxreact/MoveWrapper.h index 51e6696befb..22a9a0f238f 100644 --- a/packages/react-native/ReactCommon/cxxreact/MoveWrapper.h +++ b/packages/react-native/ReactCommon/cxxreact/MoveWrapper.h @@ -78,37 +78,42 @@ class MoveWrapper { MoveWrapper() = default; /// Move a value in. - explicit MoveWrapper(T&& t) : value(std::move(t)) {} + explicit MoveWrapper(T &&t) : value(std::move(t)) {} /// copy is move - MoveWrapper(const MoveWrapper& other) : value(std::move(other.value)) {} + MoveWrapper(const MoveWrapper &other) : value(std::move(other.value)) {} /// move is also move - MoveWrapper(MoveWrapper&& other) noexcept : value(std::move(other.value)) {} + MoveWrapper(MoveWrapper &&other) noexcept : value(std::move(other.value)) {} - const T& operator*() const { + const T &operator*() const + { return value; } - T& operator*() { + T &operator*() + { return value; } - const T* operator->() const { + const T *operator->() const + { return &value; } - T* operator->() { + T *operator->() + { return &value; } /// move the value out (sugar for std::move(*moveWrapper)) - T&& move() { + T &&move() + { return std::move(value); } // If you want these you're probably doing it wrong, though they'd be // easy enough to implement - MoveWrapper& operator=(const MoveWrapper&) = delete; - MoveWrapper& operator=(MoveWrapper&&) = delete; + MoveWrapper &operator=(const MoveWrapper &) = delete; + MoveWrapper &operator=(MoveWrapper &&) = delete; private: mutable T value; @@ -118,7 +123,8 @@ class MoveWrapper { /// is already quite transparent in its intent, this will work for lvalues as /// if you had wrapped them in std::move. template ::type> -MoveWrapper makeMoveWrapper(T&& t) { +MoveWrapper makeMoveWrapper(T &&t) +{ return MoveWrapper(std::forward(t)); } diff --git a/packages/react-native/ReactCommon/cxxreact/NativeModule.h b/packages/react-native/ReactCommon/cxxreact/NativeModule.h index 8d85cc8b38e..d8f49eabd0c 100644 --- a/packages/react-native/ReactCommon/cxxreact/NativeModule.h +++ b/packages/react-native/ReactCommon/cxxreact/NativeModule.h @@ -16,33 +16,27 @@ namespace facebook::react { #ifndef RCT_REMOVE_LEGACY_ARCH -struct [[deprecated( - "This API will be removed along with the legacy architecture.")]] MethodDescriptor { +struct [[deprecated("This API will be removed along with the legacy architecture.")]] MethodDescriptor { std::string name; // type is one of js MessageQueue.MethodTypes std::string type; - MethodDescriptor(std::string n, std::string t) - : name(std::move(n)), type(std::move(t)) {} + MethodDescriptor(std::string n, std::string t) : name(std::move(n)), type(std::move(t)) {} }; #endif // RCT_REMOVE_LEGACY_ARCH using MethodCallResult = std::optional; #ifndef RCT_REMOVE_LEGACY_ARCH -class [[deprecated( - "This API will be removed along with the legacy architecture.")]] NativeModule { +class [[deprecated("This API will be removed along with the legacy architecture.")]] NativeModule { public: virtual ~NativeModule() = default; virtual std::string getName() = 0; virtual std::string getSyncMethodName(unsigned int methodId) = 0; virtual std::vector getMethods() = 0; virtual folly::dynamic getConstants() = 0; - virtual void - invoke(unsigned int reactMethodId, folly::dynamic&& params, int callId) = 0; - virtual MethodCallResult callSerializableNativeHook( - unsigned int reactMethodId, - folly::dynamic&& args) = 0; + virtual void invoke(unsigned int reactMethodId, folly::dynamic &¶ms, int callId) = 0; + virtual MethodCallResult callSerializableNativeHook(unsigned int reactMethodId, folly::dynamic &&args) = 0; }; #endif // RCT_REMOVE_LEGACY_ARCH diff --git a/packages/react-native/ReactCommon/cxxreact/NativeToJsBridge.cpp b/packages/react-native/ReactCommon/cxxreact/NativeToJsBridge.cpp index 830613a3792..4f39102bb4e 100644 --- a/packages/react-native/ReactCommon/cxxreact/NativeToJsBridge.cpp +++ b/packages/react-native/ReactCommon/cxxreact/NativeToJsBridge.cpp @@ -38,8 +38,8 @@ namespace facebook::react { // This class manages calls from JS to native code. class [[deprecated( - "This API will be removed along with the legacy architecture.")]] JsToNativeBridge - : public react::ExecutorDelegate { + "This API will be removed along with the legacy architecture.")]] +JsToNativeBridge : public react::ExecutorDelegate { public: JsToNativeBridge( std::shared_ptr registry, diff --git a/packages/react-native/ReactCommon/cxxreact/NativeToJsBridge.h b/packages/react-native/ReactCommon/cxxreact/NativeToJsBridge.h index 92a1d1bf9d2..ac0d3a0c05b 100644 --- a/packages/react-native/ReactCommon/cxxreact/NativeToJsBridge.h +++ b/packages/react-native/ReactCommon/cxxreact/NativeToJsBridge.h @@ -38,8 +38,7 @@ class RAMBundleRegistry; // Except for loadBundleSync(), all void methods will queue // work to run on the jsQueue passed to the ctor, and return // immediately. -class [[deprecated( - "This API will be removed along with the legacy architecture.")]] NativeToJsBridge { +class [[deprecated("This API will be removed along with the legacy architecture.")]] NativeToJsBridge { public: friend class JsToNativeBridge; @@ -47,7 +46,7 @@ class [[deprecated( * This must be called on the main JS thread. */ NativeToJsBridge( - JSExecutorFactory* jsExecutorFactory, + JSExecutorFactory *jsExecutorFactory, std::shared_ptr registry, std::shared_ptr jsQueue, std::shared_ptr callback); @@ -57,15 +56,12 @@ class [[deprecated( * Executes a function with the module ID and method ID and any additional * arguments in JS. */ - void callFunction( - std::string&& module, - std::string&& method, - folly::dynamic&& arguments); + void callFunction(std::string &&module, std::string &&method, folly::dynamic &&arguments); /** * Invokes a callback with the cbID, and optional additional arguments in JS. */ - void invokeCallback(double callbackId, folly::dynamic&& arguments); + void invokeCallback(double callbackId, folly::dynamic &&arguments); /** * Sets global variables in the JS Context. @@ -86,11 +82,9 @@ class [[deprecated( std::unique_ptr startupScript, std::string sourceURL); - void registerBundle(uint32_t bundleId, const std::string& bundlePath); - void setGlobalVariable( - std::string propName, - std::unique_ptr jsonValue); - void* getJavaScriptContext(); + void registerBundle(uint32_t bundleId, const std::string &bundlePath); + void setGlobalVariable(std::string propName, std::unique_ptr jsonValue); + void *getJavaScriptContext(); bool isInspectable(); bool isBatchActive(); @@ -101,7 +95,7 @@ class [[deprecated( */ void destroy(); - void runOnExecutorQueue(std::function&& task) noexcept; + void runOnExecutorQueue(std::function &&task) noexcept; /** * NativeMethodCallInvoker is used by TurboModules to schedule work on the @@ -110,7 +104,7 @@ class [[deprecated( std::shared_ptr getDecoratedNativeMethodCallInvoker( std::shared_ptr nativeMethodCallInvoker) const; - jsinspector_modern::RuntimeTargetDelegate& getInspectorTargetDelegate(); + jsinspector_modern::RuntimeTargetDelegate &getInspectorTargetDelegate(); private: // This is used to avoid a race condition where a proxyCallback gets queued diff --git a/packages/react-native/ReactCommon/cxxreact/RAMBundleRegistry.h b/packages/react-native/ReactCommon/cxxreact/RAMBundleRegistry.h index d3d875ee8df..7951bf3dc3d 100644 --- a/packages/react-native/ReactCommon/cxxreact/RAMBundleRegistry.h +++ b/packages/react-native/ReactCommon/cxxreact/RAMBundleRegistry.h @@ -23,31 +23,28 @@ namespace facebook::react { -class RN_EXPORT [[deprecated( - "This API will be removed along with the legacy architecture.")]] RAMBundleRegistry { +class RN_EXPORT [[deprecated("This API will be removed along with the legacy architecture.")]] RAMBundleRegistry { public: constexpr static uint32_t MAIN_BUNDLE_ID = 0; - static std::unique_ptr singleBundleRegistry( - std::unique_ptr mainBundle); + static std::unique_ptr singleBundleRegistry(std::unique_ptr mainBundle); static std::unique_ptr multipleBundlesRegistry( std::unique_ptr mainBundle, std::function(std::string)> factory); explicit RAMBundleRegistry( std::unique_ptr mainBundle, - std::function(std::string)> factory = - nullptr); + std::function(std::string)> factory = nullptr); - RAMBundleRegistry(RAMBundleRegistry&&) = default; - RAMBundleRegistry& operator=(RAMBundleRegistry&&) = default; + RAMBundleRegistry(RAMBundleRegistry &&) = default; + RAMBundleRegistry &operator=(RAMBundleRegistry &&) = default; void registerBundle(uint32_t bundleId, std::string bundlePath); JSModulesUnbundle::Module getModule(uint32_t bundleId, uint32_t moduleId); virtual ~RAMBundleRegistry() = default; private: - JSModulesUnbundle* getBundle(uint32_t bundleId) const; + JSModulesUnbundle *getBundle(uint32_t bundleId) const; std::function(std::string)> m_factory; std::unordered_map m_bundlePaths; diff --git a/packages/react-native/ReactCommon/cxxreact/ReactMarker.h b/packages/react-native/ReactCommon/cxxreact/ReactMarker.h index 9c2f2e7628c..f1af8177b9a 100644 --- a/packages/react-native/ReactCommon/cxxreact/ReactMarker.h +++ b/packages/react-native/ReactCommon/cxxreact/ReactMarker.h @@ -37,14 +37,11 @@ enum ReactMarkerId { }; #ifdef __APPLE__ -using LogTaggedMarker = - std::function; // Bridge only -using LogTaggedMarkerBridgeless = - std::function; +using LogTaggedMarker = std::function; // Bridge only +using LogTaggedMarkerBridgeless = std::function; #else -typedef void ( - *LogTaggedMarker)(const ReactMarkerId, const char* tag); // Bridge only -typedef void (*LogTaggedMarkerBridgeless)(const ReactMarkerId, const char* tag); +typedef void (*LogTaggedMarker)(const ReactMarkerId, const char *tag); // Bridge only +typedef void (*LogTaggedMarkerBridgeless)(const ReactMarkerId, const char *tag); #endif #ifndef RN_EXPORT @@ -58,23 +55,20 @@ extern RN_EXPORT LogTaggedMarker logTaggedMarkerImpl; extern RN_EXPORT LogTaggedMarker logTaggedMarkerBridgelessImpl; extern RN_EXPORT void logMarker(ReactMarkerId markerId); // Bridge only -extern RN_EXPORT void logTaggedMarker( - ReactMarkerId markerId, - const char* tag); // Bridge only +extern RN_EXPORT void logTaggedMarker(ReactMarkerId markerId, + const char *tag); // Bridge only extern RN_EXPORT void logMarkerBridgeless(ReactMarkerId markerId); -extern RN_EXPORT void logTaggedMarkerBridgeless( - ReactMarkerId markerId, - const char* tag); +extern RN_EXPORT void logTaggedMarkerBridgeless(ReactMarkerId markerId, const char *tag); struct ReactMarkerEvent { const ReactMarkerId markerId; - const char* tag; + const char *tag; double time; }; class RN_EXPORT StartupLogger { public: - static StartupLogger& getInstance(); + static StartupLogger &getInstance(); void logStartupEvent(ReactMarkerId markerId, double markerTime); void reset(); @@ -87,8 +81,8 @@ class RN_EXPORT StartupLogger { private: StartupLogger() = default; - StartupLogger(const StartupLogger&) = delete; - StartupLogger& operator=(const StartupLogger&) = delete; + StartupLogger(const StartupLogger &) = delete; + StartupLogger &operator=(const StartupLogger &) = delete; double appStartupStartTime = std::nan(""); double appStartupEndTime = std::nan(""); diff --git a/packages/react-native/ReactCommon/cxxreact/RecoverableError.h b/packages/react-native/ReactCommon/cxxreact/RecoverableError.h index bf3907b9e52..980f6ce76f0 100644 --- a/packages/react-native/ReactCommon/cxxreact/RecoverableError.h +++ b/packages/react-native/ReactCommon/cxxreact/RecoverableError.h @@ -19,10 +19,10 @@ namespace facebook::react { * An exception that it is expected we should be able to recover from. */ struct RecoverableError : public std::exception { - explicit RecoverableError(const std::string& what_) - : m_what{"facebook::react::Recoverable: " + what_} {} + explicit RecoverableError(const std::string &what_) : m_what{"facebook::react::Recoverable: " + what_} {} - virtual const char* what() const noexcept override { + virtual const char *what() const noexcept override + { return m_what.c_str(); } @@ -33,10 +33,11 @@ struct RecoverableError : public std::exception { * `act` routine into a recoverable error with the same message. */ template - inline static void runRethrowingAsRecoverable(std::function act) { + inline static void runRethrowingAsRecoverable(std::function act) + { try { act(); - } catch (const E& err) { + } catch (const E &err) { throw RecoverableError(err.what()); } } diff --git a/packages/react-native/ReactCommon/cxxreact/SystraceSection.h b/packages/react-native/ReactCommon/cxxreact/SystraceSection.h index b98e17d7ddf..b32518823b6 100644 --- a/packages/react-native/ReactCommon/cxxreact/SystraceSection.h +++ b/packages/react-native/ReactCommon/cxxreact/SystraceSection.h @@ -17,11 +17,11 @@ namespace facebook::react { #if defined(WITH_LOOM_TRACE) #define SystraceSection TraceSection #else -struct [[deprecated("Use TraceSection")]] SystraceSection - : public TraceSection { +struct [[deprecated("Use TraceSection")]] SystraceSection : public TraceSection { template - explicit SystraceSection(const char* name, ConvertsToStringPiece&&... args) - : TraceSection(name, args...) {} + explicit SystraceSection(const char *name, ConvertsToStringPiece &&...args) : TraceSection(name, args...) + { + } }; #endif diff --git a/packages/react-native/ReactCommon/cxxreact/TraceSection.h b/packages/react-native/ReactCommon/cxxreact/TraceSection.h index 8b5cf045dd1..7dce45d8bde 100644 --- a/packages/react-native/ReactCommon/cxxreact/TraceSection.h +++ b/packages/react-native/ReactCommon/cxxreact/TraceSection.h @@ -69,13 +69,13 @@ namespace facebook::react { struct TraceSection { public: template - explicit TraceSection( - [[maybe_unused]] const char* name, - [[maybe_unused]] ConvertsToStringPiece&&... args) { + explicit TraceSection([[maybe_unused]] const char *name, [[maybe_unused]] ConvertsToStringPiece &&...args) + { TRACE_EVENT_BEGIN("react-native", perfetto::DynamicString{name}, args...); } - ~TraceSection() { + ~TraceSection() + { TRACE_EVENT_END("react-native"); } }; @@ -84,10 +84,10 @@ using TraceSectionUnwrapped = TraceSection; struct ConcreteTraceSection { public: template - explicit ConcreteTraceSection( - const char* name, - ConvertsToStringPiece&&... args) - : m_section(TRACE_TAG_REACT, name, args...) {} + explicit ConcreteTraceSection(const char *name, ConvertsToStringPiece &&...args) + : m_section(TRACE_TAG_REACT, name, args...) + { + } private: fbsystrace::FbSystraceSection m_section; @@ -97,9 +97,9 @@ using TraceSectionUnwrapped = ConcreteTraceSection; struct DummyTraceSection { public: template - explicit DummyTraceSection( - [[maybe_unused]] const char* name, - [[maybe_unused]] ConvertsToStringPiece&&... args) {} + explicit DummyTraceSection([[maybe_unused]] const char *name, [[maybe_unused]] ConvertsToStringPiece &&...args) + { + } }; using TraceSectionUnwrapped = DummyTraceSection; #endif @@ -110,14 +110,14 @@ using TraceSectionUnwrapped = DummyTraceSection; * In the case of WITH_LOOM_TRACE we don't use the signposts APIs because of the * templated type for TraceSection. */ -#if defined(__APPLE__) && OS_LOG_TARGET_HAS_10_15_FEATURES && \ - !defined(WITH_LOOM_TRACE) +#if defined(__APPLE__) && OS_LOG_TARGET_HAS_10_15_FEATURES && !defined(WITH_LOOM_TRACE) namespace systrace { template struct renderer { - static std::string render(const T& t) { + static std::string render(const T &t) + { std::ostringstream oss; oss << t; return oss.str(); @@ -125,19 +125,19 @@ struct renderer { }; template -static auto render(const T& t) - -> decltype(renderer::render(std::declval())) { +static auto render(const T &t) -> decltype(renderer::render(std::declval())) +{ return renderer::render(t); } inline os_log_t instrumentsLogHandle = nullptr; -static inline os_log_t getOrCreateInstrumentsLogHandle() { +static inline os_log_t getOrCreateInstrumentsLogHandle() +{ static std::once_flag flag{}; std::call_once(flag, []() { if (!instrumentsLogHandle) { - instrumentsLogHandle = os_log_create( - "dev.reactnative.instruments", OS_LOG_CATEGORY_DYNAMIC_TRACING); + instrumentsLogHandle = os_log_create("dev.reactnative.instruments", OS_LOG_CATEGORY_DYNAMIC_TRACING); } }); return instrumentsLogHandle; @@ -148,8 +148,8 @@ static inline os_log_t getOrCreateInstrumentsLogHandle() { struct TraceSection { public: template - explicit TraceSection(const char* name, ConvertsToStringPiece&&... args) - : systraceSectionUnwrapped_(name, args...) { + explicit TraceSection(const char *name, ConvertsToStringPiece &&...args) : systraceSectionUnwrapped_(name, args...) + { os_log_t instrumentsLogHandle = systrace::getOrCreateInstrumentsLogHandle(); // If the log isn't enabled, we don't want the performance overhead of the @@ -168,24 +168,14 @@ struct TraceSection { signpostID_ = os_signpost_id_make_with_pointer(instrumentsLogHandle, this); - os_signpost_interval_begin( - instrumentsLogHandle, - signpostID_, - "Systrace", - "%s begin: %s", - name, - argsString.c_str()); + os_signpost_interval_begin(instrumentsLogHandle, signpostID_, "Systrace", "%s begin: %s", name, argsString.c_str()); } - ~TraceSection() { + ~TraceSection() + { // We don't need to gate on os_signpost_enabled here because it's already // checked in os_signpost_interval_end. - os_signpost_interval_end( - systrace::instrumentsLogHandle, - signpostID_, - "Systrace", - "%s end", - name_.data()); + os_signpost_interval_end(systrace::instrumentsLogHandle, signpostID_, "Systrace", "%s end", name_.data()); } private: diff --git a/packages/react-native/ReactCommon/devtoolsruntimesettings/DevToolsRuntimeSettings.h b/packages/react-native/ReactCommon/devtoolsruntimesettings/DevToolsRuntimeSettings.h index aa6ae8dd750..d491f150d05 100644 --- a/packages/react-native/ReactCommon/devtoolsruntimesettings/DevToolsRuntimeSettings.h +++ b/packages/react-native/ReactCommon/devtoolsruntimesettings/DevToolsRuntimeSettings.h @@ -12,27 +12,24 @@ namespace facebook::react { using NativePartialReloadAndProfileConfig = - NativeReactDevToolsRuntimeSettingsModulePartialReloadAndProfileConfig< - std::optional, - std::optional>; + NativeReactDevToolsRuntimeSettingsModulePartialReloadAndProfileConfig, std::optional>; template <> struct Bridging : NativeReactDevToolsRuntimeSettingsModulePartialReloadAndProfileConfigBridging< NativePartialReloadAndProfileConfig> {}; -using NativeReloadAndProfileConfig = - NativeReactDevToolsRuntimeSettingsModuleReloadAndProfileConfig; +using NativeReloadAndProfileConfig = NativeReactDevToolsRuntimeSettingsModuleReloadAndProfileConfig; template <> struct Bridging - : NativeReactDevToolsRuntimeSettingsModuleReloadAndProfileConfigBridging< - NativeReloadAndProfileConfig> {}; + : NativeReactDevToolsRuntimeSettingsModuleReloadAndProfileConfigBridging {}; class DevToolsRuntimeSettings { public: // static to persist across Turbo Module reloads - static DevToolsRuntimeSettings& getInstance() { + static DevToolsRuntimeSettings &getInstance() + { static DevToolsRuntimeSettings instance; return instance; } @@ -44,10 +41,10 @@ class DevToolsRuntimeSettings { public: ~DevToolsRuntimeSettings() = default; - DevToolsRuntimeSettings(const DevToolsRuntimeSettings&) = delete; - DevToolsRuntimeSettings(DevToolsRuntimeSettings&&) = delete; - void operator=(const DevToolsRuntimeSettings&) = delete; - void operator=(DevToolsRuntimeSettings&&) = delete; + DevToolsRuntimeSettings(const DevToolsRuntimeSettings &) = delete; + DevToolsRuntimeSettings(DevToolsRuntimeSettings &&) = delete; + void operator=(const DevToolsRuntimeSettings &) = delete; + void operator=(DevToolsRuntimeSettings &&) = delete; void setReloadAndProfileConfig(NativePartialReloadAndProfileConfig config); NativeReloadAndProfileConfig getReloadAndProfileConfig() const; diff --git a/packages/react-native/ReactCommon/hermes/executor/HermesExecutorFactory.h b/packages/react-native/ReactCommon/hermes/executor/HermesExecutorFactory.h index 84d9891c484..ae50fd8577b 100644 --- a/packages/react-native/ReactCommon/hermes/executor/HermesExecutorFactory.h +++ b/packages/react-native/ReactCommon/hermes/executor/HermesExecutorFactory.h @@ -13,24 +13,21 @@ namespace facebook::react { -class [[deprecated( - "This API will be removed along with the legacy architecture.")]] HermesExecutorFactory +class [[deprecated("This API will be removed along with the legacy architecture.")]] HermesExecutorFactory : public JSExecutorFactory { public: explicit HermesExecutorFactory( JSIExecutor::RuntimeInstaller runtimeInstaller, - const JSIScopedTimeoutInvoker& timeoutInvoker = - JSIExecutor::defaultTimeoutInvoker, + const JSIScopedTimeoutInvoker &timeoutInvoker = JSIExecutor::defaultTimeoutInvoker, ::hermes::vm::RuntimeConfig runtimeConfig = defaultRuntimeConfig()) - : runtimeInstaller_(runtimeInstaller), - timeoutInvoker_(timeoutInvoker), - runtimeConfig_(std::move(runtimeConfig)) { + : runtimeInstaller_(runtimeInstaller), timeoutInvoker_(timeoutInvoker), runtimeConfig_(std::move(runtimeConfig)) + { assert(timeoutInvoker_ && "Should not have empty timeoutInvoker"); } void setEnableDebugger(bool enableDebugger); - void setDebuggerName(const std::string& debuggerName); + void setDebuggerName(const std::string &debuggerName); std::unique_ptr createJSExecutor( std::shared_ptr delegate, @@ -46,20 +43,18 @@ class [[deprecated( std::string debuggerName_ = "Hermes React Native"; }; -class [[deprecated( - "This API will be removed along with the legacy architecture.")]] HermesExecutor +class [[deprecated("This API will be removed along with the legacy architecture.")]] HermesExecutor : public JSIExecutor { public: HermesExecutor( std::shared_ptr runtime, std::shared_ptr delegate, std::shared_ptr jsQueue, - const JSIScopedTimeoutInvoker& timeoutInvoker, + const JSIScopedTimeoutInvoker &timeoutInvoker, RuntimeInstaller runtimeInstaller, - hermes::HermesRuntime& hermesRuntime); + hermes::HermesRuntime &hermesRuntime); - jsinspector_modern::RuntimeTargetDelegate& getRuntimeTargetDelegate() - override; + jsinspector_modern::RuntimeTargetDelegate &getRuntimeTargetDelegate() override; private: JSIScopedTimeoutInvoker timeoutInvoker_; diff --git a/packages/react-native/ReactCommon/hermes/inspector-modern/chrome/ConnectionDemux.cpp b/packages/react-native/ReactCommon/hermes/inspector-modern/chrome/ConnectionDemux.cpp index 2830d3199d6..ad07660ae18 100644 --- a/packages/react-native/ReactCommon/hermes/inspector-modern/chrome/ConnectionDemux.cpp +++ b/packages/react-native/ReactCommon/hermes/inspector-modern/chrome/ConnectionDemux.cpp @@ -89,8 +89,9 @@ DebugSessionToken ConnectionDemux::enableDebugging( auto waitForDebugger = (inspectedContexts_->find(title) != inspectedContexts_->end()); - return addPage(hermes::inspector_modern::chrome::CDPHandler::create( - std::move(adapter), title, waitForDebugger)); + return addPage( + hermes::inspector_modern::chrome::CDPHandler::create( + std::move(adapter), title, waitForDebugger)); } void ConnectionDemux::disableDebugging(DebugSessionToken session) { diff --git a/packages/react-native/ReactCommon/hermes/inspector-modern/chrome/ConnectionDemux.h b/packages/react-native/ReactCommon/hermes/inspector-modern/chrome/ConnectionDemux.h index 2fd75e563b2..cc8dae74f8a 100644 --- a/packages/react-native/ReactCommon/hermes/inspector-modern/chrome/ConnectionDemux.h +++ b/packages/react-native/ReactCommon/hermes/inspector-modern/chrome/ConnectionDemux.h @@ -30,30 +30,23 @@ namespace facebook::hermes::inspector_modern::chrome { */ class ConnectionDemux { public: - explicit ConnectionDemux( - facebook::react::jsinspector_modern::IInspector& inspector); + explicit ConnectionDemux(facebook::react::jsinspector_modern::IInspector &inspector); ~ConnectionDemux(); - ConnectionDemux(const ConnectionDemux&) = delete; - ConnectionDemux& operator=(const ConnectionDemux&) = delete; + ConnectionDemux(const ConnectionDemux &) = delete; + ConnectionDemux &operator=(const ConnectionDemux &) = delete; - DebugSessionToken enableDebugging( - std::unique_ptr adapter, - const std::string& title); + DebugSessionToken enableDebugging(std::unique_ptr adapter, const std::string &title); void disableDebugging(DebugSessionToken session); private: - int addPage( - std::shared_ptr conn); + int addPage(std::shared_ptr conn); void removePage(int pageId); - facebook::react::jsinspector_modern::IInspector& globalInspector_; + facebook::react::jsinspector_modern::IInspector &globalInspector_; std::mutex mutex_; - std::unordered_map< - int, - std::shared_ptr> - conns_; + std::unordered_map> conns_; std::shared_ptr> inspectedContexts_; }; diff --git a/packages/react-native/ReactCommon/hermes/inspector-modern/chrome/HermesRuntimeAgentDelegate.cpp b/packages/react-native/ReactCommon/hermes/inspector-modern/chrome/HermesRuntimeAgentDelegate.cpp index 451f4ec9c4e..7e3ce3b5d1f 100644 --- a/packages/react-native/ReactCommon/hermes/inspector-modern/chrome/HermesRuntimeAgentDelegate.cpp +++ b/packages/react-native/ReactCommon/hermes/inspector-modern/chrome/HermesRuntimeAgentDelegate.cpp @@ -50,19 +50,20 @@ class HermesRuntimeAgentDelegate::Impl final : public RuntimeAgentDelegate { HermesRuntime& runtime, HermesRuntimeTargetDelegate& runtimeTargetDelegate, const RuntimeExecutor& runtimeExecutor) - : hermes_(hermes::cdp::CDPAgent::create( - executionContextDescription.id, - runtimeTargetDelegate.getCDPDebugAPI(), - // RuntimeTask takes a HermesRuntime whereas our RuntimeExecutor - // takes a jsi::Runtime. - [runtimeExecutor, - &runtime](facebook::hermes::debugger::RuntimeTask fn) { - runtimeExecutor( - [&runtime, fn = std::move(fn)](auto&) { fn(runtime); }); - }, - std::move(frontendChannel), - HermesStateWrapper::unwrapDestructively( - previouslyExportedState.get()))) { + : hermes_( + hermes::cdp::CDPAgent::create( + executionContextDescription.id, + runtimeTargetDelegate.getCDPDebugAPI(), + // RuntimeTask takes a HermesRuntime whereas our RuntimeExecutor + // takes a jsi::Runtime. + [runtimeExecutor, + &runtime](facebook::hermes::debugger::RuntimeTask fn) { + runtimeExecutor( + [&runtime, fn = std::move(fn)](auto&) { fn(runtime); }); + }, + std::move(frontendChannel), + HermesStateWrapper::unwrapDestructively( + previouslyExportedState.get()))) { if (sessionState.isRuntimeDomainEnabled) { hermes_->enableRuntimeDomain(); } @@ -103,14 +104,15 @@ HermesRuntimeAgentDelegate::HermesRuntimeAgentDelegate( HermesRuntime& runtime, HermesRuntimeTargetDelegate& runtimeTargetDelegate, RuntimeExecutor runtimeExecutor) - : impl_(std::make_unique( - std::move(frontendChannel), - sessionState, - std::move(previouslyExportedState), - executionContextDescription, - runtime, - runtimeTargetDelegate, - std::move(runtimeExecutor))) {} + : impl_( + std::make_unique( + std::move(frontendChannel), + sessionState, + std::move(previouslyExportedState), + executionContextDescription, + runtime, + runtimeTargetDelegate, + std::move(runtimeExecutor))) {} bool HermesRuntimeAgentDelegate::handleRequest( const cdp::PreparsedRequest& req) { diff --git a/packages/react-native/ReactCommon/hermes/inspector-modern/chrome/HermesRuntimeAgentDelegate.h b/packages/react-native/ReactCommon/hermes/inspector-modern/chrome/HermesRuntimeAgentDelegate.h index d38e86358ca..2dbc170461a 100644 --- a/packages/react-native/ReactCommon/hermes/inspector-modern/chrome/HermesRuntimeAgentDelegate.h +++ b/packages/react-native/ReactCommon/hermes/inspector-modern/chrome/HermesRuntimeAgentDelegate.h @@ -48,12 +48,11 @@ class HermesRuntimeAgentDelegate : public RuntimeAgentDelegate { */ HermesRuntimeAgentDelegate( FrontendChannel frontendChannel, - SessionState& sessionState, - std::unique_ptr - previouslyExportedState, - const ExecutionContextDescription& executionContextDescription, - hermes::HermesRuntime& runtime, - HermesRuntimeTargetDelegate& runtimeTargetDelegate, + SessionState &sessionState, + std::unique_ptr previouslyExportedState, + const ExecutionContextDescription &executionContextDescription, + hermes::HermesRuntime &runtime, + HermesRuntimeTargetDelegate &runtimeTargetDelegate, RuntimeExecutor runtimeExecutor); /** @@ -64,10 +63,9 @@ class HermesRuntimeAgentDelegate : public RuntimeAgentDelegate { * to the request (with either a success or error message). False if the * agent expects another agent to respond to the request instead. */ - bool handleRequest(const cdp::PreparsedRequest& req) override; + bool handleRequest(const cdp::PreparsedRequest &req) override; - std::unique_ptr getExportedState() - override; + std::unique_ptr getExportedState() override; private: class Impl; @@ -78,6 +76,5 @@ class HermesRuntimeAgentDelegate : public RuntimeAgentDelegate { } // namespace facebook::react::jsinspector_modern #else -#error \ - "HERMES_ENABLE_DEBUGGER must be enabled to use HermesRuntimeAgentDelegate." +#error "HERMES_ENABLE_DEBUGGER must be enabled to use HermesRuntimeAgentDelegate." #endif // HERMES_ENABLE_DEBUGGER diff --git a/packages/react-native/ReactCommon/hermes/inspector-modern/chrome/HermesRuntimeSamplingProfileSerializer.h b/packages/react-native/ReactCommon/hermes/inspector-modern/chrome/HermesRuntimeSamplingProfileSerializer.h index 7bc3396be2a..a81b3c70e53 100644 --- a/packages/react-native/ReactCommon/hermes/inspector-modern/chrome/HermesRuntimeSamplingProfileSerializer.h +++ b/packages/react-native/ReactCommon/hermes/inspector-modern/chrome/HermesRuntimeSamplingProfileSerializer.h @@ -15,9 +15,10 @@ namespace facebook::react::jsinspector_modern::tracing { class RawHermesRuntimeProfile : public RawRuntimeProfile { public: - explicit RawHermesRuntimeProfile( - hermes::sampling_profiler::Profile hermesProfile) - : hermesProfile_{std::move(hermesProfile)} {} + explicit RawHermesRuntimeProfile(hermes::sampling_profiler::Profile hermesProfile) + : hermesProfile_{std::move(hermesProfile)} + { + } private: hermes::sampling_profiler::Profile hermesProfile_; diff --git a/packages/react-native/ReactCommon/hermes/inspector-modern/chrome/HermesRuntimeTargetDelegate.h b/packages/react-native/ReactCommon/hermes/inspector-modern/chrome/HermesRuntimeTargetDelegate.h index 9fc4f9c85a4..07a63f2c47e 100644 --- a/packages/react-native/ReactCommon/hermes/inspector-modern/chrome/HermesRuntimeTargetDelegate.h +++ b/packages/react-native/ReactCommon/hermes/inspector-modern/chrome/HermesRuntimeTargetDelegate.h @@ -29,8 +29,7 @@ class HermesRuntimeTargetDelegate : public RuntimeTargetDelegate { /** * Creates a HermesRuntimeTargetDelegate for the given runtime. */ - explicit HermesRuntimeTargetDelegate( - std::shared_ptr hermesRuntime); + explicit HermesRuntimeTargetDelegate(std::shared_ptr hermesRuntime); ~HermesRuntimeTargetDelegate() override; @@ -38,28 +37,22 @@ class HermesRuntimeTargetDelegate : public RuntimeTargetDelegate { std::unique_ptr createAgentDelegate( jsinspector_modern::FrontendChannel frontendChannel, - jsinspector_modern::SessionState& sessionState, - std::unique_ptr - previouslyExportedState, - const jsinspector_modern::ExecutionContextDescription& - executionContextDescription, + jsinspector_modern::SessionState &sessionState, + std::unique_ptr previouslyExportedState, + const jsinspector_modern::ExecutionContextDescription &executionContextDescription, RuntimeExecutor runtimeExecutor) override; - void addConsoleMessage(jsi::Runtime& runtime, ConsoleMessage message) - override; + void addConsoleMessage(jsi::Runtime &runtime, ConsoleMessage message) override; bool supportsConsole() const override; - std::unique_ptr captureStackTrace( - jsi::Runtime& runtime, - size_t framesToSkip) override; + std::unique_ptr captureStackTrace(jsi::Runtime &runtime, size_t framesToSkip) override; void enableSamplingProfiler() override; void disableSamplingProfiler() override; tracing::RuntimeSamplingProfile collectSamplingProfile() override; - std::optional serializeStackTrace( - const StackTrace& stackTrace) override; + std::optional serializeStackTrace(const StackTrace &stackTrace) override; private: // We use the private implementation idiom to ensure this class has the same @@ -73,7 +66,7 @@ class HermesRuntimeTargetDelegate : public RuntimeTargetDelegate { #ifdef HERMES_ENABLE_DEBUGGER friend class HermesRuntimeAgentDelegate; - hermes::cdp::CDPDebugAPI& getCDPDebugAPI(); + hermes::cdp::CDPDebugAPI &getCDPDebugAPI(); #endif std::unique_ptr impl_; diff --git a/packages/react-native/ReactCommon/hermes/inspector-modern/chrome/Registration.h b/packages/react-native/ReactCommon/hermes/inspector-modern/chrome/Registration.h index 3a5853b0756..2b60c27a6ee 100644 --- a/packages/react-native/ReactCommon/hermes/inspector-modern/chrome/Registration.h +++ b/packages/react-native/ReactCommon/hermes/inspector-modern/chrome/Registration.h @@ -25,9 +25,7 @@ using DebugSessionToken = int; * should be called before any JS runs in the runtime. The returned token * can be used to disable debugging for this runtime. */ -extern DebugSessionToken enableDebugging( - std::unique_ptr adapter, - const std::string& title); +extern DebugSessionToken enableDebugging(std::unique_ptr adapter, const std::string &title); /* * disableDebugging removes this runtime from the list of debuggable JS targets diff --git a/packages/react-native/ReactCommon/jserrorhandler/JsErrorHandler.cpp b/packages/react-native/ReactCommon/jserrorhandler/JsErrorHandler.cpp index bc630ca9625..3ed51ff06c4 100644 --- a/packages/react-native/ReactCommon/jserrorhandler/JsErrorHandler.cpp +++ b/packages/react-native/ReactCommon/jserrorhandler/JsErrorHandler.cpp @@ -219,7 +219,7 @@ std::ostream& operator<<( JsErrorHandler::JsErrorHandler(JsErrorHandler::OnJsError onJsError) : _onJsError(std::move(onJsError)), - _inErrorHandler(std::make_shared(false)){ + _inErrorHandler(std::make_shared(false)) { }; diff --git a/packages/react-native/ReactCommon/jserrorhandler/JsErrorHandler.h b/packages/react-native/ReactCommon/jserrorhandler/JsErrorHandler.h index 455dc215ac6..2a7919f4c6a 100644 --- a/packages/react-native/ReactCommon/jserrorhandler/JsErrorHandler.h +++ b/packages/react-native/ReactCommon/jserrorhandler/JsErrorHandler.h @@ -21,9 +21,7 @@ class JsErrorHandler { std::string methodName; std::optional lineNumber; std::optional column; - friend std::ostream& operator<<( - std::ostream& os, - const StackFrame& frame); + friend std::ostream &operator<<(std::ostream &os, const StackFrame &frame); }; std::string message; @@ -34,25 +32,17 @@ class JsErrorHandler { int id; bool isFatal; jsi::Object extraData; - friend std::ostream& operator<<( - std::ostream& os, - const ProcessedError& error); + friend std::ostream &operator<<(std::ostream &os, const ProcessedError &error); }; - using OnJsError = - std::function; + using OnJsError = std::function; explicit JsErrorHandler(OnJsError onJsError); ~JsErrorHandler(); - void handleError( - jsi::Runtime& runtime, - jsi::JSError& error, - bool isFatal, - bool logToConsole = true); + void handleError(jsi::Runtime &runtime, jsi::JSError &error, bool isFatal, bool logToConsole = true); bool hasHandledFatalError(); - void registerErrorListener( - const std::function& listener); + void registerErrorListener(const std::function &listener); void setRuntimeReady(); bool isRuntimeReady(); void notifyOfFatalError(); @@ -70,13 +60,9 @@ class JsErrorHandler { bool _hasHandledFatalError{}; bool _isRuntimeReady{}; std::shared_ptr _inErrorHandler; - std::vector> _errorListeners; + std::vector> _errorListeners; - void handleErrorWithCppPipeline( - jsi::Runtime& runtime, - jsi::JSError& error, - bool isFatal, - bool logToConsole); + void handleErrorWithCppPipeline(jsi::Runtime &runtime, jsi::JSError &error, bool isFatal, bool logToConsole); }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/jserrorhandler/StackTraceParser.h b/packages/react-native/ReactCommon/jserrorhandler/StackTraceParser.h index e69787ca0ab..92436c4c60c 100644 --- a/packages/react-native/ReactCommon/jserrorhandler/StackTraceParser.h +++ b/packages/react-native/ReactCommon/jserrorhandler/StackTraceParser.h @@ -15,9 +15,7 @@ namespace facebook::react { class StackTraceParser { public: - static std::vector parse( - bool isHermes, - const std::string& stackString); + static std::vector parse(bool isHermes, const std::string &stackString); }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/jsi/jsi/test/testlib.cpp b/packages/react-native/ReactCommon/jsi/jsi/test/testlib.cpp index b37b4bfe471..74b820f14f6 100644 --- a/packages/react-native/ReactCommon/jsi/jsi/test/testlib.cpp +++ b/packages/react-native/ReactCommon/jsi/jsi/test/testlib.cpp @@ -44,19 +44,23 @@ TEST_P(JSITest, PropNameIDTest) { EXPECT_TRUE(PropNameID::compare(rt, movedQuux, copiedQuux)); EXPECT_TRUE(PropNameID::compare(rt, movedQuux, movedQuux)); - EXPECT_TRUE(PropNameID::compare( - rt, movedQuux, PropNameID::forAscii(rt, std::string("quux2")))); - EXPECT_FALSE(PropNameID::compare( - rt, movedQuux, PropNameID::forAscii(rt, std::string("foo")))); + EXPECT_TRUE( + PropNameID::compare( + rt, movedQuux, PropNameID::forAscii(rt, std::string("quux2")))); + EXPECT_FALSE( + PropNameID::compare( + rt, movedQuux, PropNameID::forAscii(rt, std::string("foo")))); uint8_t utf8[] = {0xF0, 0x9F, 0x86, 0x97}; PropNameID utf8PropNameID = PropNameID::forUtf8(rt, utf8, sizeof(utf8)); EXPECT_EQ( utf8PropNameID.utf8(rt), reinterpret_cast(u8"\U0001F197")); - EXPECT_TRUE(PropNameID::compare( - rt, utf8PropNameID, PropNameID::forUtf8(rt, utf8, sizeof(utf8)))); + EXPECT_TRUE( + PropNameID::compare( + rt, utf8PropNameID, PropNameID::forUtf8(rt, utf8, sizeof(utf8)))); PropNameID nonUtf8PropNameID = PropNameID::forUtf8(rt, "meow"); - EXPECT_TRUE(PropNameID::compare( - rt, nonUtf8PropNameID, PropNameID::forAscii(rt, "meow"))); + EXPECT_TRUE( + PropNameID::compare( + rt, nonUtf8PropNameID, PropNameID::forAscii(rt, "meow"))); EXPECT_EQ(nonUtf8PropNameID.utf8(rt), "meow"); PropNameID strPropNameID = PropNameID::forString(rt, String::createFromAscii(rt, "meow")); @@ -149,11 +153,12 @@ TEST_P(JSITest, ObjectTest) { obj.setProperty(rt, "oprop", oprop); obj.setProperty(rt, "aprop", Array(rt, 1)); - EXPECT_TRUE(function("function (obj) { return " - "obj.roses == 'red' && " - "obj['violets'] == 'blue' && " - "typeof obj.oprop == 'object' && " - "Array.isArray(obj.aprop); }") + EXPECT_TRUE(function( + "function (obj) { return " + "obj.roses == 'red' && " + "obj['violets'] == 'blue' && " + "typeof obj.oprop == 'object' && " + "Array.isArray(obj.aprop); }") .call(rt, obj) .getBool()); @@ -247,7 +252,7 @@ TEST_P(JSITest, HostObjectTest) { EXPECT_TRUE(cho.getHostObject(rt).get() != nullptr); struct SameRuntimeHostObject : HostObject { - SameRuntimeHostObject(Runtime& rt) : rt_(rt){}; + SameRuntimeHostObject(Runtime& rt) : rt_(rt) {}; Value get(Runtime& rt, const PropNameID& sym) override { EXPECT_EQ(&rt, &rt_); @@ -731,14 +736,15 @@ TEST_P(JSITest, HostFunctionTest) { EXPECT_TRUE(eval("cons.length == 2").getBool()); EXPECT_TRUE(eval("cons instanceof Function").getBool()); - EXPECT_TRUE(eval("(function() {" - " try {" - " cons('fail'); return false;" - " } catch (e) {" - " return ((e instanceof Error) &&" - " (e.message == 'Exception in HostFunction: ' +" - " 'expected 2 args'));" - " }})()") + EXPECT_TRUE(eval( + "(function() {" + " try {" + " cons('fail'); return false;" + " } catch (e) {" + " return ((e instanceof Error) &&" + " (e.message == 'Exception in HostFunction: ' +" + " 'expected 2 args'));" + " }})()") .getBool()); Function coolify = Function::createFromHostFunction( @@ -755,10 +761,11 @@ TEST_P(JSITest, HostFunctionTest) { EXPECT_TRUE(eval("coolify.name == 'coolify'").getBool()); EXPECT_TRUE(eval("coolify.length == 0").getBool()); EXPECT_TRUE(eval("coolify.bind('R&M')() == 'R&M is cool'").getBool()); - EXPECT_TRUE(eval("(function() {" - " var s = coolify.bind(function(){})();" - " return s.lastIndexOf(' is cool') == (s.length - 8);" - "})()") + EXPECT_TRUE(eval( + "(function() {" + " var s = coolify.bind(function(){})();" + " return s.lastIndexOf(' is cool') == (s.length - 8);" + "})()") .getBool()); Function lookAtMe = Function::createFromHostFunction( @@ -887,14 +894,15 @@ TEST_P(JSITest, ValueTest) { uint8_t utf8[] = "[null, 2, \"c\", \"emoji: \xf0\x9f\x86\x97\", {}]"; EXPECT_TRUE( - function("function (arr) { return " - "Array.isArray(arr) && " - "arr.length == 5 && " - "arr[0] === null && " - "arr[1] == 2 && " - "arr[2] == 'c' && " - "arr[3] == 'emoji: \\uD83C\\uDD97' && " - "typeof arr[4] == 'object'; }") + function( + "function (arr) { return " + "Array.isArray(arr) && " + "arr.length == 5 && " + "arr[0] === null && " + "arr[1] == 2 && " + "arr[2] == 'c' && " + "arr[3] == 'emoji: \\uD83C\\uDD97' && " + "typeof arr[4] == 'object'; }") .call(rt, Value::createFromJsonUtf8(rt, utf8, sizeof(utf8) - 1)) .getBool()); @@ -936,14 +944,16 @@ TEST_P(JSITest, EqualsTest) { EXPECT_TRUE(Value::strictEquals(rt, nullptr, nullptr)); EXPECT_TRUE(Value::strictEquals(rt, Value::undefined(), Value())); EXPECT_TRUE(Value::strictEquals(rt, rt.global(), Value(rt.global()))); - EXPECT_FALSE(Value::strictEquals( - rt, - std::numeric_limits::quiet_NaN(), - std::numeric_limits::quiet_NaN())); - EXPECT_FALSE(Value::strictEquals( - rt, - std::numeric_limits::signaling_NaN(), - std::numeric_limits::signaling_NaN())); + EXPECT_FALSE( + Value::strictEquals( + rt, + std::numeric_limits::quiet_NaN(), + std::numeric_limits::quiet_NaN())); + EXPECT_FALSE( + Value::strictEquals( + rt, + std::numeric_limits::signaling_NaN(), + std::numeric_limits::signaling_NaN())); EXPECT_TRUE(Value::strictEquals(rt, +0.0, -0.0)); EXPECT_TRUE(Value::strictEquals(rt, -0.0, +0.0)); @@ -1089,8 +1099,9 @@ TEST_P(JSITest, JSErrorDoesNotInfinitelyRecurse) { return rt.global().getPropertyAsObject(rt, "NotAProperty"); }; EXPECT_EQ( - function("function (f) { try { f(); return 'undefined'; }" - "catch (e) { return typeof e; } }") + function( + "function (f) { try { f(); return 'undefined'; }" + "catch (e) { return typeof e; } }") .call( rt, Function::createFromHostFunction( @@ -1330,18 +1341,21 @@ TEST_P(JSITest, SymbolTest) { EXPECT_EQ(eval("Symbol('sym')").getSymbol(rt).toString(rt), "Symbol(sym)"); // EqualsTest - EXPECT_FALSE(Symbol::strictEquals( - rt, - eval("Symbol('a')").getSymbol(rt), - eval("Symbol('a')").getSymbol(rt))); - EXPECT_TRUE(Symbol::strictEquals( - rt, - eval("Symbol.for('a')").getSymbol(rt), - eval("Symbol.for('a')").getSymbol(rt))); + EXPECT_FALSE( + Symbol::strictEquals( + rt, + eval("Symbol('a')").getSymbol(rt), + eval("Symbol('a')").getSymbol(rt))); + EXPECT_TRUE( + Symbol::strictEquals( + rt, + eval("Symbol.for('a')").getSymbol(rt), + eval("Symbol.for('a')").getSymbol(rt))); EXPECT_FALSE( Value::strictEquals(rt, eval("Symbol('a')"), eval("Symbol('a')"))); - EXPECT_TRUE(Value::strictEquals( - rt, eval("Symbol.for('a')"), eval("Symbol.for('a')"))); + EXPECT_TRUE( + Value::strictEquals( + rt, eval("Symbol.for('a')"), eval("Symbol.for('a')"))); EXPECT_FALSE(Value::strictEquals(rt, eval("Symbol('a')"), eval("'a'"))); } @@ -1352,13 +1366,15 @@ TEST_P(JSITest, JSErrorTest) { // Getting message property can throw EXPECT_THROW( - eval("var GetMessageThrows = {get message() { throw Error('ex'); }};" - "throw GetMessageThrows;"), + eval( + "var GetMessageThrows = {get message() { throw Error('ex'); }};" + "throw GetMessageThrows;"), JSIException); EXPECT_THROW( - eval("var GetMessageThrows = {get message() { throw GetMessageThrows; }};" - "throw GetMessageThrows;"), + eval( + "var GetMessageThrows = {get message() { throw GetMessageThrows; }};" + "throw GetMessageThrows;"), JSIException); // Converting exception message to String can throw @@ -1381,18 +1397,20 @@ TEST_P(JSITest, JSErrorTest) { JSIException); EXPECT_THROW( - eval("var e = Error();" - "String = function() { throw Error('ctor'); };" - "throw e;"), + eval( + "var e = Error();" + "String = function() { throw Error('ctor'); };" + "throw e;"), JSIException); // Converting an exception message to String can return a non-String EXPECT_THROW( - eval("String = function() { return 42; };" - "var e = Error();" - "e.message = 17;" - "throw e;"), + eval( + "String = function() { return 42; };" + "var e = Error();" + "e.message = 17;" + "throw e;"), JSIException); // Exception can be non-Object @@ -1404,8 +1422,9 @@ TEST_P(JSITest, JSErrorTest) { // Converting exception with no message or stack property to String can throw EXPECT_THROW( - eval("var e = {toString() { throw new Error('errstr'); }};" - "throw e;"), + eval( + "var e = {toString() { throw new Error('errstr'); }};" + "throw e;"), JSIException); } diff --git a/packages/react-native/ReactCommon/jsiexecutor/jsireact/JSIExecutor.cpp b/packages/react-native/ReactCommon/jsiexecutor/jsireact/JSIExecutor.cpp index 8922b5a18fe..0a47fcaeb0a 100644 --- a/packages/react-native/ReactCommon/jsiexecutor/jsireact/JSIExecutor.cpp +++ b/packages/react-native/ReactCommon/jsiexecutor/jsireact/JSIExecutor.cpp @@ -74,8 +74,9 @@ JSIExecutor::JSIExecutor( RuntimeInstaller runtimeInstaller) : runtime_(runtime), delegate_(delegate), - nativeModules_(std::make_shared( - delegate ? delegate->getModuleRegistry() : nullptr)), + nativeModules_( + std::make_shared( + delegate ? delegate->getModuleRegistry() : nullptr)), moduleRegistry_(delegate ? delegate->getModuleRegistry() : nullptr), scopedTimeoutInvoker_(scopedTimeoutInvoker), runtimeInstaller_(runtimeInstaller) { @@ -268,8 +269,9 @@ void JSIExecutor::invokeCallback( ret = invokeCallbackAndReturnFlushedQueue_->call( *runtime_, callbackId, valueFromDynamic(*runtime_, arguments)); } catch (...) { - std::throw_with_nested(std::runtime_error( - "Error invoking callback " + std::to_string(callbackId))); + std::throw_with_nested( + std::runtime_error( + "Error invoking callback " + std::to_string(callbackId))); } callNativeModules(ret, true); diff --git a/packages/react-native/ReactCommon/jsiexecutor/jsireact/JSIExecutor.h b/packages/react-native/ReactCommon/jsiexecutor/jsireact/JSIExecutor.h index 84b236be215..b8d8b2e11de 100644 --- a/packages/react-native/ReactCommon/jsiexecutor/jsireact/JSIExecutor.h +++ b/packages/react-native/ReactCommon/jsiexecutor/jsireact/JSIExecutor.h @@ -46,66 +46,56 @@ namespace facebook::react { // return "someBigWork, param " + std::to_string(param); // }) // -using JSIScopedTimeoutInvoker = std::function& invokee, - std::function errorMessageProducer)>; +using JSIScopedTimeoutInvoker = + std::function &invokee, std::function errorMessageProducer)>; class BigStringBuffer : public jsi::Buffer { public: - BigStringBuffer(std::unique_ptr script) - : script_(std::move(script)) {} + BigStringBuffer(std::unique_ptr script) : script_(std::move(script)) {} - size_t size() const override { + size_t size() const override + { return script_->size(); } - const uint8_t* data() const override { - return reinterpret_cast(script_->c_str()); + const uint8_t *data() const override + { + return reinterpret_cast(script_->c_str()); } private: std::unique_ptr script_; }; -class [[deprecated( - "This API will be removed along with the legacy architecture.")]] JSIExecutor - : public JSExecutor { +class [[deprecated("This API will be removed along with the legacy architecture.")]] JSIExecutor : public JSExecutor { public: - using RuntimeInstaller = std::function; + using RuntimeInstaller = std::function; JSIExecutor( std::shared_ptr runtime, std::shared_ptr delegate, - const JSIScopedTimeoutInvoker& timeoutInvoker, + const JSIScopedTimeoutInvoker &timeoutInvoker, RuntimeInstaller runtimeInstaller); void initializeRuntime() override; - void loadBundle( - std::unique_ptr script, - std::string sourceURL) override; + void loadBundle(std::unique_ptr script, std::string sourceURL) override; #ifndef RCT_REMOVE_LEGACY_ARCH void setBundleRegistry(std::unique_ptr r) override; #endif // RCT_REMOVE_LEGACY_ARCH - void registerBundle(uint32_t bundleId, const std::string& bundlePath) - override; - void callFunction( - const std::string& moduleId, - const std::string& methodId, - const folly::dynamic& arguments) override; - void invokeCallback(double callbackId, const folly::dynamic& arguments) - override; - void setGlobalVariable( - std::string propName, - std::unique_ptr jsonValue) override; + void registerBundle(uint32_t bundleId, const std::string &bundlePath) override; + void callFunction(const std::string &moduleId, const std::string &methodId, const folly::dynamic &arguments) override; + void invokeCallback(double callbackId, const folly::dynamic &arguments) override; + void setGlobalVariable(std::string propName, std::unique_ptr jsonValue) override; std::string getDescription() override; - void* getJavaScriptContext() override; + void *getJavaScriptContext() override; bool isInspectable() override; void handleMemoryPressure(int pressureLevel) override; // An implementation of JSIScopedTimeoutInvoker that simply runs the // invokee, with no timeout. static void defaultTimeoutInvoker( - const std::function& invokee, - std::function errorMessageProducer) { + const std::function &invokee, + std::function errorMessageProducer) + { (void)errorMessageProducer; invokee(); } @@ -117,10 +107,10 @@ class [[deprecated( class NativeModuleProxy; void bindBridge(); - void callNativeModules(const jsi::Value& queue, bool isEndOfBatch); - jsi::Value nativeCallSyncHook(const jsi::Value* args, size_t count); - jsi::Value nativeRequire(const jsi::Value* args, size_t count); - jsi::Value globalEvalWithSourceUrl(const jsi::Value* args, size_t count); + void callNativeModules(const jsi::Value &queue, bool isEndOfBatch); + jsi::Value nativeCallSyncHook(const jsi::Value *args, size_t count); + jsi::Value nativeRequire(const jsi::Value *args, size_t count); + jsi::Value globalEvalWithSourceUrl(const jsi::Value *args, size_t count); std::shared_ptr runtime_; std::shared_ptr delegate_; @@ -137,11 +127,10 @@ class [[deprecated( #endif // RCT_REMOVE_LEGACY_ARCH }; -using Logger = - std::function; -void bindNativeLogger(jsi::Runtime& runtime, Logger logger); +using Logger = std::function; +void bindNativeLogger(jsi::Runtime &runtime, Logger logger); -void bindNativePerformanceNow(jsi::Runtime& runtime); +void bindNativePerformanceNow(jsi::Runtime &runtime); double performanceNow(); } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/jsiexecutor/jsireact/JSINativeModules.h b/packages/react-native/ReactCommon/jsiexecutor/jsireact/JSINativeModules.h index b3fbb25c50d..c23f183a146 100644 --- a/packages/react-native/ReactCommon/jsiexecutor/jsireact/JSINativeModules.h +++ b/packages/react-native/ReactCommon/jsiexecutor/jsireact/JSINativeModules.h @@ -21,11 +21,10 @@ namespace facebook::react { /** * Holds and creates JS representations of the modules in ModuleRegistry */ -class [[deprecated( - "This API will be removed along with the legacy architecture.")]] JSINativeModules { +class [[deprecated("This API will be removed along with the legacy architecture.")]] JSINativeModules { public: explicit JSINativeModules(std::shared_ptr moduleRegistry); - jsi::Value getModule(jsi::Runtime& rt, const jsi::PropNameID& name); + jsi::Value getModule(jsi::Runtime &rt, const jsi::PropNameID &name); void reset(); private: @@ -33,9 +32,7 @@ class [[deprecated( std::shared_ptr m_moduleRegistry; std::unordered_map m_objects; - std::optional createModule( - jsi::Runtime& rt, - const std::string& name); + std::optional createModule(jsi::Runtime &rt, const std::string &name); }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/jsinspector-modern/Base64.h b/packages/react-native/ReactCommon/jsinspector-modern/Base64.h index ff720c298ac..0057445de0a 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/Base64.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/Base64.h @@ -15,19 +15,17 @@ namespace facebook::react::jsinspector_modern { namespace { // Vendored from Folly // https://github.com/facebook/folly/blob/v2024.07.08.00/folly/detail/base64_detail/Base64Scalar.h -constexpr char kBase64Charset[] = - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; +constexpr char kBase64Charset[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; -constexpr char kBase64URLCharset[] = - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; +constexpr char kBase64URLCharset[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; template struct Base64ScalarImpl { - static constexpr const char* kCharset = - isURL ? kBase64URLCharset : kBase64Charset; + static constexpr const char *kCharset = isURL ? kBase64URLCharset : kBase64Charset; // 0, 1 or 2 bytes - static constexpr char* encodeTail(const char* f, const char* l, char* o) { + static constexpr char *encodeTail(const char *f, const char *l, char *o) + { if (f == l) { return o; } @@ -59,7 +57,8 @@ struct Base64ScalarImpl { return o; } - static constexpr char* encode(const char* f, const char* l, char* o) { + static constexpr char *encode(const char *f, const char *l, char *o) + { while ((l - f) >= 3) { std::uint8_t aaab = f[0]; std::uint8_t bbcc = f[1]; @@ -84,12 +83,14 @@ struct Base64ScalarImpl { }; // https://github.com/facebook/folly/blob/v2024.07.08.00/folly/detail/base64_detail/Base64Common.h#L24 -constexpr std::size_t base64EncodedSize(std::size_t inSize) { +constexpr std::size_t base64EncodedSize(std::size_t inSize) +{ return ((inSize + 2) / 3) * 4; } } // namespace -inline std::string base64Encode(const std::string_view s) { +inline std::string base64Encode(const std::string_view s) +{ std::string res(base64EncodedSize(s.size()), '\0'); Base64ScalarImpl::encode(s.data(), s.data() + s.size(), res.data()); return res; diff --git a/packages/react-native/ReactCommon/jsinspector-modern/ConsoleMessage.h b/packages/react-native/ReactCommon/jsinspector-modern/ConsoleMessage.h index 6130ca572d7..c22a969b387 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/ConsoleMessage.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/ConsoleMessage.h @@ -43,18 +43,14 @@ struct SimpleConsoleMessage { ConsoleAPIType type; std::vector args; - SimpleConsoleMessage( - double timestamp, - ConsoleAPIType type, - std::vector args); + SimpleConsoleMessage(double timestamp, ConsoleAPIType type, std::vector args); SimpleConsoleMessage(ConsoleAPIType type, std::vector args); - SimpleConsoleMessage(const SimpleConsoleMessage& other) = delete; - SimpleConsoleMessage(SimpleConsoleMessage&& other) noexcept = default; - SimpleConsoleMessage& operator=(const SimpleConsoleMessage& other) = delete; - SimpleConsoleMessage& operator=(SimpleConsoleMessage&& other) noexcept = - default; + SimpleConsoleMessage(const SimpleConsoleMessage &other) = delete; + SimpleConsoleMessage(SimpleConsoleMessage &&other) noexcept = default; + SimpleConsoleMessage &operator=(const SimpleConsoleMessage &other) = delete; + SimpleConsoleMessage &operator=(SimpleConsoleMessage &&other) noexcept = default; ~SimpleConsoleMessage() = default; }; @@ -72,17 +68,16 @@ struct ConsoleMessage { ConsoleAPIType type, std::vector args, std::unique_ptr stackTrace = StackTrace::empty()) - : timestamp(timestamp), - type(type), - args(std::move(args)), - stackTrace(std::move(stackTrace)) {} + : timestamp(timestamp), type(type), args(std::move(args)), stackTrace(std::move(stackTrace)) + { + } - ConsoleMessage(jsi::Runtime& runtime, SimpleConsoleMessage message); + ConsoleMessage(jsi::Runtime &runtime, SimpleConsoleMessage message); - ConsoleMessage(const ConsoleMessage& other) = delete; - ConsoleMessage(ConsoleMessage&& other) noexcept = default; - ConsoleMessage& operator=(const ConsoleMessage& other) = delete; - ConsoleMessage& operator=(ConsoleMessage&& other) noexcept = default; + ConsoleMessage(const ConsoleMessage &other) = delete; + ConsoleMessage(ConsoleMessage &&other) noexcept = default; + ConsoleMessage &operator=(const ConsoleMessage &other) = delete; + ConsoleMessage &operator=(ConsoleMessage &&other) noexcept = default; ~ConsoleMessage() = default; }; diff --git a/packages/react-native/ReactCommon/jsinspector-modern/EnumArray.h b/packages/react-native/ReactCommon/jsinspector-modern/EnumArray.h index 975f4d93614..ae25023c4cf 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/EnumArray.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/EnumArray.h @@ -18,22 +18,23 @@ namespace facebook::react::jsinspector_modern { * Requires that the enum class has a kMaxValue member. */ template - requires std::is_enum_v && - std::is_same_v, int> && - requires { IndexType::kMaxValue; } && - (static_cast(IndexType::kMaxValue) < std::numeric_limits::max()) + requires std::is_enum_v && std::is_same_v, int> && + requires { IndexType::kMaxValue; } && (static_cast(IndexType::kMaxValue) < std::numeric_limits::max()) class EnumArray { public: - constexpr ValueType& operator[](IndexType i) { + constexpr ValueType &operator[](IndexType i) + { return array_[static_cast(i)]; } - constexpr const ValueType& operator[](IndexType i) const { + constexpr const ValueType &operator[](IndexType i) const + { return array_[static_cast(i)]; } - constexpr int size() const { + constexpr int size() const + { return size_; } diff --git a/packages/react-native/ReactCommon/jsinspector-modern/ExecutionContext.h b/packages/react-native/ReactCommon/jsinspector-modern/ExecutionContext.h index b8c099a9c3c..c47bfc9ba26 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/ExecutionContext.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/ExecutionContext.h @@ -31,7 +31,7 @@ class ExecutionContextSelector { /** * Returns true iff this selector matches \c context. */ - bool matches(const ExecutionContextDescription& context) const noexcept; + bool matches(const ExecutionContextDescription &context) const noexcept; /** * Returns a new selector that matches only the given execution context ID. @@ -49,15 +49,14 @@ class ExecutionContextSelector { static ExecutionContextSelector all(); ExecutionContextSelector() = delete; - ExecutionContextSelector(const ExecutionContextSelector& other) = default; - ExecutionContextSelector(ExecutionContextSelector&& other) noexcept = default; - ExecutionContextSelector& operator=(const ExecutionContextSelector& other) = - default; - ExecutionContextSelector& operator=( - ExecutionContextSelector&& other) noexcept = default; + ExecutionContextSelector(const ExecutionContextSelector &other) = default; + ExecutionContextSelector(ExecutionContextSelector &&other) noexcept = default; + ExecutionContextSelector &operator=(const ExecutionContextSelector &other) = default; + ExecutionContextSelector &operator=(ExecutionContextSelector &&other) noexcept = default; ~ExecutionContextSelector() = default; - inline bool operator==(const ExecutionContextSelector& other) const noexcept { + inline bool operator==(const ExecutionContextSelector &other) const noexcept + { return value_ == other.value_; } @@ -75,20 +74,16 @@ class ExecutionContextSelector { using Representation = std::variant; - explicit inline ExecutionContextSelector(Representation&& r) : value_(r) {} + explicit inline ExecutionContextSelector(Representation &&r) : value_(r) {} Representation value_; - friend struct std::hash< - facebook::react::jsinspector_modern::ExecutionContextSelector>; + friend struct std::hash; }; -using ExecutionContextSelectorSet = - std::unordered_set; +using ExecutionContextSelectorSet = std::unordered_set; -bool matchesAny( - const ExecutionContextDescription& context, - const ExecutionContextSelectorSet& selectors); +bool matchesAny(const ExecutionContextDescription &context, const ExecutionContextSelectorSet &selectors); } // namespace facebook::react::jsinspector_modern @@ -96,12 +91,9 @@ namespace std { template <> struct hash<::facebook::react::jsinspector_modern::ExecutionContextSelector> { - size_t operator()( - const ::facebook::react::jsinspector_modern::ExecutionContextSelector& - selector) const { - return hash<::facebook::react::jsinspector_modern:: - ExecutionContextSelector::Representation>{}( - selector.value_); + size_t operator()(const ::facebook::react::jsinspector_modern::ExecutionContextSelector &selector) const + { + return hash<::facebook::react::jsinspector_modern::ExecutionContextSelector::Representation>{}(selector.value_); } }; diff --git a/packages/react-native/ReactCommon/jsinspector-modern/FallbackRuntimeAgentDelegate.cpp b/packages/react-native/ReactCommon/jsinspector-modern/FallbackRuntimeAgentDelegate.cpp index 8e65edc9cf3..22a7b89138f 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/FallbackRuntimeAgentDelegate.cpp +++ b/packages/react-native/ReactCommon/jsinspector-modern/FallbackRuntimeAgentDelegate.cpp @@ -56,16 +56,17 @@ void FallbackRuntimeAgentDelegate::sendFallbackRuntimeWarning() { } void FallbackRuntimeAgentDelegate::sendWarningLogEntry(std::string_view text) { - frontendChannel_(cdp::jsonNotification( - "Log.entryAdded", - folly::dynamic::object( - "entry", + frontendChannel_( + cdp::jsonNotification( + "Log.entryAdded", folly::dynamic::object( - "timestamp", - duration_cast( - system_clock::now().time_since_epoch()) - .count())("source", "other")("level", "warning")( - "text", text)))); + "entry", + folly::dynamic::object( + "timestamp", + duration_cast( + system_clock::now().time_since_epoch()) + .count())("source", "other")("level", "warning")( + "text", text)))); } } // namespace facebook::react::jsinspector_modern diff --git a/packages/react-native/ReactCommon/jsinspector-modern/FallbackRuntimeAgentDelegate.h b/packages/react-native/ReactCommon/jsinspector-modern/FallbackRuntimeAgentDelegate.h index 1c9934f02e4..17eeaf666f1 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/FallbackRuntimeAgentDelegate.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/FallbackRuntimeAgentDelegate.h @@ -29,7 +29,7 @@ class FallbackRuntimeAgentDelegate : public RuntimeAgentDelegate { */ FallbackRuntimeAgentDelegate( FrontendChannel frontendChannel, - const SessionState& sessionState, + const SessionState &sessionState, std::string engineDescription); /** @@ -40,7 +40,7 @@ class FallbackRuntimeAgentDelegate : public RuntimeAgentDelegate { * to the request (with either a success or error message). False if the * agent expects another agent to respond to the request instead. */ - bool handleRequest(const cdp::PreparsedRequest& req) override; + bool handleRequest(const cdp::PreparsedRequest &req) override; private: /** diff --git a/packages/react-native/ReactCommon/jsinspector-modern/FallbackRuntimeTargetDelegate.h b/packages/react-native/ReactCommon/jsinspector-modern/FallbackRuntimeTargetDelegate.h index 9507eb2379d..0af607370a5 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/FallbackRuntimeTargetDelegate.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/FallbackRuntimeTargetDelegate.h @@ -25,20 +25,16 @@ class FallbackRuntimeTargetDelegate : public RuntimeTargetDelegate { std::unique_ptr createAgentDelegate( FrontendChannel channel, - SessionState& sessionState, - std::unique_ptr - previouslyExportedState, - const ExecutionContextDescription& executionContextDescription, + SessionState &sessionState, + std::unique_ptr previouslyExportedState, + const ExecutionContextDescription &executionContextDescription, RuntimeExecutor runtimeExecutor) override; - void addConsoleMessage(jsi::Runtime& runtime, ConsoleMessage message) - override; + void addConsoleMessage(jsi::Runtime &runtime, ConsoleMessage message) override; bool supportsConsole() const override; - std::unique_ptr captureStackTrace( - jsi::Runtime& runtime, - size_t framesToSkip) override; + std::unique_ptr captureStackTrace(jsi::Runtime &runtime, size_t framesToSkip) override; void enableSamplingProfiler() override; @@ -46,8 +42,7 @@ class FallbackRuntimeTargetDelegate : public RuntimeTargetDelegate { tracing::RuntimeSamplingProfile collectSamplingProfile() override; - std::optional serializeStackTrace( - const StackTrace& stackTrace) override; + std::optional serializeStackTrace(const StackTrace &stackTrace) override; private: std::string engineDescription_; diff --git a/packages/react-native/ReactCommon/jsinspector-modern/HostAgent.cpp b/packages/react-native/ReactCommon/jsinspector-modern/HostAgent.cpp index bebb24a3bd7..60a33116bd1 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/HostAgent.cpp +++ b/packages/react-native/ReactCommon/jsinspector-modern/HostAgent.cpp @@ -212,9 +212,10 @@ class HostAgent::Impl final { sendFuseboxNotice(); } - frontendChannel_(cdp::jsonNotification( - "ReactNativeApplication.metadataUpdated", - createHostMetadataPayload(hostMetadata_))); + frontendChannel_( + cdp::jsonNotification( + "ReactNativeApplication.metadataUpdated", + createHostMetadataPayload(hostMetadata_))); auto stashedTraceRecording = targetController_.getDelegate() @@ -251,10 +252,11 @@ class HostAgent::Impl final { auto executionContextId = req.params["executionContextId"].getInt(); if (executionContextId < (int64_t)std::numeric_limits::min() || executionContextId > (int64_t)std::numeric_limits::max()) { - frontendChannel_(cdp::jsonError( - req.id, - cdp::ErrorCode::InvalidParams, - "Invalid execution context id")); + frontendChannel_( + cdp::jsonError( + req.id, + cdp::ErrorCode::InvalidParams, + "Invalid execution context id")); return { .isFinishedHandlingRequest = true, .shouldSendOKResponse = false, @@ -264,10 +266,11 @@ class HostAgent::Impl final { ExecutionContextSelector::byId((int32_t)executionContextId); if (req.params.count("executionContextName") != 0u) { - frontendChannel_(cdp::jsonError( - req.id, - cdp::ErrorCode::InvalidParams, - "executionContextName is mutually exclusive with executionContextId")); + frontendChannel_( + cdp::jsonError( + req.id, + cdp::ErrorCode::InvalidParams, + "executionContextName is mutually exclusive with executionContextId")); return { .isFinishedHandlingRequest = true, .shouldSendOKResponse = false, @@ -390,16 +393,17 @@ class HostAgent::Impl final { for (auto arg : args) { argsArray.push_back(arg); } - frontendChannel_(cdp::jsonNotification( - "Log.entryAdded", - folly::dynamic::object( - "entry", + frontendChannel_( + cdp::jsonNotification( + "Log.entryAdded", folly::dynamic::object( - "timestamp", - duration_cast( - system_clock::now().time_since_epoch()) - .count())("source", "other")("level", "info")("text", text)( - "args", std::move(argsArray))))); + "entry", + folly::dynamic::object( + "timestamp", + duration_cast( + system_clock::now().time_since_epoch()) + .count())("source", "other")("level", "info")( + "text", text)("args", std::move(argsArray))))); } void sendFuseboxNotice() { @@ -486,13 +490,14 @@ HostAgent::HostAgent( HostTargetMetadata hostMetadata, SessionState& sessionState, VoidExecutor executor) - : impl_(std::make_unique( - *this, - frontendChannel, - targetController, - std::move(hostMetadata), - sessionState, - std::move(executor))) {} + : impl_( + std::make_unique( + *this, + frontendChannel, + targetController, + std::move(hostMetadata), + sessionState, + std::move(executor))) {} HostAgent::~HostAgent() = default; diff --git a/packages/react-native/ReactCommon/jsinspector-modern/HostAgent.h b/packages/react-native/ReactCommon/jsinspector-modern/HostAgent.h index 306c4126acd..afb8bf44ad4 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/HostAgent.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/HostAgent.h @@ -38,16 +38,16 @@ class HostAgent final { * \param executor A void executor to be used by async-aware handlers. */ HostAgent( - const FrontendChannel& frontendChannel, - HostTargetController& targetController, + const FrontendChannel &frontendChannel, + HostTargetController &targetController, HostTargetMetadata hostMetadata, - SessionState& sessionState, + SessionState &sessionState, VoidExecutor executor); - HostAgent(const HostAgent&) = delete; - HostAgent(HostAgent&&) = delete; - HostAgent& operator=(const HostAgent&) = delete; - HostAgent& operator=(HostAgent&&) = delete; + HostAgent(const HostAgent &) = delete; + HostAgent(HostAgent &&) = delete; + HostAgent &operator=(const HostAgent &) = delete; + HostAgent &operator=(HostAgent &&) = delete; ~HostAgent(); @@ -56,7 +56,7 @@ class HostAgent final { * \c FrontendChannel synchronously or asynchronously. * \param req The parsed request. */ - void handleRequest(const cdp::PreparsedRequest& req); + void handleRequest(const cdp::PreparsedRequest &req); /** * Replace the current InstanceAgent with the given one and notify the @@ -77,8 +77,7 @@ class HostAgent final { * Emits the trace recording that was captured externally, not via the * CDP-initiated request. */ - void emitExternalTraceRecording( - tracing::TraceRecordingState traceRecording) const; + void emitExternalTraceRecording(tracing::TraceRecordingState traceRecording) const; private: // We use the private implementation idiom to ensure this class has the same @@ -100,12 +99,12 @@ class HostAgent final { */ class HostTracingAgent : tracing::TargetTracingAgent { public: - explicit HostTracingAgent(tracing::TraceRecordingState& state); + explicit HostTracingAgent(tracing::TraceRecordingState &state); /** * Registers the InstanceTarget with this tracing agent. */ - void setTracedInstance(InstanceTarget* instanceTarget); + void setTracedInstance(InstanceTarget *instanceTarget); private: std::shared_ptr instanceTracingAgent_{nullptr}; diff --git a/packages/react-native/ReactCommon/jsinspector-modern/HostTarget.cpp b/packages/react-native/ReactCommon/jsinspector-modern/HostTarget.cpp index dd93631d912..f42238a2b2f 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/HostTarget.cpp +++ b/packages/react-native/ReactCommon/jsinspector-modern/HostTarget.cpp @@ -63,8 +63,9 @@ class HostTargetSession { cdp::jsonError(std::nullopt, cdp::ErrorCode::ParseError, e.what())); return; } catch (const cdp::TypeError& e) { - frontendChannel_(cdp::jsonError( - std::nullopt, cdp::ErrorCode::InvalidRequest, e.what())); + frontendChannel_( + cdp::jsonError( + std::nullopt, cdp::ErrorCode::InvalidRequest, e.what())); return; } @@ -170,28 +171,30 @@ class HostRuntimeBinding { HostTarget& target, std::string name, std::function callback) - : connection_(target.connect(std::make_unique( - [callback = std::move(callback)](const std::string& message) { - auto parsedMessage = folly::parseJson(message); + : connection_(target.connect( + std::make_unique( + [callback = std::move(callback)](const std::string& message) { + auto parsedMessage = folly::parseJson(message); - // Ignore initial Runtime.addBinding response - if (parsedMessage["id"] == 0 && - parsedMessage["result"].isObject() && - parsedMessage["result"].empty()) { - return; - } + // Ignore initial Runtime.addBinding response + if (parsedMessage["id"] == 0 && + parsedMessage["result"].isObject() && + parsedMessage["result"].empty()) { + return; + } - // Assert that we only intercept bindingCalled responses - assert( - parsedMessage["method"].asString() == - "Runtime.bindingCalled"); - callback(parsedMessage["params"]["payload"].asString()); - }))) { + // Assert that we only intercept bindingCalled responses + assert( + parsedMessage["method"].asString() == + "Runtime.bindingCalled"); + callback(parsedMessage["params"]["payload"].asString()); + }))) { // Install runtime binding - connection_->sendMessage(cdp::jsonRequest( - 0, - "Runtime.addBinding", - folly::dynamic::object("name", std::move(name)))); + connection_->sendMessage( + cdp::jsonRequest( + 0, + "Runtime.addBinding", + folly::dynamic::object("name", std::move(name)))); } private: diff --git a/packages/react-native/ReactCommon/jsinspector-modern/HostTarget.h b/packages/react-native/ReactCommon/jsinspector-modern/HostTarget.h index 0c360f83d48..aacaa3e7ced 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/HostTarget.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/HostTarget.h @@ -60,10 +60,10 @@ struct HostTargetMetadata { class HostTargetDelegate : public LoadNetworkResourceDelegate { public: HostTargetDelegate() = default; - HostTargetDelegate(const HostTargetDelegate&) = delete; - HostTargetDelegate(HostTargetDelegate&&) = delete; - HostTargetDelegate& operator=(const HostTargetDelegate&) = delete; - HostTargetDelegate& operator=(HostTargetDelegate&&) = delete; + HostTargetDelegate(const HostTargetDelegate &) = delete; + HostTargetDelegate(HostTargetDelegate &&) = delete; + HostTargetDelegate &operator=(const HostTargetDelegate &) = delete; + HostTargetDelegate &operator=(HostTargetDelegate &&) = delete; // TODO(moti): This is 1:1 the shape of the corresponding CDP message - // consider reusing typed/generated CDP interfaces when we have those. @@ -78,9 +78,9 @@ class HostTargetDelegate : public LoadNetworkResourceDelegate { /** * Equality operator, useful for unit tests */ - inline bool operator==(const PageReloadRequest& rhs) const { - return ignoreCache == rhs.ignoreCache && - scriptToEvaluateOnLoad == rhs.scriptToEvaluateOnLoad; + inline bool operator==(const PageReloadRequest &rhs) const + { + return ignoreCache == rhs.ignoreCache && scriptToEvaluateOnLoad == rhs.scriptToEvaluateOnLoad; } }; @@ -93,8 +93,8 @@ class HostTargetDelegate : public LoadNetworkResourceDelegate { /** * Equality operator, useful for unit tests */ - inline bool operator==( - const OverlaySetPausedInDebuggerMessageRequest& rhs) const { + inline bool operator==(const OverlaySetPausedInDebuggerMessageRequest &rhs) const + { return message == rhs.message; } }; @@ -112,7 +112,7 @@ class HostTargetDelegate : public LoadNetworkResourceDelegate { * the thread on which messages are dispatched to the session (that is, where * ILocalConnection::sendMessage was called). */ - virtual void onReload(const PageReloadRequest& request) = 0; + virtual void onReload(const PageReloadRequest &request) = 0; /** * Called when the debugger requests that the "paused in debugger" overlay be @@ -124,8 +124,7 @@ class HostTargetDelegate : public LoadNetworkResourceDelegate { * the timing and payload of these messages are fully controlled by the * client. */ - virtual void onSetPausedInDebuggerMessage( - const OverlaySetPausedInDebuggerMessageRequest& request) = 0; + virtual void onSetPausedInDebuggerMessage(const OverlaySetPausedInDebuggerMessageRequest &request) = 0; /** * Called by NetworkIOAgent on handling a `Network.loadNetworkResource` CDP @@ -134,8 +133,9 @@ class HostTargetDelegate : public LoadNetworkResourceDelegate { * of headers, data chunks, and errors. */ void loadNetworkResource( - const LoadNetworkResourceRequest& /*params*/, - ScopedExecutor /*executor*/) override { + const LoadNetworkResourceRequest & /*params*/, + ScopedExecutor /*executor*/) override + { throw NotImplementedException( "LoadNetworkResourceDelegate.loadNetworkResource is not implemented by this host target delegate."); } @@ -148,8 +148,8 @@ class HostTargetDelegate : public LoadNetworkResourceDelegate { * \return the trace recording state if there is one that needs to be * displayed, otherwise std::nullopt. */ - virtual std::optional - unstable_getTraceRecordingThatWillBeEmittedOnInitialization() { + virtual std::optional unstable_getTraceRecordingThatWillBeEmittedOnInitialization() + { return std::nullopt; } }; @@ -160,9 +160,9 @@ class HostTargetDelegate : public LoadNetworkResourceDelegate { */ class HostTargetController final { public: - explicit HostTargetController(HostTarget& target); + explicit HostTargetController(HostTarget &target); - HostTargetDelegate& getDelegate(); + HostTargetDelegate &getDelegate(); bool hasInstance() const; @@ -199,7 +199,7 @@ class HostTargetController final { tracing::TraceRecordingState stopTracing(); private: - HostTarget& target_; + HostTarget &target_; size_t pauseOverlayCounter_{0}; }; @@ -208,8 +208,7 @@ class HostTargetController final { * "Host" in React Native's architecture - the entity that manages the * lifecycle of a React Instance. */ -class JSINSPECTOR_EXPORT HostTarget - : public EnableExecutorFromThis { +class JSINSPECTOR_EXPORT HostTarget : public EnableExecutorFromThis { public: /** * Constructs a new HostTarget. @@ -224,14 +223,12 @@ class JSINSPECTOR_EXPORT HostTarget * that such destructor calls are safe - e.g. if using a lambda as the * executor, all captured values must be safe to destroy from any thread. */ - static std::shared_ptr create( - HostTargetDelegate& delegate, - VoidExecutor executor); + static std::shared_ptr create(HostTargetDelegate &delegate, VoidExecutor executor); - HostTarget(const HostTarget&) = delete; - HostTarget(HostTarget&&) = delete; - HostTarget& operator=(const HostTarget&) = delete; - HostTarget& operator=(HostTarget&&) = delete; + HostTarget(const HostTarget &) = delete; + HostTarget(HostTarget &&) = delete; + HostTarget &operator=(const HostTarget &) = delete; + HostTarget &operator=(HostTarget &&) = delete; ~HostTarget(); /** @@ -241,8 +238,7 @@ class JSINSPECTOR_EXPORT HostTarget * is destroyed, on the same thread where HostTarget's constructor and * destructor execute. */ - std::unique_ptr connect( - std::unique_ptr connectionToFrontend); + std::unique_ptr connect(std::unique_ptr connectionToFrontend); /** * Registers an instance with this HostTarget. @@ -254,14 +250,14 @@ class JSINSPECTOR_EXPORT HostTarget * (or the HostTarget is destroyed). \pre There isn't currently an instance * registered with this HostTarget. */ - InstanceTarget& registerInstance(InstanceTargetDelegate& delegate); + InstanceTarget ®isterInstance(InstanceTargetDelegate &delegate); /** * Unregisters an instance from this HostTarget. * \param instance The InstanceTarget reference previously returned by * registerInstance. */ - void unregisterInstance(InstanceTarget& instance); + void unregisterInstance(InstanceTarget &instance); /** * Sends an imperative command to the HostTarget. May be called from any @@ -276,8 +272,7 @@ class JSINSPECTOR_EXPORT HostTarget * * \param state A reference to the state of the active trace recording. */ - std::shared_ptr createTracingAgent( - tracing::TraceRecordingState& state); + std::shared_ptr createTracingAgent(tracing::TraceRecordingState &state); /** * Starts trace recording for this HostTarget. @@ -309,8 +304,7 @@ class JSINSPECTOR_EXPORT HostTarget * * @see \c hasActiveFrontendSession */ - void emitTraceRecordingForFirstFuseboxClient( - tracing::TraceRecordingState traceRecording) const; + void emitTraceRecordingForFirstFuseboxClient(tracing::TraceRecordingState traceRecording) const; private: /** @@ -320,9 +314,9 @@ class JSINSPECTOR_EXPORT HostTarget * receive events from this HostTarget. The caller is responsible for ensuring * that the HostTargetDelegate outlives this object. */ - HostTarget(HostTargetDelegate& delegate); + HostTarget(HostTargetDelegate &delegate); - HostTargetDelegate& delegate_; + HostTargetDelegate &delegate_; WeakList sessions_; HostTargetController controller_{*this}; // executionContextManager_ is a shared_ptr to guarantee its validity while @@ -341,11 +335,13 @@ class JSINSPECTOR_EXPORT HostTarget */ std::unique_ptr traceRecording_{nullptr}; - inline HostTargetDelegate& getDelegate() { + inline HostTargetDelegate &getDelegate() + { return delegate_; } - inline bool hasInstance() const { + inline bool hasInstance() const + { return currentInstance_ != nullptr; } @@ -355,6 +351,6 @@ class JSINSPECTOR_EXPORT HostTarget friend class HostTargetController; }; -folly::dynamic createHostMetadataPayload(const HostTargetMetadata& metadata); +folly::dynamic createHostMetadataPayload(const HostTargetMetadata &metadata); } // namespace facebook::react::jsinspector_modern diff --git a/packages/react-native/ReactCommon/jsinspector-modern/HostTargetTraceRecording.h b/packages/react-native/ReactCommon/jsinspector-modern/HostTargetTraceRecording.h index b6157d510d5..18f42e027e8 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/HostTargetTraceRecording.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/HostTargetTraceRecording.h @@ -28,22 +28,22 @@ namespace facebook::react::jsinspector_modern { */ class HostTargetTraceRecording { public: - explicit HostTargetTraceRecording( - tracing::Mode tracingMode, - HostTarget& hostTarget); + explicit HostTargetTraceRecording(tracing::Mode tracingMode, HostTarget &hostTarget); - inline bool isBackgroundInitiated() const { + inline bool isBackgroundInitiated() const + { return tracingMode_ == tracing::Mode::Background; } - inline bool isUserInitiated() const { + inline bool isUserInitiated() const + { return tracingMode_ == tracing::Mode::CDP; } /** * Updates the current traced Instance for this recording. */ - void setTracedInstance(InstanceTarget* instanceTarget); + void setTracedInstance(InstanceTarget *instanceTarget); /** * Starts the recording. @@ -68,7 +68,7 @@ class HostTargetTraceRecording { /** * The Host for which this Trace Recording is going to happen. */ - HostTarget& hostTarget_; + HostTarget &hostTarget_; /** * The state of the current Trace Recording. diff --git a/packages/react-native/ReactCommon/jsinspector-modern/InspectorFlags.h b/packages/react-native/ReactCommon/jsinspector-modern/InspectorFlags.h index a644f17663c..77610239b29 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/InspectorFlags.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/InspectorFlags.h @@ -17,7 +17,7 @@ namespace facebook::react::jsinspector_modern { */ class InspectorFlags { public: - static InspectorFlags& getInstance(); + static InspectorFlags &getInstance(); /** * Flag determining if the modern CDP backend should be enabled. @@ -52,19 +52,19 @@ class InspectorFlags { bool fuseboxEnabled; bool isProfilingBuild; bool networkInspectionEnabled; - bool operator==(const Values&) const = default; + bool operator==(const Values &) const = default; }; InspectorFlags() = default; - InspectorFlags(const InspectorFlags&) = delete; - InspectorFlags& operator=(const InspectorFlags&) = default; + InspectorFlags(const InspectorFlags &) = delete; + InspectorFlags &operator=(const InspectorFlags &) = default; ~InspectorFlags() = default; mutable std::optional cachedValues_; mutable bool inconsistentFlagsStateLogged_{false}; bool fuseboxDisabledForTest_{false}; - const Values& loadFlagsAndAssertUnchanged() const; + const Values &loadFlagsAndAssertUnchanged() const; }; } // namespace facebook::react::jsinspector_modern diff --git a/packages/react-native/ReactCommon/jsinspector-modern/InspectorInterfaces.h b/packages/react-native/ReactCommon/jsinspector-modern/InspectorInterfaces.h index fb38b0acdf8..04e45131e5e 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/InspectorInterfaces.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/InspectorInterfaces.h @@ -39,8 +39,7 @@ struct InspectorTargetCapabilities { bool prefersFuseboxFrontend = false; }; -folly::dynamic targetCapabilitiesToDynamic( - const InspectorTargetCapabilities& capabilities); +folly::dynamic targetCapabilitiesToDynamic(const InspectorTargetCapabilities &capabilities); struct InspectorPageDescription { const int id; @@ -85,8 +84,7 @@ class JSINSPECTOR_EXPORT IPageStatusListener : public IDestructible { /// IInspector tracks debuggable JavaScript targets (pages). class JSINSPECTOR_EXPORT IInspector : public IDestructible { public: - using ConnectFunc = std::function( - std::unique_ptr)>; + using ConnectFunc = std::function(std::unique_ptr)>; virtual ~IInspector() = 0; @@ -100,8 +98,8 @@ class JSINSPECTOR_EXPORT IInspector : public IDestructible { * \returns the ID assigned to the new page. */ virtual int addPage( - const std::string& description, - const std::string& vm, + const std::string &description, + const std::string &vm, ConnectFunc connectFunc, InspectorTargetCapabilities capabilities = {}) = 0; @@ -122,24 +120,21 @@ class JSINSPECTOR_EXPORT IInspector : public IDestructible { * \returns an ILocalConnection that can be used to send messages to the * page, or nullptr if the connection has been rejected. */ - virtual std::unique_ptr connect( - int pageId, - std::unique_ptr remote) = 0; + virtual std::unique_ptr connect(int pageId, std::unique_ptr remote) = 0; /** * registerPageStatusListener registers a listener that will receive events * when pages are removed. */ - virtual void registerPageStatusListener( - std::weak_ptr listener) = 0; + virtual void registerPageStatusListener(std::weak_ptr listener) = 0; }; class NotImplementedException : public std::exception { public: - explicit NotImplementedException(std::string message) - : msg_(std::move(message)) {} + explicit NotImplementedException(std::string message) : msg_(std::move(message)) {} - const char* what() const noexcept override { + const char *what() const noexcept override + { return msg_.c_str(); } @@ -149,7 +144,7 @@ class NotImplementedException : public std::exception { /// getInspectorInstance retrieves the singleton inspector that tracks all /// debuggable pages in this process. -extern IInspector& getInspectorInstance(); +extern IInspector &getInspectorInstance(); /// makeTestInspectorInstance creates an independent inspector instance that /// should only be used in tests. diff --git a/packages/react-native/ReactCommon/jsinspector-modern/InspectorPackagerConnection.cpp b/packages/react-native/ReactCommon/jsinspector-modern/InspectorPackagerConnection.cpp index 3ffd1a11495..025782f10b1 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/InspectorPackagerConnection.cpp +++ b/packages/react-native/ReactCommon/jsinspector-modern/InspectorPackagerConnection.cpp @@ -115,8 +115,9 @@ void InspectorPackagerConnection::Impl::handleConnect( // RemoteConnection::onDisconnect(), if the connection even calls it, will // be a no op (because the session is not added to `inspectorSessions_`), so // let's always notify the remote client of the disconnection ourselves. - sendToPackager(folly::dynamic::object("event", "disconnect")( - "payload", folly::dynamic::object("pageId", pageId))); + sendToPackager( + folly::dynamic::object("event", "disconnect")( + "payload", folly::dynamic::object("pageId", pageId))); return; } inspectorSessions_.emplace( @@ -369,11 +370,12 @@ InspectorPackagerConnection::InspectorPackagerConnection( std::string deviceName, std::string appName, std::unique_ptr delegate) - : impl_(Impl::create( - std::move(url), - std::move(deviceName), - std::move(appName), - std::move(delegate))) {} + : impl_( + Impl::create( + std::move(url), + std::move(deviceName), + std::move(appName), + std::move(delegate))) {} bool InspectorPackagerConnection::isConnected() const { return impl_->isConnected(); diff --git a/packages/react-native/ReactCommon/jsinspector-modern/InspectorPackagerConnection.h b/packages/react-native/ReactCommon/jsinspector-modern/InspectorPackagerConnection.h index a6d2bca845a..b55df312eab 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/InspectorPackagerConnection.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/InspectorPackagerConnection.h @@ -67,7 +67,7 @@ class InspectorPackagerConnectionDelegate { * state when created, and automatically disconnect when destroyed. */ virtual std::unique_ptr connectWebSocket( - const std::string& url, + const std::string &url, std::weak_ptr delegate) = 0; /** @@ -78,9 +78,7 @@ class InspectorPackagerConnectionDelegate { * further callbacks are being accepted, e.g. if the application is * terminating. */ - virtual void scheduleCallback( - std::function callback, - std::chrono::milliseconds delayMs) = 0; + virtual void scheduleCallback(std::function callback, std::chrono::milliseconds delayMs) = 0; }; } // namespace facebook::react::jsinspector_modern diff --git a/packages/react-native/ReactCommon/jsinspector-modern/InspectorPackagerConnectionImpl.h b/packages/react-native/ReactCommon/jsinspector-modern/InspectorPackagerConnectionImpl.h index 025727b292f..9d8ba895d60 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/InspectorPackagerConnectionImpl.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/InspectorPackagerConnectionImpl.h @@ -18,11 +18,10 @@ namespace facebook::react::jsinspector_modern { /** * Internals of InspectorPackagerConnection. */ -class InspectorPackagerConnection::Impl - : public IWebSocketDelegate, - public IPageStatusListener, - // Used to generate `weak_ptr`s we can pass around. - public std::enable_shared_from_this { +class InspectorPackagerConnection::Impl : public IWebSocketDelegate, + public IPageStatusListener, + // Used to generate `weak_ptr`s we can pass around. + public std::enable_shared_from_this { public: using SessionId = uint32_t; @@ -39,9 +38,8 @@ class InspectorPackagerConnection::Impl bool isConnected() const; void connect(); void closeQuietly(); - void sendEventToAllConnections(const std::string& event); - std::unique_ptr removeConnectionForPage( - const std::string& pageId); + void sendEventToAllConnections(const std::string &event); + std::unique_ptr removeConnectionForPage(const std::string &pageId); /** * Send a message to the packager as soon as possible. This method is safe @@ -49,10 +47,7 @@ class InspectorPackagerConnection::Impl * is sent, in which case the message will be dropped. The message is also * dropped if the session is no longer valid. */ - void scheduleSendToPackager( - folly::dynamic message, - SessionId sourceSessionId, - const std::string& sourcePageId); + void scheduleSendToPackager(folly::dynamic message, SessionId sourceSessionId, const std::string &sourcePageId); private: struct Session { @@ -66,27 +61,23 @@ class InspectorPackagerConnection::Impl std::string deviceName, std::string appName, std::unique_ptr delegate); - Impl(const Impl&) = delete; - Impl& operator=(const Impl&) = delete; + Impl(const Impl &) = delete; + Impl &operator=(const Impl &) = delete; - void handleDisconnect(const folly::const_dynamic_view& payload); - void handleConnect(const folly::const_dynamic_view& payload); - void handleWrappedEvent(const folly::const_dynamic_view& payload); - void handleProxyMessage(const folly::const_dynamic_view& message); + void handleDisconnect(const folly::const_dynamic_view &payload); + void handleConnect(const folly::const_dynamic_view &payload); + void handleWrappedEvent(const folly::const_dynamic_view &payload); + void handleProxyMessage(const folly::const_dynamic_view &message); folly::dynamic pages(); void reconnect(); void closeAllConnections(); void disposeWebSocket(); - void sendToPackager(const folly::dynamic& message); + void sendToPackager(const folly::dynamic &message); - void abort( - std::optional posixCode, - const std::string& message, - const std::string& cause); + void abort(std::optional posixCode, const std::string &message, const std::string &cause); // IWebSocketDelegate methods - virtual void didFailWithError(std::optional posixCode, std::string error) - override; + virtual void didFailWithError(std::optional posixCode, std::string error) override; virtual void didReceiveMessage(std::string_view message) override; virtual void didOpen() override; virtual void didClose() override; @@ -111,8 +102,7 @@ class InspectorPackagerConnection::Impl SessionId nextSessionId_{1}; }; -class InspectorPackagerConnection::Impl::RemoteConnection - : public IRemoteConnection { +class InspectorPackagerConnection::Impl::RemoteConnection : public IRemoteConnection { public: RemoteConnection( std::weak_ptr owningPackagerConnection, @@ -124,8 +114,7 @@ class InspectorPackagerConnection::Impl::RemoteConnection void onDisconnect() override; private: - const std::weak_ptr - owningPackagerConnection_; + const std::weak_ptr owningPackagerConnection_; const std::string pageId_; const SessionId sessionId_; }; diff --git a/packages/react-native/ReactCommon/jsinspector-modern/InstanceAgent.cpp b/packages/react-native/ReactCommon/jsinspector-modern/InstanceAgent.cpp index 33cc2fc15b3..d868160c07b 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/InstanceAgent.cpp +++ b/packages/react-native/ReactCommon/jsinspector-modern/InstanceAgent.cpp @@ -141,18 +141,19 @@ void InstanceAgent::sendConsoleMessageImmediately( for (auto& arg : message.args) { argsParam.push_back(folly::dynamic::object("type", "string")("value", arg)); } - frontendChannel_(cdp::jsonNotification( - "Runtime.consoleAPICalled", - folly::dynamic::object("type", consoleMessageTypeName(message.type))( - "timestamp", message.timestamp)("args", std::move(argsParam))( - "executionContextId", - runtimeAgent_->getExecutionContextDescription().id)( - // We use the @cdp Runtime.consoleAPICalled `context` parameter to - // mark synthetic messages generated by the backend, i.e. not - // originating in a real `console.*` API call. - "context", - runtimeAgent_->getExecutionContextDescription().name + - "#InstanceAgent"))); + frontendChannel_( + cdp::jsonNotification( + "Runtime.consoleAPICalled", + folly::dynamic::object("type", consoleMessageTypeName(message.type))( + "timestamp", message.timestamp)("args", std::move(argsParam))( + "executionContextId", + runtimeAgent_->getExecutionContextDescription().id)( + // We use the @cdp Runtime.consoleAPICalled `context` parameter to + // mark synthetic messages generated by the backend, i.e. not + // originating in a real `console.*` API call. + "context", + runtimeAgent_->getExecutionContextDescription().name + + "#InstanceAgent"))); } void InstanceAgent::maybeSendPendingConsoleMessages() { @@ -181,9 +182,10 @@ InstanceTracingAgent::~InstanceTracingAgent() { auto& performanceTracer = tracing::PerformanceTracer::getInstance(); auto performanceTraceEvents = performanceTracer.stopTracing(); if (performanceTraceEvents) { - state_.instanceTracingProfiles.emplace_back(tracing::InstanceTracingProfile{ - .performanceTraceEvents = std::move(*performanceTraceEvents), - }); + state_.instanceTracingProfiles.emplace_back( + tracing::InstanceTracingProfile{ + .performanceTraceEvents = std::move(*performanceTraceEvents), + }); } } diff --git a/packages/react-native/ReactCommon/jsinspector-modern/InstanceAgent.h b/packages/react-native/ReactCommon/jsinspector-modern/InstanceAgent.h index d465601254d..e073067c14e 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/InstanceAgent.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/InstanceAgent.h @@ -35,17 +35,14 @@ class InstanceAgent final { * object. * \param sessionState The state of the session that created this agent. */ - explicit InstanceAgent( - FrontendChannel frontendChannel, - InstanceTarget& target, - SessionState& sessionState); + explicit InstanceAgent(FrontendChannel frontendChannel, InstanceTarget &target, SessionState &sessionState); /** * Handle a CDP request. The response will be sent over the provided * \c FrontendChannel synchronously or asynchronously. * \param req The parsed request. */ - bool handleRequest(const cdp::PreparsedRequest& req); + bool handleRequest(const cdp::PreparsedRequest &req); /** * Replace the current RuntimeAgent hostAgent_ with a new one @@ -53,7 +50,7 @@ class InstanceAgent final { * \param runtime The new runtime target. May be nullptr to indicate * there's no current debuggable runtime. */ - void setCurrentRuntime(RuntimeTarget* runtime); + void setCurrentRuntime(RuntimeTarget *runtime); /** * Send a console message to the frontend, or buffer it to be sent later. @@ -66,9 +63,9 @@ class InstanceAgent final { void maybeSendPendingConsoleMessages(); FrontendChannel frontendChannel_; - InstanceTarget& target_; + InstanceTarget &target_; std::shared_ptr runtimeAgent_; - SessionState& sessionState_; + SessionState &sessionState_; }; #pragma mark - Tracing @@ -81,14 +78,14 @@ class InstanceAgent final { */ class InstanceTracingAgent : tracing::TargetTracingAgent { public: - explicit InstanceTracingAgent(tracing::TraceRecordingState& state); + explicit InstanceTracingAgent(tracing::TraceRecordingState &state); ~InstanceTracingAgent(); /** * Registers the RuntimeTarget with this tracing agent. */ - void setTracedRuntime(RuntimeTarget* runtimeTarget); + void setTracedRuntime(RuntimeTarget *runtimeTarget); private: std::shared_ptr runtimeTracingAgent_; diff --git a/packages/react-native/ReactCommon/jsinspector-modern/InstanceTarget.h b/packages/react-native/ReactCommon/jsinspector-modern/InstanceTarget.h index 4941bab53ac..77147846192 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/InstanceTarget.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/InstanceTarget.h @@ -33,10 +33,10 @@ class HostTargetTraceRecording; class InstanceTargetDelegate { public: InstanceTargetDelegate() = default; - InstanceTargetDelegate(const InstanceTargetDelegate&) = delete; - InstanceTargetDelegate(InstanceTargetDelegate&&) = default; - InstanceTargetDelegate& operator=(const InstanceTargetDelegate&) = delete; - InstanceTargetDelegate& operator=(InstanceTargetDelegate&&) = default; + InstanceTargetDelegate(const InstanceTargetDelegate &) = delete; + InstanceTargetDelegate(InstanceTargetDelegate &&) = default; + InstanceTargetDelegate &operator=(const InstanceTargetDelegate &) = delete; + InstanceTargetDelegate &operator=(InstanceTargetDelegate &&) = default; virtual ~InstanceTargetDelegate(); }; @@ -58,18 +58,16 @@ class InstanceTarget : public EnableExecutorFromThis { */ static std::shared_ptr create( std::shared_ptr executionContextManager, - InstanceTargetDelegate& delegate, + InstanceTargetDelegate &delegate, VoidExecutor executor); - InstanceTarget(const InstanceTarget&) = delete; - InstanceTarget(InstanceTarget&&) = delete; - InstanceTarget& operator=(const InstanceTarget&) = delete; - InstanceTarget& operator=(InstanceTarget&&) = delete; + InstanceTarget(const InstanceTarget &) = delete; + InstanceTarget(InstanceTarget &&) = delete; + InstanceTarget &operator=(const InstanceTarget &) = delete; + InstanceTarget &operator=(InstanceTarget &&) = delete; ~InstanceTarget(); - std::shared_ptr createAgent( - const FrontendChannel& channel, - SessionState& sessionState); + std::shared_ptr createAgent(const FrontendChannel &channel, SessionState &sessionState); /** * Creates a new InstanceTracingAgent. @@ -80,17 +78,14 @@ class InstanceTarget : public EnableExecutorFromThis { * * \param state A reference to the state of the active trace recording. */ - std::shared_ptr createTracingAgent( - tracing::TraceRecordingState& state); + std::shared_ptr createTracingAgent(tracing::TraceRecordingState &state); /** * Registers a JS runtime with this InstanceTarget. \returns a reference to * the created RuntimeTarget, which is owned by the \c InstanceTarget. All the * requirements of \c RuntimeTarget::create must be met. */ - RuntimeTarget& registerRuntime( - RuntimeTargetDelegate& delegate, - RuntimeExecutor executor); + RuntimeTarget ®isterRuntime(RuntimeTargetDelegate &delegate, RuntimeExecutor executor); /** * Unregisters a JS runtime from this InstanceTarget. This destroys the \c @@ -99,7 +94,7 @@ class InstanceTarget : public EnableExecutorFromThis { * continue to be used as long as JavaScript execution continues in the * runtime. */ - void unregisterRuntime(RuntimeTarget& runtime); + void unregisterRuntime(RuntimeTarget &runtime); private: /** @@ -110,11 +105,9 @@ class InstanceTarget : public EnableExecutorFromThis { * The caller is responsible for ensuring that the delegate outlives this * object. */ - InstanceTarget( - std::shared_ptr executionContextManager, - InstanceTargetDelegate& delegate); + InstanceTarget(std::shared_ptr executionContextManager, InstanceTargetDelegate &delegate); - InstanceTargetDelegate& delegate_; + InstanceTargetDelegate &delegate_; std::shared_ptr currentRuntime_{nullptr}; WeakList agents_; std::shared_ptr executionContextManager_; diff --git a/packages/react-native/ReactCommon/jsinspector-modern/NetworkIOAgent.cpp b/packages/react-native/ReactCommon/jsinspector-modern/NetworkIOAgent.cpp index acbae362278..b914998e96c 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/NetworkIOAgent.cpp +++ b/packages/react-native/ReactCommon/jsinspector-modern/NetworkIOAgent.cpp @@ -309,17 +309,19 @@ void NetworkIOAgent::handleLoadNetworkResource( LoadNetworkResourceRequest params; if (!req.params.isObject()) { - frontendChannel_(cdp::jsonError( - req.id, - cdp::ErrorCode::InvalidParams, - "Invalid params: not an object.")); + frontendChannel_( + cdp::jsonError( + req.id, + cdp::ErrorCode::InvalidParams, + "Invalid params: not an object.")); return; } if ((req.params.count("url") == 0u) || !req.params.at("url").isString()) { - frontendChannel_(cdp::jsonError( - requestId, - cdp::ErrorCode::InvalidParams, - "Invalid params: url is missing or not a string.")); + frontendChannel_( + cdp::jsonError( + requestId, + cdp::ErrorCode::InvalidParams, + "Invalid params: url is missing or not a string.")); return; } else { params.url = req.params.at("url").asString(); @@ -392,18 +394,20 @@ void NetworkIOAgent::handleLoadNetworkResource( void NetworkIOAgent::handleIoRead(const cdp::PreparsedRequest& req) { long long requestId = req.id; if (!req.params.isObject()) { - frontendChannel_(cdp::jsonError( - requestId, - cdp::ErrorCode::InvalidParams, - "Invalid params: not an object.")); + frontendChannel_( + cdp::jsonError( + requestId, + cdp::ErrorCode::InvalidParams, + "Invalid params: not an object.")); return; } if ((req.params.count("handle") == 0u) || !req.params.at("handle").isString()) { - frontendChannel_(cdp::jsonError( - requestId, - cdp::ErrorCode::InvalidParams, - "Invalid params: handle is missing or not a string.")); + frontendChannel_( + cdp::jsonError( + requestId, + cdp::ErrorCode::InvalidParams, + "Invalid params: handle is missing or not a string.")); return; } std::optional size = std::nullopt; @@ -411,10 +415,11 @@ void NetworkIOAgent::handleIoRead(const cdp::PreparsedRequest& req) { size = req.params.at("size").asInt(); if (size > MAX_BYTES_PER_READ) { - frontendChannel_(cdp::jsonError( - requestId, - cdp::ErrorCode::InvalidParams, - "Invalid params: size cannot be greater than 10MB.")); + frontendChannel_( + cdp::jsonError( + requestId, + cdp::ErrorCode::InvalidParams, + "Invalid params: size cannot be greater than 10MB.")); return; } } @@ -422,10 +427,11 @@ void NetworkIOAgent::handleIoRead(const cdp::PreparsedRequest& req) { auto streamId = req.params.at("handle").asString(); auto it = streams_->find(streamId); if (it == streams_->end()) { - frontendChannel_(cdp::jsonError( - requestId, - cdp::ErrorCode::InternalError, - "Stream not found with handle " + streamId)); + frontendChannel_( + cdp::jsonError( + requestId, + cdp::ErrorCode::InternalError, + "Stream not found with handle " + streamId)); return; } else { it->second->read( @@ -437,8 +443,9 @@ void NetworkIOAgent::handleIoRead(const cdp::PreparsedRequest& req) { if (auto* error = std::get_if(&resultOrError)) { // NB: Chrome DevTools calls IO.close after a read error, so any // continuing download or retained data is cleaned up at that point. - frontendChannel(cdp::jsonError( - requestId, cdp::ErrorCode::InternalError, *error)); + frontendChannel( + cdp::jsonError( + requestId, cdp::ErrorCode::InternalError, *error)); } else if (auto* result = std::get_if(&resultOrError)) { frontendChannel(cdp::jsonResult(requestId, result->toDynamic())); } else { @@ -452,28 +459,31 @@ void NetworkIOAgent::handleIoRead(const cdp::PreparsedRequest& req) { void NetworkIOAgent::handleIoClose(const cdp::PreparsedRequest& req) { long long requestId = req.id; if (!req.params.isObject()) { - frontendChannel_(cdp::jsonError( - requestId, - cdp::ErrorCode::InvalidParams, - "Invalid params: not an object.")); + frontendChannel_( + cdp::jsonError( + requestId, + cdp::ErrorCode::InvalidParams, + "Invalid params: not an object.")); return; } if ((req.params.count("handle") == 0u) || !req.params.at("handle").isString()) { - frontendChannel_(cdp::jsonError( - requestId, - cdp::ErrorCode::InvalidParams, - "Invalid params: handle is missing or not a string.")); + frontendChannel_( + cdp::jsonError( + requestId, + cdp::ErrorCode::InvalidParams, + "Invalid params: handle is missing or not a string.")); return; } auto streamId = req.params.at("handle").asString(); auto it = streams_->find(streamId); if (it == streams_->end()) { - frontendChannel_(cdp::jsonError( - requestId, - cdp::ErrorCode::InternalError, - "Stream not found: " + streamId)); + frontendChannel_( + cdp::jsonError( + requestId, + cdp::ErrorCode::InternalError, + "Stream not found: " + streamId)); } else { it->second->cancel(); streams_->erase(it->first); @@ -484,28 +494,31 @@ void NetworkIOAgent::handleIoClose(const cdp::PreparsedRequest& req) { void NetworkIOAgent::handleGetResponseBody(const cdp::PreparsedRequest& req) { long long requestId = req.id; if (!req.params.isObject()) { - frontendChannel_(cdp::jsonError( - requestId, - cdp::ErrorCode::InvalidParams, - "Invalid params: not an object.")); + frontendChannel_( + cdp::jsonError( + requestId, + cdp::ErrorCode::InvalidParams, + "Invalid params: not an object.")); return; } if ((req.params.count("requestId") == 0u) || !req.params.at("requestId").isString()) { - frontendChannel_(cdp::jsonError( - requestId, - cdp::ErrorCode::InvalidParams, - "Invalid params: requestId is missing or not a string.")); + frontendChannel_( + cdp::jsonError( + requestId, + cdp::ErrorCode::InvalidParams, + "Invalid params: requestId is missing or not a string.")); return; } auto& networkHandler = NetworkHandler::getInstance(); if (!networkHandler.isEnabled()) { - frontendChannel_(cdp::jsonError( - requestId, - cdp::ErrorCode::InvalidRequest, - "Invalid request: The \"Network\" domain is not enabled.")); + frontendChannel_( + cdp::jsonError( + requestId, + cdp::ErrorCode::InvalidRequest, + "Invalid request: The \"Network\" domain is not enabled.")); return; } @@ -513,10 +526,11 @@ void NetworkIOAgent::handleGetResponseBody(const cdp::PreparsedRequest& req) { networkHandler.getResponseBody(req.params.at("requestId").asString()); if (!storedResponse) { - frontendChannel_(cdp::jsonError( - requestId, - cdp::ErrorCode::InternalError, - "Internal error: Could not retrieve response body for the given requestId.")); + frontendChannel_( + cdp::jsonError( + requestId, + cdp::ErrorCode::InternalError, + "Internal error: Could not retrieve response body for the given requestId.")); return; } diff --git a/packages/react-native/ReactCommon/jsinspector-modern/NetworkIOAgent.h b/packages/react-native/ReactCommon/jsinspector-modern/NetworkIOAgent.h index c939e7ca18b..05fa053e1bc 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/NetworkIOAgent.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/NetworkIOAgent.h @@ -44,7 +44,8 @@ struct NetworkResource { std::optional httpStatusCode{}; std::optional netErrorName{}; std::optional headers{}; - folly::dynamic toDynamic() const { + folly::dynamic toDynamic() const + { auto dynamicResource = folly::dynamic::object("success", success); if (success) { // stream IFF successful @@ -65,7 +66,7 @@ struct NetworkResource { if (headers) { // Guaranteed if successful auto dynamicHeaders = folly::dynamic::object(); - for (const auto& pair : *headers) { + for (const auto &pair : *headers) { dynamicHeaders(pair.first, pair.second); } dynamicResource("headers", std::move(dynamicHeaders)); @@ -80,7 +81,8 @@ struct IOReadResult { std::string data; bool eof; bool base64Encoded; - folly::dynamic toDynamic() const { + folly::dynamic toDynamic() const + { auto obj = folly::dynamic::object("data", data); obj("eof", eof); obj("base64Encoded", base64Encoded); @@ -91,7 +93,8 @@ struct IOReadResult { struct GetResponseBodyResult { std::string body; bool base64Encoded; - folly::dynamic toDynamic() const { + folly::dynamic toDynamic() const + { folly::dynamic params = folly::dynamic::object; params["body"] = body; params["base64Encoded"] = base64Encoded; @@ -106,11 +109,10 @@ struct GetResponseBodyResult { class NetworkRequestListener { public: NetworkRequestListener() = default; - NetworkRequestListener(const NetworkRequestListener&) = delete; - NetworkRequestListener& operator=(const NetworkRequestListener&) = delete; - NetworkRequestListener(NetworkRequestListener&&) noexcept = default; - NetworkRequestListener& operator=(NetworkRequestListener&&) noexcept = - default; + NetworkRequestListener(const NetworkRequestListener &) = delete; + NetworkRequestListener &operator=(const NetworkRequestListener &) = delete; + NetworkRequestListener(NetworkRequestListener &&) noexcept = default; + NetworkRequestListener &operator=(NetworkRequestListener &&) noexcept = default; virtual ~NetworkRequestListener() = default; /** @@ -120,7 +122,7 @@ class NetworkRequestListener { * \param httpStatusCode The HTTP status code received. * \param headers Response headers as an unordered_map. */ - virtual void onHeaders(uint32_t httpStatusCode, const Headers& headers) = 0; + virtual void onHeaders(uint32_t httpStatusCode, const Headers &headers) = 0; /** * To be called by the delegate on receipt of data chunks. @@ -137,7 +139,7 @@ class NetworkRequestListener { * were not yet received), or as a CDP error in response to a subsequent * `IO.read`. */ - virtual void onError(const std::string& message) = 0; + virtual void onError(const std::string &message) = 0; /** * To be called by the delegate on successful completion of the request. @@ -163,12 +165,10 @@ class NetworkRequestListener { class LoadNetworkResourceDelegate { public: LoadNetworkResourceDelegate() = default; - LoadNetworkResourceDelegate(const LoadNetworkResourceDelegate&) = delete; - LoadNetworkResourceDelegate& operator=(const LoadNetworkResourceDelegate&) = - delete; - LoadNetworkResourceDelegate(LoadNetworkResourceDelegate&&) noexcept = delete; - LoadNetworkResourceDelegate& operator=( - LoadNetworkResourceDelegate&&) noexcept = delete; + LoadNetworkResourceDelegate(const LoadNetworkResourceDelegate &) = delete; + LoadNetworkResourceDelegate &operator=(const LoadNetworkResourceDelegate &) = delete; + LoadNetworkResourceDelegate(LoadNetworkResourceDelegate &&) noexcept = delete; + LoadNetworkResourceDelegate &operator=(LoadNetworkResourceDelegate &&) noexcept = delete; virtual ~LoadNetworkResourceDelegate() = default; /** @@ -185,7 +185,7 @@ class LoadNetworkResourceDelegate { * called to abort any in-flight network operation that is no longer needed. */ virtual void loadNetworkResource( - [[maybe_unused]] const LoadNetworkResourceRequest& params, + [[maybe_unused]] const LoadNetworkResourceRequest ¶ms, [[maybe_unused]] ScopedExecutor executor) = 0; }; @@ -207,18 +207,16 @@ class NetworkIOAgent { * processing incoming data or other events from network operations. */ NetworkIOAgent(FrontendChannel frontendChannel, VoidExecutor executor) - : frontendChannel_(frontendChannel), - executor_(executor), - streams_(std::make_shared()) {} + : frontendChannel_(frontendChannel), executor_(executor), streams_(std::make_shared()) + { + } /** * Handle a CDP request. The response will be sent over the provided * \c FrontendChannel synchronously or asynchronously. * \param req The parsed request. */ - bool handleRequest( - const cdp::PreparsedRequest& req, - LoadNetworkResourceDelegate& delegate); + bool handleRequest(const cdp::PreparsedRequest &req, LoadNetworkResourceDelegate &delegate); private: /** @@ -255,26 +253,24 @@ class NetworkIOAgent { * Does not catch exceptions thrown by the delegate (such as * NotImplementedException). */ - void handleLoadNetworkResource( - const cdp::PreparsedRequest& req, - LoadNetworkResourceDelegate& delegate); + void handleLoadNetworkResource(const cdp::PreparsedRequest &req, LoadNetworkResourceDelegate &delegate); /** * Handle an IO.read CDP request. Emit a chunk of data from the stream, once * enough has been downloaded, or report an error. */ - void handleIoRead(const cdp::PreparsedRequest& req); + void handleIoRead(const cdp::PreparsedRequest &req); /** * Handle an IO.close CDP request. Safely aborts any in-flight request. * Reports CDP ok if the stream is found, or a CDP error if not. */ - void handleIoClose(const cdp::PreparsedRequest& req); + void handleIoClose(const cdp::PreparsedRequest &req); /** * Handle a Network.getResponseBody CDP request. */ - void handleGetResponseBody(const cdp::PreparsedRequest& req); + void handleGetResponseBody(const cdp::PreparsedRequest &req); }; } // namespace facebook::react::jsinspector_modern diff --git a/packages/react-native/ReactCommon/jsinspector-modern/RuntimeAgent.cpp b/packages/react-native/ReactCommon/jsinspector-modern/RuntimeAgent.cpp index d1821f6b74b..fe4adabf8fd 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/RuntimeAgent.cpp +++ b/packages/react-native/ReactCommon/jsinspector-modern/RuntimeAgent.cpp @@ -111,11 +111,12 @@ void RuntimeAgent::notifyBindingCalled( return; } - frontendChannel_(cdp::jsonNotification( - "Runtime.bindingCalled", - folly::dynamic::object( - "executionContextId", executionContextDescription_.id)( - "name", bindingName)("payload", payload))); + frontendChannel_( + cdp::jsonNotification( + "Runtime.bindingCalled", + folly::dynamic::object( + "executionContextId", executionContextDescription_.id)( + "name", bindingName)("payload", payload))); } RuntimeAgent::ExportedState RuntimeAgent::getExportedState() { diff --git a/packages/react-native/ReactCommon/jsinspector-modern/RuntimeAgent.h b/packages/react-native/ReactCommon/jsinspector-modern/RuntimeAgent.h index 186eb0ba4e8..5ebd2f9ffe0 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/RuntimeAgent.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/RuntimeAgent.h @@ -46,9 +46,9 @@ class RuntimeAgent final { */ RuntimeAgent( FrontendChannel frontendChannel, - RuntimeTargetController& targetController, + RuntimeTargetController &targetController, ExecutionContextDescription executionContextDescription, - SessionState& sessionState, + SessionState &sessionState, std::unique_ptr delegate); ~RuntimeAgent(); @@ -63,16 +63,14 @@ class RuntimeAgent final { * to the request (with either a success or error message). False if the * agent expects another agent to respond to the request instead. */ - bool handleRequest(const cdp::PreparsedRequest& req); + bool handleRequest(const cdp::PreparsedRequest &req); - inline const ExecutionContextDescription& getExecutionContextDescription() - const { + inline const ExecutionContextDescription &getExecutionContextDescription() const + { return executionContextDescription_; } - void notifyBindingCalled( - const std::string& bindingName, - const std::string& payload); + void notifyBindingCalled(const std::string &bindingName, const std::string &payload); struct ExportedState { std::unique_ptr delegateState; @@ -102,8 +100,8 @@ class RuntimeAgent final { private: FrontendChannel frontendChannel_; - RuntimeTargetController& targetController_; - SessionState& sessionState_; + RuntimeTargetController &targetController_; + SessionState &sessionState_; const std::unique_ptr delegate_; const ExecutionContextDescription executionContextDescription_; }; @@ -118,14 +116,12 @@ class RuntimeAgent final { */ class RuntimeTracingAgent : tracing::TargetTracingAgent { public: - explicit RuntimeTracingAgent( - tracing::TraceRecordingState& state, - RuntimeTargetController& targetController); + explicit RuntimeTracingAgent(tracing::TraceRecordingState &state, RuntimeTargetController &targetController); ~RuntimeTracingAgent(); private: - RuntimeTargetController& targetController_; + RuntimeTargetController &targetController_; }; } // namespace facebook::react::jsinspector_modern diff --git a/packages/react-native/ReactCommon/jsinspector-modern/RuntimeAgentDelegate.h b/packages/react-native/ReactCommon/jsinspector-modern/RuntimeAgentDelegate.h index 911cacb6883..886fa54c7aa 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/RuntimeAgentDelegate.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/RuntimeAgentDelegate.h @@ -34,7 +34,7 @@ class RuntimeAgentDelegate { * to the request (with either a success or error message). False if the * agent expects another agent to respond to the request instead. */ - virtual bool handleRequest(const cdp::PreparsedRequest& req) = 0; + virtual bool handleRequest(const cdp::PreparsedRequest &req) = 0; /** * Export RuntimeAgentDelegate-specific state that should persist across @@ -43,7 +43,8 @@ class RuntimeAgentDelegate { * one (e.g. as part of an Instance reload), the state returned here will be * passed to \ref RuntimeTargetDelegate::createAgentDelegate. */ - inline virtual std::unique_ptr getExportedState() { + inline virtual std::unique_ptr getExportedState() + { return std::make_unique(); } }; diff --git a/packages/react-native/ReactCommon/jsinspector-modern/RuntimeTarget.h b/packages/react-native/ReactCommon/jsinspector-modern/RuntimeTarget.h index 61e57959486..a68a1645273 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/RuntimeTarget.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/RuntimeTarget.h @@ -52,10 +52,9 @@ class RuntimeTargetDelegate { virtual ~RuntimeTargetDelegate() = default; virtual std::unique_ptr createAgentDelegate( FrontendChannel channel, - SessionState& sessionState, - std::unique_ptr - previouslyExportedState, - const ExecutionContextDescription& executionContextDescription, + SessionState &sessionState, + std::unique_ptr previouslyExportedState, + const ExecutionContextDescription &executionContextDescription, RuntimeExecutor runtimeExecutor) = 0; /** @@ -69,9 +68,7 @@ class RuntimeTargetDelegate { * Runtime reference, if it has one, without checking it for equivalence with * the one provided here. */ - virtual void addConsoleMessage( - jsi::Runtime& runtime, - ConsoleMessage message) = 0; + virtual void addConsoleMessage(jsi::Runtime &runtime, ConsoleMessage message) = 0; /** * \returns true if the runtime supports reporting console API calls over CDP. @@ -91,9 +88,7 @@ class RuntimeTargetDelegate { * Runtime reference, if it has one, without checking it for equivalence with * the one provided here. */ - virtual std::unique_ptr captureStackTrace( - jsi::Runtime& runtime, - size_t framesToSkip = 0) = 0; + virtual std::unique_ptr captureStackTrace(jsi::Runtime &runtime, size_t framesToSkip = 0) = 0; /** * Start sampling profiler. @@ -113,8 +108,7 @@ class RuntimeTargetDelegate { * @cdp Runtime.StackTrace type, if the runtime supports it. Otherwise, * returns std::nullopt. */ - virtual std::optional serializeStackTrace( - const StackTrace& stackTrace) = 0; + virtual std::optional serializeStackTrace(const StackTrace &stackTrace) = 0; }; /** @@ -124,23 +118,20 @@ class RuntimeTargetController { public: enum class Domain { Network, Runtime, Log, kMaxValue }; - explicit RuntimeTargetController(RuntimeTarget& target); + explicit RuntimeTargetController(RuntimeTarget &target); /** * Adds a function with the given name on the runtime's global object, that * when called will send a Runtime.bindingCalled event through all connected * sessions that have registered to receive binding events for that name. */ - void installBindingHandler(const std::string& bindingName); + void installBindingHandler(const std::string &bindingName); /** * Notifies the target that an agent has received an enable or disable * message for the given domain. */ - void notifyDomainStateChanged( - Domain domain, - bool enabled, - const RuntimeAgent& notifyingAgent); + void notifyDomainStateChanged(Domain domain, bool enabled, const RuntimeAgent ¬ifyingAgent); /** * Start sampling profiler for the corresponding RuntimeTarget. @@ -156,14 +147,13 @@ class RuntimeTargetController { tracing::RuntimeSamplingProfile collectSamplingProfile(); private: - RuntimeTarget& target_; + RuntimeTarget &target_; }; /** * A Target corresponding to a JavaScript runtime. */ -class JSINSPECTOR_EXPORT RuntimeTarget - : public EnableExecutorFromThis { +class JSINSPECTOR_EXPORT RuntimeTarget : public EnableExecutorFromThis { public: /** * \param executionContextDescription A description of the execution context @@ -184,15 +174,15 @@ class JSINSPECTOR_EXPORT RuntimeTarget * executor will not be called after the RuntimeTarget is destroyed. */ static std::shared_ptr create( - const ExecutionContextDescription& executionContextDescription, - RuntimeTargetDelegate& delegate, + const ExecutionContextDescription &executionContextDescription, + RuntimeTargetDelegate &delegate, RuntimeExecutor jsExecutor, VoidExecutor selfExecutor); - RuntimeTarget(const RuntimeTarget&) = delete; - RuntimeTarget(RuntimeTarget&&) = delete; - RuntimeTarget& operator=(const RuntimeTarget&) = delete; - RuntimeTarget& operator=(RuntimeTarget&&) = delete; + RuntimeTarget(const RuntimeTarget &) = delete; + RuntimeTarget(RuntimeTarget &&) = delete; + RuntimeTarget &operator=(const RuntimeTarget &) = delete; + RuntimeTarget &operator=(RuntimeTarget &&) = delete; ~RuntimeTarget(); /** @@ -204,9 +194,7 @@ class JSINSPECTOR_EXPORT RuntimeTarget * frontend. * \returns The new agent, or nullptr if the runtime is not debuggable. */ - std::shared_ptr createAgent( - const FrontendChannel& channel, - SessionState& sessionState); + std::shared_ptr createAgent(const FrontendChannel &channel, SessionState &sessionState); /** * Creates a new RuntimeTracingAgent. @@ -216,8 +204,7 @@ class JSINSPECTOR_EXPORT RuntimeTarget * * \param state A reference to the state of the active trace recording. */ - std::shared_ptr createTracingAgent( - tracing::TraceRecordingState& state); + std::shared_ptr createTracingAgent(tracing::TraceRecordingState &state); /** * Start sampling profiler for a particular JavaScript runtime. @@ -254,11 +241,11 @@ class JSINSPECTOR_EXPORT RuntimeTarget */ RuntimeTarget( ExecutionContextDescription executionContextDescription, - RuntimeTargetDelegate& delegate, + RuntimeTargetDelegate &delegate, RuntimeExecutor jsExecutor); const ExecutionContextDescription executionContextDescription_; - RuntimeTargetDelegate& delegate_; + RuntimeTargetDelegate &delegate_; RuntimeExecutor jsExecutor_; WeakList agents_; RuntimeTargetController controller_{*this}; @@ -266,8 +253,7 @@ class JSINSPECTOR_EXPORT RuntimeTarget /** * Keeps track of the agents that have enabled various domains. */ - EnumArray> - agentsByEnabledDomain_; + EnumArray> agentsByEnabledDomain_; /** * For each Domain, contains true if the domain has been enabled by any @@ -294,7 +280,7 @@ class JSINSPECTOR_EXPORT RuntimeTarget * when called will send a Runtime.bindingCalled event through all connected * sessions that have registered to receive binding events for that name. */ - void installBindingHandler(const std::string& bindingName); + void installBindingHandler(const std::string &bindingName); /** * Installs any global values we want to expose to framework/user JavaScript @@ -342,10 +328,7 @@ class JSINSPECTOR_EXPORT RuntimeTarget * Notifies the target that an agent has received an enable or disable * message for the given domain. */ - void notifyDomainStateChanged( - Domain domain, - bool enabled, - const RuntimeAgent& notifyingAgent); + void notifyDomainStateChanged(Domain domain, bool enabled, const RuntimeAgent ¬ifyingAgent); /** * Checks whether the given domain is enabled in at least one session diff --git a/packages/react-native/ReactCommon/jsinspector-modern/RuntimeTargetConsole.cpp b/packages/react-native/ReactCommon/jsinspector-modern/RuntimeTargetConsole.cpp index 25a6e694c17..5d89b6b9f53 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/RuntimeTargetConsole.cpp +++ b/packages/react-native/ReactCommon/jsinspector-modern/RuntimeTargetConsole.cpp @@ -133,8 +133,9 @@ void consoleCount( it->second++; } std::vector vec; - vec.emplace_back(jsi::String::createFromUtf8( - runtime, label + ": "s + std::to_string(it->second))); + vec.emplace_back( + jsi::String::createFromUtf8( + runtime, label + ": "s + std::to_string(it->second))); runtimeTargetDelegate.addConsoleMessage( runtime, {timestampMs, @@ -158,8 +159,9 @@ void consoleCountReset( auto it = state.countMap.find(label); if (it == state.countMap.end()) { std::vector vec; - vec.emplace_back(jsi::String::createFromUtf8( - runtime, "Count for '"s + label + "' does not exist")); + vec.emplace_back( + jsi::String::createFromUtf8( + runtime, "Count for '"s + label + "' does not exist")); runtimeTargetDelegate.addConsoleMessage( runtime, {timestampMs, @@ -188,8 +190,9 @@ void consoleTime( state.timerTable.insert({label, timestampMs}); } else { std::vector vec; - vec.emplace_back(jsi::String::createFromUtf8( - runtime, "Timer '"s + label + "' already exists")); + vec.emplace_back( + jsi::String::createFromUtf8( + runtime, "Timer '"s + label + "' already exists")); runtimeTargetDelegate.addConsoleMessage( runtime, {timestampMs, @@ -214,8 +217,9 @@ void consoleTimeEnd( auto it = state.timerTable.find(label); if (it == state.timerTable.end()) { std::vector vec; - vec.emplace_back(jsi::String::createFromUtf8( - runtime, "Timer '"s + label + "' does not exist")); + vec.emplace_back( + jsi::String::createFromUtf8( + runtime, "Timer '"s + label + "' does not exist")); runtimeTargetDelegate.addConsoleMessage( runtime, {timestampMs, @@ -224,9 +228,10 @@ void consoleTimeEnd( std::move(stackTrace)}); } else { std::vector vec; - vec.emplace_back(jsi::String::createFromUtf8( - runtime, - label + ": "s + std::to_string(timestampMs - it->second) + " ms")); + vec.emplace_back( + jsi::String::createFromUtf8( + runtime, + label + ": "s + std::to_string(timestampMs - it->second) + " ms")); state.timerTable.erase(it); runtimeTargetDelegate.addConsoleMessage( runtime, @@ -252,8 +257,9 @@ void consoleTimeLog( auto it = state.timerTable.find(label); if (it == state.timerTable.end()) { std::vector vec; - vec.emplace_back(jsi::String::createFromUtf8( - runtime, "Timer '"s + label + "' does not exist")); + vec.emplace_back( + jsi::String::createFromUtf8( + runtime, "Timer '"s + label + "' does not exist")); runtimeTargetDelegate.addConsoleMessage( runtime, {timestampMs, @@ -262,9 +268,10 @@ void consoleTimeLog( std::move(stackTrace)}); } else { std::vector vec; - vec.emplace_back(jsi::String::createFromUtf8( - runtime, - label + ": "s + std::to_string(timestampMs - it->second) + " ms")); + vec.emplace_back( + jsi::String::createFromUtf8( + runtime, + label + ": "s + std::to_string(timestampMs - it->second) + " ms")); if (count > 1) { for (size_t i = 1; i != count; ++i) { vec.emplace_back(runtime, args[i]); diff --git a/packages/react-native/ReactCommon/jsinspector-modern/ScopedExecutor.h b/packages/react-native/ReactCommon/jsinspector-modern/ScopedExecutor.h index 3b683cd2b13..5ad157dd51a 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/ScopedExecutor.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/ScopedExecutor.h @@ -20,10 +20,9 @@ namespace facebook::react::jsinspector_modern { * the underlying Self object is destroyed while the function is pending. */ template -using ScopedExecutor = - std::function&& callback)>; +using ScopedExecutor = std::function &&callback)>; -using VoidExecutor = std::function&& callback)>; +using VoidExecutor = std::function &&callback)>; /** * Creates a ScopedExecutor from a shared (weak) pointer to Self plus some @@ -31,9 +30,8 @@ using VoidExecutor = std::function&& callback)>; * the callback with a valid reference to Self iff Self is still alive. */ template -ScopedExecutor makeScopedExecutor( - std::shared_ptr self, - ScopedExecutor executor) { +ScopedExecutor makeScopedExecutor(std::shared_ptr self, ScopedExecutor executor) +{ return makeScopedExecutor(self, makeVoidExecutor(executor)); } @@ -43,10 +41,9 @@ ScopedExecutor makeScopedExecutor( * reference to Self iff Self is still alive. */ template -ScopedExecutor makeScopedExecutor( - std::shared_ptr self, - VoidExecutor executor) { - return [self = std::weak_ptr(self), executor](auto&& callback) { +ScopedExecutor makeScopedExecutor(std::shared_ptr self, VoidExecutor executor) +{ + return [self = std::weak_ptr(self), executor](auto &&callback) { executor([self, callback = std::move(callback)]() { auto lockedSelf = self.lock(); if (!lockedSelf) { @@ -62,10 +59,9 @@ ScopedExecutor makeScopedExecutor( * parameter. */ template -VoidExecutor makeVoidExecutor(ScopedExecutor executor) { - return [executor](auto&& callback) { - executor([callback = std::move(callback)](Self&) { callback(); }); - }; +VoidExecutor makeVoidExecutor(ScopedExecutor executor) +{ + return [executor](auto &&callback) { executor([callback = std::move(callback)](Self &) { callback(); }); }; } template @@ -75,17 +71,20 @@ class EnableExecutorFromThis : public std::enable_shared_from_this { * Returns an executor that can be used to safely invoke methods on Self. * Must not be called during the constructor of Self. */ - ScopedExecutor executorFromThis() { + ScopedExecutor executorFromThis() + { assert(baseExecutor_); return makeScopedExecutor(this->shared_from_this(), baseExecutor_); } template - void setExecutor(ScopedExecutor executor) { + void setExecutor(ScopedExecutor executor) + { setExecutor(makeVoidExecutor(executor)); } - void setExecutor(VoidExecutor executor) { + void setExecutor(VoidExecutor executor) + { assert(executor); assert(!baseExecutor_); baseExecutor_ = std::move(executor); @@ -105,18 +104,15 @@ class EnableExecutorFromThis : public std::enable_shared_from_this { * on the object). */ template - requires std::derived_from< - ExecutorEnabledType, - EnableExecutorFromThis> -static void tryExecuteSync( - std::weak_ptr selfWeak, - std::invocable auto func) { + requires std::derived_from> +static void tryExecuteSync(std::weak_ptr selfWeak, std::invocable auto func) +{ if (auto self = selfWeak.lock()) { auto selfExecutor = self->executorFromThis(); OnScopeExit onScopeExit{[self, selfExecutor = std::move(selfExecutor)]() { // To ensure we never destroy `self` on the wrong thread, send // our shared_ptr back to the correct executor. - selfExecutor([self = std::move(self)](auto&) { (void)self; }); + selfExecutor([self = std::move(self)](auto &) { (void)self; }); }}; func(*self); diff --git a/packages/react-native/ReactCommon/jsinspector-modern/SessionState.h b/packages/react-native/ReactCommon/jsinspector-modern/SessionState.h index 6bb643918b8..7ea71a08dba 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/SessionState.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/SessionState.h @@ -41,8 +41,7 @@ struct SessionState { * matching Chrome's behaviour (a binding not added by the current session * will not emit events on it). */ - std::unordered_map - subscribedBindings; + std::unordered_map subscribedBindings; /** * Messages logged through the HostAgent::sendConsoleMessage and diff --git a/packages/react-native/ReactCommon/jsinspector-modern/StackTrace.h b/packages/react-native/ReactCommon/jsinspector-modern/StackTrace.h index 81aef58f8d6..94973df749c 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/StackTrace.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/StackTrace.h @@ -19,7 +19,8 @@ class StackTrace { /** * Constructs an empty stack trace. */ - static inline std::unique_ptr empty() { + static inline std::unique_ptr empty() + { return std::make_unique(); } @@ -28,10 +29,10 @@ class StackTrace { */ StackTrace() = default; - StackTrace(const StackTrace&) = delete; - StackTrace& operator=(const StackTrace&) = delete; - StackTrace(StackTrace&&) = delete; - StackTrace& operator=(StackTrace&&) = delete; + StackTrace(const StackTrace &) = delete; + StackTrace &operator=(const StackTrace &) = delete; + StackTrace(StackTrace &&) = delete; + StackTrace &operator=(StackTrace &&) = delete; virtual ~StackTrace() = default; }; diff --git a/packages/react-native/ReactCommon/jsinspector-modern/TracingAgent.cpp b/packages/react-native/ReactCommon/jsinspector-modern/TracingAgent.cpp index 15878012fed..e661b0e741a 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/TracingAgent.cpp +++ b/packages/react-native/ReactCommon/jsinspector-modern/TracingAgent.cpp @@ -55,10 +55,11 @@ bool TracingAgent::handleRequest(const cdp::PreparsedRequest& req) { if (req.method == "Tracing.start") { // @cdp Tracing.start support is experimental. if (sessionState_.isDebuggerDomainEnabled) { - frontendChannel_(cdp::jsonError( - req.id, - cdp::ErrorCode::InternalError, - "Debugger domain is expected to be disabled before starting Tracing")); + frontendChannel_( + cdp::jsonError( + req.id, + cdp::ErrorCode::InternalError, + "Debugger domain is expected to be disabled before starting Tracing")); return true; } @@ -66,10 +67,11 @@ bool TracingAgent::handleRequest(const cdp::PreparsedRequest& req) { bool didNotHaveAlreadyRunningRecording = hostTargetController_.startTracing(tracing::Mode::CDP); if (!didNotHaveAlreadyRunningRecording) { - frontendChannel_(cdp::jsonError( - req.id, - cdp::ErrorCode::InvalidRequest, - "Tracing has already been started")); + frontendChannel_( + cdp::jsonError( + req.id, + cdp::ErrorCode::InvalidRequest, + "Tracing has already been started")); return true; } @@ -103,9 +105,10 @@ void TracingAgent::emitExternalTraceRecording( void TracingAgent::emitTraceRecording( tracing::TraceRecordingState traceRecording) const { auto dataCollectedCallback = [this](folly::dynamic&& eventsChunk) { - frontendChannel_(cdp::jsonNotification( - "Tracing.dataCollected", - folly::dynamic::object("value", std::move(eventsChunk)))); + frontendChannel_( + cdp::jsonNotification( + "Tracing.dataCollected", + folly::dynamic::object("value", std::move(eventsChunk)))); }; tracing::TraceRecordingStateSerializer::emitAsDataCollectedChunks( std::move(traceRecording), @@ -113,9 +116,10 @@ void TracingAgent::emitTraceRecording( TRACE_EVENT_CHUNK_SIZE, PROFILE_TRACE_EVENT_CHUNK_SIZE); - frontendChannel_(cdp::jsonNotification( - "Tracing.tracingComplete", - folly::dynamic::object("dataLossOccurred", false))); + frontendChannel_( + cdp::jsonNotification( + "Tracing.tracingComplete", + folly::dynamic::object("dataLossOccurred", false))); } } // namespace facebook::react::jsinspector_modern diff --git a/packages/react-native/ReactCommon/jsinspector-modern/TracingAgent.h b/packages/react-native/ReactCommon/jsinspector-modern/TracingAgent.h index 22a06cac85a..9a27dcbe718 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/TracingAgent.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/TracingAgent.h @@ -29,10 +29,7 @@ class TracingAgent { * is attached to. The caller is responsible for ensuring that the * HostTargetDelegate and underlying HostTarget both outlive the agent. */ - TracingAgent( - FrontendChannel frontendChannel, - SessionState& sessionState, - HostTargetController& hostTargetController); + TracingAgent(FrontendChannel frontendChannel, SessionState &sessionState, HostTargetController &hostTargetController); ~TracingAgent(); @@ -41,13 +38,12 @@ class TracingAgent { * \c FrontendChannel synchronously or asynchronously. * \param req The parsed request. */ - bool handleRequest(const cdp::PreparsedRequest& req); + bool handleRequest(const cdp::PreparsedRequest &req); /** * Emits the Trace Recording that was stashed externally by the HostTarget. */ - void emitExternalTraceRecording( - tracing::TraceRecordingState traceRecording) const; + void emitExternalTraceRecording(tracing::TraceRecordingState traceRecording) const; private: /** @@ -55,9 +51,9 @@ class TracingAgent { */ FrontendChannel frontendChannel_; - SessionState& sessionState_; + SessionState &sessionState_; - HostTargetController& hostTargetController_; + HostTargetController &hostTargetController_; /** * Emits the captured Trace Recording state in a series of diff --git a/packages/react-native/ReactCommon/jsinspector-modern/UniqueMonostate.h b/packages/react-native/ReactCommon/jsinspector-modern/UniqueMonostate.h index 7766e94399c..319ad9e63b6 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/UniqueMonostate.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/UniqueMonostate.h @@ -18,28 +18,28 @@ namespace facebook::react::jsinspector_modern { */ template struct UniqueMonostate { - constexpr bool operator==( - const UniqueMonostate& /*unused*/) const noexcept { + constexpr bool operator==(const UniqueMonostate & /*unused*/) const noexcept + { return true; } - constexpr bool operator!=( - const UniqueMonostate& /*unused*/) const noexcept { + constexpr bool operator!=(const UniqueMonostate & /*unused*/) const noexcept + { return false; } - constexpr bool operator<( - const UniqueMonostate& /*unused*/) const noexcept { + constexpr bool operator<(const UniqueMonostate & /*unused*/) const noexcept + { return false; } - constexpr bool operator>( - const UniqueMonostate& /*unused*/) const noexcept { + constexpr bool operator>(const UniqueMonostate & /*unused*/) const noexcept + { return false; } - constexpr bool operator<=( - const UniqueMonostate& /*unused*/) const noexcept { + constexpr bool operator<=(const UniqueMonostate & /*unused*/) const noexcept + { return true; } - constexpr bool operator>=( - const UniqueMonostate& /*unused*/) const noexcept { + constexpr bool operator>=(const UniqueMonostate & /*unused*/) const noexcept + { return true; } }; @@ -50,9 +50,8 @@ namespace std { template struct hash<::facebook::react::jsinspector_modern::UniqueMonostate> { - size_t operator()( - const ::facebook::react::jsinspector_modern::UniqueMonostate< - key>& /*unused*/) const noexcept { + size_t operator()(const ::facebook::react::jsinspector_modern::UniqueMonostate & /*unused*/) const noexcept + { return key; } }; diff --git a/packages/react-native/ReactCommon/jsinspector-modern/Utf8.h b/packages/react-native/ReactCommon/jsinspector-modern/Utf8.h index aa87c131a64..4e82e3df0bd 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/Utf8.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/Utf8.h @@ -19,7 +19,8 @@ namespace facebook::react::jsinspector_modern { * * \param buffer Buffer to operate on - will be resized if necessary. */ -inline void truncateToValidUTF8(std::vector& buffer) { +inline void truncateToValidUTF8(std::vector &buffer) +{ const auto length = buffer.size(); // Ensure we don't cut a UTF-8 code point in the middle by removing any // trailing bytes representing an incomplete UTF-8 code point. @@ -31,8 +32,7 @@ inline void truncateToValidUTF8(std::vector& buffer) { int continuationBytes = 0; // Find the first byte of the UTF-8 code point (topmost bits 11) and count // the number of continuation bytes following it. - while ((buffer[length - continuationBytes - 1] & 0b11000000) != - 0b11000000) { + while ((buffer[length - continuationBytes - 1] & 0b11000000) != 0b11000000) { continuationBytes++; if (continuationBytes > 3 || continuationBytes >= length - 1) { throw std::runtime_error("Invalid UTF-8 sequence"); @@ -46,8 +46,7 @@ inline void truncateToValidUTF8(std::vector& buffer) { // by a 0. char mask = static_cast(0b11111000 << (3 - continuationBytes)); char expectedBitsAfterMask = static_cast(mask << 1); - if (continuationBytes == 0 || - (firstByteOfSequence & mask) != expectedBitsAfterMask) { + if (continuationBytes == 0 || (firstByteOfSequence & mask) != expectedBitsAfterMask) { // Remove the trailing continuation bytes, if any, and the first byte. buffer.resize(length - (continuationBytes + 1)); } diff --git a/packages/react-native/ReactCommon/jsinspector-modern/WeakList.h b/packages/react-native/ReactCommon/jsinspector-modern/WeakList.h index 4e097c67b13..00338c344ab 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/WeakList.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/WeakList.h @@ -30,7 +30,8 @@ class WeakList { * to destroyed elements) will be removed during iteration. */ template - void forEach(Fn&& fn) const { + void forEach(Fn &&fn) const + { for (auto it = ptrs_.begin(); it != ptrs_.end();) { if (auto ptr = it->lock()) { fn(*ptr); @@ -49,9 +50,10 @@ class WeakList { * As a side effect, any null pointers in the underlying list (corresponding * to destroyed elements) will be removed during this method. */ - size_t size() const { + size_t size() const + { size_t count{0}; - forEach([&count](const auto&) { ++count; }); + forEach([&count](const auto &) { ++count; }); return count; } @@ -61,14 +63,16 @@ class WeakList { * As a side effect, any null pointers in the underlying list (corresponding * to destroyed elements) will be removed during this method. */ - bool empty() const { + bool empty() const + { return !size(); } /** * Inserts an element into the list. */ - void insert(std::weak_ptr ptr) { + void insert(std::weak_ptr ptr) + { ptrs_.push_back(ptr); } diff --git a/packages/react-native/ReactCommon/jsinspector-modern/WebSocketInterfaces.h b/packages/react-native/ReactCommon/jsinspector-modern/WebSocketInterfaces.h index 09798fbed31..28cd9797b87 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/WebSocketInterfaces.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/WebSocketInterfaces.h @@ -43,9 +43,7 @@ class IWebSocketDelegate { * \param posixCode POSIX errno value if available, otherwise nullopt. * \param error Error description. */ - virtual void didFailWithError( - std::optional posixCode, - std::string error) = 0; + virtual void didFailWithError(std::optional posixCode, std::string error) = 0; /** * Called when a message has been received from the socket. diff --git a/packages/react-native/ReactCommon/jsinspector-modern/cdp/CdpJson.h b/packages/react-native/ReactCommon/jsinspector-modern/cdp/CdpJson.h index 12e536366e0..89576d96295 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/cdp/CdpJson.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/cdp/CdpJson.h @@ -52,7 +52,8 @@ struct PreparsedRequest { /** * Equality operator, useful for unit tests */ - inline bool operator==(const PreparsedRequest& rhs) const { + inline bool operator==(const PreparsedRequest &rhs) const + { return id == rhs.id && method == rhs.method && params == rhs.params; } @@ -92,10 +93,7 @@ using ParseError = folly::json::parse_error; * \param code Integer code from cdp::ErrorCode. * \param message Optional, brief human-readable error message. */ -std::string jsonError( - std::optional id, - ErrorCode code, - std::optional message = std::nullopt); +std::string jsonError(std::optional id, ErrorCode code, std::optional message = std::nullopt); /** * Returns a JSON-formatted string representing a successful response. @@ -105,9 +103,7 @@ std::string jsonError( * \param id The id of the request that this response corresponds to. * \param result Result payload, defaulting to {}. */ -std::string jsonResult( - RequestId id, - const folly::dynamic& result = folly::dynamic::object()); +std::string jsonResult(RequestId id, const folly::dynamic &result = folly::dynamic::object()); /** * Returns a JSON-formatted string representing a unilateral notification. @@ -117,9 +113,7 @@ std::string jsonResult( * \param method Notification (aka "event") method. * \param params Optional payload object. */ -std::string jsonNotification( - const std::string& method, - std::optional params = std::nullopt); +std::string jsonNotification(const std::string &method, std::optional params = std::nullopt); /** * Returns a JSON-formatted string representing a request. @@ -130,9 +124,6 @@ std::string jsonNotification( * \param method Requested method. * \param params Optional payload object. */ -std::string jsonRequest( - RequestId id, - const std::string& method, - std::optional params = std::nullopt); +std::string jsonRequest(RequestId id, const std::string &method, std::optional params = std::nullopt); } // namespace facebook::react::jsinspector_modern::cdp diff --git a/packages/react-native/ReactCommon/jsinspector-modern/network/BoundedRequestBuffer.h b/packages/react-native/ReactCommon/jsinspector-modern/network/BoundedRequestBuffer.h index 7ec1d3f9bbd..a84c728aa1c 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/network/BoundedRequestBuffer.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/network/BoundedRequestBuffer.h @@ -40,17 +40,14 @@ class BoundedRequestBuffer { * \param base64Encoded True if the data is base64-encoded, false otherwise. * \return True if the response body was stored, false otherwise. */ - bool put( - const std::string& requestId, - std::string_view data, - bool base64Encoded) noexcept; + bool put(const std::string &requestId, std::string_view data, bool base64Encoded) noexcept; /** * Retrieve a response preview by requestId. * \param requestId The unique identifier for the request. * \return A shared pointer to the request data if found, otherwise nullptr. */ - std::shared_ptr get(const std::string& requestId) const; + std::shared_ptr get(const std::string &requestId) const; /** * Remove all entries from the buffer. @@ -58,8 +55,7 @@ class BoundedRequestBuffer { void clear(); private: - std::unordered_map> - responses_; + std::unordered_map> responses_; std::deque order_; size_t currentSize_ = 0; }; diff --git a/packages/react-native/ReactCommon/jsinspector-modern/network/CdpNetwork.h b/packages/react-native/ReactCommon/jsinspector-modern/network/CdpNetwork.h index 156bf56fe8a..2246057ac46 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/network/CdpNetwork.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/network/CdpNetwork.h @@ -45,11 +45,8 @@ struct Response { * Convenience function to construct a `Response` from the generic * `ResponseInfo` input object. */ - static Response fromInputParams( - const std::string& url, - uint16_t status, - const Headers& headers, - int encodedDataLength); + static Response + fromInputParams(const std::string &url, uint16_t status, const Headers &headers, int encodedDataLength); folly::dynamic toDynamic() const; }; @@ -144,6 +141,6 @@ struct LoadingFinishedParams { * * https://chromedevtools.github.io/devtools-protocol/tot/Network/#type-ResourceType */ -std::string resourceTypeFromMimeType(const std::string& mimeType); +std::string resourceTypeFromMimeType(const std::string &mimeType); } // namespace facebook::react::jsinspector_modern::cdp::network diff --git a/packages/react-native/ReactCommon/jsinspector-modern/network/HttpUtils.h b/packages/react-native/ReactCommon/jsinspector-modern/network/HttpUtils.h index 3cabf2438a3..78cee7663c9 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/network/HttpUtils.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/network/HttpUtils.h @@ -23,6 +23,6 @@ std::string httpReasonPhrase(uint16_t status); * Get the MIME type for a response based on the 'Content-Type' header. If * the header is not present, returns 'application/octet-stream'. */ -std::string mimeTypeFromHeaders(const Headers& headers); +std::string mimeTypeFromHeaders(const Headers &headers); } // namespace facebook::react::jsinspector_modern diff --git a/packages/react-native/ReactCommon/jsinspector-modern/network/NetworkHandler.cpp b/packages/react-native/ReactCommon/jsinspector-modern/network/NetworkHandler.cpp index 6fb59b3ea98..0025a731b45 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/network/NetworkHandler.cpp +++ b/packages/react-native/ReactCommon/jsinspector-modern/network/NetworkHandler.cpp @@ -105,8 +105,9 @@ void NetworkHandler::onRequestWillBeSentExtraInfo( .connectTiming = {.requestTime = getCurrentUnixTimestampSeconds()}, }; - frontendChannel_(cdp::jsonNotification( - "Network.requestWillBeSentExtraInfo", params.toDynamic())); + frontendChannel_( + cdp::jsonNotification( + "Network.requestWillBeSentExtraInfo", params.toDynamic())); } void NetworkHandler::onResponseReceived( diff --git a/packages/react-native/ReactCommon/jsinspector-modern/network/NetworkHandler.h b/packages/react-native/ReactCommon/jsinspector-modern/network/NetworkHandler.h index 3ae55fc2fc1..f451ffa99d9 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/network/NetworkHandler.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/network/NetworkHandler.h @@ -33,7 +33,7 @@ using Headers = std::map; */ class NetworkHandler { public: - static NetworkHandler& getInstance(); + static NetworkHandler &getInstance(); /** * Set the channel used to send CDP events to the frontend. This should be @@ -58,7 +58,8 @@ class NetworkHandler { /** * Returns whether network debugging is currently enabled. */ - inline bool isEnabled() const { + inline bool isEnabled() const + { return enabled_.load(std::memory_order_acquire); } @@ -66,41 +67,34 @@ class NetworkHandler { * @cdp Network.requestWillBeSent */ void onRequestWillBeSent( - const std::string& requestId, - const cdp::network::Request& request, - const std::optional& redirectResponse); + const std::string &requestId, + const cdp::network::Request &request, + const std::optional &redirectResponse); /** * @cdp Network.requestWillBeSentExtraInfo */ - void onRequestWillBeSentExtraInfo( - const std::string& requestId, - const Headers& headers); + void onRequestWillBeSentExtraInfo(const std::string &requestId, const Headers &headers); /** * @cdp Network.responseReceived */ - void onResponseReceived( - const std::string& requestId, - const cdp::network::Response& response); + void onResponseReceived(const std::string &requestId, const cdp::network::Response &response); /** * @cdp Network.dataReceived */ - void onDataReceived( - const std::string& requestId, - int dataLength, - int encodedDataLength); + void onDataReceived(const std::string &requestId, int dataLength, int encodedDataLength); /** * @cdp Network.loadingFinished */ - void onLoadingFinished(const std::string& requestId, int encodedDataLength); + void onLoadingFinished(const std::string &requestId, int encodedDataLength); /** * @cdp Network.loadingFailed */ - void onLoadingFailed(const std::string& requestId, bool cancelled); + void onLoadingFailed(const std::string &requestId, bool cancelled); /** * Store the fetched response body for a text or image network response. @@ -110,10 +104,7 @@ class NetworkHandler { * * Should be called after checking \ref NetworkHandler::isEnabled. */ - void storeResponseBody( - const std::string& requestId, - std::string_view body, - bool base64Encoded); + void storeResponseBody(const std::string &requestId, std::string_view body, bool base64Encoded); /** * Retrieve a stored response body for a given request ID. @@ -121,30 +112,27 @@ class NetworkHandler { * \returns An optional tuple of [responseBody, base64Encoded]. Returns * nullopt if no entry is found in the buffer. */ - std::optional> getResponseBody( - const std::string& requestId); + std::optional> getResponseBody(const std::string &requestId); /** * Associate the given stack trace with the given request ID. */ - void recordRequestInitiatorStack( - const std::string& requestId, - folly::dynamic stackTrace); + void recordRequestInitiatorStack(const std::string &requestId, folly::dynamic stackTrace); private: NetworkHandler() = default; - NetworkHandler(const NetworkHandler&) = delete; - NetworkHandler& operator=(const NetworkHandler&) = delete; + NetworkHandler(const NetworkHandler &) = delete; + NetworkHandler &operator=(const NetworkHandler &) = delete; ~NetworkHandler() = default; std::atomic enabled_{false}; - inline bool isEnabledNoSync() const { + inline bool isEnabledNoSync() const + { return enabled_.load(std::memory_order_relaxed); } - std::optional consumeStoredRequestInitiator( - const std::string& requestId); + std::optional consumeStoredRequestInitiator(const std::string &requestId); FrontendChannel frontendChannel_; diff --git a/packages/react-native/ReactCommon/jsinspector-modern/tests/FollyDynamicMatchers.h b/packages/react-native/ReactCommon/jsinspector-modern/tests/FollyDynamicMatchers.h index f1f42f625d6..2877d7e9766 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/tests/FollyDynamicMatchers.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/tests/FollyDynamicMatchers.h @@ -17,9 +17,8 @@ namespace facebook { namespace folly_dynamic_matchers_utils { std::string as_string(std::string value); -std::string as_string(const folly::dynamic& value); -std::string explain_error( - folly::dynamic::json_pointer_resolution_error error); +std::string as_string(const folly::dynamic &value); +std::string explain_error(folly::dynamic::json_pointer_resolution_error error); } // namespace folly_dynamic_matchers_utils @@ -32,11 +31,11 @@ std::string explain_error( MATCHER_P( JsonParsed, innerMatcher, - std::string{"parsed as JSON "} + - testing::DescribeMatcher(innerMatcher, negation)) { + std::string{"parsed as JSON "} + testing::DescribeMatcher(innerMatcher, negation)) +{ using namespace ::testing; using namespace folly_dynamic_matchers_utils; - const auto& json = arg; + const auto &json = arg; folly::dynamic parsed = folly::parseJson(as_string(json)); return ExplainMatchResult(innerMatcher, parsed, result_listener); } @@ -45,14 +44,10 @@ MATCHER_P( * Given a folly::dynamic argument, asserts that it is deeply equal to the * result of parsing the given JSON string. */ -MATCHER_P( - JsonEq, - expected, - std::string{"deeply equals "} + - folly::toPrettyJson(folly::parseJson(expected))) { +MATCHER_P(JsonEq, expected, std::string{"deeply equals "} + folly::toPrettyJson(folly::parseJson(expected))) +{ using namespace ::testing; - return ExplainMatchResult( - JsonParsed(Eq(folly::parseJson(expected))), arg, result_listener); + return ExplainMatchResult(JsonParsed(Eq(folly::parseJson(expected))), arg, result_listener); } /** @@ -63,17 +58,15 @@ MATCHER_P2( AtJsonPtr, jsonPointer, innerMatcher, - std::string{"value at "} + jsonPointer + " " + - testing::DescribeMatcher(innerMatcher, negation)) { + std::string{"value at "} + jsonPointer + " " + testing::DescribeMatcher(innerMatcher, negation)) +{ using namespace ::testing; using namespace folly_dynamic_matchers_utils; auto resolved_ptr = arg.try_get_ptr(folly::json_pointer::parse(jsonPointer)); if (resolved_ptr.hasValue()) { - return ExplainMatchResult( - innerMatcher, *resolved_ptr.value().value, result_listener); + return ExplainMatchResult(innerMatcher, *resolved_ptr.value().value, result_listener); } - *result_listener << "has no value at " << jsonPointer << " because of error: " - << explain_error(resolved_ptr.error()); + *result_listener << "has no value at " << jsonPointer << " because of error: " << explain_error(resolved_ptr.error()); return false; } @@ -84,8 +77,8 @@ MATCHER_P2( MATCHER_P( DynamicString, innerMatcher, - std::string{"string value "} + - testing::DescribeMatcher(innerMatcher, negation)) { + std::string{"string value "} + testing::DescribeMatcher(innerMatcher, negation)) +{ using namespace ::testing; using namespace folly_dynamic_matchers_utils; if (!arg.isString()) { @@ -100,7 +93,8 @@ MATCHER_P( * string. Not technically specific to GMock, but convenient to have in a test * suite. */ -inline folly::dynamic operator""_json(const char* s, size_t n) { +inline folly::dynamic operator""_json(const char *s, size_t n) +{ return folly::parseJson(std::string{s, n}); } diff --git a/packages/react-native/ReactCommon/jsinspector-modern/tests/GmockHelpers.h b/packages/react-native/ReactCommon/jsinspector-modern/tests/GmockHelpers.h index 164d9e44413..a6ceb7ad8a6 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/tests/GmockHelpers.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/tests/GmockHelpers.h @@ -13,10 +13,8 @@ * A variant of GMOCK_ON_CALL_IMPL that allows specifying the source location as * a std::source_location parameter. */ -#define GMOCK_ON_CALL_WITH_SOURCE_LOCATION_IMPL_( \ - location, mock_expr, Setter, call) \ - ((mock_expr).gmock_##call)( \ - ::testing::internal::GetWithoutMatchers(), nullptr) \ +#define GMOCK_ON_CALL_WITH_SOURCE_LOCATION_IMPL_(location, mock_expr, Setter, call) \ + ((mock_expr).gmock_##call)(::testing::internal::GetWithoutMatchers(), nullptr) \ .Setter((location).file_name(), (location).line(), #mock_expr, #call) /** @@ -24,5 +22,4 @@ * std::source_location parameter; */ #define EXPECT_CALL_WITH_SOURCE_LOCATION(location, obj, call) \ - GMOCK_ON_CALL_WITH_SOURCE_LOCATION_IMPL_( \ - location, obj, InternalExpectedAt, call) + GMOCK_ON_CALL_WITH_SOURCE_LOCATION_IMPL_(location, obj, InternalExpectedAt, call) diff --git a/packages/react-native/ReactCommon/jsinspector-modern/tests/HostTargetTest.cpp b/packages/react-native/ReactCommon/jsinspector-modern/tests/HostTargetTest.cpp index 82bc955762f..88fef17ce04 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/tests/HostTargetTest.cpp +++ b/packages/react-native/ReactCommon/jsinspector-modern/tests/HostTargetTest.cpp @@ -180,9 +180,10 @@ TEST_F(HostTargetProtocolTest, PageReloadMethod) { EXPECT_CALL( hostTargetDelegate_, - onReload(Eq(HostTargetDelegate::PageReloadRequest{ - .ignoreCache = std::nullopt, - .scriptToEvaluateOnLoad = std::nullopt}))) + onReload( + Eq(HostTargetDelegate::PageReloadRequest{ + .ignoreCache = std::nullopt, + .scriptToEvaluateOnLoad = std::nullopt}))) .RetiresOnSaturation(); EXPECT_CALL(fromPage(), onMessage(JsonEq(R"({ "id": 1, @@ -196,8 +197,10 @@ TEST_F(HostTargetProtocolTest, PageReloadMethod) { EXPECT_CALL( hostTargetDelegate_, - onReload(Eq(HostTargetDelegate::PageReloadRequest{ - .ignoreCache = true, .scriptToEvaluateOnLoad = "alert('hello');"}))) + onReload( + Eq(HostTargetDelegate::PageReloadRequest{ + .ignoreCache = true, + .scriptToEvaluateOnLoad = "alert('hello');"}))) .RetiresOnSaturation(); EXPECT_CALL(fromPage(), onMessage(JsonEq(R"({ "id": 2, diff --git a/packages/react-native/ReactCommon/jsinspector-modern/tests/InspectorMocks.h b/packages/react-native/ReactCommon/jsinspector-modern/tests/InspectorMocks.h index 212f7510d5e..d83ed861884 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/tests/InspectorMocks.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/tests/InspectorMocks.h @@ -25,12 +25,9 @@ namespace facebook::react::jsinspector_modern { class MockWebSocket : public IWebSocket { public: - MockWebSocket( - const std::string& url, - std::weak_ptr delegate) - : url{url}, delegate{delegate} { - EXPECT_TRUE(this->delegate.lock()) - << "Delegate should exist when provided to createWebSocket"; + MockWebSocket(const std::string &url, std::weak_ptr delegate) : url{url}, delegate{delegate} + { + EXPECT_TRUE(this->delegate.lock()) << "Delegate should exist when provided to createWebSocket"; } const std::string url; @@ -40,7 +37,8 @@ class MockWebSocket : public IWebSocket { * Convenience method to access the delegate from tests. * \pre The delegate has not been destroyed. */ - IWebSocketDelegate& getDelegate() { + IWebSocketDelegate &getDelegate() + { auto delegateStrong = this->delegate.lock(); EXPECT_TRUE(delegateStrong); return *delegateStrong; @@ -61,15 +59,18 @@ class MockRemoteConnection : public IRemoteConnection { class MockLocalConnection : public ILocalConnection { public: - explicit MockLocalConnection( - std::unique_ptr remoteConnection) - : remoteConnection_{std::move(remoteConnection)} {} + explicit MockLocalConnection(std::unique_ptr remoteConnection) + : remoteConnection_{std::move(remoteConnection)} + { + } - IRemoteConnection& getRemoteConnection() { + IRemoteConnection &getRemoteConnection() + { return *remoteConnection_; } - std::unique_ptr dangerouslyReleaseRemoteConnection() { + std::unique_ptr dangerouslyReleaseRemoteConnection() + { return std::move(remoteConnection_); } @@ -81,22 +82,18 @@ class MockLocalConnection : public ILocalConnection { std::unique_ptr remoteConnection_; }; -class MockInspectorPackagerConnectionDelegate - : public InspectorPackagerConnectionDelegate { +class MockInspectorPackagerConnectionDelegate : public InspectorPackagerConnectionDelegate { public: - explicit MockInspectorPackagerConnectionDelegate(folly::Executor& executor) - : executor_(executor) { + explicit MockInspectorPackagerConnectionDelegate(folly::Executor &executor) : executor_(executor) + { using namespace testing; - ON_CALL(*this, scheduleCallback(_, _)) - .WillByDefault(Invoke<>([this](auto callback, auto delay) { - if (auto scheduledExecutor = - dynamic_cast(&executor_)) { - scheduledExecutor->scheduleAt( - callback, scheduledExecutor->now() + delay); - } else { - executor_.add(callback); - } - })); + ON_CALL(*this, scheduleCallback(_, _)).WillByDefault(Invoke<>([this](auto callback, auto delay) { + if (auto scheduledExecutor = dynamic_cast(&executor_)) { + scheduledExecutor->scheduleAt(callback, scheduledExecutor->now() + delay); + } else { + executor_.add(callback); + } + })); EXPECT_CALL(*this, scheduleCallback(_, _)).Times(AnyNumber()); } @@ -104,7 +101,7 @@ class MockInspectorPackagerConnectionDelegate MOCK_METHOD( std::unique_ptr, connectWebSocket, - (const std::string& url, std::weak_ptr delegate), + (const std::string &url, std::weak_ptr delegate), (override)); MOCK_METHOD( void, @@ -113,26 +110,26 @@ class MockInspectorPackagerConnectionDelegate (override)); private: - folly::Executor& executor_; + folly::Executor &executor_; }; class MockHostTargetDelegate : public HostTargetDelegate { public: // HostTargetDelegate methods - HostTargetMetadata getMetadata() override { + HostTargetMetadata getMetadata() override + { return {.integrationName = "MockHostTargetDelegate"}; } - MOCK_METHOD(void, onReload, (const PageReloadRequest& request), (override)); + MOCK_METHOD(void, onReload, (const PageReloadRequest &request), (override)); MOCK_METHOD( void, onSetPausedInDebuggerMessage, - (const OverlaySetPausedInDebuggerMessageRequest& request), + (const OverlaySetPausedInDebuggerMessageRequest &request), (override)); MOCK_METHOD( void, loadNetworkResource, - (const LoadNetworkResourceRequest& params, - ScopedExecutor executor), + (const LoadNetworkResourceRequest ¶ms, ScopedExecutor executor), (override)); }; @@ -145,17 +142,12 @@ class MockRuntimeTargetDelegate : public RuntimeTargetDelegate { std::unique_ptr, createAgentDelegate, (FrontendChannel channel, - SessionState& sessionState, - std::unique_ptr - previouslyExportedState, - const ExecutionContextDescription&, + SessionState &sessionState, + std::unique_ptr previouslyExportedState, + const ExecutionContextDescription &, RuntimeExecutor), (override)); - MOCK_METHOD( - void, - addConsoleMessage, - (jsi::Runtime & runtime, ConsoleMessage message), - (override)); + MOCK_METHOD(void, addConsoleMessage, (jsi::Runtime & runtime, ConsoleMessage message), (override)); MOCK_METHOD(bool, supportsConsole, (), (override, const)); MOCK_METHOD( std::unique_ptr, @@ -164,18 +156,11 @@ class MockRuntimeTargetDelegate : public RuntimeTargetDelegate { (override)); MOCK_METHOD(void, enableSamplingProfiler, (), (override)); MOCK_METHOD(void, disableSamplingProfiler, (), (override)); - MOCK_METHOD( - tracing::RuntimeSamplingProfile, - collectSamplingProfile, - (), - (override)); - MOCK_METHOD( - std::optional, - serializeStackTrace, - (const StackTrace& stackTrace), - (override)); + MOCK_METHOD(tracing::RuntimeSamplingProfile, collectSamplingProfile, (), (override)); + MOCK_METHOD(std::optional, serializeStackTrace, (const StackTrace &stackTrace), (override)); - inline MockRuntimeTargetDelegate() { + inline MockRuntimeTargetDelegate() + { using namespace testing; // Silence "uninteresting mock function call" warnings for methods that @@ -189,23 +174,21 @@ class MockRuntimeAgentDelegate : public RuntimeAgentDelegate { public: inline MockRuntimeAgentDelegate( FrontendChannel frontendChannel, - SessionState& sessionState, + SessionState &sessionState, std::unique_ptr /*unused*/, ExecutionContextDescription executionContextDescription, - const RuntimeExecutor& /*runtimeExecutor*/) + const RuntimeExecutor & /*runtimeExecutor*/) : frontendChannel(std::move(frontendChannel)), sessionState(sessionState), - executionContextDescription(std::move(executionContextDescription)) {} + executionContextDescription(std::move(executionContextDescription)) + { + } // RuntimeAgentDelegate methods - MOCK_METHOD( - bool, - handleRequest, - (const cdp::PreparsedRequest& req), - (override)); + MOCK_METHOD(bool, handleRequest, (const cdp::PreparsedRequest &req), (override)); const FrontendChannel frontendChannel; - SessionState& sessionState; + SessionState &sessionState; const ExecutionContextDescription executionContextDescription; }; diff --git a/packages/react-native/ReactCommon/jsinspector-modern/tests/InspectorPackagerConnectionTest.cpp b/packages/react-native/ReactCommon/jsinspector-modern/tests/InspectorPackagerConnectionTest.cpp index ca73058026c..a75f47029bf 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/tests/InspectorPackagerConnectionTest.cpp +++ b/packages/react-native/ReactCommon/jsinspector-modern/tests/InspectorPackagerConnectionTest.cpp @@ -35,11 +35,12 @@ template class InspectorPackagerConnectionTestBase : public testing::Test { protected: InspectorPackagerConnectionTestBase() - : packagerConnection_(InspectorPackagerConnection{ - "ws://mock-host:12345", - "my-device", - "my-app", - packagerConnectionDelegates_.make_unique(asyncExecutor_)}) { + : packagerConnection_( + InspectorPackagerConnection{ + "ws://mock-host:12345", + "my-device", + "my-app", + packagerConnectionDelegates_.make_unique(asyncExecutor_)}) { auto makeSocket = webSockets_.lazily_make_unique< const std::string&, std::weak_ptr>(); @@ -283,14 +284,15 @@ TEST_F(InspectorPackagerConnectionTest, TestSendReceiveEvents) { .lazily_make_unique>()); // Connect to the page. - webSockets_[0]->getDelegate().didReceiveMessage(fmt::format( - R"({{ + webSockets_[0]->getDelegate().didReceiveMessage( + fmt::format( + R"({{ "event": "connect", "payload": {{ "pageId": {0} }} }})", - toJson(std::to_string(pageId)))); + toJson(std::to_string(pageId)))); ASSERT_TRUE(localConnections_[0]); // Send an event from the mocked backend (local) to the frontend (remote) @@ -323,16 +325,17 @@ TEST_F(InspectorPackagerConnectionTest, TestSendReceiveEvents) { AtJsonPtr("/params", ElementsAre("arg1", "arg2")))))) .RetiresOnSaturation(); - webSockets_[0]->getDelegate().didReceiveMessage(fmt::format( - R"({{ + webSockets_[0]->getDelegate().didReceiveMessage( + fmt::format( + R"({{ "event": "wrappedEvent", "payload": {{ "pageId": {0}, "wrappedEvent": {1} }} }})", - toJson(std::to_string(pageId)), - toJson(R"({ + toJson(std::to_string(pageId)), + toJson(R"({ "method": "FakeDomain.fakeMethod", "id": 1234, "params": ["arg1", "arg2"] @@ -362,11 +365,12 @@ TEST_F(InspectorPackagerConnectionTest, TestSendReceiveEventsToMultiplePages) { const int kNumPages = 2; for (int i = 0; i < kNumPages; ++i) { - pageIds.push_back(getInspectorInstance().addPage( - "mock-description", - "mock-vm", - localConnections_ - .lazily_make_unique>())); + pageIds.push_back( + getInspectorInstance().addPage( + "mock-description", + "mock-vm", + localConnections_ + .lazily_make_unique>())); if (i > 0) { ASSERT_NE(pageIds[i], pageIds[i - 1]) << "Received duplicate page IDs from inspector."; @@ -375,14 +379,15 @@ TEST_F(InspectorPackagerConnectionTest, TestSendReceiveEventsToMultiplePages) { for (int i = 0; i < kNumPages; ++i) { // Connect to the i-th page. - webSockets_[0]->getDelegate().didReceiveMessage(fmt::format( - R"({{ + webSockets_[0]->getDelegate().didReceiveMessage( + fmt::format( + R"({{ "event": "connect", "payload": {{ "pageId": {0} }} }})", - toJson(std::to_string(pageIds[i])))); + toJson(std::to_string(pageIds[i])))); ASSERT_TRUE(localConnections_[i]); } @@ -417,16 +422,17 @@ TEST_F(InspectorPackagerConnectionTest, TestSendReceiveEventsToMultiplePages) { *localConnections_[i], sendMessage(JsonParsed(AtJsonPtr("/method", Eq(method))))) .RetiresOnSaturation(); - webSockets_[0]->getDelegate().didReceiveMessage(fmt::format( - R"({{ + webSockets_[0]->getDelegate().didReceiveMessage( + fmt::format( + R"({{ "event": "wrappedEvent", "payload": {{ "pageId": {0}, "wrappedEvent": {1} }} }})", - toJson(std::to_string(pageIds[i])), - toJson(toJson(dynamic::object("method", method))))); + toJson(std::to_string(pageIds[i])), + toJson(toJson(dynamic::object("method", method))))); } for (int i = 0; i < kNumPages; ++i) { @@ -447,14 +453,15 @@ TEST_F(InspectorPackagerConnectionTest, TestSendEventToAllConnections) { .lazily_make_unique>()); // Connect to the page. - webSockets_[0]->getDelegate().didReceiveMessage(fmt::format( - R"({{ + webSockets_[0]->getDelegate().didReceiveMessage( + fmt::format( + R"({{ "event": "connect", "payload": {{ "pageId": {0} }} }})", - toJson(std::to_string(pageId)))); + toJson(std::to_string(pageId)))); ASSERT_TRUE(localConnections_[0]); // Impersonate the frontend (remote) to send a message to all (local) @@ -488,26 +495,28 @@ TEST_F(InspectorPackagerConnectionTest, TestConnectThenDisconnect) { .lazily_make_unique>()); // Connect to the page. - webSockets_[0]->getDelegate().didReceiveMessage(fmt::format( - R"({{ + webSockets_[0]->getDelegate().didReceiveMessage( + fmt::format( + R"({{ "event": "connect", "payload": {{ "pageId": {0} }} }})", - toJson(std::to_string(pageId)))); + toJson(std::to_string(pageId)))); ASSERT_TRUE(localConnections_[0]); // Disconnect from the page. EXPECT_CALL(*localConnections_[0], disconnect()).RetiresOnSaturation(); - webSockets_[0]->getDelegate().didReceiveMessage(fmt::format( - R"({{ + webSockets_[0]->getDelegate().didReceiveMessage( + fmt::format( + R"({{ "event": "disconnect", "payload": {{ "pageId": {0} }} }})", - toJson(std::to_string(pageId)))); + toJson(std::to_string(pageId)))); EXPECT_FALSE(localConnections_[0]); } @@ -523,14 +532,15 @@ TEST_F(InspectorPackagerConnectionTest, TestConnectThenCloseSocket) { .lazily_make_unique>()); // Connect to the page. - webSockets_[0]->getDelegate().didReceiveMessage(fmt::format( - R"({{ + webSockets_[0]->getDelegate().didReceiveMessage( + fmt::format( + R"({{ "event": "connect", "payload": {{ "pageId": {0} }} }})", - toJson(std::to_string(pageId)))); + toJson(std::to_string(pageId)))); ASSERT_TRUE(localConnections_[0]); // Notify that the socket was closed. @@ -551,14 +561,15 @@ TEST_F(InspectorPackagerConnectionTest, TestConnectThenSocketFailure) { .lazily_make_unique>()); // Connect to the page. - webSockets_[0]->getDelegate().didReceiveMessage(fmt::format( - R"({{ + webSockets_[0]->getDelegate().didReceiveMessage( + fmt::format( + R"({{ "event": "connect", "payload": {{ "pageId": {0} }} }})", - toJson(std::to_string(pageId)))); + toJson(std::to_string(pageId)))); ASSERT_TRUE(localConnections_[0]); // Notify that the socket was closed (implicitly, as the result of an error). @@ -581,14 +592,15 @@ TEST_F( .lazily_make_unique>()); // Connect to the page. - webSockets_[0]->getDelegate().didReceiveMessage(fmt::format( - R"({{ + webSockets_[0]->getDelegate().didReceiveMessage( + fmt::format( + R"({{ "event": "connect", "payload": {{ "pageId": {0} }} }})", - toJson(std::to_string(pageId)))); + toJson(std::to_string(pageId)))); ASSERT_TRUE(localConnections_[0]); // Notify that the socket was closed (implicitly, as the result of an error). @@ -627,26 +639,28 @@ TEST_F( .lazily_make_unique>()); // Connect to the page. - webSockets_[0]->getDelegate().didReceiveMessage(fmt::format( - R"({{ + webSockets_[0]->getDelegate().didReceiveMessage( + fmt::format( + R"({{ "event": "connect", "payload": {{ "pageId": {0} }} }})", - toJson(std::to_string(pageId)))); + toJson(std::to_string(pageId)))); ASSERT_TRUE(localConnections_[0]); // Try connecting to the same page again. This results in a disconnection. EXPECT_CALL(*localConnections_[0], disconnect()).RetiresOnSaturation(); - webSockets_[0]->getDelegate().didReceiveMessage(fmt::format( - R"({{ + webSockets_[0]->getDelegate().didReceiveMessage( + fmt::format( + R"({{ "event": "connect", "payload": {{ "pageId": {0} }} }})", - toJson(std::to_string(pageId)))); + toJson(std::to_string(pageId)))); EXPECT_FALSE(localConnections_[0]); } @@ -662,37 +676,40 @@ TEST_F(InspectorPackagerConnectionTest, TestMultipleDisconnect) { .lazily_make_unique>()); // Connect to the page. - webSockets_[0]->getDelegate().didReceiveMessage(fmt::format( - R"({{ + webSockets_[0]->getDelegate().didReceiveMessage( + fmt::format( + R"({{ "event": "connect", "payload": {{ "pageId": {0} }} }})", - toJson(std::to_string(pageId)))); + toJson(std::to_string(pageId)))); ASSERT_TRUE(localConnections_[0]); // Disconnect from the page. EXPECT_CALL(*localConnections_[0], disconnect()).RetiresOnSaturation(); - webSockets_[0]->getDelegate().didReceiveMessage(fmt::format( - R"({{ + webSockets_[0]->getDelegate().didReceiveMessage( + fmt::format( + R"({{ "event": "disconnect", "payload": {{ "pageId": {0} }} }})", - toJson(std::to_string(pageId)))); + toJson(std::to_string(pageId)))); EXPECT_FALSE(localConnections_[0]); // Disconnect again. This is a noop. - webSockets_[0]->getDelegate().didReceiveMessage(fmt::format( - R"({{ + webSockets_[0]->getDelegate().didReceiveMessage( + fmt::format( + R"({{ "event": "disconnect", "payload": {{ "pageId": {0} }} }})", - toJson(std::to_string(pageId)))); + toJson(std::to_string(pageId)))); EXPECT_FALSE(localConnections_[0]); } @@ -708,40 +725,43 @@ TEST_F(InspectorPackagerConnectionTest, TestDisconnectThenSendEvent) { .lazily_make_unique>()); // Connect to the page. - webSockets_[0]->getDelegate().didReceiveMessage(fmt::format( - R"({{ + webSockets_[0]->getDelegate().didReceiveMessage( + fmt::format( + R"({{ "event": "connect", "payload": {{ "pageId": {0} }} }})", - toJson(std::to_string(pageId)))); + toJson(std::to_string(pageId)))); ASSERT_TRUE(localConnections_[0]); // Disconnect from the page. EXPECT_CALL(*localConnections_[0], disconnect()).RetiresOnSaturation(); - webSockets_[0]->getDelegate().didReceiveMessage(fmt::format( - R"({{ + webSockets_[0]->getDelegate().didReceiveMessage( + fmt::format( + R"({{ "event": "disconnect", "payload": {{ "pageId": {0} }} }})", - toJson(std::to_string(pageId)))); + toJson(std::to_string(pageId)))); EXPECT_FALSE(localConnections_[0]); // Send an event from the frontend (remote) to the backend (local). This // is a noop. - webSockets_[0]->getDelegate().didReceiveMessage(fmt::format( - R"({{ + webSockets_[0]->getDelegate().didReceiveMessage( + fmt::format( + R"({{ "event": "wrappedEvent", "payload": {{ "pageId": {0}, "wrappedEvent": {1} }} }})", - toJson(std::to_string(pageId)), - toJson(R"({ + toJson(std::to_string(pageId)), + toJson(R"({ "method": "FakeDomain.fakeMethod", "id": 1234, "params": ["arg1", "arg2"] @@ -756,15 +776,16 @@ TEST_F(InspectorPackagerConnectionTest, TestSendEventToUnknownPage) { // Send an event from the frontend (remote) to the backend (local). This // is a noop (except for logging). - webSockets_[0]->getDelegate().didReceiveMessage(fmt::format( - R"({{ + webSockets_[0]->getDelegate().didReceiveMessage( + fmt::format( + R"({{ "event": "wrappedEvent", "payload": {{ "pageId": "1234", "wrappedEvent": {0} }} }})", - toJson(R"({ + toJson(R"({ "method": "FakeDomain.fakeMethod", "id": 1234, "params": ["arg1", "arg2"] @@ -923,14 +944,15 @@ TEST_F( .lazily_make_unique>()); // Connect to the page. - retainedWebSocketDelegate->didReceiveMessage(fmt::format( - R"({{ + retainedWebSocketDelegate->didReceiveMessage( + fmt::format( + R"({{ "event": "connect", "payload": {{ "pageId": {0} }} }})", - toJson(std::to_string(pageId)))); + toJson(std::to_string(pageId)))); ASSERT_TRUE(localConnections_[0]); // Send an event from the frontend (remote) to the backend (local) and @@ -943,16 +965,17 @@ TEST_F( AtJsonPtr("/params", ElementsAre("arg1", "arg2")))))) .RetiresOnSaturation(); - retainedWebSocketDelegate->didReceiveMessage(fmt::format( - R"({{ + retainedWebSocketDelegate->didReceiveMessage( + fmt::format( + R"({{ "event": "wrappedEvent", "payload": {{ "pageId": {0}, "wrappedEvent": {1} }} }})", - toJson(std::to_string(pageId)), - toJson(R"({ + toJson(std::to_string(pageId)), + toJson(R"({ "method": "FakeDomain.fakeMethod", "id": 1234, "params": ["arg1", "arg2"] @@ -977,14 +1000,15 @@ TEST_F(InspectorPackagerConnectionTest, TestDestroyConnectionOnPageRemoved) { .lazily_make_unique>()); // Connect to the page. - webSockets_[0]->getDelegate().didReceiveMessage(fmt::format( - R"({{ + webSockets_[0]->getDelegate().didReceiveMessage( + fmt::format( + R"({{ "event": "connect", "payload": {{ "pageId": {0} }} }})", - toJson(std::to_string(pageId)))); + toJson(std::to_string(pageId)))); EXPECT_TRUE(localConnections_[0]); // Remove the page. @@ -1007,14 +1031,15 @@ TEST_F( .lazily_make_unique>()); // Connect to the page. - webSockets_[0]->getDelegate().didReceiveMessage(fmt::format( - R"({{ + webSockets_[0]->getDelegate().didReceiveMessage( + fmt::format( + R"({{ "event": "connect", "payload": {{ "pageId": {0} }} }})", - toJson(std::to_string(pageId)))); + toJson(std::to_string(pageId)))); ASSERT_TRUE(localConnections_[0]); // Send an event from the mocked backend (local) to the frontend (remote) @@ -1047,14 +1072,15 @@ TEST_F( .lazily_make_unique>()); // Connect to the page. - webSockets_[0]->getDelegate().didReceiveMessage(fmt::format( - R"({{ + webSockets_[0]->getDelegate().didReceiveMessage( + fmt::format( + R"({{ "event": "connect", "payload": {{ "pageId": {0} }} }})", - toJson(std::to_string(pageId)))); + toJson(std::to_string(pageId)))); ASSERT_TRUE(localConnections_[0]); // Send an event from the mocked backend (local) to the frontend (remote) @@ -1066,25 +1092,27 @@ TEST_F( // Disconnect from the page. EXPECT_CALL(*localConnections_[0], disconnect()).RetiresOnSaturation(); - webSockets_[0]->getDelegate().didReceiveMessage(fmt::format( - R"({{ + webSockets_[0]->getDelegate().didReceiveMessage( + fmt::format( + R"({{ "event": "disconnect", "payload": {{ "pageId": {0} }} }})", - toJson(std::to_string(pageId)))); + toJson(std::to_string(pageId)))); EXPECT_FALSE(localConnections_[0]); // Connect to the same page again. - webSockets_[0]->getDelegate().didReceiveMessage(fmt::format( - R"({{ + webSockets_[0]->getDelegate().didReceiveMessage( + fmt::format( + R"({{ "event": "connect", "payload": {{ "pageId": {0} }} }})", - toJson(std::to_string(pageId)))); + toJson(std::to_string(pageId)))); EXPECT_TRUE(localConnections_[1]); @@ -1129,14 +1157,15 @@ TEST_F( .lazily_make_unique>()); // Connect to the page. - webSockets_[0]->getDelegate().didReceiveMessage(fmt::format( - R"({{ + webSockets_[0]->getDelegate().didReceiveMessage( + fmt::format( + R"({{ "event": "connect", "payload": {{ "pageId": {0} }} }})", - toJson(std::to_string(pageId)))); + toJson(std::to_string(pageId)))); ASSERT_TRUE(localConnections_[0]); // Send an event from the mocked backend (local) to the frontend (remote) @@ -1153,25 +1182,27 @@ TEST_F( // Disconnect from the page. EXPECT_CALL(*localConnections_[0], disconnect()).RetiresOnSaturation(); - webSockets_[0]->getDelegate().didReceiveMessage(fmt::format( - R"({{ + webSockets_[0]->getDelegate().didReceiveMessage( + fmt::format( + R"({{ "event": "disconnect", "payload": {{ "pageId": {0} }} }})", - toJson(std::to_string(pageId)))); + toJson(std::to_string(pageId)))); EXPECT_FALSE(localConnections_[0]); // Connect to the same page again. - webSockets_[0]->getDelegate().didReceiveMessage(fmt::format( - R"({{ + webSockets_[0]->getDelegate().didReceiveMessage( + fmt::format( + R"({{ "event": "connect", "payload": {{ "pageId": {0} }} }})", - toJson(std::to_string(pageId)))); + toJson(std::to_string(pageId)))); EXPECT_TRUE(localConnections_[1]); @@ -1258,25 +1289,27 @@ TEST_F(InspectorPackagerConnectionTest, TestRejectedPageConnection) { AtJsonPtr("/payload/pageId", Eq(std::to_string(pageId))))))) .RetiresOnSaturation(); - webSockets_[0]->getDelegate().didReceiveMessage(fmt::format( - R"({{ + webSockets_[0]->getDelegate().didReceiveMessage( + fmt::format( + R"({{ "event": "connect", "payload": {{ "pageId": {0} }} }})", - toJson(std::to_string(pageId)))); + toJson(std::to_string(pageId)))); - webSockets_[0]->getDelegate().didReceiveMessage(fmt::format( - R"({{ + webSockets_[0]->getDelegate().didReceiveMessage( + fmt::format( + R"({{ "event": "wrappedEvent", "payload": {{ "pageId": {0}, "wrappedEvent": {1} }} }})", - toJson(std::to_string(pageId)), - toJson(R"({ + toJson(std::to_string(pageId)), + toJson(R"({ "method": "FakeDomain.fakeMethod", "id": 1, "params": ["arg1", "arg2"] @@ -1293,25 +1326,27 @@ TEST_F(InspectorPackagerConnectionTest, TestRejectedPageConnection) { AtJsonPtr("/payload/pageId", Eq(std::to_string(pageId))))))) .RetiresOnSaturation(); - webSockets_[0]->getDelegate().didReceiveMessage(fmt::format( - R"({{ + webSockets_[0]->getDelegate().didReceiveMessage( + fmt::format( + R"({{ "event": "connect", "payload": {{ "pageId": {0} }} }})", - toJson(std::to_string(pageId)))); + toJson(std::to_string(pageId)))); - webSockets_[0]->getDelegate().didReceiveMessage(fmt::format( - R"({{ + webSockets_[0]->getDelegate().didReceiveMessage( + fmt::format( + R"({{ "event": "wrappedEvent", "payload": {{ "pageId": {0}, "wrappedEvent": {1} }} }})", - toJson(std::to_string(pageId)), - toJson(R"({ + toJson(std::to_string(pageId)), + toJson(R"({ "method": "FakeDomain.fakeMethod", "id": 2, "params": ["arg1", "arg2"] @@ -1321,14 +1356,15 @@ TEST_F(InspectorPackagerConnectionTest, TestRejectedPageConnection) { // page. mockNextConnectionBehavior = Accept; - webSockets_[0]->getDelegate().didReceiveMessage(fmt::format( - R"({{ + webSockets_[0]->getDelegate().didReceiveMessage( + fmt::format( + R"({{ "event": "connect", "payload": {{ "pageId": {0} }} }})", - toJson(std::to_string(pageId)))); + toJson(std::to_string(pageId)))); EXPECT_CALL( *localConnections_[0], @@ -1338,16 +1374,17 @@ TEST_F(InspectorPackagerConnectionTest, TestRejectedPageConnection) { AtJsonPtr("/params", ElementsAre("arg1", "arg2")))))) .RetiresOnSaturation(); - webSockets_[0]->getDelegate().didReceiveMessage(fmt::format( - R"({{ + webSockets_[0]->getDelegate().didReceiveMessage( + fmt::format( + R"({{ "event": "wrappedEvent", "payload": {{ "pageId": {0}, "wrappedEvent": {1} }} }})", - toJson(std::to_string(pageId)), - toJson(R"({ + toJson(std::to_string(pageId)), + toJson(R"({ "method": "FakeDomain.fakeMethod", "id": 3, "params": ["arg1", "arg2"] diff --git a/packages/react-native/ReactCommon/jsinspector-modern/tests/JsiIntegrationTest.cpp b/packages/react-native/ReactCommon/jsinspector-modern/tests/JsiIntegrationTest.cpp index 4285ec8d589..3df2f0b2fce 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/tests/JsiIntegrationTest.cpp +++ b/packages/react-native/ReactCommon/jsinspector-modern/tests/JsiIntegrationTest.cpp @@ -534,13 +534,14 @@ TYPED_TEST(JsiIntegrationHermesTest, EvaluateExpressionInExecutionContext) { } } })")); - this->toPage_->sendMessage(fmt::format( - R"({{ + this->toPage_->sendMessage( + fmt::format( + R"({{ "id": 1, "method": "Runtime.evaluate", "params": {{"expression": "42", "contextId": {0}}} }})", - std::to_string(executionContextId))); + std::to_string(executionContextId))); // Silence notifications about execution contexts. this->expectMessageFromPage(JsonEq(R"({ @@ -556,13 +557,14 @@ TYPED_TEST(JsiIntegrationHermesTest, EvaluateExpressionInExecutionContext) { // Now the old execution context is stale. this->expectMessageFromPage( JsonParsed(AllOf(AtJsonPtr("/id", 3), AtJsonPtr("/error/code", -32600)))); - this->toPage_->sendMessage(fmt::format( - R"({{ + this->toPage_->sendMessage( + fmt::format( + R"({{ "id": 3, "method": "Runtime.evaluate", "params": {{"expression": "10000", "contextId": {0}}} }})", - std::to_string(executionContextId))); + std::to_string(executionContextId))); } #if !defined(HERMES_STATIC_HERMES) @@ -785,48 +787,52 @@ TYPED_TEST(JsiIntegrationHermesTest, ReleaseRemoteObject) { // Ensure we can get the properties of the object. this->expectMessageFromPage(JsonParsed( AllOf(AtJsonPtr("/id", 2), AtJsonPtr("/result/result", SizeIs(Gt(0)))))); - this->toPage_->sendMessage(fmt::format( - R"({{ + this->toPage_->sendMessage( + fmt::format( + R"({{ "id": 2, "method": "Runtime.getProperties", "params": {{"objectId": {}, "ownProperties": true}} }})", - folly::toJson(objectId))); + folly::toJson(objectId))); // Release the object. this->expectMessageFromPage(JsonEq(R"({ "id": 3, "result": {} })")); - this->toPage_->sendMessage(fmt::format( - R"({{ + this->toPage_->sendMessage( + fmt::format( + R"({{ "id": 3, "method": "Runtime.releaseObject", "params": {{"objectId": {}, "ownProperties": true}} }})", - folly::toJson(objectId))); + folly::toJson(objectId))); // Getting properties for a released object results in an error. this->expectMessageFromPage( JsonParsed(AllOf(AtJsonPtr("/id", 4), AtJsonPtr("/error/code", -32000)))); - this->toPage_->sendMessage(fmt::format( - R"({{ + this->toPage_->sendMessage( + fmt::format( + R"({{ "id": 4, "method": "Runtime.getProperties", "params": {{"objectId": {}, "ownProperties": true}} }})", - folly::toJson(objectId))); + folly::toJson(objectId))); // Releasing an already released object is an error. this->expectMessageFromPage( JsonParsed(AllOf(AtJsonPtr("/id", 5), AtJsonPtr("/error/code", -32000)))); - this->toPage_->sendMessage(fmt::format( - R"({{ + this->toPage_->sendMessage( + fmt::format( + R"({{ "id": 5, "method": "Runtime.releaseObject", "params": {{"objectId": {}, "ownProperties": true}} }})", - folly::toJson(objectId))); + folly::toJson(objectId))); } TYPED_TEST(JsiIntegrationHermesTest, ReleaseRemoteObjectGroup) { @@ -851,13 +857,14 @@ TYPED_TEST(JsiIntegrationHermesTest, ReleaseRemoteObjectGroup) { // Ensure we can get the properties of the object. this->expectMessageFromPage(JsonParsed( AllOf(AtJsonPtr("/id", 2), AtJsonPtr("/result/result", SizeIs(Gt(0)))))); - this->toPage_->sendMessage(fmt::format( - R"({{ + this->toPage_->sendMessage( + fmt::format( + R"({{ "id": 2, "method": "Runtime.getProperties", "params": {{"objectId": {}, "ownProperties": true}} }})", - folly::toJson(objectId))); + folly::toJson(objectId))); // Release the object group containing our object. this->expectMessageFromPage(JsonEq(R"({ @@ -873,13 +880,14 @@ TYPED_TEST(JsiIntegrationHermesTest, ReleaseRemoteObjectGroup) { // Getting properties for a released object results in an error. this->expectMessageFromPage( JsonParsed(AllOf(AtJsonPtr("/id", 4), AtJsonPtr("/error/code", -32000)))); - this->toPage_->sendMessage(fmt::format( - R"({{ + this->toPage_->sendMessage( + fmt::format( + R"({{ "id": 4, "method": "Runtime.getProperties", "params": {{"objectId": {}, "ownProperties": true}} }})", - folly::toJson(objectId))); + folly::toJson(objectId))); // Releasing an already released object group is a no-op. this->expectMessageFromPage(JsonEq(R"({ diff --git a/packages/react-native/ReactCommon/jsinspector-modern/tests/JsiIntegrationTest.h b/packages/react-native/ReactCommon/jsinspector-modern/tests/JsiIntegrationTest.h index d6a34b24f56..8f0b6e22665 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/tests/JsiIntegrationTest.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/tests/JsiIntegrationTest.h @@ -44,27 +44,29 @@ namespace facebook::react::jsinspector_modern { * the provided folly::Executor) and the corresponding jsi::Runtime. */ template -class JsiIntegrationPortableTestBase : public ::testing::Test, - private HostTargetDelegate { +class JsiIntegrationPortableTestBase : public ::testing::Test, private HostTargetDelegate { protected: Executor executor_; JsiIntegrationPortableTestBase(InspectorFlagOverrides overrides = {}) - : inspectorFlagsGuard_(overrides), engineAdapter_{executor_} {} + : inspectorFlagsGuard_(overrides), engineAdapter_{executor_} + { + } - void SetUp() override { + void SetUp() override + { // NOTE: Using SetUp() so we can call virtual methods like // setupRuntimeBeforeRegistration(). page_ = HostTarget::create(*this, inspectorExecutor_); instance_ = &page_->registerInstance(instanceTargetDelegate_); setupRuntimeBeforeRegistration(engineAdapter_->getRuntime()); - runtimeTarget_ = &instance_->registerRuntime( - engineAdapter_->getRuntimeTargetDelegate(), - engineAdapter_->getRuntimeExecutor()); + runtimeTarget_ = + &instance_->registerRuntime(engineAdapter_->getRuntimeTargetDelegate(), engineAdapter_->getRuntimeExecutor()); loadMainBundle(); } - ~JsiIntegrationPortableTestBase() override { + ~JsiIntegrationPortableTestBase() override + { toPage_.reset(); if (runtimeTarget_ != nullptr) { EXPECT_TRUE(instance_); @@ -88,10 +90,10 @@ class JsiIntegrationPortableTestBase : public ::testing::Test, * fixture classes to set up the runtime before registering it with the * CDP backend. */ - virtual void setupRuntimeBeforeRegistration(jsi::Runtime& /*runtime*/) {} + virtual void setupRuntimeBeforeRegistration(jsi::Runtime & /*runtime*/) {} - void connect( - std::source_location location = std::source_location::current()) { + void connect(std::source_location location = std::source_location::current()) + { ASSERT_FALSE(toPage_) << "Can only connect once in a JSI integration test."; toPage_ = page_->connect(remoteConnections_.make_unique()); @@ -101,17 +103,16 @@ class JsiIntegrationPortableTestBase : public ::testing::Test, location, fromPage(), onMessage(JsonParsed(AllOf( - AtJsonPtr("/method", "Runtime.consoleAPICalled"), - AtJsonPtr("/params/context", "main#InstanceAgent"))))) + AtJsonPtr("/method", "Runtime.consoleAPICalled"), AtJsonPtr("/params/context", "main#InstanceAgent"))))) .Times(AnyNumber()); // We'll always get an onDisconnect call when we tear // down the test. Expect it in order to satisfy the strict mock. - EXPECT_CALL_WITH_SOURCE_LOCATION( - location, *remoteConnections_[0], onDisconnect()); + EXPECT_CALL_WITH_SOURCE_LOCATION(location, *remoteConnections_[0], onDisconnect()); } - void reload() { + void reload() + { if (runtimeTarget_ != nullptr) { ASSERT_TRUE(instance_); instance_->unregisterRuntime(*runtimeTarget_); @@ -125,22 +126,21 @@ class JsiIntegrationPortableTestBase : public ::testing::Test, engineAdapter_.emplace(executor_); instance_ = &page_->registerInstance(instanceTargetDelegate_); setupRuntimeBeforeRegistration(engineAdapter_->getRuntime()); - runtimeTarget_ = &instance_->registerRuntime( - engineAdapter_->getRuntimeTargetDelegate(), - engineAdapter_->getRuntimeExecutor()); + runtimeTarget_ = + &instance_->registerRuntime(engineAdapter_->getRuntimeTargetDelegate(), engineAdapter_->getRuntimeExecutor()); loadMainBundle(); } - MockRemoteConnection& fromPage() { + MockRemoteConnection &fromPage() + { assert(toPage_); return *remoteConnections_[0]; } - VoidExecutor inspectorExecutor_ = [this](auto callback) { - executor_.add(callback); - }; + VoidExecutor inspectorExecutor_ = [this](auto callback) { executor_.add(callback); }; - jsi::Value eval(std::string_view code) { + jsi::Value eval(std::string_view code) + { return engineAdapter_->getRuntime().evaluateJavaScript( std::make_shared(std::string(code)), ""); } @@ -151,24 +151,25 @@ class JsiIntegrationPortableTestBase : public ::testing::Test, */ template std::shared_ptr> expectMessageFromPage( - Matcher&& matcher, - std::source_location location = std::source_location::current()) { + Matcher &&matcher, + std::source_location location = std::source_location::current()) + { using namespace ::testing; ScopedTrace scope(location.file_name(), location.line(), ""); - std::shared_ptr result = - std::make_shared>(std::nullopt); + std::shared_ptr result = std::make_shared>(std::nullopt); EXPECT_CALL_WITH_SOURCE_LOCATION(location, fromPage(), onMessage(matcher)) - .WillOnce( - ([result](auto message) { *result = folly::parseJson(message); })) + .WillOnce(([result](auto message) { *result = folly::parseJson(message); })) .RetiresOnSaturation(); return result; } - RuntimeTargetDelegate& dangerouslyGetRuntimeTargetDelegate() { + RuntimeTargetDelegate &dangerouslyGetRuntimeTargetDelegate() + { return engineAdapter_->getRuntimeTargetDelegate(); } - jsi::Runtime& dangerouslyGetRuntime() { + jsi::Runtime &dangerouslyGetRuntime() + { return engineAdapter_->getRuntime(); } @@ -176,32 +177,33 @@ class JsiIntegrationPortableTestBase : public ::testing::Test, public: SecondaryConnection( std::unique_ptr toPage, - JsiIntegrationPortableTestBase& test, + JsiIntegrationPortableTestBase &test, size_t remoteConnectionIndex) - : toPage_(std::move(toPage)), - remoteConnectionIndex_(remoteConnectionIndex), - test_(test) {} + : toPage_(std::move(toPage)), remoteConnectionIndex_(remoteConnectionIndex), test_(test) + { + } - ILocalConnection& toPage() { + ILocalConnection &toPage() + { return *toPage_; } - MockRemoteConnection& fromPage() { + MockRemoteConnection &fromPage() + { return *test_.remoteConnections_[remoteConnectionIndex_]; } private: std::unique_ptr toPage_; size_t remoteConnectionIndex_; - JsiIntegrationPortableTestBase& test_; + JsiIntegrationPortableTestBase &test_; }; - SecondaryConnection connectSecondary( - std::source_location location = std::source_location::current()) { + SecondaryConnection connectSecondary(std::source_location location = std::source_location::current()) + { auto toPage = page_->connect(remoteConnections_.make_unique()); - SecondaryConnection secondary{ - std::move(toPage), *this, remoteConnections_.objectsVended() - 1}; + SecondaryConnection secondary{std::move(toPage), *this, remoteConnections_.objectsVended() - 1}; using namespace ::testing; // Default to ignoring console messages originating inside the backend. @@ -209,29 +211,26 @@ class JsiIntegrationPortableTestBase : public ::testing::Test, location, secondary.fromPage(), onMessage(JsonParsed(AllOf( - AtJsonPtr("/method", "Runtime.consoleAPICalled"), - AtJsonPtr("/params/context", "main#InstanceAgent"))))) + AtJsonPtr("/method", "Runtime.consoleAPICalled"), AtJsonPtr("/params/context", "main#InstanceAgent"))))) .Times(AnyNumber()); // We'll always get an onDisconnect call when we tear // down the test. Expect it in order to satisfy the strict mock. - EXPECT_CALL_WITH_SOURCE_LOCATION( - location, secondary.fromPage(), onDisconnect()); + EXPECT_CALL_WITH_SOURCE_LOCATION(location, secondary.fromPage(), onDisconnect()); return secondary; } std::shared_ptr page_; - InstanceTarget* instance_{}; - RuntimeTarget* runtimeTarget_{}; + InstanceTarget *instance_{}; + RuntimeTarget *runtimeTarget_{}; InspectorFlagOverridesGuard inspectorFlagsGuard_; MockInstanceTargetDelegate instanceTargetDelegate_; std::optional engineAdapter_; private: - UniquePtrFactory<::testing::StrictMock> - remoteConnections_; + UniquePtrFactory<::testing::StrictMock> remoteConnections_; protected: // NOTE: Needs to be destroyed before page_. @@ -240,17 +239,18 @@ class JsiIntegrationPortableTestBase : public ::testing::Test, private: // HostTargetDelegate methods - HostTargetMetadata getMetadata() override { + HostTargetMetadata getMetadata() override + { return {.integrationName = "JsiIntegrationTest"}; } - void onReload(const PageReloadRequest& request) override { + void onReload(const PageReloadRequest &request) override + { (void)request; reload(); } - void onSetPausedInDebuggerMessage( - const OverlaySetPausedInDebuggerMessageRequest& /*request*/) override {} + void onSetPausedInDebuggerMessage(const OverlaySetPausedInDebuggerMessageRequest & /*request*/) override {} }; } // namespace facebook::react::jsinspector_modern diff --git a/packages/react-native/ReactCommon/jsinspector-modern/tests/NetworkReporterTest.cpp b/packages/react-native/ReactCommon/jsinspector-modern/tests/NetworkReporterTest.cpp index dea8c2e30de..21ba36af0bd 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/tests/NetworkReporterTest.cpp +++ b/packages/react-native/ReactCommon/jsinspector-modern/tests/NetworkReporterTest.cpp @@ -450,15 +450,16 @@ TEST_P(NetworkReporterTest, testCompleteNetworkFlow) { "base64Encoded": false } })")); - this->toPage_->sendMessage(fmt::format( - R"({{ + this->toPage_->sendMessage( + fmt::format( + R"({{ "id": 2, "method": "Network.getResponseBody", "params": {{ "requestId": {0} }} }})", - folly::toJson(requestId))); + folly::toJson(requestId))); this->expectMessageFromPage(JsonEq(R"({ "id": 3, @@ -494,15 +495,16 @@ TEST_P(NetworkReporterTest, testGetResponseBodyWithBase64) { "base64Encoded": true } })")); - this->toPage_->sendMessage(fmt::format( - R"({{ + this->toPage_->sendMessage( + fmt::format( + R"({{ "id": 2, "method": "Network.getResponseBody", "params": {{ "requestId": {0} }} }})", - folly::toJson(requestId))); + folly::toJson(requestId))); this->expectMessageFromPage(JsonEq(R"({ "id": 3, diff --git a/packages/react-native/ReactCommon/jsinspector-modern/tests/ReactInstanceIntegrationTest.h b/packages/react-native/ReactCommon/jsinspector-modern/tests/ReactInstanceIntegrationTest.h index 3d53e5e5143..fdd8226224d 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/tests/ReactInstanceIntegrationTest.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/tests/ReactInstanceIntegrationTest.h @@ -27,29 +27,27 @@ enum ReactInstanceIntegrationTestMode { FUSEBOX, }; -class ReactInstanceIntegrationTest - : public Test, - public ::testing::WithParamInterface { +class ReactInstanceIntegrationTest : public Test, + public ::testing::WithParamInterface { protected: ReactInstanceIntegrationTest(); void SetUp() override; void TearDown() override; - jsi::Value run(const std::string& script); + jsi::Value run(const std::string &script); bool verbose(bool isVerbose); - void send( - const std::string& method, - const folly::dynamic& params = folly::dynamic::object()); - void sendJSONString(const std::string& message); + void send(const std::string &method, const folly::dynamic ¶ms = folly::dynamic::object()); + void sendJSONString(const std::string &message); - jsi::Runtime* runtime; + jsi::Runtime *runtime; std::unique_ptr instance; std::shared_ptr messageQueueThread; std::shared_ptr errorHandler; - NiceMock& getRemoteConnection() { + NiceMock &getRemoteConnection() + { EXPECT_EQ(mockRemoteConnections_.objectsVended(), 1); auto rawPtr = mockRemoteConnections_[0]; assert(rawPtr); diff --git a/packages/react-native/ReactCommon/jsinspector-modern/tests/ReactNativeMocks.h b/packages/react-native/ReactCommon/jsinspector-modern/tests/ReactNativeMocks.h index 362a4d991e2..2798a71a4ff 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/tests/ReactNativeMocks.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/tests/ReactNativeMocks.h @@ -26,10 +26,10 @@ class MockTimerRegistry : public react::PlatformTimerRegistry { class MockMessageQueueThread : public react::MessageQueueThread { public: - void runOnQueue(std::function&& func) override; + void runOnQueue(std::function &&func) override; // Unused - void runOnQueueSync(std::function&& callback) override; + void runOnQueueSync(std::function &&callback) override; // Unused void quitSynchronous() override; @@ -48,9 +48,10 @@ class MockMessageQueueThread : public react::MessageQueueThread { class ErrorUtils : public jsi::HostObject { public: - jsi::Value get(jsi::Runtime& rt, const jsi::PropNameID& name) override; + jsi::Value get(jsi::Runtime &rt, const jsi::PropNameID &name) override; - void reportFatalError(jsi::JSError&& error) { + void reportFatalError(jsi::JSError &&error) + { errors_.push_back(std::move(error)); } diff --git a/packages/react-native/ReactCommon/jsinspector-modern/tests/UniquePtrFactory.h b/packages/react-native/ReactCommon/jsinspector-modern/tests/UniquePtrFactory.h index 62edd59d356..d89c8f4295f 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/tests/UniquePtrFactory.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/tests/UniquePtrFactory.h @@ -30,19 +30,17 @@ namespace facebook { */ template class UniquePtrFactory { - static_assert( - std::has_virtual_destructor_v, - "T must have a virtual destructor"); + static_assert(std::has_virtual_destructor_v, "T must have a virtual destructor"); public: /** * Creates a new object of type T, and returns a unique_ptr wrapping it. */ template - std::unique_ptr make_unique(Args&&... args) { + std::unique_ptr make_unique(Args &&...args) + { size_t index = objectPtrs_.size(); - auto ptr = - std::make_unique(*this, index, std::forward(args)...); + auto ptr = std::make_unique(*this, index, std::forward(args)...); objectPtrs_.push_back(ptr.get()); return ptr; } @@ -52,17 +50,17 @@ class UniquePtrFactory { * function may only be used while the factory is alive. */ template - std::function(Args&&...)> lazily_make_unique() { - return [this](Args&&... args) { - return make_unique(std::forward(args)...); - }; + std::function(Args &&...)> lazily_make_unique() + { + return [this](Args &&...args) { return make_unique(std::forward(args)...); }; } /** * Returns a pointer to the `index`th object created by this factory, * or nullptr if the object has been destroyed (or not created yet). */ - T* operator[](size_t index) { + T *operator[](size_t index) + { return index >= objectPtrs_.size() ? nullptr : objectPtrs_[index]; } @@ -70,7 +68,8 @@ class UniquePtrFactory { * Returns a pointer to the `index`th object created by this factory, * or nullptr if the object has been destroyed (or not created yet). */ - const T* operator[](size_t index) const { + const T *operator[](size_t index) const + { return index >= objectPtrs_.size() ? nullptr : objectPtrs_[index]; } @@ -78,7 +77,8 @@ class UniquePtrFactory { * Returns the total number of objects created by this factory, including * those that have already been destroyed. */ - size_t objectsVended() const { + size_t objectsVended() const + { return objectPtrs_.size(); } @@ -92,19 +92,20 @@ class UniquePtrFactory { class Facade : public T { public: template - Facade(UniquePtrFactory& container, size_t index, Args&&... args) - : T(std::forward(args)...), - container_(container), - index_(index) {} + Facade(UniquePtrFactory &container, size_t index, Args &&...args) + : T(std::forward(args)...), container_(container), index_(index) + { + } - virtual ~Facade() override { + virtual ~Facade() override + { container_.objectPtrs_[index_] = nullptr; } - UniquePtrFactory& container_; + UniquePtrFactory &container_; size_t index_; }; - std::vector objectPtrs_; + std::vector objectPtrs_; }; } // namespace facebook diff --git a/packages/react-native/ReactCommon/jsinspector-modern/tests/engines/JsiIntegrationTestGenericEngineAdapter.h b/packages/react-native/ReactCommon/jsinspector-modern/tests/engines/JsiIntegrationTestGenericEngineAdapter.h index 836d09530bf..0783eae801a 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/tests/engines/JsiIntegrationTestGenericEngineAdapter.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/tests/engines/JsiIntegrationTestGenericEngineAdapter.h @@ -26,19 +26,19 @@ namespace facebook::react::jsinspector_modern { */ class JsiIntegrationTestGenericEngineAdapter { public: - explicit JsiIntegrationTestGenericEngineAdapter(folly::Executor& jsExecutor); + explicit JsiIntegrationTestGenericEngineAdapter(folly::Executor &jsExecutor); static InspectorFlagOverrides getInspectorFlagOverrides() noexcept; - RuntimeTargetDelegate& getRuntimeTargetDelegate(); + RuntimeTargetDelegate &getRuntimeTargetDelegate(); - jsi::Runtime& getRuntime() const noexcept; + jsi::Runtime &getRuntime() const noexcept; RuntimeExecutor getRuntimeExecutor() const noexcept; private: std::unique_ptr runtime_; - folly::Executor& jsExecutor_; + folly::Executor &jsExecutor_; jsinspector_modern::FallbackRuntimeTargetDelegate runtimeTargetDelegate_; }; diff --git a/packages/react-native/ReactCommon/jsinspector-modern/tests/engines/JsiIntegrationTestHermesEngineAdapter.h b/packages/react-native/ReactCommon/jsinspector-modern/tests/engines/JsiIntegrationTestHermesEngineAdapter.h index 8bf3b2dcb86..a1b1eeb4923 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/tests/engines/JsiIntegrationTestHermesEngineAdapter.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/tests/engines/JsiIntegrationTestHermesEngineAdapter.h @@ -26,19 +26,19 @@ namespace facebook::react::jsinspector_modern { */ class JsiIntegrationTestHermesEngineAdapter { public: - explicit JsiIntegrationTestHermesEngineAdapter(folly::Executor& jsExecutor); + explicit JsiIntegrationTestHermesEngineAdapter(folly::Executor &jsExecutor); static InspectorFlagOverrides getInspectorFlagOverrides() noexcept; - RuntimeTargetDelegate& getRuntimeTargetDelegate(); + RuntimeTargetDelegate &getRuntimeTargetDelegate(); - jsi::Runtime& getRuntime() const noexcept; + jsi::Runtime &getRuntime() const noexcept; RuntimeExecutor getRuntimeExecutor() const noexcept; private: std::shared_ptr runtime_; - folly::Executor& jsExecutor_; + folly::Executor &jsExecutor_; HermesRuntimeTargetDelegate runtimeTargetDelegate_; }; diff --git a/packages/react-native/ReactCommon/jsinspector-modern/tests/utils/InspectorFlagOverridesGuard.h b/packages/react-native/ReactCommon/jsinspector-modern/tests/utils/InspectorFlagOverridesGuard.h index d86201c15c7..84401fd1703 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/tests/utils/InspectorFlagOverridesGuard.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/tests/utils/InspectorFlagOverridesGuard.h @@ -30,13 +30,11 @@ struct InspectorFlagOverrides { */ class InspectorFlagOverridesGuard { public: - explicit InspectorFlagOverridesGuard(const InspectorFlagOverrides& overrides); - InspectorFlagOverridesGuard(const InspectorFlagOverridesGuard&) = delete; - InspectorFlagOverridesGuard(InspectorFlagOverridesGuard&&) = default; - InspectorFlagOverridesGuard& operator=(const InspectorFlagOverridesGuard&) = - delete; - InspectorFlagOverridesGuard& operator=(InspectorFlagOverridesGuard&&) = - default; + explicit InspectorFlagOverridesGuard(const InspectorFlagOverrides &overrides); + InspectorFlagOverridesGuard(const InspectorFlagOverridesGuard &) = delete; + InspectorFlagOverridesGuard(InspectorFlagOverridesGuard &&) = default; + InspectorFlagOverridesGuard &operator=(const InspectorFlagOverridesGuard &) = delete; + InspectorFlagOverridesGuard &operator=(InspectorFlagOverridesGuard &&) = default; ~InspectorFlagOverridesGuard(); }; diff --git a/packages/react-native/ReactCommon/jsinspector-modern/tracing/ConsoleTimeStamp.h b/packages/react-native/ReactCommon/jsinspector-modern/tracing/ConsoleTimeStamp.h index a57a27074aa..79f5575d851 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/tracing/ConsoleTimeStamp.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/tracing/ConsoleTimeStamp.h @@ -37,7 +37,8 @@ enum class ConsoleTimeStampColor { Error, }; -inline std::string consoleTimeStampColorToString(ConsoleTimeStampColor color) { +inline std::string consoleTimeStampColorToString(ConsoleTimeStampColor color) +{ switch (color) { case ConsoleTimeStampColor::Primary: return "primary"; @@ -66,8 +67,8 @@ inline std::string consoleTimeStampColorToString(ConsoleTimeStampColor color) { } }; -inline std::optional getConsoleTimeStampColorFromString( - const std::string& str) { +inline std::optional getConsoleTimeStampColorFromString(const std::string &str) +{ if (str == "primary") { return ConsoleTimeStampColor::Primary; } else if (str == "primary-light") { diff --git a/packages/react-native/ReactCommon/jsinspector-modern/tracing/EventLoopReporter.h b/packages/react-native/ReactCommon/jsinspector-modern/tracing/EventLoopReporter.h index 211fe139cba..62932fc0cc9 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/tracing/EventLoopReporter.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/tracing/EventLoopReporter.h @@ -22,10 +22,10 @@ struct EventLoopReporter { public: explicit EventLoopReporter(EventLoopPhase phase); - EventLoopReporter(const EventLoopReporter&) = delete; - EventLoopReporter(EventLoopReporter&&) = delete; - EventLoopReporter& operator=(const EventLoopReporter&) = delete; - EventLoopReporter& operator=(EventLoopReporter&&) = delete; + EventLoopReporter(const EventLoopReporter &) = delete; + EventLoopReporter(EventLoopReporter &&) = delete; + EventLoopReporter &operator=(const EventLoopReporter &) = delete; + EventLoopReporter &operator=(EventLoopReporter &&) = delete; ~EventLoopReporter(); diff --git a/packages/react-native/ReactCommon/jsinspector-modern/tracing/PerformanceTracer.cpp b/packages/react-native/ReactCommon/jsinspector-modern/tracing/PerformanceTracer.cpp index 8cd38188c34..a8cf4c26d4c 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/tracing/PerformanceTracer.cpp +++ b/packages/react-native/ReactCommon/jsinspector-modern/tracing/PerformanceTracer.cpp @@ -107,24 +107,26 @@ std::optional> PerformanceTracer::stopTracing() { // This could happen for non-bridgeless apps, where Performance interface is // not supported and no spec-compliant Event Loop implementation. - events.emplace_back(TraceEvent{ - .name = "TracingStartedInPage", - .cat = "disabled-by-default-devtools.timeline", - .ph = 'I', - .ts = currentTraceStartTime, - .pid = processId_, - .tid = getCurrentThreadId(), - .args = folly::dynamic::object("data", folly::dynamic::object()), - }); + events.emplace_back( + TraceEvent{ + .name = "TracingStartedInPage", + .cat = "disabled-by-default-devtools.timeline", + .ph = 'I', + .ts = currentTraceStartTime, + .pid = processId_, + .tid = getCurrentThreadId(), + .args = folly::dynamic::object("data", folly::dynamic::object()), + }); - events.emplace_back(TraceEvent{ - .name = "ReactNative-TracingStopped", - .cat = "disabled-by-default-devtools.timeline", - .ph = 'I', - .ts = currentTraceEndTime, - .pid = processId_, - .tid = getCurrentThreadId(), - }); + events.emplace_back( + TraceEvent{ + .name = "ReactNative-TracingStopped", + .cat = "disabled-by-default-devtools.timeline", + .ph = 'I', + .ts = currentTraceEndTime, + .pid = processId_, + .tid = getCurrentThreadId(), + }); currentTraceMaxDuration_ = std::nullopt; return events; @@ -143,12 +145,13 @@ void PerformanceTracer::reportMark( return; } - enqueueEvent(PerformanceTracerEventMark{ - .name = name, - .start = start, - .detail = std::move(detail), - .threadId = getCurrentThreadId(), - }); + enqueueEvent( + PerformanceTracerEventMark{ + .name = name, + .start = start, + .detail = std::move(detail), + .threadId = getCurrentThreadId(), + }); } void PerformanceTracer::reportMeasure( @@ -165,13 +168,14 @@ void PerformanceTracer::reportMeasure( return; } - enqueueEvent(PerformanceTracerEventMeasure{ - .name = name, - .start = start, - .duration = duration, - .detail = std::move(detail), - .threadId = getCurrentThreadId(), - }); + enqueueEvent( + PerformanceTracerEventMeasure{ + .name = name, + .start = start, + .duration = duration, + .detail = std::move(detail), + .threadId = getCurrentThreadId(), + }); } void PerformanceTracer::reportTimeStamp( @@ -190,15 +194,16 @@ void PerformanceTracer::reportTimeStamp( return; } - enqueueEvent(PerformanceTracerEventTimeStamp{ - .name = name, - .start = std::move(start), - .end = std::move(end), - .trackName = std::move(trackName), - .trackGroup = std::move(trackGroup), - .color = std::move(color), - .threadId = getCurrentThreadId(), - }); + enqueueEvent( + PerformanceTracerEventTimeStamp{ + .name = name, + .start = std::move(start), + .end = std::move(end), + .trackName = std::move(trackName), + .trackGroup = std::move(trackGroup), + .color = std::move(color), + .threadId = getCurrentThreadId(), + }); } void PerformanceTracer::reportEventLoopTask( @@ -213,11 +218,12 @@ void PerformanceTracer::reportEventLoopTask( return; } - enqueueEvent(PerformanceTracerEventEventLoopTask{ - .start = start, - .end = end, - .threadId = getCurrentThreadId(), - }); + enqueueEvent( + PerformanceTracerEventEventLoopTask{ + .start = start, + .end = end, + .threadId = getCurrentThreadId(), + }); } void PerformanceTracer::reportEventLoopMicrotasks( @@ -232,11 +238,12 @@ void PerformanceTracer::reportEventLoopMicrotasks( return; } - enqueueEvent(PerformanceTracerEventEventLoopMicrotask{ - .start = start, - .end = end, - .threadId = getCurrentThreadId(), - }); + enqueueEvent( + PerformanceTracerEventEventLoopMicrotask{ + .start = start, + .end = end, + .threadId = getCurrentThreadId(), + }); } void PerformanceTracer::reportResourceSendRequest( @@ -257,14 +264,15 @@ void PerformanceTracer::reportResourceSendRequest( auto resourceType = jsinspector_modern::cdp::network::resourceTypeFromMimeType( jsinspector_modern::mimeTypeFromHeaders(headers)); - enqueueEvent(PerformanceTracerResourceSendRequest{ - .requestId = devtoolsRequestId, - .url = url, - .start = start, - .requestMethod = requestMethod, - .resourceType = resourceType, - .threadId = getCurrentThreadId(), - }); + enqueueEvent( + PerformanceTracerResourceSendRequest{ + .requestId = devtoolsRequestId, + .url = url, + .start = start, + .requestMethod = requestMethod, + .resourceType = resourceType, + .threadId = getCurrentThreadId(), + }); } void PerformanceTracer::reportResourceReceiveResponse( @@ -283,17 +291,18 @@ void PerformanceTracer::reportResourceReceiveResponse( return; } - enqueueEvent(PerformanceTracerResourceReceiveResponse{ - .requestId = devtoolsRequestId, - .start = start, - .encodedDataLength = encodedDataLength, - .headers = headers, - .mimeType = jsinspector_modern::mimeTypeFromHeaders(headers), - .protocol = "h2", - .statusCode = statusCode, - .timing = std::move(timingData), - .threadId = getCurrentThreadId(), - }); + enqueueEvent( + PerformanceTracerResourceReceiveResponse{ + .requestId = devtoolsRequestId, + .start = start, + .encodedDataLength = encodedDataLength, + .headers = headers, + .mimeType = jsinspector_modern::mimeTypeFromHeaders(headers), + .protocol = "h2", + .statusCode = statusCode, + .timing = std::move(timingData), + .threadId = getCurrentThreadId(), + }); } void PerformanceTracer::reportResourceFinish( @@ -310,13 +319,14 @@ void PerformanceTracer::reportResourceFinish( return; } - enqueueEvent(PerformanceTracerResourceFinish{ - .requestId = devtoolsRequestId, - .start = start, - .encodedDataLength = encodedDataLength, - .decodedBodyLength = decodedBodyLength, - .threadId = getCurrentThreadId(), - }); + enqueueEvent( + PerformanceTracerResourceFinish{ + .requestId = devtoolsRequestId, + .start = start, + .encodedDataLength = encodedDataLength, + .decodedBodyLength = decodedBodyLength, + .threadId = getCurrentThreadId(), + }); } /* static */ TraceEvent PerformanceTracer::constructRuntimeProfileTraceEvent( @@ -481,26 +491,28 @@ void PerformanceTracer::enqueueTraceEventsFromPerformanceTracerEvent( std::visit( overloaded{ [&](PerformanceTracerEventEventLoopTask&& event) { - events.emplace_back(TraceEvent{ - .name = "RunTask", - .cat = "disabled-by-default-devtools.timeline", - .ph = 'X', - .ts = event.start, - .pid = processId_, - .tid = event.threadId, - .dur = event.end - event.start, - }); + events.emplace_back( + TraceEvent{ + .name = "RunTask", + .cat = "disabled-by-default-devtools.timeline", + .ph = 'X', + .ts = event.start, + .pid = processId_, + .tid = event.threadId, + .dur = event.end - event.start, + }); }, [&](PerformanceTracerEventEventLoopMicrotask&& event) { - events.emplace_back(TraceEvent{ - .name = "RunMicrotasks", - .cat = "v8.execute", - .ph = 'X', - .ts = event.start, - .pid = processId_, - .tid = event.threadId, - .dur = event.end - event.start, - }); + events.emplace_back( + TraceEvent{ + .name = "RunMicrotasks", + .cat = "v8.execute", + .ph = 'X', + .ts = event.start, + .pid = processId_, + .tid = event.threadId, + .dur = event.end - event.start, + }); }, [&](PerformanceTracerEventMark&& event) { folly::dynamic eventArgs = folly::dynamic::object(); @@ -511,15 +523,16 @@ void PerformanceTracer::enqueueTraceEventsFromPerformanceTracerEvent( "detail", folly::toJson(event.detail))); } - events.emplace_back(TraceEvent{ - .name = std::move(event.name), - .cat = "blink.user_timing", - .ph = 'I', - .ts = event.start, - .pid = processId_, - .tid = event.threadId, - .args = std::move(eventArgs), - }); + events.emplace_back( + TraceEvent{ + .name = std::move(event.name), + .cat = "blink.user_timing", + .ph = 'I', + .ts = event.start, + .pid = processId_, + .tid = event.threadId, + .args = std::move(eventArgs), + }); }, [&](PerformanceTracerEventMeasure&& event) { folly::dynamic beginEventArgs = folly::dynamic::object(); @@ -530,25 +543,27 @@ void PerformanceTracer::enqueueTraceEventsFromPerformanceTracerEvent( auto eventId = ++performanceMeasureCount_; - events.emplace_back(TraceEvent{ - .id = eventId, - .name = event.name, - .cat = "blink.user_timing", - .ph = 'b', - .ts = event.start, - .pid = processId_, - .tid = event.threadId, - .args = std::move(beginEventArgs), - }); - events.emplace_back(TraceEvent{ - .id = eventId, - .name = std::move(event.name), - .cat = "blink.user_timing", - .ph = 'e', - .ts = event.start + event.duration, - .pid = processId_, - .tid = event.threadId, - }); + events.emplace_back( + TraceEvent{ + .id = eventId, + .name = event.name, + .cat = "blink.user_timing", + .ph = 'b', + .ts = event.start, + .pid = processId_, + .tid = event.threadId, + .args = std::move(beginEventArgs), + }); + events.emplace_back( + TraceEvent{ + .id = eventId, + .name = std::move(event.name), + .cat = "blink.user_timing", + .ph = 'e', + .ts = event.start + event.duration, + .pid = processId_, + .tid = event.threadId, + }); }, [&](PerformanceTracerEventTimeStamp&& event) { folly::dynamic data = folly::dynamic::object("name", event.name)( @@ -580,20 +595,21 @@ void PerformanceTracer::enqueueTraceEventsFromPerformanceTracerEvent( // React is using 0.003 for Scheduler sub-tracks. auto timestamp = highResTimeStampToTracingClockTimeStamp( HighResTimeStamp::fromDOMHighResTimeStamp(0.004)); - events.emplace_back(TraceEvent{ - .name = "TimeStamp", - .cat = "devtools.timeline", - .ph = 'I', - .ts = event.createdAt, - .pid = processId_, - .tid = event.threadId, - .args = folly::dynamic::object( - "data", - folly::dynamic::object( - "name", "ReactNative-ComponentsTrack")( - "start", timestamp)("end", timestamp)( - "track", *event.trackName)), - }); + events.emplace_back( + TraceEvent{ + .name = "TimeStamp", + .cat = "devtools.timeline", + .ph = 'I', + .ts = event.createdAt, + .pid = processId_, + .tid = event.threadId, + .args = folly::dynamic::object( + "data", + folly::dynamic::object( + "name", "ReactNative-ComponentsTrack")( + "start", timestamp)("end", timestamp)( + "track", *event.trackName)), + }); } } @@ -607,15 +623,16 @@ void PerformanceTracer::enqueueTraceEventsFromPerformanceTracerEvent( data["color"] = consoleTimeStampColorToString(*event.color); } - events.emplace_back(TraceEvent{ - .name = "TimeStamp", - .cat = "devtools.timeline", - .ph = 'I', - .ts = event.createdAt, - .pid = processId_, - .tid = event.threadId, - .args = folly::dynamic::object("data", std::move(data)), - }); + events.emplace_back( + TraceEvent{ + .name = "TimeStamp", + .cat = "devtools.timeline", + .ph = 'I', + .ts = event.createdAt, + .pid = processId_, + .tid = event.threadId, + .args = folly::dynamic::object("data", std::move(data)), + }); }, [&](PerformanceTracerResourceSendRequest&& event) { folly::dynamic data = @@ -626,16 +643,17 @@ void PerformanceTracer::enqueueTraceEventsFromPerformanceTracerEvent( "resourceType", std::move(event.resourceType))( "url", std::move(event.url)); - events.emplace_back(TraceEvent{ - .name = "ResourceSendRequest", - .cat = "devtools.timeline", - .ph = 'I', - .ts = event.start, - .pid = processId_, - .s = 't', - .tid = event.threadId, - .args = folly::dynamic::object("data", std::move(data)), - }); + events.emplace_back( + TraceEvent{ + .name = "ResourceSendRequest", + .cat = "devtools.timeline", + .ph = 'I', + .ts = event.start, + .pid = processId_, + .s = 't', + .tid = event.threadId, + .args = folly::dynamic::object("data", std::move(data)), + }); }, [&](PerformanceTracerResourceReceiveResponse&& event) { folly::dynamic headersEntries = folly::dynamic::array; @@ -651,16 +669,17 @@ void PerformanceTracer::enqueueTraceEventsFromPerformanceTracerEvent( "statusCode", event.statusCode)( "timing", std::move(event.timing)); - events.emplace_back(TraceEvent{ - .name = "ResourceReceiveResponse", - .cat = "devtools.timeline", - .ph = 'I', - .ts = event.start, - .pid = processId_, - .s = 't', - .tid = event.threadId, - .args = folly::dynamic::object("data", std::move(data)), - }); + events.emplace_back( + TraceEvent{ + .name = "ResourceReceiveResponse", + .cat = "devtools.timeline", + .ph = 'I', + .ts = event.start, + .pid = processId_, + .s = 't', + .tid = event.threadId, + .args = folly::dynamic::object("data", std::move(data)), + }); }, [&](PerformanceTracerResourceFinish&& event) { folly::dynamic data = folly::dynamic::object( @@ -668,16 +687,17 @@ void PerformanceTracer::enqueueTraceEventsFromPerformanceTracerEvent( "encodedDataLength", event.encodedDataLength)( "requestId", std::move(event.requestId)); - events.emplace_back(TraceEvent{ - .name = "ResourceFinish", - .cat = "devtools.timeline", - .ph = 'I', - .ts = event.start, - .pid = processId_, - .s = 't', - .tid = event.threadId, - .args = folly::dynamic::object("data", std::move(data)), - }); + events.emplace_back( + TraceEvent{ + .name = "ResourceFinish", + .cat = "devtools.timeline", + .ph = 'I', + .ts = event.start, + .pid = processId_, + .s = 't', + .tid = event.threadId, + .args = folly::dynamic::object("data", std::move(data)), + }); }, }, std::move(event)); diff --git a/packages/react-native/ReactCommon/jsinspector-modern/tracing/PerformanceTracer.h b/packages/react-native/ReactCommon/jsinspector-modern/tracing/PerformanceTracer.h index e93e985525e..65b44194a3f 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/tracing/PerformanceTracer.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/tracing/PerformanceTracer.h @@ -33,7 +33,7 @@ using Headers = std::map; */ class PerformanceTracer { public: - static PerformanceTracer& getInstance(); + static PerformanceTracer &getInstance(); /** * Starts a tracing session. Returns `false` if already tracing. @@ -57,7 +57,8 @@ class PerformanceTracer { * avoid doing expensive work (like formatting strings) if tracing is not * enabled. */ - inline bool isTracing() const { + inline bool isTracing() const + { return tracingAtomic_; } @@ -67,10 +68,7 @@ class PerformanceTracer { * * See https://w3c.github.io/user-timing/#mark-method. */ - void reportMark( - const std::string& name, - HighResTimeStamp start, - folly::dynamic&& detail = nullptr); + void reportMark(const std::string &name, HighResTimeStamp start, folly::dynamic &&detail = nullptr); /** * Record a `Performance.measure()` event - a labelled duration. If not @@ -79,10 +77,10 @@ class PerformanceTracer { * See https://w3c.github.io/user-timing/#measure-method. */ void reportMeasure( - const std::string& name, + const std::string &name, HighResTimeStamp start, HighResDuration duration, - folly::dynamic&& detail = nullptr); + folly::dynamic &&detail = nullptr); /** * Record a "TimeStamp" Trace Event - a labelled entry on Performance @@ -92,7 +90,7 @@ class PerformanceTracer { https://developer.chrome.com/docs/devtools/performance/extension#inject_your_data_with_consoletimestamp */ void reportTimeStamp( - const std::string& name, + const std::string &name, std::optional start = std::nullopt, std::optional end = std::nullopt, std::optional trackName = std::nullopt, @@ -118,9 +116,7 @@ class PerformanceTracer { * * If not currently tracing, this is a no-op. */ - void reportResourceWillSendRequest( - const std::string& devtoolsRequestId, - HighResTimeStamp start); + void reportResourceWillSendRequest(const std::string &devtoolsRequestId, HighResTimeStamp start); /** * Record a "ResourceSendRequest" event. Paired with other "Resource*" @@ -130,11 +126,11 @@ class PerformanceTracer { * If not currently tracing, this is a no-op. */ void reportResourceSendRequest( - const std::string& devtoolsRequestId, + const std::string &devtoolsRequestId, HighResTimeStamp start, - const std::string& url, - const std::string& requestMethod, - const Headers& headers); + const std::string &url, + const std::string &requestMethod, + const Headers &headers); /** * Record a "ResourceReceiveResponse" event. Paired with other "Resource*" @@ -144,10 +140,10 @@ class PerformanceTracer { * If not currently tracing, this is a no-op. */ void reportResourceReceiveResponse( - const std::string& devtoolsRequestId, + const std::string &devtoolsRequestId, HighResTimeStamp start, int statusCode, - const Headers& headers, + const Headers &headers, int encodedDataLength, folly::dynamic timingData); @@ -158,7 +154,7 @@ class PerformanceTracer { * If not currently tracing, this is a no-op. */ void reportResourceFinish( - const std::string& devtoolsRequestId, + const std::string &devtoolsRequestId, HighResTimeStamp start, int encodedDataLength, int decodedBodyLength); @@ -184,12 +180,12 @@ class PerformanceTracer { ProcessId processId, ProcessId threadId, HighResTimeStamp chunkTimestamp, - TraceEventProfileChunk&& traceEventProfileChunk); + TraceEventProfileChunk &&traceEventProfileChunk); private: PerformanceTracer(); - PerformanceTracer(const PerformanceTracer&) = delete; - PerformanceTracer& operator=(const PerformanceTracer&) = delete; + PerformanceTracer(const PerformanceTracer &) = delete; + PerformanceTracer &operator=(const PerformanceTracer &) = delete; ~PerformanceTracer() = default; #pragma mark - Internal trace event types @@ -306,8 +302,8 @@ class PerformanceTracer { // These fields are only used when setting a max duration on the trace. std::vector altBuffer_; - std::vector* currentBuffer_ = &buffer_; - std::vector* previousBuffer_{}; + std::vector *currentBuffer_ = &buffer_; + std::vector *previousBuffer_{}; HighResTimeStamp currentBufferStartTime_; // A flag that is used to ensure we only emit one auxiliary entry for the @@ -320,25 +316,19 @@ class PerformanceTracer { */ std::mutex mutex_; - bool startTracingImpl( - std::optional maxDuration = std::nullopt); + bool startTracingImpl(std::optional maxDuration = std::nullopt); - std::vector collectEventsAndClearBuffers( - HighResTimeStamp currentTraceEndTime); + std::vector collectEventsAndClearBuffers(HighResTimeStamp currentTraceEndTime); void collectEventsAndClearBuffer( - std::vector& events, - std::vector& buffer, + std::vector &events, + std::vector &buffer, HighResTimeStamp currentTraceEndTime); - bool isInTracingWindow( - HighResTimeStamp now, - HighResTimeStamp timeStampToCheck) const; - void enqueueEvent(PerformanceTracerEvent&& event); + bool isInTracingWindow(HighResTimeStamp now, HighResTimeStamp timeStampToCheck) const; + void enqueueEvent(PerformanceTracerEvent &&event); - HighResTimeStamp getCreatedAt(const PerformanceTracerEvent& event) const; + HighResTimeStamp getCreatedAt(const PerformanceTracerEvent &event) const; - void enqueueTraceEventsFromPerformanceTracerEvent( - std::vector& events, - PerformanceTracerEvent&& event); + void enqueueTraceEventsFromPerformanceTracerEvent(std::vector &events, PerformanceTracerEvent &&event); }; } // namespace facebook::react::jsinspector_modern::tracing diff --git a/packages/react-native/ReactCommon/jsinspector-modern/tracing/ProfileTreeNode.h b/packages/react-native/ReactCommon/jsinspector-modern/tracing/ProfileTreeNode.h index e529a658418..78736b065a3 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/tracing/ProfileTreeNode.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/tracing/ProfileTreeNode.h @@ -34,31 +34,35 @@ class ProfileTreeNode { CodeType codeType, RuntimeSamplingProfile::SampleCallStackFrame callFrame, uint32_t parentId = NO_PARENT) - : id_(id), - codeType_(codeType), - parentId_(parentId), - callFrame_(std::move(callFrame)) {} + : id_(id), codeType_(codeType), parentId_(parentId), callFrame_(std::move(callFrame)) + { + } - uint32_t getId() const { + uint32_t getId() const + { return id_; } - CodeType getCodeType() const { + CodeType getCodeType() const + { return codeType_; } - inline bool hasParent() const { + inline bool hasParent() const + { return parentId_ != NO_PARENT; } - uint32_t getParentId() const { + uint32_t getParentId() const + { return parentId_; } /** * \return call frame information that is represented by this node. */ - const RuntimeSamplingProfile::SampleCallStackFrame& getCallFrame() const { + const RuntimeSamplingProfile::SampleCallStackFrame &getCallFrame() const + { return callFrame_; } @@ -66,12 +70,12 @@ class ProfileTreeNode { * \return a pointer if the node already contains a child with the same * codeType and callFrame, nullptr otherwise. */ - ProfileTreeNode* getIfAlreadyExists( + ProfileTreeNode *getIfAlreadyExists( CodeType childCodeType, - const RuntimeSamplingProfile::SampleCallStackFrame& childCallFrame) { - for (auto& existingChild : children_) { - if (existingChild.getCodeType() == childCodeType && - existingChild.getCallFrame() == childCallFrame) { + const RuntimeSamplingProfile::SampleCallStackFrame &childCallFrame) + { + for (auto &existingChild : children_) { + if (existingChild.getCodeType() == childCodeType && existingChild.getCallFrame() == childCallFrame) { return &existingChild; } } @@ -83,12 +87,10 @@ class ProfileTreeNode { * Creates a ProfileTreeNode and links it as a child to this node. * \return a pointer to the child node. */ - ProfileTreeNode* addChild( - uint32_t childId, - CodeType childCodeType, - RuntimeSamplingProfile::SampleCallStackFrame childCallFrame) { - return &children_.emplace_back( - childId, childCodeType, std::move(childCallFrame), id_); + ProfileTreeNode * + addChild(uint32_t childId, CodeType childCodeType, RuntimeSamplingProfile::SampleCallStackFrame childCallFrame) + { + return &children_.emplace_back(childId, childCodeType, std::move(childCallFrame), id_); } private: diff --git a/packages/react-native/ReactCommon/jsinspector-modern/tracing/RuntimeSamplingProfile.h b/packages/react-native/ReactCommon/jsinspector-modern/tracing/RuntimeSamplingProfile.h index 3016aa3eda5..f5c06f50857 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/tracing/RuntimeSamplingProfile.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/tracing/RuntimeSamplingProfile.h @@ -41,8 +41,7 @@ struct RuntimeSamplingProfile { GarbageCollector, /// Garbage collection frame. }; - inline bool operator==(const SampleCallStackFrame& rhs) const noexcept = - default; + inline bool operator==(const SampleCallStackFrame &rhs) const noexcept = default; /// type of the call stack frame Kind kind; @@ -68,21 +67,18 @@ struct RuntimeSamplingProfile { /// time. struct Sample { public: - Sample( - uint64_t timestamp, - ThreadId threadId, - std::vector callStack) - : timestamp(timestamp), - threadId(threadId), - callStack(std::move(callStack)) {} + Sample(uint64_t timestamp, ThreadId threadId, std::vector callStack) + : timestamp(timestamp), threadId(threadId), callStack(std::move(callStack)) + { + } // Movable. - Sample& operator=(Sample&&) = default; - Sample(Sample&&) = default; + Sample &operator=(Sample &&) = default; + Sample(Sample &&) = default; // Not copyable. - Sample(const Sample&) = delete; - Sample& operator=(const Sample&) = delete; + Sample(const Sample &) = delete; + Sample &operator=(const Sample &) = delete; ~Sample() = default; @@ -103,15 +99,17 @@ struct RuntimeSamplingProfile { : runtimeName(std::move(runtimeName)), processId(processId), samples(std::move(samples)), - rawRuntimeProfile(std::move(rawRuntimeProfile)) {} + rawRuntimeProfile(std::move(rawRuntimeProfile)) + { + } // Movable. - RuntimeSamplingProfile& operator=(RuntimeSamplingProfile&&) = default; - RuntimeSamplingProfile(RuntimeSamplingProfile&&) = default; + RuntimeSamplingProfile &operator=(RuntimeSamplingProfile &&) = default; + RuntimeSamplingProfile(RuntimeSamplingProfile &&) = default; // Not copyable. - RuntimeSamplingProfile(const RuntimeSamplingProfile&) = delete; - RuntimeSamplingProfile& operator=(const RuntimeSamplingProfile&) = delete; + RuntimeSamplingProfile(const RuntimeSamplingProfile &) = delete; + RuntimeSamplingProfile &operator=(const RuntimeSamplingProfile &) = delete; ~RuntimeSamplingProfile() = default; diff --git a/packages/react-native/ReactCommon/jsinspector-modern/tracing/RuntimeSamplingProfileTraceEventSerializer.h b/packages/react-native/ReactCommon/jsinspector-modern/tracing/RuntimeSamplingProfileTraceEventSerializer.h index 0453e1cd289..5ce2bf65518 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/tracing/RuntimeSamplingProfileTraceEventSerializer.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/tracing/RuntimeSamplingProfileTraceEventSerializer.h @@ -29,7 +29,8 @@ constexpr uint16_t MAX_UNIQUE_NODES_PER_CHUNK = 50; struct IdGenerator { public: - uint32_t getNext() { + uint32_t getNext() + { return ++counter_; } @@ -57,21 +58,19 @@ class RuntimeSamplingProfileTraceEventSerializer { * that can be sent in a single ProfileChunk trace event. */ static void serializeAndDispatch( - RuntimeSamplingProfile&& profile, - IdGenerator& profileIdGenerator, + RuntimeSamplingProfile &&profile, + IdGenerator &profileIdGenerator, HighResTimeStamp tracingStartTime, - const std::function& - dispatchCallback, + const std::function &dispatchCallback, uint16_t traceEventChunkSize, uint16_t profileChunkSize = PROFILE_CHUNK_SIZE, uint16_t maxUniqueNodesPerChunk = MAX_UNIQUE_NODES_PER_CHUNK); static void serializeAndDispatch( - std::vector&& profiles, - IdGenerator& profileIdGenerator, + std::vector &&profiles, + IdGenerator &profileIdGenerator, HighResTimeStamp tracingStartTime, - const std::function& - dispatchCallback, + const std::function &dispatchCallback, uint16_t traceEventChunkSize, uint16_t profileChunkSize = PROFILE_CHUNK_SIZE, uint16_t maxUniqueNodesPerChunk = MAX_UNIQUE_NODES_PER_CHUNK); diff --git a/packages/react-native/ReactCommon/jsinspector-modern/tracing/TargetTracingAgent.h b/packages/react-native/ReactCommon/jsinspector-modern/tracing/TargetTracingAgent.h index dce095dd04d..f92ffe7b263 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/tracing/TargetTracingAgent.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/tracing/TargetTracingAgent.h @@ -22,12 +22,13 @@ namespace facebook::react::jsinspector_modern::tracing { */ class TargetTracingAgent { public: - explicit TargetTracingAgent(TraceRecordingState& state) : state_(state) { + explicit TargetTracingAgent(TraceRecordingState &state) : state_(state) + { (void)state_; } protected: - TraceRecordingState& state_; + TraceRecordingState &state_; }; } // namespace facebook::react::jsinspector_modern::tracing diff --git a/packages/react-native/ReactCommon/jsinspector-modern/tracing/Timing.h b/packages/react-native/ReactCommon/jsinspector-modern/tracing/Timing.h index bda8f65df22..d82bd717ff3 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/tracing/Timing.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/tracing/Timing.h @@ -19,24 +19,20 @@ namespace facebook::react::jsinspector_modern::tracing { // performance.measure calls: these should not extend the timeline window, this // is the current approach in Chromium. constexpr HighResTimeStamp TRACING_TIME_ORIGIN = - HighResTimeStamp::fromChronoSteadyClockTimePoint( - std::chrono::steady_clock::time_point()); + HighResTimeStamp::fromChronoSteadyClockTimePoint(std::chrono::steady_clock::time_point()); // Tracing timestamps are represented a time value in microseconds since // arbitrary time origin (epoch) with no fractional part. -inline uint64_t highResTimeStampToTracingClockTimeStamp( - HighResTimeStamp timestamp) { - assert( - timestamp >= TRACING_TIME_ORIGIN && - "Provided timestamp is before time origin"); +inline uint64_t highResTimeStampToTracingClockTimeStamp(HighResTimeStamp timestamp) +{ + assert(timestamp >= TRACING_TIME_ORIGIN && "Provided timestamp is before time origin"); auto duration = timestamp - TRACING_TIME_ORIGIN; - return static_cast( - static_cast(duration.toNanoseconds()) / 1e3); + return static_cast(static_cast(duration.toNanoseconds()) / 1e3); } -inline int64_t highResDurationToTracingClockDuration(HighResDuration duration) { - return static_cast( - static_cast(duration.toNanoseconds()) / 1e3); +inline int64_t highResDurationToTracingClockDuration(HighResDuration duration) +{ + return static_cast(static_cast(duration.toNanoseconds()) / 1e3); } } // namespace facebook::react::jsinspector_modern::tracing diff --git a/packages/react-native/ReactCommon/jsinspector-modern/tracing/TraceEventSerializer.h b/packages/react-native/ReactCommon/jsinspector-modern/tracing/TraceEventSerializer.h index 5cdeed877ba..38d8eb6f620 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/tracing/TraceEventSerializer.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/tracing/TraceEventSerializer.h @@ -28,7 +28,7 @@ class TraceEventSerializer { * \return A folly::dynamic object that represents a serialized into JSON * Trace Event for CDP. */ - static folly::dynamic serialize(TraceEvent&& event); + static folly::dynamic serialize(TraceEvent &&event); /** * Serialize a TraceEventProfileChunk to a folly::dynamic object. @@ -37,8 +37,7 @@ class TraceEventSerializer { * \return A folly::dynamic object that represents a serialized into JSON * "ProfileChunk" Trace Event for CDP. */ - static folly::dynamic serializeProfileChunk( - TraceEventProfileChunk&& profileChunk); + static folly::dynamic serializeProfileChunk(TraceEventProfileChunk &&profileChunk); /** * Serialize a TraceEventProfileChunk::TimeDeltas to a folly::dynamic @@ -49,8 +48,7 @@ class TraceEventSerializer { * \return A folly::dynamic object that represents a serialized "timeDeltas" * property of "ProfileChunk" Trace Event for CDP. */ - static folly::dynamic serializeProfileChunkTimeDeltas( - TraceEventProfileChunk::TimeDeltas&& deltas); + static folly::dynamic serializeProfileChunkTimeDeltas(TraceEventProfileChunk::TimeDeltas &&deltas); /** * Serialize a TraceEventProfileChunk::CPUProfile into a folly::dynamic @@ -61,8 +59,7 @@ class TraceEventSerializer { * \return A folly::dynamic object that represents a serialized "cpuProfile" * property of "ProfileChunk" Trace Event for CDP. */ - static folly::dynamic serializeProfileChunkCPUProfile( - TraceEventProfileChunk::CPUProfile&& cpuProfile); + static folly::dynamic serializeProfileChunkCPUProfile(TraceEventProfileChunk::CPUProfile &&cpuProfile); /** * Serialize a TraceEventProfileChunk::CPUProfile::Node into a folly::dynamic @@ -73,8 +70,7 @@ class TraceEventSerializer { * \return A folly::dynamic object that represents a serialized * "cpuProfile.nodes[i]" property of "ProfileChunk" Trace Event for CDP. */ - static folly::dynamic serializeProfileChunkCPUProfileNode( - TraceEventProfileChunk::CPUProfile::Node&& node); + static folly::dynamic serializeProfileChunkCPUProfileNode(TraceEventProfileChunk::CPUProfile::Node &&node); /** * Serialize a TraceEventProfileChunk::CPUProfile::Node::CallFrame into a @@ -87,7 +83,7 @@ class TraceEventSerializer { * CDP. */ static folly::dynamic serializeProfileChunkCPUProfileNodeCallFrame( - TraceEventProfileChunk::CPUProfile::Node::CallFrame&& callFrame); + TraceEventProfileChunk::CPUProfile::Node::CallFrame &&callFrame); }; } // namespace facebook::react::jsinspector_modern::tracing diff --git a/packages/react-native/ReactCommon/jsinspector-modern/tracing/TraceRecordingStateSerializer.h b/packages/react-native/ReactCommon/jsinspector-modern/tracing/TraceRecordingStateSerializer.h index 469519e6afc..3936eab663b 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/tracing/TraceRecordingStateSerializer.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/tracing/TraceRecordingStateSerializer.h @@ -28,14 +28,14 @@ class TraceRecordingStateSerializer { * chunkCallback. */ static void emitAsDataCollectedChunks( - TraceRecordingState&& recording, - const std::function& chunkCallback, + TraceRecordingState &&recording, + const std::function &chunkCallback, uint16_t performanceTraceEventsChunkSize, uint16_t profileTraceEventsChunkSize); static void emitPerformanceTraceEvents( - std::vector&& events, - const std::function& chunkCallback, + std::vector &&events, + const std::function &chunkCallback, uint16_t chunkSize); }; diff --git a/packages/react-native/ReactCommon/jsitooling/react/runtime/JSRuntimeFactory.h b/packages/react-native/ReactCommon/jsitooling/react/runtime/JSRuntimeFactory.h index 29f7ec932aa..22759cb33bb 100644 --- a/packages/react-native/ReactCommon/jsitooling/react/runtime/JSRuntimeFactory.h +++ b/packages/react-native/ReactCommon/jsitooling/react/runtime/JSRuntimeFactory.h @@ -21,7 +21,7 @@ class MessageQueueThread; */ class JSRuntime { public: - virtual jsi::Runtime& getRuntime() noexcept = 0; + virtual jsi::Runtime &getRuntime() noexcept = 0; virtual ~JSRuntime() = default; @@ -30,7 +30,7 @@ class JSRuntime { * this JSRuntime. This reference must remain valid for the duration of the * JSRuntime's lifetime. */ - virtual jsinspector_modern::RuntimeTargetDelegate& getRuntimeTargetDelegate(); + virtual jsinspector_modern::RuntimeTargetDelegate &getRuntimeTargetDelegate(); /** * Run initialize work that must happen on the runtime's JS thread. Used for @@ -45,8 +45,7 @@ class JSRuntime { * Initialized by \c getRuntimeTargetDelegate if not overridden, and then * never changes. */ - std::optional - runtimeTargetDelegate_; + std::optional runtimeTargetDelegate_; }; /** @@ -54,8 +53,7 @@ class JSRuntime { */ class JSRuntimeFactory { public: - virtual std::unique_ptr createJSRuntime( - std::shared_ptr msgQueueThread) noexcept = 0; + virtual std::unique_ptr createJSRuntime(std::shared_ptr msgQueueThread) noexcept = 0; virtual ~JSRuntimeFactory() = default; }; @@ -65,7 +63,7 @@ class JSRuntimeFactory { */ class JSIRuntimeHolder : public JSRuntime { public: - jsi::Runtime& getRuntime() noexcept override; + jsi::Runtime &getRuntime() noexcept override; explicit JSIRuntimeHolder(std::unique_ptr runtime); diff --git a/packages/react-native/ReactCommon/jsitooling/react/runtime/JSRuntimeFactoryCAPI.h b/packages/react-native/ReactCommon/jsitooling/react/runtime/JSRuntimeFactoryCAPI.h index 8ae96fc7d7c..41d8204bd04 100644 --- a/packages/react-native/ReactCommon/jsitooling/react/runtime/JSRuntimeFactoryCAPI.h +++ b/packages/react-native/ReactCommon/jsitooling/react/runtime/JSRuntimeFactoryCAPI.h @@ -14,7 +14,7 @@ extern "C" { /** JSRuntimeFactory pointer representation in C. */ -typedef void* JSRuntimeFactoryRef; +typedef void *JSRuntimeFactoryRef; /** Function used to destroy instance of JSRuntimeFactory. diff --git a/packages/react-native/ReactCommon/logger/react_native_log.h b/packages/react-native/ReactCommon/logger/react_native_log.h index 3d26ea6b77f..7b7b4f6a713 100644 --- a/packages/react-native/ReactCommon/logger/react_native_log.h +++ b/packages/react-native/ReactCommon/logger/react_native_log.h @@ -14,20 +14,20 @@ enum ReactNativeLogLevel { ReactNativeLogLevelFatal = 4 }; -using reactnativelogfunctype = void (*)(ReactNativeLogLevel, const char*); +using reactnativelogfunctype = void (*)(ReactNativeLogLevel, const char *); #ifdef __cplusplus extern "C" { #endif // __cplusplus void set_react_native_logfunc(reactnativelogfunctype newlogfunc); -void react_native_log_info(const char* message); -void react_native_log_warn(const char* message); -void react_native_log_error(const char* message); -void react_native_log_fatal(const char* message); +void react_native_log_info(const char *message); +void react_native_log_warn(const char *message); +void react_native_log_error(const char *message); +void react_native_log_fatal(const char *message); -void _react_native_log(ReactNativeLogLevel level, const char* message); -void _react_native_log_default(ReactNativeLogLevel level, const char* message); +void _react_native_log(ReactNativeLogLevel level, const char *message); +void _react_native_log_default(ReactNativeLogLevel level, const char *message); #ifdef __cplusplus } #endif // __cpusplus diff --git a/packages/react-native/ReactCommon/react/bridging/AString.h b/packages/react-native/ReactCommon/react/bridging/AString.h index 0592955320d..b5d48354ef2 100644 --- a/packages/react-native/ReactCommon/react/bridging/AString.h +++ b/packages/react-native/ReactCommon/react/bridging/AString.h @@ -16,25 +16,27 @@ namespace facebook::react { template <> struct Bridging { - static std::string fromJs(jsi::Runtime& rt, const jsi::String& value) { + static std::string fromJs(jsi::Runtime &rt, const jsi::String &value) + { return value.utf8(rt); } - static jsi::String toJs(jsi::Runtime& rt, const std::string& value) { + static jsi::String toJs(jsi::Runtime &rt, const std::string &value) + { return jsi::String::createFromUtf8(rt, value); } }; template <> struct Bridging { - static jsi::String toJs(jsi::Runtime& rt, std::string_view value) { - return jsi::String::createFromUtf8( - rt, reinterpret_cast(value.data()), value.length()); + static jsi::String toJs(jsi::Runtime &rt, std::string_view value) + { + return jsi::String::createFromUtf8(rt, reinterpret_cast(value.data()), value.length()); } }; template <> -struct Bridging : Bridging {}; +struct Bridging : Bridging {}; template struct Bridging : Bridging {}; diff --git a/packages/react-native/ReactCommon/react/bridging/Array.h b/packages/react-native/ReactCommon/react/bridging/Array.h index 9686ef38c84..89108201ce0 100644 --- a/packages/react-native/ReactCommon/react/bridging/Array.h +++ b/packages/react-native/ReactCommon/react/bridging/Array.h @@ -24,35 +24,31 @@ namespace array_detail { template struct BridgingStatic { - static jsi::Array toJs( - jsi::Runtime& rt, - const T& array, - const std::shared_ptr& jsInvoker) { + static jsi::Array toJs(jsi::Runtime &rt, const T &array, const std::shared_ptr &jsInvoker) + { return toJs(rt, array, jsInvoker, std::make_index_sequence{}); } private: template static jsi::Array toJs( - facebook::jsi::Runtime& rt, - const T& array, - const std::shared_ptr& jsInvoker, - std::index_sequence /*unused*/) { - return jsi::Array::createWithElements( - rt, bridging::toJs(rt, std::get(array), jsInvoker)...); + facebook::jsi::Runtime &rt, + const T &array, + const std::shared_ptr &jsInvoker, + std::index_sequence /*unused*/) + { + return jsi::Array::createWithElements(rt, bridging::toJs(rt, std::get(array), jsInvoker)...); } }; template struct BridgingDynamic { - static jsi::Array toJs( - jsi::Runtime& rt, - const T& list, - const std::shared_ptr& jsInvoker) { + static jsi::Array toJs(jsi::Runtime &rt, const T &list, const std::shared_ptr &jsInvoker) + { jsi::Array result(rt, list.size()); size_t index = 0; - for (const auto& item : list) { + for (const auto &item : list) { result.setValueAtIndex(rt, index++, bridging::toJs(rt, item, jsInvoker)); } @@ -63,18 +59,15 @@ struct BridgingDynamic { } // namespace array_detail template -struct Bridging> - : array_detail::BridgingStatic, N> { - static std::array fromJs( - facebook::jsi::Runtime& rt, - const jsi::Array& array, - const std::shared_ptr& jsInvoker) { +struct Bridging> : array_detail::BridgingStatic, N> { + static std::array + fromJs(facebook::jsi::Runtime &rt, const jsi::Array &array, const std::shared_ptr &jsInvoker) + { size_t length = array.length(rt); std::array result; for (size_t i = 0; i < length; i++) { - result[i] = - bridging::fromJs(rt, array.getValueAtIndex(rt, i), jsInvoker); + result[i] = bridging::fromJs(rt, array.getValueAtIndex(rt, i), jsInvoker); } return result; @@ -82,12 +75,10 @@ struct Bridging> }; template -struct Bridging> - : array_detail::BridgingStatic, 2> { - static std::pair fromJs( - facebook::jsi::Runtime& rt, - const jsi::Array& array, - const std::shared_ptr& jsInvoker) { +struct Bridging> : array_detail::BridgingStatic, 2> { + static std::pair + fromJs(facebook::jsi::Runtime &rt, const jsi::Array &array, const std::shared_ptr &jsInvoker) + { return std::make_pair( bridging::fromJs(rt, array.getValueAtIndex(rt, 0), jsInvoker), bridging::fromJs(rt, array.getValueAtIndex(rt, 1), jsInvoker)); @@ -95,35 +86,29 @@ struct Bridging> }; template -struct Bridging> - : array_detail::BridgingStatic, sizeof...(Types)> {}; +struct Bridging> : array_detail::BridgingStatic, sizeof...(Types)> {}; template -struct Bridging> : array_detail::BridgingDynamic> { -}; +struct Bridging> : array_detail::BridgingDynamic> {}; template -struct Bridging> - : array_detail::BridgingDynamic> {}; +struct Bridging> : array_detail::BridgingDynamic> {}; template struct Bridging> : array_detail::BridgingDynamic> {}; template -struct Bridging> - : array_detail::BridgingDynamic> { - static std::vector fromJs( - facebook::jsi::Runtime& rt, - const jsi::Array& array, - const std::shared_ptr& jsInvoker) { +struct Bridging> : array_detail::BridgingDynamic> { + static std::vector + fromJs(facebook::jsi::Runtime &rt, const jsi::Array &array, const std::shared_ptr &jsInvoker) + { size_t length = array.length(rt); std::vector vector; vector.reserve(length); for (size_t i = 0; i < length; i++) { - vector.push_back( - bridging::fromJs(rt, array.getValueAtIndex(rt, i), jsInvoker)); + vector.push_back(bridging::fromJs(rt, array.getValueAtIndex(rt, i), jsInvoker)); } return vector; @@ -132,16 +117,14 @@ struct Bridging> template struct Bridging> : array_detail::BridgingDynamic> { - static std::set fromJs( - facebook::jsi::Runtime& rt, - const jsi::Array& array, - const std::shared_ptr& jsInvoker) { + static std::set + fromJs(facebook::jsi::Runtime &rt, const jsi::Array &array, const std::shared_ptr &jsInvoker) + { size_t length = array.length(rt); std::set set; for (size_t i = 0; i < length; i++) { - set.insert( - bridging::fromJs(rt, array.getValueAtIndex(rt, i), jsInvoker)); + set.insert(bridging::fromJs(rt, array.getValueAtIndex(rt, i), jsInvoker)); } return set; diff --git a/packages/react-native/ReactCommon/react/bridging/Base.h b/packages/react-native/ReactCommon/react/bridging/Base.h index 8265c47338a..fcae10f42de 100644 --- a/packages/react-native/ReactCommon/react/bridging/Base.h +++ b/packages/react-native/ReactCommon/react/bridging/Base.h @@ -24,7 +24,7 @@ struct Bridging; template <> struct Bridging { // Highly generic code may result in "casting" to void. - static void fromJs(jsi::Runtime& /*unused*/, const jsi::Value& /*unused*/) {} + static void fromJs(jsi::Runtime & /*unused*/, const jsi::Value & /*unused*/) {} }; namespace bridging { @@ -51,9 +51,7 @@ struct bridging_wrapper { // Convert lambda types to move-only function types since we can't specialize // Bridging templates for arbitrary lambdas. template -struct bridging_wrapper< - T, - std::void_t::operator())>> +struct bridging_wrapper::operator())>> : function_wrapper::operator())> {}; } // namespace detail @@ -63,71 +61,45 @@ using bridging_t = typename detail::bridging_wrapper::type; template requires is_jsi_v -auto fromJs( - jsi::Runtime& rt, - JSArgT&& value, - const std::shared_ptr& /*unused*/) - -> decltype(static_cast( - std::move(convert(rt, std::forward(value))))) +auto fromJs(jsi::Runtime &rt, JSArgT &&value, const std::shared_ptr & /*unused*/) + -> decltype(static_cast(std::move(convert(rt, std::forward(value))))) { - return static_cast( - std::move(convert(rt, std::forward(value)))); + return static_cast(std::move(convert(rt, std::forward(value)))); } template -auto fromJs( - jsi::Runtime& rt, - JSArgT&& value, - const std::shared_ptr& /*unused*/) - -> decltype(Bridging>::fromJs( - rt, - convert(rt, std::forward(value)))) { - return Bridging>::fromJs( - rt, convert(rt, std::forward(value))); +auto fromJs(jsi::Runtime &rt, JSArgT &&value, const std::shared_ptr & /*unused*/) + -> decltype(Bridging>::fromJs(rt, convert(rt, std::forward(value)))) +{ + return Bridging>::fromJs(rt, convert(rt, std::forward(value))); } template -auto fromJs( - jsi::Runtime& rt, - JSArgT&& value, - const std::shared_ptr& jsInvoker) - -> decltype(Bridging>::fromJs( - rt, - convert(rt, std::forward(value)), - jsInvoker)) { - return Bridging>::fromJs( - rt, convert(rt, std::forward(value)), jsInvoker); +auto fromJs(jsi::Runtime &rt, JSArgT &&value, const std::shared_ptr &jsInvoker) + -> decltype(Bridging>::fromJs(rt, convert(rt, std::forward(value)), jsInvoker)) +{ + return Bridging>::fromJs(rt, convert(rt, std::forward(value)), jsInvoker); } template requires is_jsi_v -auto toJs( - jsi::Runtime& rt, - T&& value, - const std::shared_ptr& /*unused*/ = nullptr) - -> remove_cvref_t { +auto toJs(jsi::Runtime &rt, T &&value, const std::shared_ptr & /*unused*/ = nullptr) -> remove_cvref_t +{ return convert(rt, std::forward(value)); } template -auto toJs( - jsi::Runtime& rt, - T&& value, - const std::shared_ptr& /*unused*/ = nullptr) - -> decltype(Bridging>::toJs(rt, std::forward(value))) { +auto toJs(jsi::Runtime &rt, T &&value, const std::shared_ptr & /*unused*/ = nullptr) + -> decltype(Bridging>::toJs(rt, std::forward(value))) +{ return Bridging>::toJs(rt, std::forward(value)); } template -auto toJs( - jsi::Runtime& rt, - T&& value, - const std::shared_ptr& jsInvoker) - -> decltype(Bridging>::toJs( - rt, - std::forward(value), - jsInvoker)) { +auto toJs(jsi::Runtime &rt, T &&value, const std::shared_ptr &jsInvoker) + -> decltype(Bridging>::toJs(rt, std::forward(value), jsInvoker)) +{ return Bridging>::toJs(rt, std::forward(value), jsInvoker); } @@ -138,19 +110,13 @@ template inline constexpr bool supportsFromJs< T, Arg, - std::void_t( - std::declval(), - std::declval(), - nullptr))>> = true; + std::void_t(std::declval(), std::declval(), nullptr))>> = true; template inline constexpr bool supportsFromJs< T, jsi::Value, - std::void_t( - std::declval(), - std::declval(), - nullptr))>> = true; + std::void_t(std::declval(), std::declval(), nullptr))>> = true; template inline constexpr bool supportsToJs = false; @@ -159,31 +125,15 @@ template inline constexpr bool supportsToJs< JSReturnT, ReturnT, - std::void_t(), - std::declval(), - nullptr))>> = - std::is_convertible_v< - decltype(toJs( - std::declval(), - std::declval(), - nullptr)), - ReturnT>; + std::void_t(), std::declval(), nullptr))>> = + std::is_convertible_v(), std::declval(), nullptr)), ReturnT>; template inline constexpr bool supportsToJs< ReturnT, jsi::Value, - std::void_t(), - std::declval(), - nullptr))>> = - std::is_convertible_v< - decltype(toJs( - std::declval(), - std::declval(), - nullptr)), - jsi::Value>; + std::void_t(), std::declval(), nullptr))>> = + std::is_convertible_v(), std::declval(), nullptr)), jsi::Value>; } // namespace bridging } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/bridging/Bool.h b/packages/react-native/ReactCommon/react/bridging/Bool.h index 1a3912ac1fb..10bb7500abd 100644 --- a/packages/react-native/ReactCommon/react/bridging/Bool.h +++ b/packages/react-native/ReactCommon/react/bridging/Bool.h @@ -13,11 +13,13 @@ namespace facebook::react { template <> struct Bridging { - static bool fromJs(jsi::Runtime& /*unused*/, const jsi::Value& value) { + static bool fromJs(jsi::Runtime & /*unused*/, const jsi::Value &value) + { return value.asBool(); } - static bool toJs(jsi::Runtime& /*unused*/, bool value) { + static bool toJs(jsi::Runtime & /*unused*/, bool value) + { return value; } }; diff --git a/packages/react-native/ReactCommon/react/bridging/CallbackWrapper.h b/packages/react-native/ReactCommon/react/bridging/CallbackWrapper.h index 3f0d4c8129a..a6c5083ef26 100644 --- a/packages/react-native/ReactCommon/react/bridging/CallbackWrapper.h +++ b/packages/react-native/ReactCommon/react/bridging/CallbackWrapper.h @@ -20,46 +20,47 @@ class CallInvoker; // Helper for passing jsi::Function arg to other methods. class CallbackWrapper : public LongLivedObject { private: - CallbackWrapper( - jsi::Function&& callback, - jsi::Runtime& runtime, - std::shared_ptr jsInvoker) - : LongLivedObject(runtime), - callback_(std::move(callback)), - jsInvoker_(std::move(jsInvoker)) {} + CallbackWrapper(jsi::Function &&callback, jsi::Runtime &runtime, std::shared_ptr jsInvoker) + : LongLivedObject(runtime), callback_(std::move(callback)), jsInvoker_(std::move(jsInvoker)) + { + } jsi::Function callback_; std::shared_ptr jsInvoker_; public: - static std::weak_ptr createWeak( - jsi::Function&& callback, - jsi::Runtime& runtime, - std::shared_ptr jsInvoker) { - auto wrapper = std::shared_ptr(new CallbackWrapper( - std::move(callback), runtime, std::move(jsInvoker))); + static std::weak_ptr + createWeak(jsi::Function &&callback, jsi::Runtime &runtime, std::shared_ptr jsInvoker) + { + auto wrapper = + std::shared_ptr(new CallbackWrapper(std::move(callback), runtime, std::move(jsInvoker))); LongLivedObjectCollection::get(runtime).add(wrapper); return wrapper; } // Delete the enclosed jsi::Function - void destroy() { + void destroy() + { allowRelease(); } - jsi::Function& callback() noexcept { + jsi::Function &callback() noexcept + { return callback_; } - jsi::Runtime& runtime() noexcept { + jsi::Runtime &runtime() noexcept + { return runtime_; } - CallInvoker& jsInvoker() noexcept { + CallInvoker &jsInvoker() noexcept + { return *(jsInvoker_); } - std::shared_ptr jsInvokerPtr() noexcept { + std::shared_ptr jsInvokerPtr() noexcept + { return jsInvoker_; } }; diff --git a/packages/react-native/ReactCommon/react/bridging/Class.h b/packages/react-native/ReactCommon/react/bridging/Class.h index 083bd6f0987..16bc0cf0aba 100644 --- a/packages/react-native/ReactCommon/react/bridging/Class.h +++ b/packages/react-native/ReactCommon/react/bridging/Class.h @@ -11,64 +11,41 @@ namespace facebook::react::bridging { -template < - typename JSReturnT, - typename ClassT, - typename ReturnT, - typename... ArgsT, - typename... JSArgsT> +template JSReturnT callFromJs( - jsi::Runtime& rt, - ReturnT (ClassT::*method)(jsi::Runtime&, ArgsT...), - const std::shared_ptr& jsInvoker, - ClassT* instance, - JSArgsT&&... args) { - static_assert( - sizeof...(ArgsT) == sizeof...(JSArgsT), "Incorrect arguments length"); - static_assert( - (supportsFromJs && ...), "Incompatible arguments"); + jsi::Runtime &rt, + ReturnT (ClassT::*method)(jsi::Runtime &, ArgsT...), + const std::shared_ptr &jsInvoker, + ClassT *instance, + JSArgsT &&...args) +{ + static_assert(sizeof...(ArgsT) == sizeof...(JSArgsT), "Incorrect arguments length"); + static_assert((supportsFromJs && ...), "Incompatible arguments"); if constexpr (std::is_void_v) { - static_assert( - std::is_void_v, - "Method must return void when JSReturnT is void"); + static_assert(std::is_void_v, "Method must return void when JSReturnT is void"); } if constexpr (std::is_void_v) { - (instance->*method)( - rt, fromJs(rt, std::forward(args), jsInvoker)...); + (instance->*method)(rt, fromJs(rt, std::forward(args), jsInvoker)...); } else if constexpr (std::is_void_v) { - static_assert( - std::is_same_v, - "Void functions may only return undefined"); + static_assert(std::is_same_v, "Void functions may only return undefined"); - (instance->*method)( - rt, fromJs(rt, std::forward(args), jsInvoker)...); + (instance->*method)(rt, fromJs(rt, std::forward(args), jsInvoker)...); return jsi::Value(); - } else if constexpr ( - is_jsi_v || supportsToJs) { + } else if constexpr (is_jsi_v || supportsToJs) { static_assert(supportsToJs, "Incompatible return type"); - return toJs( - rt, - (instance->*method)( - rt, fromJs(rt, std::forward(args), jsInvoker)...), - jsInvoker); + return toJs(rt, (instance->*method)(rt, fromJs(rt, std::forward(args), jsInvoker)...), jsInvoker); } else if constexpr (is_optional_jsi_v) { static_assert( - is_optional_v - ? supportsToJs< - typename ReturnT::value_type, - typename JSReturnT::value_type> - : supportsToJs, + is_optional_v ? supportsToJs + : supportsToJs, "Incompatible return type"); - auto result = toJs( - rt, - (instance->*method)( - rt, fromJs(rt, std::forward(args), jsInvoker)...), - jsInvoker); + auto result = + toJs(rt, (instance->*method)(rt, fromJs(rt, std::forward(args), jsInvoker)...), jsInvoker); if constexpr (std::is_same_v) { if (result.isNull() || result.isUndefined()) { @@ -78,20 +55,20 @@ JSReturnT callFromJs( return convert(rt, std::move(result)); } else { - static_assert( - std::is_convertible_v, "Incompatible return type"); - return (instance->*method)( - rt, fromJs(rt, std::forward(args), jsInvoker)...); + static_assert(std::is_convertible_v, "Incompatible return type"); + return (instance->*method)(rt, fromJs(rt, std::forward(args), jsInvoker)...); } } template -constexpr size_t getParameterCount(ReturnT (* /*unused*/)(ArgsT...)) { +constexpr size_t getParameterCount(ReturnT (* /*unused*/)(ArgsT...)) +{ return sizeof...(ArgsT); } template -constexpr size_t getParameterCount(ReturnT (Class::* /*unused*/)(ArgsT...)) { +constexpr size_t getParameterCount(ReturnT (Class::* /*unused*/)(ArgsT...)) +{ return sizeof...(ArgsT); } diff --git a/packages/react-native/ReactCommon/react/bridging/Convert.h b/packages/react-native/ReactCommon/react/bridging/Convert.h index 7659cb06d2a..51622c555ca 100644 --- a/packages/react-native/ReactCommon/react/bridging/Convert.h +++ b/packages/react-native/ReactCommon/react/bridging/Convert.h @@ -19,10 +19,8 @@ template using remove_cvref_t = std::remove_cv_t>; template -inline constexpr bool is_jsi_v = - std::is_same_v> || - std::is_same_v> || - std::is_base_of_v>; +inline constexpr bool is_jsi_v = std::is_same_v> || + std::is_same_v> || std::is_base_of_v>; template struct is_optional : std::false_type {}; @@ -37,9 +35,8 @@ template inline constexpr bool is_optional_jsi_v = false; template -inline constexpr bool - is_optional_jsi_v>> = - is_jsi_v; +inline constexpr bool is_optional_jsi_v>> = + is_jsi_v; template struct Converter; @@ -48,10 +45,10 @@ template struct ConverterBase { using BaseT = remove_cvref_t; - ConverterBase(jsi::Runtime& rt, T&& value) - : rt_(rt), value_(std::forward(value)) {} + ConverterBase(jsi::Runtime &rt, T &&value) : rt_(rt), value_(std::forward(value)) {} - operator BaseT() && { + operator BaseT() && + { if constexpr (std::is_lvalue_reference_v) { // Copy the reference into a Value that then can be moved from. auto value = jsi::Value(rt_, value_); @@ -79,17 +76,16 @@ struct ConverterBase { // Ensure non-reference type can be converted to the desired type. std::is_convertible_v, U>, int> = 0> - operator U() && { + operator U() && + { return Converter(rt_, std::move(*this).operator BaseT()); } - template < - typename U, - std::enable_if_t && std::is_same_v, int> = 0> + template && std::is_same_v, int> = 0> operator U() && = delete; // Prevent unwanted upcasting of JSI values. protected: - jsi::Runtime& rt_; + jsi::Runtime &rt_; T value_; }; @@ -102,19 +98,23 @@ template <> struct Converter : public ConverterBase { using ConverterBase::ConverterBase; - operator jsi::String() && { + operator jsi::String() && + { return std::move(value_).asString(rt_); } - operator jsi::Object() && { + operator jsi::Object() && + { return std::move(value_).asObject(rt_); } - operator jsi::Array() && { + operator jsi::Array() && + { return std::move(value_).asObject(rt_).asArray(rt_); } - operator jsi::Function() && { + operator jsi::Function() && + { return std::move(value_).asObject(rt_).asFunction(rt_); } }; @@ -123,21 +123,26 @@ template <> struct Converter : public ConverterBase { using ConverterBase::ConverterBase; - operator jsi::Array() && { + operator jsi::Array() && + { return std::move(value_).asArray(rt_); } - operator jsi::Function() && { + operator jsi::Function() && + { return std::move(value_).asFunction(rt_); } }; template struct Converter> : public ConverterBase { - Converter(jsi::Runtime& rt, std::optional value) - : ConverterBase(rt, value ? std::move(*value) : jsi::Value::null()) {} + Converter(jsi::Runtime &rt, std::optional value) + : ConverterBase(rt, value ? std::move(*value) : jsi::Value::null()) + { + } - operator std::optional() && { + operator std::optional() && + { if (value_.isNull() || value_.isUndefined()) { return {}; } @@ -146,24 +151,26 @@ struct Converter> : public ConverterBase { }; template , int> = 0> -auto convert(jsi::Runtime& rt, T&& value) { +auto convert(jsi::Runtime &rt, T &&value) +{ return Converter(rt, std::forward(value)); } -template < - typename T, - std::enable_if_t || std::is_scalar_v, int> = 0> -auto convert(jsi::Runtime& rt, std::optional value) { +template || std::is_scalar_v, int> = 0> +auto convert(jsi::Runtime &rt, std::optional value) +{ return Converter>(rt, std::move(value)); } template , int> = 0> -auto convert(jsi::Runtime& /*rt*/, T&& value) { +auto convert(jsi::Runtime & /*rt*/, T &&value) +{ return value; } template -auto convert(jsi::Runtime& /*rt*/, Converter&& converter) { +auto convert(jsi::Runtime & /*rt*/, Converter &&converter) +{ return std::move(converter); } diff --git a/packages/react-native/ReactCommon/react/bridging/Dynamic.h b/packages/react-native/ReactCommon/react/bridging/Dynamic.h index 90d1954386f..b0626632592 100644 --- a/packages/react-native/ReactCommon/react/bridging/Dynamic.h +++ b/packages/react-native/ReactCommon/react/bridging/Dynamic.h @@ -14,11 +14,13 @@ namespace facebook::react { template <> struct Bridging { - static folly::dynamic fromJs(jsi::Runtime& rt, const jsi::Value& value) { + static folly::dynamic fromJs(jsi::Runtime &rt, const jsi::Value &value) + { return jsi::dynamicFromValue(rt, value); } - static jsi::Value toJs(jsi::Runtime& rt, const folly::dynamic& value) { + static jsi::Value toJs(jsi::Runtime &rt, const folly::dynamic &value) + { return jsi::valueFromDynamic(rt, value); } }; diff --git a/packages/react-native/ReactCommon/react/bridging/Error.h b/packages/react-native/ReactCommon/react/bridging/Error.h index e8b45973a33..621fd0bfb08 100644 --- a/packages/react-native/ReactCommon/react/bridging/Error.h +++ b/packages/react-native/ReactCommon/react/bridging/Error.h @@ -16,9 +16,10 @@ class Error { // TODO (T114055466): Retain stack trace (at least caller location) Error(std::string message) : message_(std::move(message)) {} - Error(const char* message) : Error(std::string(message)) {} + Error(const char *message) : Error(std::string(message)) {} - const std::string& message() const { + const std::string &message() const + { return message_; } @@ -28,22 +29,26 @@ class Error { template <> struct Bridging { - static jsi::JSError fromJs(jsi::Runtime& rt, const jsi::Value& value) { + static jsi::JSError fromJs(jsi::Runtime &rt, const jsi::Value &value) + { return jsi::JSError(rt, jsi::Value(rt, value)); } - static jsi::JSError fromJs(jsi::Runtime& rt, jsi::Value&& value) { + static jsi::JSError fromJs(jsi::Runtime &rt, jsi::Value &&value) + { return jsi::JSError(rt, std::move(value)); } - static jsi::Value toJs(jsi::Runtime& rt, std::string message) { + static jsi::Value toJs(jsi::Runtime &rt, std::string message) + { return jsi::Value(rt, jsi::JSError(rt, std::move(message)).value()); } }; template <> struct Bridging { - static jsi::Value toJs(jsi::Runtime& rt, const Error& error) { + static jsi::Value toJs(jsi::Runtime &rt, const Error &error) + { return jsi::Value(rt, jsi::JSError(rt, error.message()).value()); } }; diff --git a/packages/react-native/ReactCommon/react/bridging/EventEmitter.h b/packages/react-native/ReactCommon/react/bridging/EventEmitter.h index a635ce1bae1..3a76abcc36c 100644 --- a/packages/react-native/ReactCommon/react/bridging/EventEmitter.h +++ b/packages/react-native/ReactCommon/react/bridging/EventEmitter.h @@ -13,22 +13,21 @@ #include #include -#define FRIEND_TEST(test_case_name, test_name) \ - friend class test_case_name##_##test_name##_Test +#define FRIEND_TEST(test_case_name, test_name) friend class test_case_name##_##test_name##_Test namespace facebook::react { class EventSubscription { public: - explicit EventSubscription(std::function remove) - : remove_(std::move(remove)) {} + explicit EventSubscription(std::function remove) : remove_(std::move(remove)) {} ~EventSubscription() = default; - EventSubscription(EventSubscription&&) noexcept = default; - EventSubscription& operator=(EventSubscription&&) noexcept = default; - EventSubscription(const EventSubscription&) = delete; - EventSubscription& operator=(const EventSubscription&) = delete; + EventSubscription(EventSubscription &&) noexcept = default; + EventSubscription &operator=(EventSubscription &&) noexcept = default; + EventSubscription(const EventSubscription &) = delete; + EventSubscription &operator=(const EventSubscription &) = delete; - void remove() { + void remove() + { remove_(); } @@ -39,23 +38,18 @@ class EventSubscription { template <> struct Bridging { - static EventSubscription fromJs( - jsi::Runtime& rt, - const jsi::Object& value, - const std::shared_ptr& jsInvoker) { - auto listener = bridging::fromJs>( - rt, value.getProperty(rt, "remove"), jsInvoker); - return EventSubscription( - [listener = std::move(listener)]() mutable { listener(); }); + static EventSubscription + fromJs(jsi::Runtime &rt, const jsi::Object &value, const std::shared_ptr &jsInvoker) + { + auto listener = bridging::fromJs>(rt, value.getProperty(rt, "remove"), jsInvoker); + return EventSubscription([listener = std::move(listener)]() mutable { listener(); }); } - static jsi::Object toJs( - jsi::Runtime& rt, - const EventSubscription& eventSubscription, - const std::shared_ptr& jsInvoker) { + static jsi::Object + toJs(jsi::Runtime &rt, const EventSubscription &eventSubscription, const std::shared_ptr &jsInvoker) + { auto result = jsi::Object(rt); - result.setProperty( - rt, "remove", bridging::toJs(rt, eventSubscription.remove_, jsInvoker)); + result.setProperty(rt, "remove", bridging::toJs(rt, eventSubscription.remove_, jsInvoker)); return result; } }; @@ -64,24 +58,21 @@ class IAsyncEventEmitter { public: IAsyncEventEmitter() noexcept = default; virtual ~IAsyncEventEmitter() noexcept = default; - IAsyncEventEmitter(IAsyncEventEmitter&&) noexcept = default; - IAsyncEventEmitter& operator=(IAsyncEventEmitter&&) noexcept = default; - IAsyncEventEmitter(const IAsyncEventEmitter&) = delete; - IAsyncEventEmitter& operator=(const IAsyncEventEmitter&) = delete; + IAsyncEventEmitter(IAsyncEventEmitter &&) noexcept = default; + IAsyncEventEmitter &operator=(IAsyncEventEmitter &&) noexcept = default; + IAsyncEventEmitter(const IAsyncEventEmitter &) = delete; + IAsyncEventEmitter &operator=(const IAsyncEventEmitter &) = delete; - virtual jsi::Object get( - jsi::Runtime& rt, - const std::shared_ptr& jsInvoker) const = 0; + virtual jsi::Object get(jsi::Runtime &rt, const std::shared_ptr &jsInvoker) const = 0; }; template class AsyncEventEmitter : public IAsyncEventEmitter { - static_assert( - sizeof...(Args) <= 1, - "AsyncEventEmitter must have at most one argument"); + static_assert(sizeof...(Args) <= 1, "AsyncEventEmitter must have at most one argument"); public: - AsyncEventEmitter() : state_(std::make_shared()) { + AsyncEventEmitter() : state_(std::make_shared()) + { listen_ = [state = state_](AsyncCallback listener) { std::lock_guard lock(state->mutex); auto listenerId = state->listenerId++; @@ -93,30 +84,29 @@ class AsyncEventEmitter : public IAsyncEventEmitter { }; } ~AsyncEventEmitter() override = default; - AsyncEventEmitter(AsyncEventEmitter&&) noexcept = default; - AsyncEventEmitter& operator=(AsyncEventEmitter&&) noexcept = default; - AsyncEventEmitter(const AsyncEventEmitter&) = delete; - AsyncEventEmitter& operator=(const AsyncEventEmitter&) = delete; + AsyncEventEmitter(AsyncEventEmitter &&) noexcept = default; + AsyncEventEmitter &operator=(AsyncEventEmitter &&) noexcept = default; + AsyncEventEmitter(const AsyncEventEmitter &) = delete; + AsyncEventEmitter &operator=(const AsyncEventEmitter &) = delete; - void emit(std::function&& converter) { + void emit(std::function &&converter) + { std::lock_guard lock(state_->mutex); - for (auto& [_, listener] : state_->listeners) { - listener.call([converter](jsi::Runtime& rt, jsi::Function& jsFunction) { - jsFunction.call(rt, converter(rt)); - }); + for (auto &[_, listener] : state_->listeners) { + listener.call([converter](jsi::Runtime &rt, jsi::Function &jsFunction) { jsFunction.call(rt, converter(rt)); }); } } - void emit(Args... value) { + void emit(Args... value) + { std::lock_guard lock(state_->mutex); - for (const auto& [_, listener] : state_->listeners) { + for (const auto &[_, listener] : state_->listeners) { listener.call(static_cast(value)...); } } - jsi::Object get( - jsi::Runtime& rt, - const std::shared_ptr& jsInvoker) const override { + jsi::Object get(jsi::Runtime &rt, const std::shared_ptr &jsInvoker) const override + { return bridging::toJs(rt, listen_, jsInvoker); } @@ -136,10 +126,9 @@ class AsyncEventEmitter : public IAsyncEventEmitter { template struct Bridging> { - static jsi::Object toJs( - jsi::Runtime& rt, - const AsyncEventEmitter& eventEmitter, - const std::shared_ptr& jsInvoker) { + static jsi::Object + toJs(jsi::Runtime &rt, const AsyncEventEmitter &eventEmitter, const std::shared_ptr &jsInvoker) + { return eventEmitter.get(rt, jsInvoker); } }; diff --git a/packages/react-native/ReactCommon/react/bridging/Function.h b/packages/react-native/ReactCommon/react/bridging/Function.h index 01ac6af9420..eb5d08749b5 100644 --- a/packages/react-native/ReactCommon/react/bridging/Function.h +++ b/packages/react-native/ReactCommon/react/bridging/Function.h @@ -21,37 +21,34 @@ class SyncCallback; template class AsyncCallback { public: - AsyncCallback( - jsi::Runtime& runtime, - jsi::Function function, - std::shared_ptr jsInvoker) - : callback_(std::make_shared>( - runtime, - std::move(function), - std::move(jsInvoker))) {} + AsyncCallback(jsi::Runtime &runtime, jsi::Function function, std::shared_ptr jsInvoker) + : callback_(std::make_shared>(runtime, std::move(function), std::move(jsInvoker))) + { + } - void operator()(Args... args) const noexcept { + void operator()(Args... args) const noexcept + { call(std::forward(args)...); } - void call(Args... args) const noexcept { + void call(Args... args) const noexcept + { callWithArgs(std::nullopt, std::forward(args)...); } - void callWithPriority(SchedulerPriority priority, Args... args) - const noexcept { + void callWithPriority(SchedulerPriority priority, Args... args) const noexcept + { callWithArgs(priority, std::forward(args)...); } - void call(std::function&& callImpl) - const noexcept { + void call(std::function &&callImpl) const noexcept + { callWithFunction(std::nullopt, std::move(callImpl)); } - void callWithPriority( - SchedulerPriority priority, - std::function&& callImpl) - const noexcept { + void callWithPriority(SchedulerPriority priority, std::function &&callImpl) + const noexcept + { callWithFunction(priority, std::move(callImpl)); } @@ -60,15 +57,14 @@ class AsyncCallback { std::shared_ptr> callback_; - void callWithArgs(std::optional priority, Args... args) - const noexcept { + void callWithArgs(std::optional priority, Args... args) const noexcept + { if (auto wrapper = callback_->wrapper_.lock()) { auto fn = [callback = callback_, - argsPtr = std::make_shared>( - std::make_tuple(std::forward(args)...))]( - jsi::Runtime&) { callback->apply(std::move(*argsPtr)); }; + argsPtr = std::make_shared>(std::make_tuple(std::forward(args)...))]( + jsi::Runtime &) { callback->apply(std::move(*argsPtr)); }; - auto& jsInvoker = wrapper->jsInvoker(); + auto &jsInvoker = wrapper->jsInvoker(); if (priority) { jsInvoker.invokeAsync(*priority, std::move(fn)); } else { @@ -79,20 +75,19 @@ class AsyncCallback { void callWithFunction( std::optional priority, - std::function&& callImpl) - const noexcept { + std::function &&callImpl) const noexcept + { if (auto wrapper = callback_->wrapper_.lock()) { // Capture callback_ and not wrapper_. If callback_ is deallocated or the // JSVM is shutdown before the async task is scheduled, the underlying // function will have been deallocated. - auto fn = [callback = callback_, - callImpl = std::move(callImpl)](jsi::Runtime& rt) { + auto fn = [callback = callback_, callImpl = std::move(callImpl)](jsi::Runtime &rt) { if (auto wrapper2 = callback->wrapper_.lock()) { callImpl(rt, wrapper2->callback()); } }; - auto& jsInvoker = wrapper->jsInvoker(); + auto &jsInvoker = wrapper->jsInvoker(); if (priority) { jsInvoker.invokeAsync(*priority, std::move(fn)); } else { @@ -108,40 +103,39 @@ class AsyncCallback { template class SyncCallback { public: - SyncCallback( - jsi::Runtime& rt, - jsi::Function function, - std::shared_ptr jsInvoker) - : wrapper_(CallbackWrapper::createWeak( - std::move(function), - rt, - std::move(jsInvoker))) {} + SyncCallback(jsi::Runtime &rt, jsi::Function function, std::shared_ptr jsInvoker) + : wrapper_(CallbackWrapper::createWeak(std::move(function), rt, std::move(jsInvoker))) + { + } // Disallow copying, as we can no longer safely destroy the callback // from the destructor if there's multiple copies - SyncCallback(const SyncCallback&) = delete; - SyncCallback& operator=(const SyncCallback&) = delete; + SyncCallback(const SyncCallback &) = delete; + SyncCallback &operator=(const SyncCallback &) = delete; // Allow move - SyncCallback(SyncCallback&& other) noexcept - : wrapper_(std::move(other.wrapper_)) {} + SyncCallback(SyncCallback &&other) noexcept : wrapper_(std::move(other.wrapper_)) {} - SyncCallback& operator=(SyncCallback&& other) noexcept { + SyncCallback &operator=(SyncCallback &&other) noexcept + { wrapper_ = std::move(other.wrapper_); return *this; } - ~SyncCallback() { + ~SyncCallback() + { if (auto wrapper = wrapper_.lock()) { wrapper->destroy(); } } - R operator()(Args... args) const { + R operator()(Args... args) const + { return call(std::forward(args)...); } - R call(Args... args) const { + R call(Args... args) const + { auto wrapper = wrapper_.lock(); // If the wrapper has been deallocated, we can no longer provide a return @@ -154,19 +148,15 @@ class SyncCallback { } } - auto& callback = wrapper->callback(); - auto& rt = wrapper->runtime(); + auto &callback = wrapper->callback(); + auto &rt = wrapper->runtime(); auto jsInvoker = wrapper->jsInvokerPtr(); if constexpr (std::is_void_v) { - callback.call( - rt, bridging::toJs(rt, std::forward(args), jsInvoker)...); + callback.call(rt, bridging::toJs(rt, std::forward(args), jsInvoker)...); } else { return bridging::fromJs( - rt, - callback.call( - rt, bridging::toJs(rt, std::forward(args), jsInvoker)...), - jsInvoker); + rt, callback.call(rt, bridging::toJs(rt, std::forward(args), jsInvoker)...), jsInvoker); } } @@ -174,13 +164,14 @@ class SyncCallback { friend AsyncCallback; friend Bridging; - R apply(std::tuple&& args) const { + R apply(std::tuple &&args) const + { return apply(std::move(args), std::index_sequence_for{}); } template - R apply(std::tuple&& args, std::index_sequence /*unused*/) - const { + R apply(std::tuple &&args, std::index_sequence /*unused*/) const + { return call(std::move(std::get(args))...); } @@ -190,32 +181,28 @@ class SyncCallback { template struct Bridging> { - static AsyncCallback fromJs( - jsi::Runtime& rt, - jsi::Function&& value, - const std::shared_ptr& jsInvoker) { + static AsyncCallback + fromJs(jsi::Runtime &rt, jsi::Function &&value, const std::shared_ptr &jsInvoker) + { return AsyncCallback(rt, std::move(value), jsInvoker); } - static jsi::Function toJs( - jsi::Runtime& rt, - const AsyncCallback& value) { + static jsi::Function toJs(jsi::Runtime &rt, const AsyncCallback &value) + { return value.callback_->function_.getFunction(rt); } }; template struct Bridging> { - static SyncCallback fromJs( - jsi::Runtime& rt, - jsi::Function&& value, - const std::shared_ptr& jsInvoker) { + static SyncCallback + fromJs(jsi::Runtime &rt, jsi::Function &&value, const std::shared_ptr &jsInvoker) + { return SyncCallback(rt, std::move(value), jsInvoker); } - static jsi::Function toJs( - jsi::Runtime& rt, - const SyncCallback& value) { + static jsi::Function toJs(jsi::Runtime &rt, const SyncCallback &value) + { return value.function_.getFunction(rt); } }; @@ -227,19 +214,14 @@ struct Bridging> { static constexpr size_t kArgumentCount = sizeof...(Args); - static jsi::Function toJs( - jsi::Runtime& rt, - Func fn, - const std::shared_ptr& jsInvoker) { + static jsi::Function toJs(jsi::Runtime &rt, Func fn, const std::shared_ptr &jsInvoker) + { return jsi::Function::createFromHostFunction( rt, jsi::PropNameID::forAscii(rt, "BridgedFunction"), kArgumentCount, [fn = std::make_shared(std::move(fn)), jsInvoker]( - jsi::Runtime& rt, - const jsi::Value&, - const jsi::Value* args, - size_t count) -> jsi::Value { + jsi::Runtime &rt, const jsi::Value &, const jsi::Value *args, size_t count) -> jsi::Value { if (count < kArgumentCount) { throw jsi::JSError(rt, "Incorrect number of arguments"); } @@ -248,10 +230,7 @@ struct Bridging> { callFromJs(*fn, rt, args, jsInvoker, IndexSequence{}); return jsi::Value(); } else { - return bridging::toJs( - rt, - callFromJs(*fn, rt, args, jsInvoker, IndexSequence{}), - jsInvoker); + return bridging::toJs(rt, callFromJs(*fn, rt, args, jsInvoker, IndexSequence{}), jsInvoker); } }); } @@ -259,11 +238,12 @@ struct Bridging> { private: template static R callFromJs( - Func& fn, - jsi::Runtime& rt, - const jsi::Value* args, - const std::shared_ptr& jsInvoker, - std::index_sequence /*unused*/) { + Func &fn, + jsi::Runtime &rt, + const jsi::Value *args, + const std::shared_ptr &jsInvoker, + std::index_sequence /*unused*/) + { return fn(bridging::fromJs(rt, args[Index], jsInvoker)...); } }; @@ -271,8 +251,7 @@ struct Bridging> { template struct Bridging< std::function, - std::enable_if_t< - !std::is_same_v, std::function>>> + std::enable_if_t, std::function>>> : Bridging> {}; template diff --git a/packages/react-native/ReactCommon/react/bridging/HighResTimeStamp.h b/packages/react-native/ReactCommon/react/bridging/HighResTimeStamp.h index ea3aa83bc62..83807d54e87 100644 --- a/packages/react-native/ReactCommon/react/bridging/HighResTimeStamp.h +++ b/packages/react-native/ReactCommon/react/bridging/HighResTimeStamp.h @@ -14,26 +14,26 @@ namespace facebook::react { template <> struct Bridging { - static HighResTimeStamp fromJs( - jsi::Runtime& /*rt*/, - const jsi::Value& jsiValue) { + static HighResTimeStamp fromJs(jsi::Runtime & /*rt*/, const jsi::Value &jsiValue) + { return HighResTimeStamp::fromDOMHighResTimeStamp(jsiValue.asNumber()); } - static double toJs(jsi::Runtime& /*rt*/, const HighResTimeStamp& value) { + static double toJs(jsi::Runtime & /*rt*/, const HighResTimeStamp &value) + { return value.toDOMHighResTimeStamp(); } }; template <> struct Bridging { - static HighResDuration fromJs( - jsi::Runtime& /*rt*/, - const jsi::Value& jsiValue) { + static HighResDuration fromJs(jsi::Runtime & /*rt*/, const jsi::Value &jsiValue) + { return HighResDuration::fromDOMHighResTimeStamp(jsiValue.asNumber()); } - static double toJs(jsi::Runtime& /*rt*/, const HighResDuration& value) { + static double toJs(jsi::Runtime & /*rt*/, const HighResDuration &value) + { return value.toDOMHighResTimeStamp(); } }; diff --git a/packages/react-native/ReactCommon/react/bridging/LongLivedObject.h b/packages/react-native/ReactCommon/react/bridging/LongLivedObject.h index d043a0a9a91..1e3ff3f97bc 100644 --- a/packages/react-native/ReactCommon/react/bridging/LongLivedObject.h +++ b/packages/react-native/ReactCommon/react/bridging/LongLivedObject.h @@ -32,9 +32,9 @@ class LongLivedObject { virtual void allowRelease(); protected: - explicit LongLivedObject(jsi::Runtime& runtime) : runtime_(runtime) {} + explicit LongLivedObject(jsi::Runtime &runtime) : runtime_(runtime) {} virtual ~LongLivedObject() = default; - jsi::Runtime& runtime_; + jsi::Runtime &runtime_; }; /** @@ -42,14 +42,14 @@ class LongLivedObject { */ class LongLivedObjectCollection { public: - static LongLivedObjectCollection& get(jsi::Runtime& runtime); + static LongLivedObjectCollection &get(jsi::Runtime &runtime); LongLivedObjectCollection() = default; - LongLivedObjectCollection(const LongLivedObjectCollection&) = delete; - void operator=(const LongLivedObjectCollection&) = delete; + LongLivedObjectCollection(const LongLivedObjectCollection &) = delete; + void operator=(const LongLivedObjectCollection &) = delete; void add(std::shared_ptr o); - void remove(const LongLivedObject* o); + void remove(const LongLivedObject *o); void clear(); size_t size() const; diff --git a/packages/react-native/ReactCommon/react/bridging/Number.h b/packages/react-native/ReactCommon/react/bridging/Number.h index 68b4c259440..2fb0c8a9b0d 100644 --- a/packages/react-native/ReactCommon/react/bridging/Number.h +++ b/packages/react-native/ReactCommon/react/bridging/Number.h @@ -13,44 +13,52 @@ namespace facebook::react { template <> struct Bridging { - static double fromJs(jsi::Runtime& /*unused*/, const jsi::Value& value) { + static double fromJs(jsi::Runtime & /*unused*/, const jsi::Value &value) + { return value.asNumber(); } - static double toJs(jsi::Runtime& /*unused*/, double value) { + static double toJs(jsi::Runtime & /*unused*/, double value) + { return value; } }; template <> struct Bridging { - static float fromJs(jsi::Runtime& /*unused*/, const jsi::Value& value) { + static float fromJs(jsi::Runtime & /*unused*/, const jsi::Value &value) + { return (float)value.asNumber(); } - static float toJs(jsi::Runtime& /*unused*/, float value) { + static float toJs(jsi::Runtime & /*unused*/, float value) + { return value; } }; template <> struct Bridging { - static int32_t fromJs(jsi::Runtime& /*unused*/, const jsi::Value& value) { + static int32_t fromJs(jsi::Runtime & /*unused*/, const jsi::Value &value) + { return (int32_t)value.asNumber(); } - static int32_t toJs(jsi::Runtime& /*unused*/, int32_t value) { + static int32_t toJs(jsi::Runtime & /*unused*/, int32_t value) + { return value; } }; template <> struct Bridging { - static uint32_t fromJs(jsi::Runtime& /*unused*/, const jsi::Value& value) { + static uint32_t fromJs(jsi::Runtime & /*unused*/, const jsi::Value &value) + { return (uint32_t)value.asNumber(); } - static jsi::Value toJs(jsi::Runtime& /*unused*/, uint32_t value) { + static jsi::Value toJs(jsi::Runtime & /*unused*/, uint32_t value) + { return double(value); } }; diff --git a/packages/react-native/ReactCommon/react/bridging/Object.h b/packages/react-native/ReactCommon/react/bridging/Object.h index 89e5714b798..0ccd3a24e1e 100644 --- a/packages/react-native/ReactCommon/react/bridging/Object.h +++ b/packages/react-native/ReactCommon/react/bridging/Object.h @@ -17,24 +17,26 @@ namespace facebook::react { template <> struct Bridging { - static jsi::WeakObject fromJs(jsi::Runtime& rt, const jsi::Object& value) { + static jsi::WeakObject fromJs(jsi::Runtime &rt, const jsi::Object &value) + { return jsi::WeakObject(rt, value); } - static jsi::Value toJs(jsi::Runtime& rt, jsi::WeakObject& value) { + static jsi::Value toJs(jsi::Runtime &rt, jsi::WeakObject &value) + { return value.lock(rt); } }; template -struct Bridging< - std::shared_ptr, - std::enable_if_t>> { - static std::shared_ptr fromJs(jsi::Runtime& rt, const jsi::Object& value) { +struct Bridging, std::enable_if_t>> { + static std::shared_ptr fromJs(jsi::Runtime &rt, const jsi::Object &value) + { return value.getHostObject(rt); } - static jsi::Object toJs(jsi::Runtime& rt, std::shared_ptr value) { + static jsi::Object toJs(jsi::Runtime &rt, std::shared_ptr value) + { return jsi::Object::createFromHostObject(rt, std::move(value)); } }; @@ -43,10 +45,8 @@ namespace map_detail { template struct Bridging { - static T fromJs( - jsi::Runtime& rt, - const jsi::Object& value, - const std::shared_ptr& jsInvoker) { + static T fromJs(jsi::Runtime &rt, const jsi::Object &value, const std::shared_ptr &jsInvoker) + { T result; auto propertyNames = value.getPropertyNames(rt); auto length = propertyNames.length(rt); @@ -56,24 +56,18 @@ struct Bridging { result.emplace( bridging::fromJs(rt, propertyName, jsInvoker), - bridging::fromJs( - rt, value.getProperty(rt, propertyName.asString(rt)), jsInvoker)); + bridging::fromJs(rt, value.getProperty(rt, propertyName.asString(rt)), jsInvoker)); } return result; } - static jsi::Object toJs( - jsi::Runtime& rt, - const T& map, - const std::shared_ptr& jsInvoker) { + static jsi::Object toJs(jsi::Runtime &rt, const T &map, const std::shared_ptr &jsInvoker) + { auto resultObject = jsi::Object(rt); - for (const auto& [key, value] : map) { - resultObject.setProperty( - rt, - jsi::PropNameID::forUtf8(rt, key), - bridging::toJs(rt, value, jsInvoker)); + for (const auto &[key, value] : map) { + resultObject.setProperty(rt, jsi::PropNameID::forUtf8(rt, key), bridging::toJs(rt, value, jsInvoker)); } return resultObject; @@ -83,8 +77,7 @@ struct Bridging { } // namespace map_detail template -struct Bridging> - : map_detail::Bridging> {}; +struct Bridging> : map_detail::Bridging> {}; template struct Bridging> diff --git a/packages/react-native/ReactCommon/react/bridging/Promise.h b/packages/react-native/ReactCommon/react/bridging/Promise.h index 6dfb0d9b067..a1f17f813ad 100644 --- a/packages/react-native/ReactCommon/react/bridging/Promise.h +++ b/packages/react-native/ReactCommon/react/bridging/Promise.h @@ -18,13 +18,12 @@ namespace facebook::react { template class AsyncPromise { - static_assert( - sizeof...(T) <= 1, - "AsyncPromise must have at most one argument"); + static_assert(sizeof...(T) <= 1, "AsyncPromise must have at most one argument"); public: - AsyncPromise(jsi::Runtime& rt, const std::shared_ptr& jsInvoker) - : state_(std::make_shared()) { + AsyncPromise(jsi::Runtime &rt, const std::shared_ptr &jsInvoker) + : state_(std::make_shared()) + { auto constructor = rt.global().getPropertyAsFunction(rt, "Promise"); auto promise = constructor.callAsConstructor( @@ -32,23 +31,21 @@ class AsyncPromise { bridging::toJs( rt, // Safe to capture this since this is called synchronously. - [this]( - AsyncCallback resolve, - const AsyncCallback& reject) { + [this](AsyncCallback resolve, const AsyncCallback &reject) { state_->resolve = std::move(resolve); state_->reject = std::move(reject); }, jsInvoker)); - auto promiseHolder = - std::make_shared(rt, promise.asObject(rt)); + auto promiseHolder = std::make_shared(rt, promise.asObject(rt)); LongLivedObjectCollection::get(rt).add(promiseHolder); // The shared state can retain the promise holder weakly now. state_->promiseHolder = promiseHolder; } - void resolve(T... value) { + void resolve(T... value) + { std::lock_guard lock(state_->mutex); if (state_->resolve) { @@ -58,7 +55,8 @@ class AsyncPromise { } } - void reject(Error error) { + void reject(Error error) + { std::lock_guard lock(state_->mutex); if (state_->reject) { @@ -68,7 +66,8 @@ class AsyncPromise { } } - jsi::Object get(jsi::Runtime& rt) const { + jsi::Object get(jsi::Runtime &rt) const + { if (auto holder = state_->promiseHolder.lock()) { return jsi::Value(rt, holder->promise).asObject(rt); } else { @@ -78,14 +77,14 @@ class AsyncPromise { private: struct PromiseHolder : LongLivedObject { - PromiseHolder(jsi::Runtime& runtime, jsi::Object p) - : LongLivedObject(runtime), promise(std::move(p)) {} + PromiseHolder(jsi::Runtime &runtime, jsi::Object p) : LongLivedObject(runtime), promise(std::move(p)) {} jsi::Object promise; }; struct SharedState { - ~SharedState() { + ~SharedState() + { if (auto holder = promiseHolder.lock()) { holder->allowRelease(); } @@ -102,7 +101,8 @@ class AsyncPromise { template struct Bridging> { - static jsi::Object toJs(jsi::Runtime& rt, const AsyncPromise& promise) { + static jsi::Object toJs(jsi::Runtime &rt, const AsyncPromise &promise) + { return promise.get(rt); } }; diff --git a/packages/react-native/ReactCommon/react/bridging/Value.h b/packages/react-native/ReactCommon/react/bridging/Value.h index dfd832c8a2f..deb99ad5d39 100644 --- a/packages/react-native/ReactCommon/react/bridging/Value.h +++ b/packages/react-native/ReactCommon/react/bridging/Value.h @@ -16,7 +16,8 @@ namespace facebook::react { template <> struct Bridging { - static std::nullptr_t fromJs(jsi::Runtime& rt, const jsi::Value& value) { + static std::nullptr_t fromJs(jsi::Runtime &rt, const jsi::Value &value) + { if (value.isNull() || value.isUndefined()) { return nullptr; } else { @@ -24,17 +25,17 @@ struct Bridging { } } - static std::nullptr_t toJs(jsi::Runtime& /*unused*/, std::nullptr_t) { + static std::nullptr_t toJs(jsi::Runtime & /*unused*/, std::nullptr_t) + { return nullptr; } }; template struct Bridging> { - static std::optional fromJs( - jsi::Runtime& rt, - const jsi::Value& value, - const std::shared_ptr& jsInvoker) { + static std::optional + fromJs(jsi::Runtime &rt, const jsi::Value &value, const std::shared_ptr &jsInvoker) + { if (value.isNull() || value.isUndefined()) { return {}; } @@ -42,20 +43,17 @@ struct Bridging> { } template - static std::optional fromJs( - jsi::Runtime& rt, - const std::optional& value, - const std::shared_ptr& jsInvoker) { + static std::optional + fromJs(jsi::Runtime &rt, const std::optional &value, const std::shared_ptr &jsInvoker) + { if (value) { return bridging::fromJs(rt, *value, jsInvoker); } return {}; } - static jsi::Value toJs( - jsi::Runtime& rt, - const std::optional& value, - const std::shared_ptr& jsInvoker) { + static jsi::Value toJs(jsi::Runtime &rt, const std::optional &value, const std::shared_ptr &jsInvoker) + { if (value) { return bridging::toJs(rt, *value, jsInvoker); } @@ -64,13 +62,9 @@ struct Bridging> { }; template -struct Bridging< - std::shared_ptr, - std::enable_if_t>> { - static jsi::Value toJs( - jsi::Runtime& rt, - const std::shared_ptr& ptr, - const std::shared_ptr& jsInvoker) { +struct Bridging, std::enable_if_t>> { + static jsi::Value toJs(jsi::Runtime &rt, const std::shared_ptr &ptr, const std::shared_ptr &jsInvoker) + { if (ptr) { return bridging::toJs(rt, *ptr, jsInvoker); } @@ -80,10 +74,8 @@ struct Bridging< template struct Bridging> { - static jsi::Value toJs( - jsi::Runtime& rt, - const std::unique_ptr& ptr, - const std::shared_ptr& jsInvoker) { + static jsi::Value toJs(jsi::Runtime &rt, const std::unique_ptr &ptr, const std::shared_ptr &jsInvoker) + { if (ptr) { return bridging::toJs(rt, *ptr, jsInvoker); } @@ -93,10 +85,9 @@ struct Bridging> { template struct Bridging> { - static jsi::Value toJs( - jsi::Runtime& rt, - const std::weak_ptr& weakPtr, - const std::shared_ptr& jsInvoker) { + static jsi::Value + toJs(jsi::Runtime &rt, const std::weak_ptr &weakPtr, const std::shared_ptr &jsInvoker) + { if (auto ptr = weakPtr.lock()) { return bridging::toJs(rt, *ptr, jsInvoker); } diff --git a/packages/react-native/ReactCommon/react/bridging/tests/BridgingTest.cpp b/packages/react-native/ReactCommon/react/bridging/tests/BridgingTest.cpp index 804d4a1f3f3..8faa3979131 100644 --- a/packages/react-native/ReactCommon/react/bridging/tests/BridgingTest.cpp +++ b/packages/react-native/ReactCommon/react/bridging/tests/BridgingTest.cpp @@ -140,15 +140,17 @@ TEST_F(BridgingTest, weakbjectTest) { auto object = jsi::Object(rt); auto weakobject = jsi::WeakObject(rt, object); - EXPECT_TRUE(jsi::Object::strictEquals( - rt, - object, - bridging::fromJs(rt, object, invoker) - .lock(rt) - .asObject(rt))); + EXPECT_TRUE( + jsi::Object::strictEquals( + rt, + object, + bridging::fromJs(rt, object, invoker) + .lock(rt) + .asObject(rt))); - EXPECT_TRUE(jsi::Object::strictEquals( - rt, object, bridging::toJs(rt, weakobject).asObject(rt))); + EXPECT_TRUE( + jsi::Object::strictEquals( + rt, object, bridging::toJs(rt, weakobject).asObject(rt))); } TEST_F(BridgingTest, arrayTest) { @@ -443,11 +445,12 @@ void addEventSubscription( rt, [lastEvent = lastEvent](const EventType& event) { *lastEvent = event; }, invoker); - eventSubscriptionsWithListener.emplace_back(std::make_pair( - jsi::Object(eventEmitterJs.asFunction(rt) - .callWithThis(rt, eventEmitterJs, listenJs) - .asObject(rt)), - std::move(lastEvent))); + eventSubscriptionsWithListener.emplace_back( + std::make_pair( + jsi::Object(eventEmitterJs.asFunction(rt) + .callWithThis(rt, eventEmitterJs, listenJs) + .asObject(rt)), + std::move(lastEvent))); } } // namespace diff --git a/packages/react-native/ReactCommon/react/bridging/tests/BridgingTest.h b/packages/react-native/ReactCommon/react/bridging/tests/BridgingTest.h index 533feeceaca..71a072acd3c 100644 --- a/packages/react-native/ReactCommon/react/bridging/tests/BridgingTest.h +++ b/packages/react-native/ReactCommon/react/bridging/tests/BridgingTest.h @@ -18,46 +18,54 @@ namespace facebook::react { class BridgingTest : public ::testing::Test { public: - BridgingTest(BridgingTest& other) = delete; - BridgingTest& operator=(BridgingTest& other) = delete; - BridgingTest(BridgingTest&& other) = delete; - BridgingTest& operator=(BridgingTest&& other) = delete; + BridgingTest(BridgingTest &other) = delete; + BridgingTest &operator=(BridgingTest &other) = delete; + BridgingTest(BridgingTest &&other) = delete; + BridgingTest &operator=(BridgingTest &&other) = delete; protected: BridgingTest() - : runtime(hermes::makeHermesRuntime( - ::hermes::vm::RuntimeConfig::Builder() - // Make promises work with Hermes microtasks. - .withMicrotaskQueue(true) - .build())), + : runtime( + hermes::makeHermesRuntime( + ::hermes::vm::RuntimeConfig::Builder() + // Make promises work with Hermes microtasks. + .withMicrotaskQueue(true) + .build())), rt(*runtime), - invoker(std::make_shared(*runtime)) {} + invoker(std::make_shared(*runtime)) + { + } - ~BridgingTest() override { + ~BridgingTest() override + { LongLivedObjectCollection::get(rt).clear(); } - void TearDown() override { + void TearDown() override + { flushQueue(); // After flushing the invoker queue, we shouldn't leak memory. EXPECT_EQ(0, LongLivedObjectCollection::get(rt).size()); } - jsi::Value eval(const std::string& js) { + jsi::Value eval(const std::string &js) + { return rt.global().getPropertyAsFunction(rt, "eval").call(rt, js); } - jsi::Function function(const std::string& js) { + jsi::Function function(const std::string &js) + { return eval(("(" + js + ")").c_str()).getObject(rt).getFunction(rt); } - void flushQueue() { + void flushQueue() + { invoker->flushQueue(); } std::shared_ptr runtime; - jsi::Runtime& rt; + jsi::Runtime &rt; std::shared_ptr invoker; }; diff --git a/packages/react-native/ReactCommon/react/bridging/tests/ClassTest.cpp b/packages/react-native/ReactCommon/react/bridging/tests/ClassTest.cpp index 67b63410bca..4c1d195a277 100644 --- a/packages/react-native/ReactCommon/react/bridging/tests/ClassTest.cpp +++ b/packages/react-native/ReactCommon/react/bridging/tests/ClassTest.cpp @@ -56,11 +56,12 @@ TEST_F(BridgingTest, callFromJsTest) { auto object = jsi::Object(rt); - EXPECT_TRUE(jsi::Object::strictEquals( - rt, - object, - bridging::callFromJs( - rt, &TestClass::getObject, invoker, &instance, object))); + EXPECT_TRUE( + jsi::Object::strictEquals( + rt, + object, + bridging::callFromJs( + rt, &TestClass::getObject, invoker, &instance, object))); auto promise = bridging::callFromJs( rt, diff --git a/packages/react-native/ReactCommon/react/debug/react_native_assert.h b/packages/react-native/ReactCommon/react/debug/react_native_assert.h index 1d399d45421..d209e0041bb 100644 --- a/packages/react-native/ReactCommon/react/debug/react_native_assert.h +++ b/packages/react-native/ReactCommon/react/debug/react_native_assert.h @@ -37,17 +37,12 @@ #ifdef __cplusplus extern "C" { #endif // __cplusplus -void react_native_assert_fail( - const char* func, - const char* file, - int line, - const char* expr); +void react_native_assert_fail(const char *func, const char *file, int line, const char *expr); #ifdef __cplusplus } #endif // __cpusplus -#define react_native_assert(e) \ - ((e) ? (void)0 : react_native_assert_fail(__func__, __FILE__, __LINE__, #e)) +#define react_native_assert(e) ((e) ? (void)0 : react_native_assert_fail(__func__, __FILE__, __LINE__, #e)) #else // __ANDROID__ diff --git a/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlagsOverridesOSSStable.h b/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlagsOverridesOSSStable.h index f165dda8753..1a3bce00363 100644 --- a/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlagsOverridesOSSStable.h +++ b/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlagsOverridesOSSStable.h @@ -11,22 +11,26 @@ namespace facebook::react { -class ReactNativeFeatureFlagsOverridesOSSStable - : public ReactNativeFeatureFlagsDefaults { +class ReactNativeFeatureFlagsOverridesOSSStable : public ReactNativeFeatureFlagsDefaults { public: - bool enableBridgelessArchitecture() override { + bool enableBridgelessArchitecture() override + { return true; } - bool enableFabricRenderer() override { + bool enableFabricRenderer() override + { return true; } - bool useTurboModules() override { + bool useTurboModules() override + { return true; } - bool useNativeViewConfigsInBridgelessMode() override { + bool useNativeViewConfigsInBridgelessMode() override + { return true; } - bool useShadowNodeStateOnClone() override { + bool useShadowNodeStateOnClone() override + { return true; } }; diff --git a/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/CxxTurboModuleUtils.h b/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/CxxTurboModuleUtils.h index 378cb17cd6c..c000fc87cd3 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/CxxTurboModuleUtils.h +++ b/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/CxxTurboModuleUtils.h @@ -15,10 +15,7 @@ namespace facebook::react { -std::unordered_map< - std::string, - std::function< - std::shared_ptr(std::shared_ptr jsInvoker)>>& +std::unordered_map(std::shared_ptr jsInvoker)>> & globalExportedCxxTurboModuleMap(); /** @@ -29,7 +26,6 @@ globalExportedCxxTurboModuleMap(); */ void registerCxxModuleToGlobalModuleMap( std::string name, - std::function( - std::shared_ptr jsInvoker)> moduleProviderFunc); + std::function(std::shared_ptr jsInvoker)> moduleProviderFunc); } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/TurboCxxModule.h b/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/TurboCxxModule.h index 97720aeabb7..df3800bb1b9 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/TurboCxxModule.h +++ b/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/TurboCxxModule.h @@ -24,22 +24,13 @@ namespace facebook::react { */ class JSI_EXPORT TurboCxxModule : public TurboModule { public: - TurboCxxModule( - std::unique_ptr cxxModule, - std::shared_ptr jsInvoker); + TurboCxxModule(std::unique_ptr cxxModule, std::shared_ptr jsInvoker); - facebook::jsi::Value create( - facebook::jsi::Runtime& runtime, - const facebook::jsi::PropNameID& propName) override; + facebook::jsi::Value create(facebook::jsi::Runtime &runtime, const facebook::jsi::PropNameID &propName) override; - std::vector getPropertyNames( - facebook::jsi::Runtime& runtime) override; + std::vector getPropertyNames(facebook::jsi::Runtime &runtime) override; - jsi::Value invokeMethod( - jsi::Runtime& runtime, - const std::string& methodName, - const jsi::Value* args, - size_t count); + jsi::Value invokeMethod(jsi::Runtime &runtime, const std::string &methodName, const jsi::Value *args, size_t count); private: std::vector cxxMethods_; diff --git a/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/TurboModule.h b/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/TurboModule.h index 478ba2d6226..59e852c2e5f 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/TurboModule.h +++ b/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/TurboModule.h @@ -36,9 +36,7 @@ enum TurboModuleMethodValueKind { /** * Determines TurboModuleMethodValueKind based on the jsi::Value type. */ -TurboModuleMethodValueKind getTurboModuleMethodValueKind( - jsi::Runtime& rt, - const jsi::Value* value); +TurboModuleMethodValueKind getTurboModuleMethodValueKind(jsi::Runtime &rt, const jsi::Value *value); class TurboCxxModule; class TurboModuleBinding; @@ -55,21 +53,20 @@ class JSI_EXPORT TurboModule : public jsi::HostObject { // JS representation. To customize lookup of properties, override `create`. // Note: keep this method declared inline to avoid conflicts // between RTTI and non-RTTI compilation units - jsi::Value get(jsi::Runtime& runtime, const jsi::PropNameID& propName) - override { + jsi::Value get(jsi::Runtime &runtime, const jsi::PropNameID &propName) override + { auto prop = create(runtime, propName); // If we have a JS wrapper, cache the result of this lookup // We don't cache misses, to allow for methodMap_ to dynamically be // extended if (jsRepresentation_ && !prop.isUndefined()) { - jsRepresentation_->lock(runtime).asObject(runtime).setProperty( - runtime, propName, prop); + jsRepresentation_->lock(runtime).asObject(runtime).setProperty(runtime, propName, prop); } return prop; } - std::vector getPropertyNames( - jsi::Runtime& runtime) override { + std::vector getPropertyNames(jsi::Runtime &runtime) override + { std::vector result; result.reserve(methodMap_.size()); for (auto it = methodMap_.cbegin(); it != methodMap_.cend(); ++it) { @@ -84,20 +81,14 @@ class JSI_EXPORT TurboModule : public jsi::HostObject { struct MethodMetadata { size_t argCount; - jsi::Value (*invoker)( - jsi::Runtime& rt, - TurboModule& turboModule, - const jsi::Value* args, - size_t count); + jsi::Value (*invoker)(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value *args, size_t count); }; std::unordered_map methodMap_; friend class TurboModuleTestFixtureInternal; - std::unordered_map> - eventEmitterMap_; + std::unordered_map> eventEmitterMap_; - using ArgFactory = - std::function& args)>; + using ArgFactory = std::function &args)>; /** * Calls RCTDeviceEventEmitter.emit to JavaScript, with given event name and @@ -111,35 +102,31 @@ class JSI_EXPORT TurboModule : public jsi::HostObject { * args.emplace_back(jsi::Value(42)); * }); */ - void emitDeviceEvent( - const std::string& eventName, - ArgFactory&& argFactory = nullptr); + void emitDeviceEvent(const std::string &eventName, ArgFactory &&argFactory = nullptr); // Backwards compatibility version void emitDeviceEvent( - jsi::Runtime& /*runtime*/, + jsi::Runtime & /*runtime*/, - const std::string& eventName, - ArgFactory&& argFactory = nullptr) { + const std::string &eventName, + ArgFactory &&argFactory = nullptr) + { emitDeviceEvent(eventName, std::move(argFactory)); } - virtual jsi::Value create( - jsi::Runtime& runtime, - const jsi::PropNameID& propName) { + virtual jsi::Value create(jsi::Runtime &runtime, const jsi::PropNameID &propName) + { std::string propNameUtf8 = propName.utf8(runtime); - if (auto methodIter = methodMap_.find(propNameUtf8); - methodIter != methodMap_.end()) { - const MethodMetadata& meta = methodIter->second; + if (auto methodIter = methodMap_.find(propNameUtf8); methodIter != methodMap_.end()) { + const MethodMetadata &meta = methodIter->second; return jsi::Function::createFromHostFunction( runtime, propName, static_cast(meta.argCount), [this, meta]( - jsi::Runtime& rt, - [[maybe_unused]] const jsi::Value& thisVal, - const jsi::Value* args, - size_t count) { return meta.invoker(rt, *this, args, count); }); + jsi::Runtime &rt, [[maybe_unused]] const jsi::Value &thisVal, const jsi::Value *args, size_t count) { + return meta.invoker(rt, *this, args, count); + }); } else if (auto eventEmitterIter = eventEmitterMap_.find(propNameUtf8); eventEmitterIter != eventEmitterMap_.end()) { return eventEmitterIter->second->get(runtime, jsInvoker_); @@ -158,7 +145,6 @@ class JSI_EXPORT TurboModule : public jsi::HostObject { * An app/platform-specific provider function to get an instance of a module * given a name. */ -using TurboModuleProviderFunctionType = - std::function(const std::string& name)>; +using TurboModuleProviderFunctionType = std::function(const std::string &name)>; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/TurboModuleBinding.h b/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/TurboModuleBinding.h index 0ed5c2b4da7..a4a7ef22211 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/TurboModuleBinding.h +++ b/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/TurboModuleBinding.h @@ -28,15 +28,14 @@ class TurboModuleBinding { * Thread synchronization must be enforced externally. */ static void install( - jsi::Runtime& runtime, - TurboModuleProviderFunctionType&& moduleProvider, - TurboModuleProviderFunctionType&& legacyModuleProvider = nullptr, - std::shared_ptr longLivedObjectCollection = - nullptr); + jsi::Runtime &runtime, + TurboModuleProviderFunctionType &&moduleProvider, + TurboModuleProviderFunctionType &&legacyModuleProvider = nullptr, + std::shared_ptr longLivedObjectCollection = nullptr); TurboModuleBinding( - jsi::Runtime& runtime, - TurboModuleProviderFunctionType&& moduleProvider, + jsi::Runtime &runtime, + TurboModuleProviderFunctionType &&moduleProvider, std::shared_ptr longLivedObjectCollection); virtual ~TurboModuleBinding(); @@ -48,10 +47,9 @@ class TurboModuleBinding { * A lookup function exposed to JS to get an instance of a TurboModule * for the given name. */ - jsi::Value getModule(jsi::Runtime& runtime, const std::string& moduleName) - const; + jsi::Value getModule(jsi::Runtime &runtime, const std::string &moduleName) const; - jsi::Runtime& runtime_; + jsi::Runtime &runtime_; TurboModuleProviderFunctionType moduleProvider_; std::shared_ptr longLivedObjectCollection_; }; diff --git a/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/TurboModulePerfLogger.h b/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/TurboModulePerfLogger.h index 8a7d1c9edba..06c2045741e 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/TurboModulePerfLogger.h +++ b/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/TurboModulePerfLogger.h @@ -11,71 +11,57 @@ #include namespace facebook::react::TurboModulePerfLogger { -void enableLogging(std::unique_ptr&& logger); +void enableLogging(std::unique_ptr &&logger); void disableLogging(); -void moduleDataCreateStart(const char* moduleName, int32_t id); -void moduleDataCreateEnd(const char* moduleName, int32_t id); +void moduleDataCreateStart(const char *moduleName, int32_t id); +void moduleDataCreateEnd(const char *moduleName, int32_t id); /** * Create NativeModule platform object */ -void moduleCreateStart(const char* moduleName, int32_t id); -void moduleCreateCacheHit(const char* moduleName, int32_t id); -void moduleCreateConstructStart(const char* moduleName, int32_t id); -void moduleCreateConstructEnd(const char* moduleName, int32_t id); -void moduleCreateSetUpStart(const char* moduleName, int32_t id); -void moduleCreateSetUpEnd(const char* moduleName, int32_t id); -void moduleCreateEnd(const char* moduleName, int32_t id); -void moduleCreateFail(const char* moduleName, int32_t id); +void moduleCreateStart(const char *moduleName, int32_t id); +void moduleCreateCacheHit(const char *moduleName, int32_t id); +void moduleCreateConstructStart(const char *moduleName, int32_t id); +void moduleCreateConstructEnd(const char *moduleName, int32_t id); +void moduleCreateSetUpStart(const char *moduleName, int32_t id); +void moduleCreateSetUpEnd(const char *moduleName, int32_t id); +void moduleCreateEnd(const char *moduleName, int32_t id); +void moduleCreateFail(const char *moduleName, int32_t id); /** * JS require beginning */ -void moduleJSRequireBeginningStart(const char* moduleName); -void moduleJSRequireBeginningCacheHit(const char* moduleName); -void moduleJSRequireBeginningEnd(const char* moduleName); -void moduleJSRequireBeginningFail(const char* moduleName); +void moduleJSRequireBeginningStart(const char *moduleName); +void moduleJSRequireBeginningCacheHit(const char *moduleName); +void moduleJSRequireBeginningEnd(const char *moduleName); +void moduleJSRequireBeginningFail(const char *moduleName); /** * JS require ending */ -void moduleJSRequireEndingStart(const char* moduleName); -void moduleJSRequireEndingEnd(const char* moduleName); -void moduleJSRequireEndingFail(const char* moduleName); +void moduleJSRequireEndingStart(const char *moduleName); +void moduleJSRequireEndingEnd(const char *moduleName); +void moduleJSRequireEndingFail(const char *moduleName); // Sync method calls -void syncMethodCallStart(const char* moduleName, const char* methodName); -void syncMethodCallArgConversionStart( - const char* moduleName, - const char* methodName); -void syncMethodCallArgConversionEnd( - const char* moduleName, - const char* methodName); -void syncMethodCallExecutionStart( - const char* moduleName, - const char* methodName); -void syncMethodCallExecutionEnd(const char* moduleName, const char* methodName); -void syncMethodCallReturnConversionStart( - const char* moduleName, - const char* methodName); -void syncMethodCallReturnConversionEnd( - const char* moduleName, - const char* methodName); -void syncMethodCallEnd(const char* moduleName, const char* methodName); -void syncMethodCallFail(const char* moduleName, const char* methodName); +void syncMethodCallStart(const char *moduleName, const char *methodName); +void syncMethodCallArgConversionStart(const char *moduleName, const char *methodName); +void syncMethodCallArgConversionEnd(const char *moduleName, const char *methodName); +void syncMethodCallExecutionStart(const char *moduleName, const char *methodName); +void syncMethodCallExecutionEnd(const char *moduleName, const char *methodName); +void syncMethodCallReturnConversionStart(const char *moduleName, const char *methodName); +void syncMethodCallReturnConversionEnd(const char *moduleName, const char *methodName); +void syncMethodCallEnd(const char *moduleName, const char *methodName); +void syncMethodCallFail(const char *moduleName, const char *methodName); // Async method calls -void asyncMethodCallStart(const char* moduleName, const char* methodName); -void asyncMethodCallArgConversionStart( - const char* moduleName, - const char* methodName); -void asyncMethodCallArgConversionEnd( - const char* moduleName, - const char* methodName); -void asyncMethodCallDispatch(const char* moduleName, const char* methodName); -void asyncMethodCallEnd(const char* moduleName, const char* methodName); -void asyncMethodCallFail(const char* moduleName, const char* methodName); +void asyncMethodCallStart(const char *moduleName, const char *methodName); +void asyncMethodCallArgConversionStart(const char *moduleName, const char *methodName); +void asyncMethodCallArgConversionEnd(const char *moduleName, const char *methodName); +void asyncMethodCallDispatch(const char *moduleName, const char *methodName); +void asyncMethodCallEnd(const char *moduleName, const char *methodName); +void asyncMethodCallFail(const char *moduleName, const char *methodName); /** * Pre-processing async method call batch @@ -84,25 +70,10 @@ void asyncMethodCallBatchPreprocessStart(); void asyncMethodCallBatchPreprocessEnd(int batchSize); // Async method call execution -void asyncMethodCallExecutionStart( - const char* moduleName, - const char* methodName, - int32_t id); -void asyncMethodCallExecutionArgConversionStart( - const char* moduleName, - const char* methodName, - int32_t id); -void asyncMethodCallExecutionArgConversionEnd( - const char* moduleName, - const char* methodName, - int32_t id); -void asyncMethodCallExecutionEnd( - const char* moduleName, - const char* methodName, - int32_t id); -void asyncMethodCallExecutionFail( - const char* moduleName, - const char* methodName, - int32_t id); +void asyncMethodCallExecutionStart(const char *moduleName, const char *methodName, int32_t id); +void asyncMethodCallExecutionArgConversionStart(const char *moduleName, const char *methodName, int32_t id); +void asyncMethodCallExecutionArgConversionEnd(const char *moduleName, const char *methodName, int32_t id); +void asyncMethodCallExecutionEnd(const char *moduleName, const char *methodName, int32_t id); +void asyncMethodCallExecutionFail(const char *moduleName, const char *methodName, int32_t id); } // namespace facebook::react::TurboModulePerfLogger diff --git a/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/TurboModuleUtils.h b/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/TurboModuleUtils.h index 7968611db99..0c436aa13d7 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/TurboModuleUtils.h +++ b/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/TurboModuleUtils.h @@ -16,19 +16,16 @@ namespace facebook::react { struct Promise : public LongLivedObject { - Promise(jsi::Runtime& rt, jsi::Function resolve, jsi::Function reject); + Promise(jsi::Runtime &rt, jsi::Function resolve, jsi::Function reject); - void resolve(const jsi::Value& result); - void reject(const std::string& message); + void resolve(const jsi::Value &result); + void reject(const std::string &message); jsi::Function resolve_; jsi::Function reject_; }; -using PromiseSetupFunctionType = - std::function)>; -jsi::Value createPromiseAsJSIValue( - jsi::Runtime& rt, - PromiseSetupFunctionType&& func); +using PromiseSetupFunctionType = std::function)>; +jsi::Value createPromiseAsJSIValue(jsi::Runtime &rt, PromiseSetupFunctionType &&func); } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/TurboModuleWithJSIBindings.h b/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/TurboModuleWithJSIBindings.h index c7c912a6ad7..205297aa83b 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/TurboModuleWithJSIBindings.h +++ b/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/TurboModuleWithJSIBindings.h @@ -18,12 +18,10 @@ class TurboModuleWithJSIBindings { public: virtual ~TurboModuleWithJSIBindings() = default; - static void installJSIBindings( - const std::shared_ptr& cxxModule, - jsi::Runtime& runtime); + static void installJSIBindings(const std::shared_ptr &cxxModule, jsi::Runtime &runtime); private: - virtual void installJSIBindingsWithRuntime(jsi::Runtime& runtime) = 0; + virtual void installJSIBindingsWithRuntime(jsi::Runtime &runtime) = 0; }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/nativemodule/core/platform/android/ReactCommon/JavaInteropTurboModule.h b/packages/react-native/ReactCommon/react/nativemodule/core/platform/android/ReactCommon/JavaInteropTurboModule.h index 2eb706d7323..c70923bc936 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/core/platform/android/ReactCommon/JavaInteropTurboModule.h +++ b/packages/react-native/ReactCommon/react/nativemodule/core/platform/android/ReactCommon/JavaInteropTurboModule.h @@ -28,22 +28,20 @@ class JSI_EXPORT JavaInteropTurboModule : public JavaTurboModule { }; JavaInteropTurboModule( - const JavaTurboModule::InitParams& params, - const std::vector& methodDescriptors); + const JavaTurboModule::InitParams ¶ms, + const std::vector &methodDescriptors); - std::vector getPropertyNames( - facebook::jsi::Runtime& runtime) override; + std::vector getPropertyNames(facebook::jsi::Runtime &runtime) override; protected: - jsi::Value create(jsi::Runtime& runtime, const jsi::PropNameID& propName) - override; + jsi::Value create(jsi::Runtime &runtime, const jsi::PropNameID &propName) override; private: std::vector methodDescriptors_; std::vector methodIDs_; jsi::Value constantsCache_; - const jsi::Value& getConstants(jsi::Runtime& runtime); + const jsi::Value &getConstants(jsi::Runtime &runtime); bool exportsConstants(); }; diff --git a/packages/react-native/ReactCommon/react/nativemodule/core/platform/android/ReactCommon/JavaTurboModule.h b/packages/react-native/ReactCommon/react/nativemodule/core/platform/android/ReactCommon/JavaTurboModule.h index 0674f617aeb..c42f1c7dbac 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/core/platform/android/ReactCommon/JavaTurboModule.h +++ b/packages/react-native/ReactCommon/react/nativemodule/core/platform/android/ReactCommon/JavaTurboModule.h @@ -18,14 +18,11 @@ namespace facebook::react { struct JTurboModule : jni::JavaClass { - static auto constexpr kJavaDescriptor = - "Lcom/facebook/react/turbomodule/core/interfaces/TurboModule;"; + static auto constexpr kJavaDescriptor = "Lcom/facebook/react/turbomodule/core/interfaces/TurboModule;"; }; -struct JTurboModuleWithJSIBindings - : jni::JavaClass { - static auto constexpr kJavaDescriptor = - "Lcom/facebook/react/turbomodule/core/interfaces/TurboModuleWithJSIBindings;"; +struct JTurboModuleWithJSIBindings : jni::JavaClass { + static auto constexpr kJavaDescriptor = "Lcom/facebook/react/turbomodule/core/interfaces/TurboModuleWithJSIBindings;"; }; class JSI_EXPORT JavaTurboModule : public TurboModule { @@ -38,23 +35,23 @@ class JSI_EXPORT JavaTurboModule : public TurboModule { std::shared_ptr nativeMethodCallInvoker; }; - JavaTurboModule(const InitParams& params); + JavaTurboModule(const InitParams ¶ms); virtual ~JavaTurboModule(); jsi::Value invokeJavaMethod( - jsi::Runtime& runtime, + jsi::Runtime &runtime, TurboModuleMethodValueKind valueKind, - const std::string& methodName, - const std::string& methodSignature, - const jsi::Value* args, + const std::string &methodName, + const std::string &methodSignature, + const jsi::Value *args, size_t argCount, - jmethodID& cachedMethodID); + jmethodID &cachedMethodID); protected: void configureEventEmitterCallback(); - [[deprecated]] void setEventEmitterCallback( - jni::alias_ref /*unused*/) { + [[deprecated]] void setEventEmitterCallback(jni::alias_ref /*unused*/) + { configureEventEmitterCallback(); } diff --git a/packages/react-native/ReactCommon/react/nativemodule/core/platform/ios/ReactCommon/RCTInteropTurboModule.mm b/packages/react-native/ReactCommon/react/nativemodule/core/platform/ios/ReactCommon/RCTInteropTurboModule.mm index bdf4c397ef5..da0b87f995a 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/core/platform/ios/ReactCommon/RCTInteropTurboModule.mm +++ b/packages/react-native/ReactCommon/react/nativemodule/core/platform/ios/ReactCommon/RCTInteropTurboModule.mm @@ -511,8 +511,9 @@ void ObjCInteropTurboModule::setInvocationArg( return; } - const char *BLOCK_TYPE = @encode(__typeof__(^{ - })); + const char *BLOCK_TYPE = @encode( + __typeof__(^{ + })); if (objCArgType == BLOCK_TYPE) { /** diff --git a/packages/react-native/ReactCommon/react/nativemodule/core/tests/TurboModuleTestFixture.h b/packages/react-native/ReactCommon/react/nativemodule/core/tests/TurboModuleTestFixture.h index c98f0595fb5..7043bb30a13 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/core/tests/TurboModuleTestFixture.h +++ b/packages/react-native/ReactCommon/react/nativemodule/core/tests/TurboModuleTestFixture.h @@ -20,35 +20,34 @@ namespace facebook::react { class TurboModuleTestFixtureInternal { public: - static bool containsEventEmitter( - TurboModule& turboModule, - const std::string& eventEmitterName) { + static bool containsEventEmitter(TurboModule &turboModule, const std::string &eventEmitterName) + { return turboModule.eventEmitterMap_.contains(eventEmitterName); } static const std::shared_ptr getEventEmitter( - TurboModule& turboModule, - const std::string& eventEmitterName) { + TurboModule &turboModule, + const std::string &eventEmitterName) + { return turboModule.eventEmitterMap_.at(eventEmitterName); } }; template -class TurboModuleTestFixture : public TurboModuleTestFixtureInternal, - public ::testing::Test { - static_assert( - std::is_base_of::value, - "T must be derived from TurboModule"); +class TurboModuleTestFixture : public TurboModuleTestFixtureInternal, public ::testing::Test { + static_assert(std::is_base_of::value, "T must be derived from TurboModule"); public: explicit TurboModuleTestFixture(Args... args) : runtime_(hermes::makeHermesRuntime()), jsInvoker_(std::make_shared(*runtime_)), - module_(std::make_shared(jsInvoker_, std::forward(args)...)) {} + module_(std::make_shared(jsInvoker_, std::forward(args)...)) + { + } - void SetUp() override { - auto setImmediateName = - jsi::PropNameID::forAscii(*runtime_, "setImmediate"); + void SetUp() override + { + auto setImmediateName = jsi::PropNameID::forAscii(*runtime_, "setImmediate"); runtime_->global().setProperty( *runtime_, setImmediateName, @@ -57,13 +56,9 @@ class TurboModuleTestFixture : public TurboModuleTestFixtureInternal, setImmediateName, 1, [jsInvoker = jsInvoker_]( - jsi::Runtime& rt, - [[maybe_unused]] const jsi::Value& thisVal, - const jsi::Value* args, - size_t count) { + jsi::Runtime &rt, [[maybe_unused]] const jsi::Value &thisVal, const jsi::Value *args, size_t count) { react_native_assert(count >= 1); - jsInvoker->invokeAsync([cb = std::make_shared( - rt, args[0])](jsi::Runtime& rt) { + jsInvoker->invokeAsync([cb = std::make_shared(rt, args[0])](jsi::Runtime &rt) { cb->asObject(rt).asFunction(rt).call(rt); }); return jsi::Value::undefined(); @@ -71,54 +66,45 @@ class TurboModuleTestFixture : public TurboModuleTestFixtureInternal, } template - EventSubscription addEventEmitterListener( - jsi::Runtime& rt, - const std::string& eventEmitterName, - Listener&& listener) { + EventSubscription addEventEmitterListener(jsi::Runtime &rt, const std::string &eventEmitterName, Listener &&listener) + { EXPECT_TRUE(containsEventEmitter(*module_, eventEmitterName)); auto listenJs = bridging::toJs( rt, - [listener = std::forward(listener)]( - const EventType&... event) { listener(event...); }, + [listener = std::forward(listener)](const EventType &...event) { listener(event...); }, jsInvoker_); std::shared_ptr> eventEmitter = - std::static_pointer_cast>( - getEventEmitter(*module_, eventEmitterName)); + std::static_pointer_cast>(getEventEmitter(*module_, eventEmitterName)); jsi::Object eventEmitterJs = bridging::toJs(rt, *eventEmitter, jsInvoker_); auto eventSubscriptionJs = - jsi::Object(eventEmitterJs.asFunction(rt) - .callWithThis(rt, eventEmitterJs, listenJs) - .asObject(rt)); - return bridging::fromJs( - rt, eventSubscriptionJs, jsInvoker_); + jsi::Object(eventEmitterJs.asFunction(rt).callWithThis(rt, eventEmitterJs, listenJs).asObject(rt)); + return bridging::fromJs(rt, eventSubscriptionJs, jsInvoker_); } - void TearDown() override { + void TearDown() override + { module_ = nullptr; jsInvoker_ = nullptr; runtime_ = nullptr; } template - std::optional resolvePromise( - const AsyncPromise& asyncPromise) { + std::optional resolvePromise(const AsyncPromise &asyncPromise) + { auto promise = asyncPromise.get(*runtime_); std::optional result = std::nullopt; promise.getPropertyAsFunction(*runtime_, "then") .callWithThis( *runtime_, promise, - bridging::toJs( - *runtime_, - [&](TPromise value) { result = std::move(value); }, - jsInvoker_)); + bridging::toJs(*runtime_, [&](TPromise value) { result = std::move(value); }, jsInvoker_)); jsInvoker_->flushQueue(); return result; } template - std::optional handleError( - const AsyncPromise& asyncPromise) { + std::optional handleError(const AsyncPromise &asyncPromise) + { auto promise = asyncPromise.get(*runtime_); std::optional message; promise.getPropertyAsFunction(*runtime_, "catch") @@ -128,10 +114,8 @@ class TurboModuleTestFixture : public TurboModuleTestFixtureInternal, bridging::toJs( *runtime_, [&](jsi::Object error) { - message = bridging::fromJs( - *runtime_, - error.getProperty(*runtime_, "message"), - jsInvoker_); + message = + bridging::fromJs(*runtime_, error.getProperty(*runtime_, "message"), jsInvoker_); }, jsInvoker_)); jsInvoker_->flushQueue(); @@ -139,28 +123,25 @@ class TurboModuleTestFixture : public TurboModuleTestFixtureInternal, } template - AsyncCallback makeAsyncCallback( - std::function&& callback) { + AsyncCallback makeAsyncCallback(std::function &&callback) + { auto func = jsi::Function::createFromHostFunction( *runtime_, jsi::PropNameID::forAscii(*runtime_, "callback"), 1, [jsInvoker = jsInvoker_, callback = std::move(callback)]( - jsi::Runtime& rt, - [[maybe_unused]] const jsi::Value& thisVal, - const jsi::Value* args, - size_t count) { + jsi::Runtime &rt, [[maybe_unused]] const jsi::Value &thisVal, const jsi::Value *args, size_t count) { if (count < 1) { throw jsi::JSINativeException("callback: Missing argument"); } - callback( - Bridging::fromJs(rt, args[0].asObject(rt), jsInvoker)); + callback(Bridging::fromJs(rt, args[0].asObject(rt), jsInvoker)); return jsi::Value::undefined(); }); return {*runtime_, std::move(func), jsInvoker_}; } - void expectAndFlushQueue(size_t queueSize) { + void expectAndFlushQueue(size_t queueSize) + { EXPECT_EQ(jsInvoker_->queueSize(), queueSize); jsInvoker_->flushQueue(); } diff --git a/packages/react-native/ReactCommon/react/nativemodule/cputime/CPUTime.h b/packages/react-native/ReactCommon/react/nativemodule/cputime/CPUTime.h index fa78ed5e616..4896a412cfc 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/cputime/CPUTime.h +++ b/packages/react-native/ReactCommon/react/nativemodule/cputime/CPUTime.h @@ -26,7 +26,8 @@ const double NANOSECONDS_IN_A_SECOND = 1000000000; #ifdef __MACH__ namespace { -inline double getConversionFactor() { +inline double getConversionFactor() +{ double conversionFactor; mach_timebase_info_data_t info; mach_timebase_info(&info); @@ -41,40 +42,42 @@ namespace facebook::react { #if defined USE_POSIX_TIME -inline double getCPUTimeNanos() { - struct timespec time {}; +inline double getCPUTimeNanos() +{ + struct timespec time{}; clock_gettime(CLOCK_THREAD_CPUTIME_ID, &time); - return static_cast(time.tv_sec) * NANOSECONDS_IN_A_SECOND + - static_cast(time.tv_nsec); + return static_cast(time.tv_sec) * NANOSECONDS_IN_A_SECOND + static_cast(time.tv_nsec); } -inline bool hasAccurateCPUTimeNanosForBenchmarks() { +inline bool hasAccurateCPUTimeNanosForBenchmarks() +{ return true; } #elif defined __MACH__ -inline double getCPUTimeNanos() { +inline double getCPUTimeNanos() +{ static auto conversionFactor = getConversionFactor(); uint64_t time = mach_absolute_time(); return static_cast(time) * conversionFactor; } -inline bool hasAccurateCPUTimeNanosForBenchmarks() { +inline bool hasAccurateCPUTimeNanosForBenchmarks() +{ return true; } #else -inline double getCPUTimeNanos() { +inline double getCPUTimeNanos() +{ auto now = std::chrono::steady_clock::now(); - return static_cast( - std::chrono::duration_cast( - now.time_since_epoch()) - .count()); + return static_cast(std::chrono::duration_cast(now.time_since_epoch()).count()); } -inline bool hasAccurateCPUTimeNanosForBenchmarks() { +inline bool hasAccurateCPUTimeNanosForBenchmarks() +{ return false; } diff --git a/packages/react-native/ReactCommon/react/nativemodule/cputime/NativeCPUTime.h b/packages/react-native/ReactCommon/react/nativemodule/cputime/NativeCPUTime.h index c6e60b4f666..2d4637b3439 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/cputime/NativeCPUTime.h +++ b/packages/react-native/ReactCommon/react/nativemodule/cputime/NativeCPUTime.h @@ -21,8 +21,8 @@ class NativeCPUTime : public NativeCPUTimeCxxSpec { public: explicit NativeCPUTime(std::shared_ptr jsInvoker); - double getCPUTimeNanos(jsi::Runtime& runtime); - bool hasAccurateCPUTimeNanosForBenchmarks(jsi::Runtime& runtime); + double getCPUTimeNanos(jsi::Runtime &runtime); + bool hasAccurateCPUTimeNanosForBenchmarks(jsi::Runtime &runtime); }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/nativemodule/defaults/DefaultTurboModules.h b/packages/react-native/ReactCommon/react/nativemodule/defaults/DefaultTurboModules.h index 4b5b905ec73..315e40e3366 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/defaults/DefaultTurboModules.h +++ b/packages/react-native/ReactCommon/react/nativemodule/defaults/DefaultTurboModules.h @@ -11,8 +11,8 @@ namespace facebook::react { struct DefaultTurboModules { static std::shared_ptr getTurboModule( - const std::string& name, - const std::shared_ptr& jsInvoker); + const std::string &name, + const std::shared_ptr &jsInvoker); }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/nativemodule/devtoolsruntimesettings/DevToolsRuntimeSettingsModule.h b/packages/react-native/ReactCommon/react/nativemodule/devtoolsruntimesettings/DevToolsRuntimeSettingsModule.h index ef674bcef30..41f986e0b67 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/devtoolsruntimesettings/DevToolsRuntimeSettingsModule.h +++ b/packages/react-native/ReactCommon/react/nativemodule/devtoolsruntimesettings/DevToolsRuntimeSettingsModule.h @@ -12,16 +12,13 @@ namespace facebook::react { class DevToolsRuntimeSettingsModule - : public NativeReactDevToolsRuntimeSettingsModuleCxxSpec< - DevToolsRuntimeSettingsModule> { + : public NativeReactDevToolsRuntimeSettingsModuleCxxSpec { public: DevToolsRuntimeSettingsModule(std::shared_ptr jsInvoker); - void setReloadAndProfileConfig( - jsi::Runtime& rt, - NativePartialReloadAndProfileConfig config); + void setReloadAndProfileConfig(jsi::Runtime &rt, NativePartialReloadAndProfileConfig config); - NativeReloadAndProfileConfig getReloadAndProfileConfig(jsi::Runtime& rt); + NativeReloadAndProfileConfig getReloadAndProfileConfig(jsi::Runtime &rt); }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/nativemodule/dom/NativeDOM.h b/packages/react-native/ReactCommon/react/nativemodule/dom/NativeDOM.h index 1c6a1c84e7b..19157a9cd9d 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/dom/NativeDOM.h +++ b/packages/react-native/ReactCommon/react/nativemodule/dom/NativeDOM.h @@ -21,14 +21,11 @@ namespace facebook::react { -using MeasureOnSuccessCallback = - SyncCallback; +using MeasureOnSuccessCallback = SyncCallback; -using MeasureInWindowOnSuccessCallback = - SyncCallback; +using MeasureInWindowOnSuccessCallback = SyncCallback; -using MeasureLayoutOnSuccessCallback = - SyncCallback; +using MeasureLayoutOnSuccessCallback = SyncCallback; class NativeDOM : public NativeDOMCxxSpec { public: @@ -36,21 +33,15 @@ class NativeDOM : public NativeDOMCxxSpec { #pragma mark - Methods from the `Node` interface (for `ReadOnlyNode`). - double compareDocumentPosition( - jsi::Runtime& rt, - jsi::Value nativeNodeReference, - jsi::Value otherNativeNodeReference); + double compareDocumentPosition(jsi::Runtime &rt, jsi::Value nativeNodeReference, jsi::Value otherNativeNodeReference); - std::vector getChildNodes( - jsi::Runtime& rt, - jsi::Value nativeNodeReference); + std::vector getChildNodes(jsi::Runtime &rt, jsi::Value nativeNodeReference); - jsi::Value - getElementById(jsi::Runtime& rt, SurfaceId surfaceId, const std::string& id); + jsi::Value getElementById(jsi::Runtime &rt, SurfaceId surfaceId, const std::string &id); - jsi::Value getParentNode(jsi::Runtime& rt, jsi::Value nativeNodeReference); + jsi::Value getParentNode(jsi::Runtime &rt, jsi::Value nativeNodeReference); - bool isConnected(jsi::Runtime& rt, jsi::Value nativeNodeReference); + bool isConnected(jsi::Runtime &rt, jsi::Value nativeNodeReference); #pragma mark - Methods from the `Element` interface (for `ReactNativeElement`). @@ -58,97 +49,68 @@ class NativeDOM : public NativeDOMCxxSpec { /* topWidth: */ int, /* rightWidth: */ int, /* bottomWidth: */ int, - /* leftWidth: */ int> - getBorderWidth( - jsi::Runtime& rt, - std::shared_ptr shadowNode); + /* leftWidth: */ int> getBorderWidth(jsi::Runtime &rt, std::shared_ptr shadowNode); std::tuple< /* x: */ double, /* y: */ double, /* width: */ double, /* height: */ double> - getBoundingClientRect( - jsi::Runtime& rt, - std::shared_ptr shadowNode, - bool includeTransform); + getBoundingClientRect(jsi::Runtime &rt, std::shared_ptr shadowNode, bool includeTransform); std::tuple getInnerSize( - jsi::Runtime& rt, + jsi::Runtime &rt, std::shared_ptr shadowNode); - std::tuple - getScrollPosition( - jsi::Runtime& rt, + std::tuple getScrollPosition( + jsi::Runtime &rt, std::shared_ptr shadowNode); std::tuple getScrollSize( - jsi::Runtime& rt, + jsi::Runtime &rt, std::shared_ptr shadowNode); - std::string getTagName( - jsi::Runtime& rt, - std::shared_ptr shadowNode); + std::string getTagName(jsi::Runtime &rt, std::shared_ptr shadowNode); - std::string getTextContent( - jsi::Runtime& rt, - std::shared_ptr shadowNode); + std::string getTextContent(jsi::Runtime &rt, std::shared_ptr shadowNode); - bool hasPointerCapture( - jsi::Runtime& rt, - std::shared_ptr shadowNode, - double pointerId); + bool hasPointerCapture(jsi::Runtime &rt, std::shared_ptr shadowNode, double pointerId); - void releasePointerCapture( - jsi::Runtime& rt, - std::shared_ptr shadowNode, - double pointerId); + void releasePointerCapture(jsi::Runtime &rt, std::shared_ptr shadowNode, double pointerId); - void setPointerCapture( - jsi::Runtime& rt, - std::shared_ptr shadowNode, - double pointerId); + void setPointerCapture(jsi::Runtime &rt, std::shared_ptr shadowNode, double pointerId); #pragma mark - Methods from the `HTMLElement` interface (for `ReactNativeElement`). std::tuple< /* offsetParent: */ jsi::Value, /* top: */ double, - /* left: */ double> - getOffset(jsi::Runtime& rt, std::shared_ptr shadowNode); + /* left: */ double> getOffset(jsi::Runtime &rt, std::shared_ptr shadowNode); #pragma mark - Special methods to handle the root node. - jsi::Value linkRootNode( - jsi::Runtime& rt, - SurfaceId surfaceId, - jsi::Value instanceHandle); + jsi::Value linkRootNode(jsi::Runtime &rt, SurfaceId surfaceId, jsi::Value instanceHandle); #pragma mark - Legacy layout APIs (for `ReactNativeElement`). - void measure( - jsi::Runtime& rt, - std::shared_ptr shadowNode, - const MeasureOnSuccessCallback& callback); + void + measure(jsi::Runtime &rt, std::shared_ptr shadowNode, const MeasureOnSuccessCallback &callback); void measureInWindow( - jsi::Runtime& rt, + jsi::Runtime &rt, std::shared_ptr shadowNode, - const MeasureInWindowOnSuccessCallback& callback); + const MeasureInWindowOnSuccessCallback &callback); void measureLayout( - jsi::Runtime& rt, + jsi::Runtime &rt, std::shared_ptr shadowNode, std::shared_ptr relativeToShadowNode, jsi::Function onFail, - const MeasureLayoutOnSuccessCallback& onSuccess); + const MeasureLayoutOnSuccessCallback &onSuccess); #pragma mark - Legacy direct manipulation APIs (for `ReactNativeElement`). - void setNativeProps( - jsi::Runtime& rt, - std::shared_ptr shadowNode, - jsi::Value updatePayload); + void setNativeProps(jsi::Runtime &rt, std::shared_ptr shadowNode, jsi::Value updatePayload); }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/nativemodule/fantomtestspecificmethods/NativeFantomTestSpecificMethods.h b/packages/react-native/ReactCommon/react/nativemodule/fantomtestspecificmethods/NativeFantomTestSpecificMethods.h index 164f9e53588..a82fa536122 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/fantomtestspecificmethods/NativeFantomTestSpecificMethods.h +++ b/packages/react-native/ReactCommon/react/nativemodule/fantomtestspecificmethods/NativeFantomTestSpecificMethods.h @@ -13,16 +13,13 @@ namespace facebook::react { struct FantomForcedCloneCommitHook; -class NativeFantomTestSpecificMethods - : public NativeFantomTestSpecificMethodsCxxSpec< - NativeFantomTestSpecificMethods> { +class NativeFantomTestSpecificMethods : public NativeFantomTestSpecificMethodsCxxSpec { public: - explicit NativeFantomTestSpecificMethods( - std::shared_ptr jsInvoker); + explicit NativeFantomTestSpecificMethods(std::shared_ptr jsInvoker); - void registerForcedCloneCommitHook(jsi::Runtime& runtime); + void registerForcedCloneCommitHook(jsi::Runtime &runtime); - void takeFunctionAndNoop(jsi::Runtime& runtime, jsi::Function callback); + void takeFunctionAndNoop(jsi::Runtime &runtime, jsi::Function callback); private: std::shared_ptr fantomForcedCloneCommitHook_{}; diff --git a/packages/react-native/ReactCommon/react/nativemodule/fantomtestspecificmethods/internal/FantomForcedCloneCommitHook.h b/packages/react-native/ReactCommon/react/nativemodule/fantomtestspecificmethods/internal/FantomForcedCloneCommitHook.h index 85ca4d5d352..66c537f9f4a 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/fantomtestspecificmethods/internal/FantomForcedCloneCommitHook.h +++ b/packages/react-native/ReactCommon/react/nativemodule/fantomtestspecificmethods/internal/FantomForcedCloneCommitHook.h @@ -14,16 +14,14 @@ namespace facebook::react { struct FantomForcedCloneCommitHook : public UIManagerCommitHook { - void commitHookWasRegistered( - const UIManager& /*uiManager*/) noexcept override; + void commitHookWasRegistered(const UIManager & /*uiManager*/) noexcept override; - void commitHookWasUnregistered( - const UIManager& /*uiManager*/) noexcept override; + void commitHookWasUnregistered(const UIManager & /*uiManager*/) noexcept override; RootShadowNode::Unshared shadowTreeWillCommit( - const ShadowTree& shadowTree, - const std::shared_ptr& oldRootShadowNode, - const RootShadowNode::Unshared& newRootShadowNode) noexcept override; + const ShadowTree &shadowTree, + const std::shared_ptr &oldRootShadowNode, + const RootShadowNode::Unshared &newRootShadowNode) noexcept override; }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/nativemodule/idlecallbacks/NativeIdleCallbacks.h b/packages/react-native/ReactCommon/react/nativemodule/idlecallbacks/NativeIdleCallbacks.h index 5fe2c126db5..8ac5fc627c2 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/idlecallbacks/NativeIdleCallbacks.h +++ b/packages/react-native/ReactCommon/react/nativemodule/idlecallbacks/NativeIdleCallbacks.h @@ -17,25 +17,21 @@ namespace facebook::react { using CallbackHandle = jsi::Object; -using NativeRequestIdleCallbackOptions = - NativeIdleCallbacksRequestIdleCallbackOptions< - std::optional>; +using NativeRequestIdleCallbackOptions = NativeIdleCallbacksRequestIdleCallbackOptions>; template <> struct Bridging - : NativeIdleCallbacksRequestIdleCallbackOptionsBridging< - NativeRequestIdleCallbackOptions> {}; + : NativeIdleCallbacksRequestIdleCallbackOptionsBridging {}; -class NativeIdleCallbacks - : public NativeIdleCallbacksCxxSpec { +class NativeIdleCallbacks : public NativeIdleCallbacksCxxSpec { public: NativeIdleCallbacks(std::shared_ptr jsInvoker); CallbackHandle requestIdleCallback( - jsi::Runtime& runtime, - SyncCallback&& callback, + jsi::Runtime &runtime, + SyncCallback &&callback, std::optional options); - void cancelIdleCallback(jsi::Runtime& runtime, jsi::Object handle); + void cancelIdleCallback(jsi::Runtime &runtime, jsi::Object handle); }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/nativemodule/intersectionobserver/NativeIntersectionObserver.h b/packages/react-native/ReactCommon/react/nativemodule/intersectionobserver/NativeIntersectionObserver.h index 65c1e443aa2..dc399a5201e 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/intersectionobserver/NativeIntersectionObserver.h +++ b/packages/react-native/ReactCommon/react/nativemodule/intersectionobserver/NativeIntersectionObserver.h @@ -19,78 +19,67 @@ namespace facebook::react { using NativeIntersectionObserverIntersectionObserverId = int32_t; using RectAsTuple = std::tuple; -using NativeIntersectionObserverObserveOptions = - NativeIntersectionObserverNativeIntersectionObserverObserveOptions< - // intersectionObserverId - NativeIntersectionObserverIntersectionObserverId, - // rootShadowNode - std::optional>, - // targetShadowNode - std::shared_ptr, - // thresholds - std::vector, - // rootThresholds - std::optional>, - // rootMargin - std::optional>; +using NativeIntersectionObserverObserveOptions = NativeIntersectionObserverNativeIntersectionObserverObserveOptions< + // intersectionObserverId + NativeIntersectionObserverIntersectionObserverId, + // rootShadowNode + std::optional>, + // targetShadowNode + std::shared_ptr, + // thresholds + std::vector, + // rootThresholds + std::optional>, + // rootMargin + std::optional>; template <> struct Bridging : NativeIntersectionObserverNativeIntersectionObserverObserveOptionsBridging< NativeIntersectionObserverObserveOptions> {}; -using NativeIntersectionObserverEntry = - NativeIntersectionObserverNativeIntersectionObserverEntry< - // intersectionObserverId - NativeIntersectionObserverIntersectionObserverId, - // targetInstanceHandle - jsi::Value, - // targetRect - RectAsTuple, - // rootRect - RectAsTuple, - // intersectionRect - RectAsTuple, - // isIntersectingAboveThresholds - bool, - // time - HighResTimeStamp>; +using NativeIntersectionObserverEntry = NativeIntersectionObserverNativeIntersectionObserverEntry< + // intersectionObserverId + NativeIntersectionObserverIntersectionObserverId, + // targetInstanceHandle + jsi::Value, + // targetRect + RectAsTuple, + // rootRect + RectAsTuple, + // intersectionRect + RectAsTuple, + // isIntersectingAboveThresholds + bool, + // time + HighResTimeStamp>; template <> struct Bridging - : NativeIntersectionObserverNativeIntersectionObserverEntryBridging< - NativeIntersectionObserverEntry> {}; + : NativeIntersectionObserverNativeIntersectionObserverEntryBridging {}; -class NativeIntersectionObserver - : public NativeIntersectionObserverCxxSpec { +class NativeIntersectionObserver : public NativeIntersectionObserverCxxSpec { public: NativeIntersectionObserver(std::shared_ptr jsInvoker); - jsi::Object observeV2( - jsi::Runtime& runtime, - NativeIntersectionObserverObserveOptions options); + jsi::Object observeV2(jsi::Runtime &runtime, NativeIntersectionObserverObserveOptions options); - void unobserveV2( - jsi::Runtime& runtime, - IntersectionObserverObserverId intersectionObserverId, - jsi::Object targetToken); + void + unobserveV2(jsi::Runtime &runtime, IntersectionObserverObserverId intersectionObserverId, jsi::Object targetToken); - void connect( - jsi::Runtime& runtime, - AsyncCallback<> notifyIntersectionObserversCallback); + void connect(jsi::Runtime &runtime, AsyncCallback<> notifyIntersectionObserversCallback); - void disconnect(jsi::Runtime& runtime); + void disconnect(jsi::Runtime &runtime); - std::vector takeRecords( - jsi::Runtime& runtime); + std::vector takeRecords(jsi::Runtime &runtime); private: IntersectionObserverManager intersectionObserverManager_{}; - static UIManager& getUIManagerFromRuntime(jsi::Runtime& runtime); + static UIManager &getUIManagerFromRuntime(jsi::Runtime &runtime); static NativeIntersectionObserverEntry convertToNativeModuleEntry( - const IntersectionObserverEntry& entry, - jsi::Runtime& runtime); + const IntersectionObserverEntry &entry, + jsi::Runtime &runtime); }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/nativemodule/microtasks/NativeMicrotasks.h b/packages/react-native/ReactCommon/react/nativemodule/microtasks/NativeMicrotasks.h index 44068b8c96f..40b6949ea77 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/microtasks/NativeMicrotasks.h +++ b/packages/react-native/ReactCommon/react/nativemodule/microtasks/NativeMicrotasks.h @@ -19,7 +19,7 @@ class NativeMicrotasks : public NativeMicrotasksCxxSpec { public: NativeMicrotasks(std::shared_ptr jsInvoker); - void queueMicrotask(jsi::Runtime& runtime, jsi::Function callback); + void queueMicrotask(jsi::Runtime &runtime, jsi::Function callback); }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/nativemodule/mutationobserver/NativeMutationObserver.cpp b/packages/react-native/ReactCommon/react/nativemodule/mutationobserver/NativeMutationObserver.cpp index f15b741178a..1dab573fafc 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/mutationobserver/NativeMutationObserver.cpp +++ b/packages/react-native/ReactCommon/react/nativemodule/mutationobserver/NativeMutationObserver.cpp @@ -113,13 +113,14 @@ void NativeMutationObserver::onMutations(std::vector& records) { TraceSection s("NativeMutationObserver::onMutations"); for (const auto& record : records) { - pendingRecords_.emplace_back(NativeMutationRecord{ - record.mutationObserverId, - // FIXME(T157129303) Instead of assuming we can call into JS from here, - // we should use an API that explicitly indicates it. - getPublicInstanceFromShadowNode(*record.targetShadowNode), - getPublicInstancesFromShadowNodes(record.addedShadowNodes), - getPublicInstancesFromShadowNodes(record.removedShadowNodes)}); + pendingRecords_.emplace_back( + NativeMutationRecord{ + record.mutationObserverId, + // FIXME(T157129303) Instead of assuming we can call into JS from + // here, we should use an API that explicitly indicates it. + getPublicInstanceFromShadowNode(*record.targetShadowNode), + getPublicInstancesFromShadowNodes(record.addedShadowNodes), + getPublicInstancesFromShadowNodes(record.removedShadowNodes)}); } notifyMutationObserversIfNecessary(); diff --git a/packages/react-native/ReactCommon/react/nativemodule/mutationobserver/NativeMutationObserver.h b/packages/react-native/ReactCommon/react/nativemodule/mutationobserver/NativeMutationObserver.h index 8601276d383..bbb5737e90c 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/mutationobserver/NativeMutationObserver.h +++ b/packages/react-native/ReactCommon/react/nativemodule/mutationobserver/NativeMutationObserver.h @@ -15,19 +15,17 @@ namespace facebook::react { -using NativeMutationObserverObserveOptions = - NativeMutationObserverNativeMutationObserverObserveOptions< - // mutationObserverId - MutationObserverId, - // targetShadowNode - std::shared_ptr, - // subtree - bool>; +using NativeMutationObserverObserveOptions = NativeMutationObserverNativeMutationObserverObserveOptions< + // mutationObserverId + MutationObserverId, + // targetShadowNode + std::shared_ptr, + // subtree + bool>; template <> struct Bridging - : NativeMutationObserverNativeMutationObserverObserveOptionsBridging< - NativeMutationObserverObserveOptions> {}; + : NativeMutationObserverNativeMutationObserverObserveOptionsBridging {}; using NativeMutationRecord = NativeMutationObserverNativeMutationRecord< // mutationObserverId @@ -40,31 +38,24 @@ using NativeMutationRecord = NativeMutationObserverNativeMutationRecord< std::vector>; template <> -struct Bridging - : NativeMutationObserverNativeMutationRecordBridging { -}; +struct Bridging : NativeMutationObserverNativeMutationRecordBridging {}; -class NativeMutationObserver - : public NativeMutationObserverCxxSpec { +class NativeMutationObserver : public NativeMutationObserverCxxSpec { public: NativeMutationObserver(std::shared_ptr jsInvoker); - void observe( - jsi::Runtime& runtime, - const NativeMutationObserverObserveOptions& options); + void observe(jsi::Runtime &runtime, const NativeMutationObserverObserveOptions &options); - void unobserveAll( - jsi::Runtime& runtime, - MutationObserverId mutationObserverId); + void unobserveAll(jsi::Runtime &runtime, MutationObserverId mutationObserverId); void connect( - jsi::Runtime& runtime, + jsi::Runtime &runtime, jsi::Function notifyMutationObservers, SyncCallback getPublicInstanceFromInstanceHandle); - void disconnect(jsi::Runtime& runtime); + void disconnect(jsi::Runtime &runtime); - std::vector takeRecords(jsi::Runtime& runtime); + std::vector takeRecords(jsi::Runtime &runtime); private: MutationObserverManager mutationObserverManager_{}; @@ -75,20 +66,18 @@ class NativeMutationObserver // notifications as microtasks when mutations occur. This is safe because // mutations will only happen when executing JavaScript and because this // native module will never survive the runtime. - jsi::Runtime* runtime_{}; + jsi::Runtime *runtime_{}; bool notifiedMutationObservers_{}; std::optional notifyMutationObservers_; - std::optional> - getPublicInstanceFromInstanceHandle_; + std::optional> getPublicInstanceFromInstanceHandle_; - void onMutations(std::vector& records); + void onMutations(std::vector &records); void notifyMutationObserversIfNecessary(); - jsi::Value getPublicInstanceFromShadowNode( - const ShadowNode& shadowNode) const; + jsi::Value getPublicInstanceFromShadowNode(const ShadowNode &shadowNode) const; std::vector getPublicInstancesFromShadowNodes( - const std::vector>& shadowNodes) const; + const std::vector> &shadowNodes) const; }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/nativemodule/samples/platform/android/ReactCommon/SampleTurboModuleJSIBindings.h b/packages/react-native/ReactCommon/react/nativemodule/samples/platform/android/ReactCommon/SampleTurboModuleJSIBindings.h index 33f6f785a7f..03b9f5f5e19 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/samples/platform/android/ReactCommon/SampleTurboModuleJSIBindings.h +++ b/packages/react-native/ReactCommon/react/nativemodule/samples/platform/android/ReactCommon/SampleTurboModuleJSIBindings.h @@ -13,11 +13,9 @@ namespace facebook::react { -class SampleTurboModuleJSIBindings - : public jni::JavaClass { +class SampleTurboModuleJSIBindings : public jni::JavaClass { public: - static constexpr const char* kJavaDescriptor = - "Lcom/facebook/fbreact/specs/SampleTurboModule;"; + static constexpr const char *kJavaDescriptor = "Lcom/facebook/fbreact/specs/SampleTurboModule;"; SampleTurboModuleJSIBindings() = default; @@ -25,8 +23,8 @@ class SampleTurboModuleJSIBindings private: // Using static function as a simple demonstration - static jni::local_ref - getBindingsInstaller(jni::alias_ref jobj); + static jni::local_ref getBindingsInstaller( + jni::alias_ref jobj); }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/nativemodule/samples/platform/android/ReactCommon/SampleTurboModuleSpec.h b/packages/react-native/ReactCommon/react/nativemodule/samples/platform/android/ReactCommon/SampleTurboModuleSpec.h index bd6059e7a19..9662cc9b4f6 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/samples/platform/android/ReactCommon/SampleTurboModuleSpec.h +++ b/packages/react-native/ReactCommon/react/nativemodule/samples/platform/android/ReactCommon/SampleTurboModuleSpec.h @@ -20,12 +20,12 @@ namespace facebook::react { */ class JSI_EXPORT NativeSampleTurboModuleSpecJSI : public JavaTurboModule { public: - NativeSampleTurboModuleSpecJSI(const JavaTurboModule::InitParams& params); + NativeSampleTurboModuleSpecJSI(const JavaTurboModule::InitParams ¶ms); }; JSI_EXPORT std::shared_ptr SampleTurboModuleSpec_ModuleProvider( - const std::string& moduleName, - const JavaTurboModule::InitParams& params); + const std::string &moduleName, + const JavaTurboModule::InitParams ¶ms); } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/nativemodule/samples/platform/ios/ReactCommon/RCTSampleLegacyModule.mm b/packages/react-native/ReactCommon/react/nativemodule/samples/platform/ios/ReactCommon/RCTSampleLegacyModule.mm index 8c623a8b5c4..f6788d1db74 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/samples/platform/ios/ReactCommon/RCTSampleLegacyModule.mm +++ b/packages/react-native/ReactCommon/react/nativemodule/samples/platform/ios/ReactCommon/RCTSampleLegacyModule.mm @@ -149,10 +149,8 @@ RCT_EXPORT_METHOD(getValueWithCallback : (RCTResponseSenderBlock)callback) callback(@[ @"value from callback!" ]); } -RCT_EXPORT_METHOD(getValueWithPromise - : (BOOL)error resolve - : (RCTPromiseResolveBlock)resolve reject - : (RCTPromiseRejectBlock)reject) +RCT_EXPORT_METHOD( + getValueWithPromise : (BOOL)error resolve : (RCTPromiseResolveBlock)resolve reject : (RCTPromiseRejectBlock)reject) { if ((resolve == nullptr) || (reject == nullptr)) { return; @@ -184,10 +182,8 @@ RCT_EXPORT_SYNCHRONOUS_TYPED_METHOD(NSDictionary *, getObjectThrows : (NSDiction @throw myException; } -RCT_EXPORT_METHOD(promiseThrows - : (BOOL)error resolve - : (RCTPromiseResolveBlock)resolve reject - : (RCTPromiseRejectBlock)reject) +RCT_EXPORT_METHOD( + promiseThrows : (BOOL)error resolve : (RCTPromiseResolveBlock)resolve reject : (RCTPromiseRejectBlock)reject) { NSException *myException = [NSException exceptionWithName:@"Excepption" reason:@"Intentional exception from ObjC promiseThrows" @@ -206,10 +202,8 @@ RCT_EXPORT_SYNCHRONOUS_TYPED_METHOD(NSDictionary *, getObjectAssert : (NSDiction return arg; } -RCT_EXPORT_METHOD(promiseAssert - : (BOOL)error resolve - : (RCTPromiseResolveBlock)resolve reject - : (RCTPromiseRejectBlock)reject) +RCT_EXPORT_METHOD( + promiseAssert : (BOOL)error resolve : (RCTPromiseResolveBlock)resolve reject : (RCTPromiseRejectBlock)reject) { RCTAssert(false, @"Intentional assert from ObjC promiseAssert"); } diff --git a/packages/react-native/ReactCommon/react/nativemodule/samples/platform/ios/ReactCommon/RCTSampleTurboModule.mm b/packages/react-native/ReactCommon/react/nativemodule/samples/platform/ios/ReactCommon/RCTSampleTurboModule.mm index 9da48632091..7486ffcb9ff 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/samples/platform/ios/ReactCommon/RCTSampleTurboModule.mm +++ b/packages/react-native/ReactCommon/react/nativemodule/samples/platform/ios/ReactCommon/RCTSampleTurboModule.mm @@ -149,10 +149,8 @@ RCT_EXPORT_METHOD(getValueWithCallback : (RCTResponseSenderBlock)callback) callback(@[ @"value from callback!" ]); } -RCT_EXPORT_METHOD(getValueWithPromise - : (BOOL)error resolve - : (RCTPromiseResolveBlock)resolve reject - : (RCTPromiseRejectBlock)reject) +RCT_EXPORT_METHOD( + getValueWithPromise : (BOOL)error resolve : (RCTPromiseResolveBlock)resolve reject : (RCTPromiseRejectBlock)reject) { if ((resolve == nullptr) || (reject == nullptr)) { return; diff --git a/packages/react-native/ReactCommon/react/nativemodule/webperformance/NativePerformance.h b/packages/react-native/ReactCommon/react/nativemodule/webperformance/NativePerformance.h index d065889205a..b2c0a9952e9 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/webperformance/NativePerformance.h +++ b/packages/react-native/ReactCommon/react/nativemodule/webperformance/NativePerformance.h @@ -23,26 +23,25 @@ namespace facebook::react { using NativePerformancePerformanceObserverCallback = AsyncCallback<>; -using NativePerformancePerformanceObserverObserveOptions = - NativePerformancePerformanceObserverInit< - // entryTypes - std::optional>, - // type - std::optional, - // buffered - std::optional, - // durationThreshold - std::optional>; +using NativePerformancePerformanceObserverObserveOptions = NativePerformancePerformanceObserverInit< + // entryTypes + std::optional>, + // type + std::optional, + // buffered + std::optional, + // durationThreshold + std::optional>; template <> struct Bridging { - static PerformanceEntryType fromJs( - jsi::Runtime& /*rt*/, - const jsi::Value& value) { + static PerformanceEntryType fromJs(jsi::Runtime & /*rt*/, const jsi::Value &value) + { return static_cast(value.asNumber()); } - static int toJs(jsi::Runtime& /*rt*/, const PerformanceEntryType& value) { + static int toJs(jsi::Runtime & /*rt*/, const PerformanceEntryType &value) + { return static_cast(value); } }; @@ -74,13 +73,11 @@ struct NativePerformanceEntry { }; template <> -struct Bridging - : NativePerformanceRawPerformanceEntryBridging {}; +struct Bridging : NativePerformanceRawPerformanceEntryBridging {}; template <> struct Bridging - : NativePerformancePerformanceObserverInitBridging< - NativePerformancePerformanceObserverObserveOptions> {}; + : NativePerformancePerformanceObserverInitBridging {}; class NativePerformance : public NativePerformanceCxxSpec { public: @@ -89,84 +86,67 @@ class NativePerformance : public NativePerformanceCxxSpec { #pragma mark - DOM Performance (High Resolution Time) (https://www.w3.org/TR/hr-time-3/#dom-performance) // https://www.w3.org/TR/hr-time-3/#now-method - HighResTimeStamp now(jsi::Runtime& rt); + HighResTimeStamp now(jsi::Runtime &rt); // https://www.w3.org/TR/hr-time-3/#timeorigin-attribute - HighResDuration timeOrigin(jsi::Runtime& rt); + HighResDuration timeOrigin(jsi::Runtime &rt); #pragma mark - User Timing Level 3 functions (https://w3c.github.io/user-timing/) - void reportMark( - jsi::Runtime& rt, - const std::string& name, - HighResTimeStamp time, - jsi::Value entry); + void reportMark(jsi::Runtime &rt, const std::string &name, HighResTimeStamp time, jsi::Value entry); void reportMeasure( - jsi::Runtime& rt, - const std::string& name, + jsi::Runtime &rt, + const std::string &name, HighResTimeStamp startTime, HighResDuration duration, jsi::Value entry); - std::optional getMarkTime(jsi::Runtime& rt, const std::string& name); + std::optional getMarkTime(jsi::Runtime &rt, const std::string &name); // https://w3c.github.io/user-timing/#clearmarks-method - void clearMarks( - jsi::Runtime& rt, - std::optional entryName = std::nullopt); + void clearMarks(jsi::Runtime &rt, std::optional entryName = std::nullopt); // https://w3c.github.io/user-timing/#clearmeasures-method - void clearMeasures( - jsi::Runtime& rt, - std::optional entryName = std::nullopt); + void clearMeasures(jsi::Runtime &rt, std::optional entryName = std::nullopt); #pragma mark - Performance Timeline (https://w3c.github.io/performance-timeline/#performance-timeline) // https://www.w3.org/TR/performance-timeline/#getentries-method - std::vector getEntries(jsi::Runtime& rt); + std::vector getEntries(jsi::Runtime &rt); // https://www.w3.org/TR/performance-timeline/#getentriesbytype-method - std::vector getEntriesByType( - jsi::Runtime& rt, - PerformanceEntryType entryType); + std::vector getEntriesByType(jsi::Runtime &rt, PerformanceEntryType entryType); // https://www.w3.org/TR/performance-timeline/#getentriesbyname-method std::vector getEntriesByName( - jsi::Runtime& rt, - const std::string& entryName, + jsi::Runtime &rt, + const std::string &entryName, std::optional entryType = std::nullopt); #pragma mark - Performance Observer (https://w3c.github.io/performance-timeline/#the-performanceobserver-interface) - jsi::Object createObserver( - jsi::Runtime& rt, - NativePerformancePerformanceObserverCallback callback); + jsi::Object createObserver(jsi::Runtime &rt, NativePerformancePerformanceObserverCallback callback); // https://www.w3.org/TR/performance-timeline/#dom-performanceobservercallbackoptions-droppedentriescount - double getDroppedEntriesCount(jsi::Runtime& rt, jsi::Object observerObj); + double getDroppedEntriesCount(jsi::Runtime &rt, jsi::Object observerObj); - void observe( - jsi::Runtime& rt, - jsi::Object observer, - NativePerformancePerformanceObserverObserveOptions options); - void disconnect(jsi::Runtime& rt, jsi::Object observer); + void observe(jsi::Runtime &rt, jsi::Object observer, NativePerformancePerformanceObserverObserveOptions options); + void disconnect(jsi::Runtime &rt, jsi::Object observer); std::vector takeRecords( - jsi::Runtime& rt, + jsi::Runtime &rt, jsi::Object observerObj, // When called via `observer.takeRecords` it should be in insertion order. // When called via the observer callback, it should be in chronological // order with respect to `startTime`. bool sort); - std::vector getSupportedPerformanceEntryTypes( - jsi::Runtime& rt); + std::vector getSupportedPerformanceEntryTypes(jsi::Runtime &rt); #pragma mark - Event Timing API functions (https://www.w3.org/TR/event-timing/) // https://www.w3.org/TR/event-timing/#dom-performance-eventcounts - std::vector> getEventCounts( - jsi::Runtime& rt); + std::vector> getEventCounts(jsi::Runtime &rt); #pragma mark - Non-standard memory functions @@ -181,18 +161,17 @@ class NativePerformance : public NativePerformanceCxxSpec { // // Note that we use int64_t here and it's ok to lose precision in JS doubles // for heap size information, as double's 2^53 sig bytes is large enough. - std::unordered_map getSimpleMemoryInfo(jsi::Runtime& rt); + std::unordered_map getSimpleMemoryInfo(jsi::Runtime &rt); #pragma mark - RN-specific startup timing // Collect and return the RN app startup timing information for performance // tracking. - std::unordered_map getReactNativeStartupTiming( - jsi::Runtime& rt); + std::unordered_map getReactNativeStartupTiming(jsi::Runtime &rt); #pragma mark - Testing - void clearEventCountsForTesting(jsi::Runtime& rt); + void clearEventCountsForTesting(jsi::Runtime &rt); }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/networking/NetworkReporter.h b/packages/react-native/ReactCommon/react/networking/NetworkReporter.h index 807ce89fc88..1a5cc3318fc 100644 --- a/packages/react-native/ReactCommon/react/networking/NetworkReporter.h +++ b/packages/react-native/ReactCommon/react/networking/NetworkReporter.h @@ -47,7 +47,7 @@ struct ResourceTimingData { */ class NetworkReporter { public: - static NetworkReporter& getInstance(); + static NetworkReporter &getInstance(); /** * Returns whether network tracking over CDP is currently enabled. @@ -65,10 +65,10 @@ class NetworkReporter { * https://w3c.github.io/resource-timing/#dom-performanceresourcetiming-requeststart */ void reportRequestStart( - const std::string& requestId, - const RequestInfo& requestInfo, + const std::string &requestId, + const RequestInfo &requestInfo, int encodedDataLength, - const std::optional& redirectResponse); + const std::optional &redirectResponse); /** * Report timestamp for sending the network request, and (in a debug build) @@ -82,9 +82,7 @@ class NetworkReporter { * * https://w3c.github.io/resource-timing/#dom-performanceresourcetiming-connectstart */ - void reportConnectionTiming( - const std::string& requestId, - const std::optional& headers); + void reportConnectionTiming(const std::string &requestId, const std::optional &headers); /** * Report when HTTP response headers have been received, corresponding to @@ -96,10 +94,7 @@ class NetworkReporter { * * https://w3c.github.io/resource-timing/#dom-performanceresourcetiming-responsestart */ - void reportResponseStart( - const std::string& requestId, - const ResponseInfo& responseInfo, - int encodedDataLength); + void reportResponseStart(const std::string &requestId, const ResponseInfo &responseInfo, int encodedDataLength); /** * Report when additional chunks of the response body have been received. @@ -107,10 +102,7 @@ class NetworkReporter { * Corresponds to `Network.dataReceived` in CDP (used for progress bar * rendering). */ - void reportDataReceived( - const std::string& requestId, - int dataLength, - const std::optional& encodedDataLength); + void reportDataReceived(const std::string &requestId, int dataLength, const std::optional &encodedDataLength); /** * Report when a network request is complete and we are no longer receiving @@ -122,14 +114,14 @@ class NetworkReporter { * * https://w3c.github.io/resource-timing/#dom-performanceresourcetiming-responseend */ - void reportResponseEnd(const std::string& requestId, int encodedDataLength); + void reportResponseEnd(const std::string &requestId, int encodedDataLength); /** * Report when a network request has failed. * * Corresponds to `Network.loadingFailed` in CDP. */ - void reportRequestFailed(const std::string& requestId, bool cancelled) const; + void reportRequestFailed(const std::string &requestId, bool cancelled) const; /** * Store the fetched response body for a text or image network response. @@ -141,15 +133,12 @@ class NetworkReporter { * * Should be called after checking \ref NetworkReporter::isDebuggingEnabled. */ - void storeResponseBody( - const std::string& requestId, - std::string_view body, - bool base64Encoded); + void storeResponseBody(const std::string &requestId, std::string_view body, bool base64Encoded); private: NetworkReporter() = default; - NetworkReporter(const NetworkReporter&) = delete; - NetworkReporter& operator=(const NetworkReporter&) = delete; + NetworkReporter(const NetworkReporter &) = delete; + NetworkReporter &operator=(const NetworkReporter &) = delete; ~NetworkReporter() = default; std::unordered_map perfTimingsBuffer_{}; diff --git a/packages/react-native/ReactCommon/react/performance/cdpmetrics/CdpInteractionTypes.h b/packages/react-native/ReactCommon/react/performance/cdpmetrics/CdpInteractionTypes.h index c6c32751974..9348cc3e98c 100644 --- a/packages/react-native/ReactCommon/react/performance/cdpmetrics/CdpInteractionTypes.h +++ b/packages/react-native/ReactCommon/react/performance/cdpmetrics/CdpInteractionTypes.h @@ -12,10 +12,9 @@ namespace facebook::react { -using InteractionTypesMap = - std::unordered_map; +using InteractionTypesMap = std::unordered_map; -const InteractionTypesMap& getInteractionTypes(); +const InteractionTypesMap &getInteractionTypes(); std::string_view getInteractionTypeForEvent(std::string_view eventName); diff --git a/packages/react-native/ReactCommon/react/performance/cdpmetrics/CdpMetricsReporter.h b/packages/react-native/ReactCommon/react/performance/cdpmetrics/CdpMetricsReporter.h index 386ded4b8fc..87c9400434a 100644 --- a/packages/react-native/ReactCommon/react/performance/cdpmetrics/CdpMetricsReporter.h +++ b/packages/react-native/ReactCommon/react/performance/cdpmetrics/CdpMetricsReporter.h @@ -27,7 +27,7 @@ class CdpMetricsReporter : public PerformanceEntryReporterEventTimingListener { public: explicit CdpMetricsReporter(RuntimeExecutor runtimeExecutor); - void onEventTimingEntry(const PerformanceEventTiming& entry) override; + void onEventTimingEntry(const PerformanceEventTiming &entry) override; private: const RuntimeExecutor runtimeExecutor_{}; diff --git a/packages/react-native/ReactCommon/react/performance/timeline/CircularBuffer.h b/packages/react-native/ReactCommon/react/performance/timeline/CircularBuffer.h index aa24bb30221..a9c44281c32 100644 --- a/packages/react-native/ReactCommon/react/performance/timeline/CircularBuffer.h +++ b/packages/react-native/ReactCommon/react/performance/timeline/CircularBuffer.h @@ -25,7 +25,8 @@ namespace facebook::react { template class CircularBuffer { public: - explicit CircularBuffer(size_t maxSize) : maxSize_(maxSize) { + explicit CircularBuffer(size_t maxSize) : maxSize_(maxSize) + { entries_.reserve(maxSize_); } @@ -36,7 +37,8 @@ class CircularBuffer { * buffer reached the max allowed size, in which case `true` is returned. If * no items were overridden `false` is returned. */ - bool add(const T& el) { + bool add(const T &el) + { if (entries_.size() < maxSize_) { // Haven't reached max buffer size yet, just add and grow the buffer entries_.emplace_back(el); @@ -49,15 +51,18 @@ class CircularBuffer { } } - T& operator[](size_t idx) { + T &operator[](size_t idx) + { return entries_[(position_ + idx) % entries_.size()]; } - size_t size() const { + size_t size() const + { return entries_.size(); } - void clear() { + void clear() + { entries_.clear(); position_ = 0; } @@ -65,12 +70,13 @@ class CircularBuffer { /** * Clears buffer entries by predicate */ - void clear(std::function predicate) { + void clear(std::function predicate) + { std::vector entries; entries.reserve(maxSize_); for (size_t i = 0; i < entries_.size(); i++) { - T& el = entries_[(i + position_) % entries_.size()]; + T &el = entries_[(i + position_) % entries_.size()]; if (predicate(el)) { continue; } @@ -85,7 +91,8 @@ class CircularBuffer { /** * Retrieves buffer entries, whether consumed or not */ - std::vector getEntries() const { + std::vector getEntries() const + { std::vector res; getEntries(res); return res; @@ -94,27 +101,25 @@ class CircularBuffer { /** * Retrieves buffer entries, whether consumed or not, with predicate */ - std::vector getEntries(std::function predicate) const { + std::vector getEntries(std::function predicate) const + { std::vector res; getEntries(res, predicate); return res; } - void getEntries(std::vector& res) const { + void getEntries(std::vector &res) const + { const size_t oldSize = res.size(); res.resize(oldSize + entries_.size()); - std::copy( - entries_.begin() + position_, entries_.end(), res.begin() + oldSize); - std::copy( - entries_.begin(), - entries_.begin() + position_, - res.begin() + oldSize + entries_.size() - position_); + std::copy(entries_.begin() + position_, entries_.end(), res.begin() + oldSize); + std::copy(entries_.begin(), entries_.begin() + position_, res.begin() + oldSize + entries_.size() - position_); } - void getEntries(std::vector& res, std::function predicate) - const { + void getEntries(std::vector &res, std::function predicate) const + { for (size_t i = 0; i < entries_.size(); i++) { - const T& el = entries_[(i + position_) % entries_.size()]; + const T &el = entries_[(i + position_) % entries_.size()]; if (predicate(el)) { res.push_back(el); } diff --git a/packages/react-native/ReactCommon/react/performance/timeline/PerformanceEntry.h b/packages/react-native/ReactCommon/react/performance/timeline/PerformanceEntry.h index dbccf4ba844..1b727535217 100644 --- a/packages/react-native/ReactCommon/react/performance/timeline/PerformanceEntry.h +++ b/packages/react-native/ReactCommon/react/performance/timeline/PerformanceEntry.h @@ -38,8 +38,7 @@ struct PerformanceMark : AbstractPerformanceEntry { }; struct PerformanceMeasure : AbstractPerformanceEntry { - static constexpr PerformanceEntryType entryType = - PerformanceEntryType::MEASURE; + static constexpr PerformanceEntryType entryType = PerformanceEntryType::MEASURE; }; struct PerformanceEventTiming : AbstractPerformanceEntry { @@ -54,13 +53,11 @@ struct PerformanceEventTiming : AbstractPerformanceEntry { }; struct PerformanceLongTaskTiming : AbstractPerformanceEntry { - static constexpr PerformanceEntryType entryType = - PerformanceEntryType::LONGTASK; + static constexpr PerformanceEntryType entryType = PerformanceEntryType::LONGTASK; }; struct PerformanceResourceTiming : AbstractPerformanceEntry { - static constexpr PerformanceEntryType entryType = - PerformanceEntryType::RESOURCE; + static constexpr PerformanceEntryType entryType = PerformanceEntryType::RESOURCE; /** Aligns with `startTime`. */ HighResTimeStamp fetchStart; HighResTimeStamp requestStart; @@ -83,9 +80,10 @@ using PerformanceEntry = std::variant< PerformanceResourceTiming>; struct PerformanceEntrySorter { - bool operator()(const PerformanceEntry& lhs, const PerformanceEntry& rhs) { + bool operator()(const PerformanceEntry &lhs, const PerformanceEntry &rhs) + { return std::visit( - [](const auto& left, const auto& right) { + [](const auto &left, const auto &right) { if (left.startTime != right.startTime) { return left.startTime < right.startTime; } diff --git a/packages/react-native/ReactCommon/react/performance/timeline/PerformanceEntryBuffer.h b/packages/react-native/ReactCommon/react/performance/timeline/PerformanceEntryBuffer.h index c3ce79d3412..418b344fbbb 100644 --- a/packages/react-native/ReactCommon/react/performance/timeline/PerformanceEntryBuffer.h +++ b/packages/react-native/ReactCommon/react/performance/timeline/PerformanceEntryBuffer.h @@ -28,13 +28,11 @@ class PerformanceEntryBuffer { explicit PerformanceEntryBuffer() = default; virtual ~PerformanceEntryBuffer() = default; - virtual void add(const PerformanceEntry& entry) = 0; - virtual void getEntries(std::vector& target) const = 0; - virtual void getEntries( - std::vector& target, - const std::string& name) const = 0; + virtual void add(const PerformanceEntry &entry) = 0; + virtual void getEntries(std::vector &target) const = 0; + virtual void getEntries(std::vector &target, const std::string &name) const = 0; virtual void clear() = 0; - virtual void clear(const std::string& name) = 0; + virtual void clear(const std::string &name) = 0; }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/performance/timeline/PerformanceEntryCircularBuffer.h b/packages/react-native/ReactCommon/react/performance/timeline/PerformanceEntryCircularBuffer.h index cfdaf81ff8d..95163b5392a 100644 --- a/packages/react-native/ReactCommon/react/performance/timeline/PerformanceEntryCircularBuffer.h +++ b/packages/react-native/ReactCommon/react/performance/timeline/PerformanceEntryCircularBuffer.h @@ -17,15 +17,13 @@ class PerformanceEntryCircularBuffer : public PerformanceEntryBuffer { explicit PerformanceEntryCircularBuffer(size_t size) : buffer_(size) {} ~PerformanceEntryCircularBuffer() override = default; - void add(const PerformanceEntry& entry) override; + void add(const PerformanceEntry &entry) override; - void getEntries(std::vector& target) const override; - void getEntries( - std::vector& target, - const std::string& name) const override; + void getEntries(std::vector &target) const override; + void getEntries(std::vector &target, const std::string &name) const override; void clear() override; - void clear(const std::string& name) override; + void clear(const std::string &name) override; private: CircularBuffer buffer_; diff --git a/packages/react-native/ReactCommon/react/performance/timeline/PerformanceEntryKeyedBuffer.h b/packages/react-native/ReactCommon/react/performance/timeline/PerformanceEntryKeyedBuffer.h index b65c6f949f5..5d895d5873e 100644 --- a/packages/react-native/ReactCommon/react/performance/timeline/PerformanceEntryKeyedBuffer.h +++ b/packages/react-native/ReactCommon/react/performance/timeline/PerformanceEntryKeyedBuffer.h @@ -18,18 +18,16 @@ class PerformanceEntryKeyedBuffer : public PerformanceEntryBuffer { public: PerformanceEntryKeyedBuffer() = default; - void add(const PerformanceEntry& entry) override; + void add(const PerformanceEntry &entry) override; - void getEntries(std::vector& target) const override; + void getEntries(std::vector &target) const override; - void getEntries( - std::vector& target, - const std::string& name) const override; + void getEntries(std::vector &target, const std::string &name) const override; void clear() override; - void clear(const std::string& name) override; + void clear(const std::string &name) override; - std::optional find(const std::string& name) const; + std::optional find(const std::string &name) const; private: std::unordered_map> entryMap_{}; diff --git a/packages/react-native/ReactCommon/react/performance/timeline/PerformanceEntryReporter.h b/packages/react-native/ReactCommon/react/performance/timeline/PerformanceEntryReporter.h index 3e2c3e67456..5e52a0edcd3 100644 --- a/packages/react-native/ReactCommon/react/performance/timeline/PerformanceEntryReporter.h +++ b/packages/react-native/ReactCommon/react/performance/timeline/PerformanceEntryReporter.h @@ -28,8 +28,7 @@ constexpr size_t EVENT_BUFFER_SIZE = 150; constexpr size_t LONG_TASK_BUFFER_SIZE = 200; constexpr size_t RESOURCE_TIMING_BUFFER_SIZE = 250; -constexpr HighResDuration LONG_TASK_DURATION_THRESHOLD = - HighResDuration::fromMilliseconds(50); +constexpr HighResDuration LONG_TASK_DURATION_THRESHOLD = HighResDuration::fromMilliseconds(50); class PerformanceEntryReporter { public: @@ -39,68 +38,56 @@ class PerformanceEntryReporter { // the same thread. // TODO: Consider passing it as a parameter to the corresponding modules at // creation time instead of having the singleton. - static std::shared_ptr& getInstance(); + static std::shared_ptr &getInstance(); - PerformanceObserverRegistry& getObserverRegistry() { + PerformanceObserverRegistry &getObserverRegistry() + { return *observerRegistry_; } std::vector getEntries() const; - void getEntries(std::vector& dest) const; + void getEntries(std::vector &dest) const; - std::vector getEntries( - PerformanceEntryType entryType) const; - void getEntries( - std::vector& dest, - PerformanceEntryType entryType) const; + std::vector getEntries(PerformanceEntryType entryType) const; + void getEntries(std::vector &dest, PerformanceEntryType entryType) const; - std::vector getEntries( - PerformanceEntryType entryType, - const std::string& entryName) const; - void getEntries( - std::vector& dest, - PerformanceEntryType entryType, - const std::string& entryName) const; + std::vector getEntries(PerformanceEntryType entryType, const std::string &entryName) const; + void getEntries(std::vector &dest, PerformanceEntryType entryType, const std::string &entryName) + const; void clearEntries(); void clearEntries(PerformanceEntryType entryType); - void clearEntries( - PerformanceEntryType entryType, - const std::string& entryName); + void clearEntries(PerformanceEntryType entryType, const std::string &entryName); - void addEventTimingListener( - PerformanceEntryReporterEventTimingListener* listener); - void removeEventTimingListener( - PerformanceEntryReporterEventTimingListener* listener); + void addEventTimingListener(PerformanceEntryReporterEventTimingListener *listener); + void removeEventTimingListener(PerformanceEntryReporterEventTimingListener *listener); static std::vector getSupportedEntryTypes(); uint32_t getDroppedEntriesCount(PerformanceEntryType type) const noexcept; - const std::unordered_map& getEventCounts() const { + const std::unordered_map &getEventCounts() const + { return eventCounts_; } void clearEventCounts(); - std::optional getMarkTime( - const std::string& markName) const; + std::optional getMarkTime(const std::string &markName) const; using UserTimingDetailProvider = std::function; - void reportMark( - const std::string& name, - HighResTimeStamp startTime, - UserTimingDetailProvider&& detailProvider = nullptr); + void + reportMark(const std::string &name, HighResTimeStamp startTime, UserTimingDetailProvider &&detailProvider = nullptr); void reportMeasure( - const std::string& name, + const std::string &name, HighResTimeStamp startTime, HighResDuration duration, - UserTimingDetailProvider&& detailProvider = nullptr); + UserTimingDetailProvider &&detailProvider = nullptr); void reportEvent( - const std::string& name, + const std::string &name, HighResTimeStamp startTime, HighResDuration duration, HighResTimeStamp processingStart, @@ -111,7 +98,7 @@ class PerformanceEntryReporter { void reportLongTask(HighResTimeStamp startTime, HighResDuration duration); void reportResourceTiming( - const std::string& url, + const std::string &url, HighResTimeStamp fetchStart, HighResTimeStamp requestStart, std::optional connectStart, @@ -119,7 +106,7 @@ class PerformanceEntryReporter { HighResTimeStamp responseStart, HighResTimeStamp responseEnd, int responseStatus, - const std::string& contentType, + const std::string &contentType, int encodedBodySize, int decodedBodySize); @@ -129,19 +116,17 @@ class PerformanceEntryReporter { mutable std::shared_mutex buffersMutex_; PerformanceEntryCircularBuffer eventBuffer_{EVENT_BUFFER_SIZE}; PerformanceEntryCircularBuffer longTaskBuffer_{LONG_TASK_BUFFER_SIZE}; - PerformanceEntryCircularBuffer resourceTimingBuffer_{ - RESOURCE_TIMING_BUFFER_SIZE}; + PerformanceEntryCircularBuffer resourceTimingBuffer_{RESOURCE_TIMING_BUFFER_SIZE}; PerformanceEntryKeyedBuffer markBuffer_; PerformanceEntryKeyedBuffer measureBuffer_; std::unordered_map eventCounts_; mutable std::shared_mutex listenersMutex_; - std::vector - eventTimingListeners_{}; + std::vector eventTimingListeners_{}; - const inline PerformanceEntryBuffer& getBuffer( - PerformanceEntryType entryType) const { + const inline PerformanceEntryBuffer &getBuffer(PerformanceEntryType entryType) const + { switch (entryType) { case PerformanceEntryType::EVENT: return eventBuffer_; @@ -160,7 +145,8 @@ class PerformanceEntryReporter { } } - inline PerformanceEntryBuffer& getBufferRef(PerformanceEntryType entryType) { + inline PerformanceEntryBuffer &getBufferRef(PerformanceEntryType entryType) + { switch (entryType) { case PerformanceEntryType::EVENT: return eventBuffer_; @@ -179,17 +165,13 @@ class PerformanceEntryReporter { } } - void traceMark( - const PerformanceMark& entry, - UserTimingDetailProvider&& detailProvider) const; - void traceMeasure( - const PerformanceMeasure& entry, - UserTimingDetailProvider&& detailProvider) const; + void traceMark(const PerformanceMark &entry, UserTimingDetailProvider &&detailProvider) const; + void traceMeasure(const PerformanceMeasure &entry, UserTimingDetailProvider &&detailProvider) const; void traceResourceTiming( - const PerformanceResourceTiming& entry, - const std::optional& devtoolsRequestId, - const std::optional& requestMethod, - const std::optional& resourceType) const; + const PerformanceResourceTiming &entry, + const std::optional &devtoolsRequestId, + const std::optional &requestMethod, + const std::optional &resourceType) const; }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/performance/timeline/PerformanceEntryReporterListeners.h b/packages/react-native/ReactCommon/react/performance/timeline/PerformanceEntryReporterListeners.h index e4bc1461b89..fe9fb60c783 100644 --- a/packages/react-native/ReactCommon/react/performance/timeline/PerformanceEntryReporterListeners.h +++ b/packages/react-native/ReactCommon/react/performance/timeline/PerformanceEntryReporterListeners.h @@ -18,7 +18,7 @@ class PerformanceEntryReporterEventTimingListener { public: virtual ~PerformanceEntryReporterEventTimingListener() = default; - virtual void onEventTimingEntry(const PerformanceEventTiming& /*entry*/) {} + virtual void onEventTimingEntry(const PerformanceEventTiming & /*entry*/) {} }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/performance/timeline/PerformanceObserver.h b/packages/react-native/ReactCommon/react/performance/timeline/PerformanceObserver.h index 8b387ec753c..c397bf14ae3 100644 --- a/packages/react-native/ReactCommon/react/performance/timeline/PerformanceObserver.h +++ b/packages/react-native/ReactCommon/react/performance/timeline/PerformanceObserver.h @@ -19,8 +19,7 @@ namespace facebook::react { -using PerformanceObserverEntryTypeFilter = - std::unordered_set; +using PerformanceObserverEntryTypeFilter = std::unordered_set; using PerformanceObserverCallback = std::function; /** @@ -52,8 +51,7 @@ struct PerformanceObserverObserveSingleOptions { * Entries are pushed to the observer by the `PerformanceEntryReporter` class, * through the `PerformanceObserverRegistry` class which acts as a central hub. */ -class PerformanceObserver - : public std::enable_shared_from_this { +class PerformanceObserver : public std::enable_shared_from_this { private: struct PrivateUseCreateMethod { explicit PrivateUseCreateMethod() = default; @@ -62,15 +60,17 @@ class PerformanceObserver public: explicit PerformanceObserver( PrivateUseCreateMethod /*unused*/, - PerformanceObserverRegistry& registry, - PerformanceObserverCallback&& callback) - : registry_(registry), callback_(std::move(callback)) {} + PerformanceObserverRegistry ®istry, + PerformanceObserverCallback &&callback) + : registry_(registry), callback_(std::move(callback)) + { + } static std::shared_ptr create( - PerformanceObserverRegistry& registry, - PerformanceObserverCallback&& callback) { - return std::make_shared( - PrivateUseCreateMethod(), registry, std::move(callback)); + PerformanceObserverRegistry ®istry, + PerformanceObserverCallback &&callback) + { + return std::make_shared(PrivateUseCreateMethod(), registry, std::move(callback)); } ~PerformanceObserver() = default; @@ -78,7 +78,7 @@ class PerformanceObserver /** * Append entry to the buffer if this observer should handle this entry. */ - void handleEntry(const PerformanceEntry& entry); + void handleEntry(const PerformanceEntry &entry); /** * Returns current observer buffer and clears it. @@ -95,9 +95,7 @@ class PerformanceObserver * calls to this methods remove any previous watch configuration (as per * spec). */ - void observe( - PerformanceEntryType type, - PerformanceObserverObserveSingleOptions options = {}); + void observe(PerformanceEntryType type, PerformanceObserverObserveSingleOptions options = {}); /** * Configures the observer to watch for specified entry type. @@ -122,7 +120,7 @@ class PerformanceObserver private: void scheduleFlushBuffer(); - PerformanceObserverRegistry& registry_; + PerformanceObserverRegistry ®istry_; PerformanceObserverCallback callback_; PerformanceObserverEntryTypeFilter observedTypes_; @@ -133,9 +131,8 @@ class PerformanceObserver bool requiresDroppedEntries_ = false; }; -inline bool operator==( - const PerformanceObserver& lhs, - const PerformanceObserver& rhs) { +inline bool operator==(const PerformanceObserver &lhs, const PerformanceObserver &rhs) +{ return &lhs == &rhs; } diff --git a/packages/react-native/ReactCommon/react/performance/timeline/PerformanceObserverRegistry.h b/packages/react-native/ReactCommon/react/performance/timeline/PerformanceObserverRegistry.h index 78c01c43697..dc3c7d4a4e6 100644 --- a/packages/react-native/ReactCommon/react/performance/timeline/PerformanceObserverRegistry.h +++ b/packages/react-native/ReactCommon/react/performance/timeline/PerformanceObserverRegistry.h @@ -41,14 +41,11 @@ class PerformanceObserverRegistry { * Delegates specified performance `entry` to all registered observers * in this registry. */ - void queuePerformanceEntry(const PerformanceEntry& entry); + void queuePerformanceEntry(const PerformanceEntry &entry); private: mutable std::mutex observersMutex_; - std::set< - std::shared_ptr, - std::owner_less>> - observers_; + std::set, std::owner_less>> observers_; }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/animated/AnimatedModule.cpp b/packages/react-native/ReactCommon/react/renderer/animated/AnimatedModule.cpp index d03cd98595a..dcc592c0e70 100644 --- a/packages/react-native/ReactCommon/react/renderer/animated/AnimatedModule.cpp +++ b/packages/react-native/ReactCommon/react/renderer/animated/AnimatedModule.cpp @@ -111,11 +111,12 @@ void AnimatedModule::startAnimatingNode( jsi::Object config, AnimationEndCallback endCallback) { auto configDynamic = dynamicFromValue(rt, jsi::Value(rt, config)); - operations_.emplace_back(StartAnimatingNodeOp{ - .animationId = animationId, - .nodeTag = nodeTag, - .config = std::move(configDynamic), - .endCallback = std::move(endCallback)}); + operations_.emplace_back( + StartAnimatingNodeOp{ + .animationId = animationId, + .nodeTag = nodeTag, + .config = std::move(configDynamic), + .endCallback = std::move(endCallback)}); } void AnimatedModule::stopAnimation(jsi::Runtime& /*rt*/, int animationId) { @@ -180,10 +181,11 @@ void AnimatedModule::addAnimatedEventToView( std::string eventName, jsi::Object eventMapping) { auto eventMappingDynamic = dynamicFromValue(rt, jsi::Value(rt, eventMapping)); - operations_.emplace_back(AddAnimatedEventToViewOp{ - .viewTag = viewTag, - .eventName = std::move(eventName), - .eventMapping = std::move(eventMappingDynamic)}); + operations_.emplace_back( + AddAnimatedEventToViewOp{ + .viewTag = viewTag, + .eventName = std::move(eventName), + .eventMapping = std::move(eventMappingDynamic)}); } void AnimatedModule::removeAnimatedEventFromView( @@ -191,10 +193,11 @@ void AnimatedModule::removeAnimatedEventFromView( Tag viewTag, std::string eventName, Tag animatedNodeTag) { - operations_.emplace_back(RemoveAnimatedEventFromViewOp{ - .viewTag = viewTag, - .eventName = std::move(eventName), - .animatedNodeTag = animatedNodeTag}); + operations_.emplace_back( + RemoveAnimatedEventFromViewOp{ + .viewTag = viewTag, + .eventName = std::move(eventName), + .animatedNodeTag = animatedNodeTag}); } void AnimatedModule::addListener( diff --git a/packages/react-native/ReactCommon/react/renderer/animated/AnimatedModule.h b/packages/react-native/ReactCommon/react/renderer/animated/AnimatedModule.h index a0f84ccbb2c..45614247448 100644 --- a/packages/react-native/ReactCommon/react/renderer/animated/AnimatedModule.h +++ b/packages/react-native/ReactCommon/react/renderer/animated/AnimatedModule.h @@ -23,8 +23,7 @@ namespace facebook::react { -class AnimatedModule : public NativeAnimatedModuleCxxSpec, - public TurboModuleWithJSIBindings { +class AnimatedModule : public NativeAnimatedModuleCxxSpec, public TurboModuleWithJSIBindings { #pragma mark - Operation structures for each type of animated operation struct CreateAnimatedNodeOp { Tag tag{}; @@ -140,70 +139,58 @@ class AnimatedModule : public NativeAnimatedModuleCxxSpec, std::shared_ptr jsInvoker, std::shared_ptr nodesManagerProvider); - void startOperationBatch(jsi::Runtime& rt); + void startOperationBatch(jsi::Runtime &rt); - void finishOperationBatch(jsi::Runtime& rt); + void finishOperationBatch(jsi::Runtime &rt); - void createAnimatedNode(jsi::Runtime& rt, Tag tag, jsi::Object config); + void createAnimatedNode(jsi::Runtime &rt, Tag tag, jsi::Object config); - void updateAnimatedNodeConfig(jsi::Runtime& rt, Tag tag, jsi::Object config); + void updateAnimatedNodeConfig(jsi::Runtime &rt, Tag tag, jsi::Object config); - void - getValue(jsi::Runtime& rt, Tag tag, AsyncCallback saveValueCallback); + void getValue(jsi::Runtime &rt, Tag tag, AsyncCallback saveValueCallback); - void startListeningToAnimatedNodeValue(jsi::Runtime& rt, Tag tag); + void startListeningToAnimatedNodeValue(jsi::Runtime &rt, Tag tag); - void stopListeningToAnimatedNodeValue(jsi::Runtime& rt, Tag tag); + void stopListeningToAnimatedNodeValue(jsi::Runtime &rt, Tag tag); - void connectAnimatedNodes(jsi::Runtime& rt, Tag parentTag, Tag childTag); + void connectAnimatedNodes(jsi::Runtime &rt, Tag parentTag, Tag childTag); - void disconnectAnimatedNodes(jsi::Runtime& rt, Tag parentTag, Tag childTag); + void disconnectAnimatedNodes(jsi::Runtime &rt, Tag parentTag, Tag childTag); void startAnimatingNode( - jsi::Runtime& rt, + jsi::Runtime &rt, int animationId, Tag nodeTag, jsi::Object config, AnimationEndCallback endCallback); - void stopAnimation(jsi::Runtime& rt, int animationId); + void stopAnimation(jsi::Runtime &rt, int animationId); - void setAnimatedNodeValue(jsi::Runtime& rt, Tag nodeTag, double value); + void setAnimatedNodeValue(jsi::Runtime &rt, Tag nodeTag, double value); - void setAnimatedNodeOffset(jsi::Runtime& rt, Tag nodeTag, double offset); + void setAnimatedNodeOffset(jsi::Runtime &rt, Tag nodeTag, double offset); - void flattenAnimatedNodeOffset(jsi::Runtime& rt, Tag nodeTag); + void flattenAnimatedNodeOffset(jsi::Runtime &rt, Tag nodeTag); - void extractAnimatedNodeOffset(jsi::Runtime& rt, Tag nodeTag); + void extractAnimatedNodeOffset(jsi::Runtime &rt, Tag nodeTag); - void connectAnimatedNodeToView(jsi::Runtime& rt, Tag nodeTag, Tag viewTag); + void connectAnimatedNodeToView(jsi::Runtime &rt, Tag nodeTag, Tag viewTag); - void - disconnectAnimatedNodeFromView(jsi::Runtime& rt, Tag nodeTag, Tag viewTag); + void disconnectAnimatedNodeFromView(jsi::Runtime &rt, Tag nodeTag, Tag viewTag); - void restoreDefaultValues(jsi::Runtime& rt, Tag nodeTag); + void restoreDefaultValues(jsi::Runtime &rt, Tag nodeTag); - void dropAnimatedNode(jsi::Runtime& rt, Tag tag); + void dropAnimatedNode(jsi::Runtime &rt, Tag tag); - void addAnimatedEventToView( - jsi::Runtime& rt, - Tag viewTag, - std::string eventName, - jsi::Object eventMapping); + void addAnimatedEventToView(jsi::Runtime &rt, Tag viewTag, std::string eventName, jsi::Object eventMapping); - void removeAnimatedEventFromView( - jsi::Runtime& rt, - Tag viewTag, - std::string eventName, - Tag animatedNodeTag); + void removeAnimatedEventFromView(jsi::Runtime &rt, Tag viewTag, std::string eventName, Tag animatedNodeTag); - void addListener(jsi::Runtime& rt, const std::string& eventName); + void addListener(jsi::Runtime &rt, const std::string &eventName); - void removeListeners(jsi::Runtime& rt, int count); + void removeListeners(jsi::Runtime &rt, int count); - void queueAndExecuteBatchedOperations( - jsi::Runtime& rt, - jsi::Array operationsAndArgs); + void queueAndExecuteBatchedOperations(jsi::Runtime &rt, jsi::Array operationsAndArgs); private: std::shared_ptr nodesManagerProvider_; @@ -211,8 +198,8 @@ class AnimatedModule : public NativeAnimatedModuleCxxSpec, std::vector preOperations_; std::vector operations_; - void executeOperation(const Operation& operation); - void installJSIBindingsWithRuntime(jsi::Runtime& runtime) override; + void executeOperation(const Operation &operation); + void installJSIBindingsWithRuntime(jsi::Runtime &runtime) override; }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/animated/EventEmitterListener.h b/packages/react-native/ReactCommon/react/renderer/animated/EventEmitterListener.h index ce526ec39c7..c2f783fe2e4 100644 --- a/packages/react-native/ReactCommon/react/renderer/animated/EventEmitterListener.h +++ b/packages/react-native/ReactCommon/react/renderer/animated/EventEmitterListener.h @@ -32,10 +32,11 @@ class EventListenerContainerT { * Returns true if event was handled by the listener, false to continue * default dispatch. */ - bool willDispatchEvent(TArgs... args) { + bool willDispatchEvent(TArgs... args) + { std::shared_lock lock(mutex_); bool handled = false; - for (const auto& listener : eventListeners_) { + for (const auto &listener : eventListeners_) { handled = (*listener)(args...); if (handled) { break; @@ -44,16 +45,16 @@ class EventListenerContainerT { return handled; } - void addListener(std::shared_ptr> listener) { + void addListener(std::shared_ptr> listener) + { std::unique_lock lock(mutex_); eventListeners_.push_back(std::move(listener)); } - void removeListener( - const std::shared_ptr>& listener) { + void removeListener(const std::shared_ptr> &listener) + { std::unique_lock lock(mutex_); - auto it = - std::find(eventListeners_.begin(), eventListeners_.end(), listener); + auto it = std::find(eventListeners_.begin(), eventListeners_.end(), listener); if (it != eventListeners_.end()) { eventListeners_.erase(it); } @@ -64,9 +65,7 @@ class EventListenerContainerT { std::vector>> eventListeners_; }; -using EventEmitterListener = - EventListenerT; -using EventEmitterListenerContainer = - EventListenerContainerT; +using EventEmitterListener = EventListenerT; +using EventEmitterListenerContainer = EventListenerContainerT; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/animated/MergedValueDispatcher.h b/packages/react-native/ReactCommon/react/renderer/animated/MergedValueDispatcher.h index c0a073632ec..8926e69c161 100644 --- a/packages/react-native/ReactCommon/react/renderer/animated/MergedValueDispatcher.h +++ b/packages/react-native/ReactCommon/react/renderer/animated/MergedValueDispatcher.h @@ -21,9 +21,8 @@ namespace facebook::react { */ class MergedValueDispatcher { public: - using DispatchFunction = std::function&&)>; - using MergedValueFunction = - std::function&& tagToProps)>; + using DispatchFunction = std::function &&)>; + using MergedValueFunction = std::function &&tagToProps)>; /** * Creates a MergedValueDispatcher with the given dispatch function. @@ -33,9 +32,7 @@ class MergedValueDispatcher { * @param latestValueFunction - function that will be called on the target * thread with all values merged. */ - explicit MergedValueDispatcher( - DispatchFunction dispatchFunction, - MergedValueFunction mergedValueFunction); + explicit MergedValueDispatcher(DispatchFunction dispatchFunction, MergedValueFunction mergedValueFunction); /** * Dispatches the given value. If a dispatch is already pending, this will @@ -43,7 +40,7 @@ class MergedValueDispatcher { * * @param value - value to be dispatched. */ - void dispatch(const std::unordered_map& value); + void dispatch(const std::unordered_map &value); private: DispatchFunction dispatchFunction_; diff --git a/packages/react-native/ReactCommon/react/renderer/animated/NativeAnimatedNodesManager.cpp b/packages/react-native/ReactCommon/react/renderer/animated/NativeAnimatedNodesManager.cpp index 119ee2574e8..bcfaba306f1 100644 --- a/packages/react-native/ReactCommon/react/renderer/animated/NativeAnimatedNodesManager.cpp +++ b/packages/react-native/ReactCommon/react/renderer/animated/NativeAnimatedNodesManager.cpp @@ -609,9 +609,10 @@ void NativeAnimatedNodesManager::updateNodes( #endif const auto connectedToFinishedAnimation = is_node_connected_to_finished_animation(node, nodeTag, false); - nodesQueue.emplace_back(NodesQueueItem{ - .node = node, - .connectedToFinishedAnimation = connectedToFinishedAnimation}); + nodesQueue.emplace_back( + NodesQueueItem{ + .node = node, + .connectedToFinishedAnimation = connectedToFinishedAnimation}); } } } @@ -632,9 +633,10 @@ void NativeAnimatedNodesManager::updateNodes( const auto connectedToFinishedAnimation = is_node_connected_to_finished_animation( child, childTag, nextNode.connectedToFinishedAnimation); - nodesQueue.emplace_back(NodesQueueItem{ - .node = child, - .connectedToFinishedAnimation = connectedToFinishedAnimation}); + nodesQueue.emplace_back( + NodesQueueItem{ + .node = child, + .connectedToFinishedAnimation = connectedToFinishedAnimation}); } } } @@ -664,9 +666,10 @@ void NativeAnimatedNodesManager::updateNodes( #endif const auto connectedToFinishedAnimation = is_node_connected_to_finished_animation(node, nodeTag, false); - nodesQueue.emplace_back(NodesQueueItem{ - .node = node, - .connectedToFinishedAnimation = connectedToFinishedAnimation}); + nodesQueue.emplace_back( + NodesQueueItem{ + .node = node, + .connectedToFinishedAnimation = connectedToFinishedAnimation}); } } } @@ -698,9 +701,10 @@ void NativeAnimatedNodesManager::updateNodes( const auto connectedToFinishedAnimation = is_node_connected_to_finished_animation( child, childTag, nextNode.connectedToFinishedAnimation); - nodesQueue.emplace_back(NodesQueueItem{ - .node = child, - .connectedToFinishedAnimation = connectedToFinishedAnimation}); + nodesQueue.emplace_back( + NodesQueueItem{ + .node = child, + .connectedToFinishedAnimation = connectedToFinishedAnimation}); } #ifdef REACT_NATIVE_DEBUG else if (child->bfsColor == animatedGraphBFSColor_) { diff --git a/packages/react-native/ReactCommon/react/renderer/animated/NativeAnimatedNodesManager.h b/packages/react-native/ReactCommon/react/renderer/animated/NativeAnimatedNodesManager.h index dd953ca3f29..200e76dee2c 100644 --- a/packages/react-native/ReactCommon/react/renderer/animated/NativeAnimatedNodesManager.h +++ b/packages/react-native/ReactCommon/react/renderer/animated/NativeAnimatedNodesManager.h @@ -44,45 +44,36 @@ class Scheduler; using ValueListenerCallback = std::function; using UiTask = std::function; -using EndResult = NativeAnimatedTurboModuleEndResult< - bool, - std::optional, - std::optional>; +using EndResult = NativeAnimatedTurboModuleEndResult, std::optional>; using AnimationEndCallback = AsyncCallback; template <> -struct Bridging - : NativeAnimatedTurboModuleEndResultBridging {}; +struct Bridging : NativeAnimatedTurboModuleEndResultBridging {}; class NativeAnimatedNodesManager { public: - using DirectManipulationCallback = - std::function; - using FabricCommitCallback = - std::function&)>; + using DirectManipulationCallback = std::function; + using FabricCommitCallback = std::function &)>; using StartOnRenderCallback = std::function; using StopOnRenderCallback = std::function; explicit NativeAnimatedNodesManager( - DirectManipulationCallback&& directManipulationCallback, - FabricCommitCallback&& fabricCommitCallback, - StartOnRenderCallback&& startOnRenderCallback = nullptr, - StopOnRenderCallback&& stopOnRenderCallback = nullptr) noexcept; + DirectManipulationCallback &&directManipulationCallback, + FabricCommitCallback &&fabricCommitCallback, + StartOnRenderCallback &&startOnRenderCallback = nullptr, + StopOnRenderCallback &&stopOnRenderCallback = nullptr) noexcept; - explicit NativeAnimatedNodesManager( - std::shared_ptr animationBackend) noexcept; + explicit NativeAnimatedNodesManager(std::shared_ptr animationBackend) noexcept; ~NativeAnimatedNodesManager() noexcept; - template < - typename T, - typename = std::enable_if_t>> - T* getAnimatedNode(Tag tag) const + template >> + T *getAnimatedNode(Tag tag) const requires(std::is_base_of_v) { if (auto it = animatedNodes_.find(tag); it != animatedNodes_.end()) { - return static_cast(it->second.get()); + return static_cast(it->second.get()); } return nullptr; } @@ -92,9 +83,9 @@ class NativeAnimatedNodesManager { #pragma mark - Graph // Called from JS thread - void createAnimatedNodeAsync(Tag tag, const folly::dynamic& config) noexcept; + void createAnimatedNodeAsync(Tag tag, const folly::dynamic &config) noexcept; - void createAnimatedNode(Tag tag, const folly::dynamic& config) noexcept; + void createAnimatedNode(Tag tag, const folly::dynamic &config) noexcept; void connectAnimatedNodes(Tag parentTag, Tag childTag) noexcept; @@ -128,35 +119,26 @@ class NativeAnimatedNodesManager { folly::dynamic config, std::optional endCallback) noexcept; - void stopAnimation( - int animationId, - bool isTrackingAnimation = false) noexcept; + void stopAnimation(int animationId, bool isTrackingAnimation = false) noexcept; - void addAnimatedEventToView( - Tag viewTag, - const std::string& eventName, - const folly::dynamic& eventMapping) noexcept; + void addAnimatedEventToView(Tag viewTag, const std::string &eventName, const folly::dynamic &eventMapping) noexcept; - void removeAnimatedEventFromView( - Tag viewTag, - const std::string& eventName, - Tag animatedValueTag) noexcept; + void removeAnimatedEventFromView(Tag viewTag, const std::string &eventName, Tag animatedValueTag) noexcept; - std::shared_ptr getEventEmitterListener() noexcept { + std::shared_ptr getEventEmitterListener() noexcept + { return ensureEventEmitterListener(); } #pragma mark - Listeners - void startListeningToAnimatedNodeValue( - Tag tag, - ValueListenerCallback&& callback) noexcept; + void startListeningToAnimatedNodeValue(Tag tag, ValueListenerCallback &&callback) noexcept; void stopListeningToAnimatedNodeValue(Tag tag) noexcept; void schedulePropsCommit( Tag viewTag, - const folly::dynamic& props, + const folly::dynamic &props, bool layoutStyleUpdated, bool forceFabricCommit) noexcept; @@ -174,7 +156,8 @@ class NativeAnimatedNodesManager { */ bool commitProps(); - void scheduleOnUI(UiTask&& task) { + void scheduleOnUI(UiTask &&task) + { { std::lock_guard lock(uiTasksMutex_); operations_.push_back(std::move(task)); @@ -190,8 +173,7 @@ class NativeAnimatedNodesManager { void startRenderCallbackIfNeeded(bool isAsync); - void updateNodes( - const std::set& finishedAnimationValueNodes = {}) noexcept; + void updateNodes(const std::set &finishedAnimationValueNodes = {}) noexcept; folly::dynamic managedProps(Tag tag) const noexcept; @@ -212,22 +194,16 @@ class NativeAnimatedNodesManager { std::shared_ptr ensureEventEmitterListener() noexcept; - void handleAnimatedEvent( - Tag tag, - const std::string& eventName, - const EventPayload& payload) noexcept; + void handleAnimatedEvent(Tag tag, const std::string &eventName, const EventPayload &payload) noexcept; std::weak_ptr animationBackend_; - std::unique_ptr animatedNode( - Tag tag, - const folly::dynamic& config) noexcept; + std::unique_ptr animatedNode(Tag tag, const folly::dynamic &config) noexcept; static thread_local bool isOnRenderThread_; std::mutex animatedNodesCreatedAsyncMutex_; - std::unordered_map> - animatedNodesCreatedAsync_; + std::unordered_map> animatedNodesCreatedAsync_; std::unordered_map> animatedNodes_; std::unordered_map connectedAnimatedNodes_; std::unordered_map> activeAnimations_; diff --git a/packages/react-native/ReactCommon/react/renderer/animated/NativeAnimatedNodesManagerProvider.cpp b/packages/react-native/ReactCommon/react/renderer/animated/NativeAnimatedNodesManagerProvider.cpp index 61c2b13a716..87859a666f5 100644 --- a/packages/react-native/ReactCommon/react/renderer/animated/NativeAnimatedNodesManagerProvider.cpp +++ b/packages/react-native/ReactCommon/react/renderer/animated/NativeAnimatedNodesManagerProvider.cpp @@ -134,22 +134,24 @@ NativeAnimatedNodesManagerProvider::getOrCreate( addEventEmitterListener( nativeAnimatedNodesManager_->getEventEmitterListener()); - uiManager->addEventListener(std::make_shared( - [eventEmitterListenerContainerWeak = - std::weak_ptr( - eventEmitterListenerContainer_)](const RawEvent& rawEvent) { - const auto& eventTarget = rawEvent.eventTarget; - const auto& eventPayload = rawEvent.eventPayload; - if (eventTarget && eventPayload) { - if (auto eventEmitterListenerContainer = - eventEmitterListenerContainerWeak.lock(); - eventEmitterListenerContainer != nullptr) { - return eventEmitterListenerContainer->willDispatchEvent( - eventTarget->getTag(), rawEvent.type, *eventPayload); - } - } - return false; - })); + uiManager->addEventListener( + std::make_shared( + [eventEmitterListenerContainerWeak = + std::weak_ptr( + eventEmitterListenerContainer_)]( + const RawEvent& rawEvent) { + const auto& eventTarget = rawEvent.eventTarget; + const auto& eventPayload = rawEvent.eventPayload; + if (eventTarget && eventPayload) { + if (auto eventEmitterListenerContainer = + eventEmitterListenerContainerWeak.lock(); + eventEmitterListenerContainer != nullptr) { + return eventEmitterListenerContainer->willDispatchEvent( + eventTarget->getTag(), rawEvent.type, *eventPayload); + } + } + return false; + })); uiManager->setNativeAnimatedDelegate(nativeAnimatedDelegate_); diff --git a/packages/react-native/ReactCommon/react/renderer/animated/NativeAnimatedNodesManagerProvider.h b/packages/react-native/ReactCommon/react/renderer/animated/NativeAnimatedNodesManagerProvider.h index f1b60a84ef4..362fa77e7a3 100644 --- a/packages/react-native/ReactCommon/react/renderer/animated/NativeAnimatedNodesManagerProvider.h +++ b/packages/react-native/ReactCommon/react/renderer/animated/NativeAnimatedNodesManagerProvider.h @@ -17,12 +17,10 @@ class AnimatedMountingOverrideDelegate; class NativeAnimatedNodesManagerProvider { public: - using FrameRateListenerCallback = - std::function; + using FrameRateListenerCallback = std::function; // when isAsync is true, it means StartOnRenderCallback is invoked from js // thread, otherwise from main thread - using StartOnRenderCallback = - std::function&&, bool /* isAsync */)>; + using StartOnRenderCallback = std::function &&, bool /* isAsync */)>; using StopOnRenderCallback = NativeAnimatedNodesManager::StopOnRenderCallback; NativeAnimatedNodesManagerProvider( @@ -31,12 +29,11 @@ class NativeAnimatedNodesManagerProvider { FrameRateListenerCallback frameRateListenerCallback = nullptr); std::shared_ptr getOrCreate( - jsi::Runtime& runtime, + jsi::Runtime &runtime, std::shared_ptr jsInvoker); // Native Event Listeners - void addEventEmitterListener( - const std::shared_ptr& listener); + void addEventEmitterListener(const std::shared_ptr &listener); std::shared_ptr getEventEmitterListener(); @@ -48,8 +45,7 @@ class NativeAnimatedNodesManagerProvider { std::shared_ptr eventEmitterListener_; std::shared_ptr nativeAnimatedDelegate_; - std::shared_ptr - animatedMountingOverrideDelegate_; + std::shared_ptr animatedMountingOverrideDelegate_; FrameRateListenerCallback frameRateListenerCallback_; @@ -59,24 +55,21 @@ class NativeAnimatedNodesManagerProvider { std::unique_ptr mergedValueDispatcher_; }; -class UIManagerNativeAnimatedDelegateImpl - : public UIManagerNativeAnimatedDelegate { +class UIManagerNativeAnimatedDelegateImpl : public UIManagerNativeAnimatedDelegate { public: explicit UIManagerNativeAnimatedDelegateImpl( - NativeAnimatedNodesManagerProvider::FrameRateListenerCallback - frameRateListenerCallback); + NativeAnimatedNodesManagerProvider::FrameRateListenerCallback frameRateListenerCallback); void runAnimationFrame() override; - void setNativeAnimatedNodesManager( - std::weak_ptr manager) { + void setNativeAnimatedNodesManager(std::weak_ptr manager) + { nativeAnimatedNodesManager_ = manager; } private: std::weak_ptr nativeAnimatedNodesManager_; - NativeAnimatedNodesManagerProvider::FrameRateListenerCallback - frameRateListenerCallback_; + NativeAnimatedNodesManagerProvider::FrameRateListenerCallback frameRateListenerCallback_; }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/animated/drivers/AnimationDriver.h b/packages/react-native/ReactCommon/react/renderer/animated/drivers/AnimationDriver.h index 5d810ae2b21..528ac782b70 100644 --- a/packages/react-native/ReactCommon/react/renderer/animated/drivers/AnimationDriver.h +++ b/packages/react-native/ReactCommon/react/renderer/animated/drivers/AnimationDriver.h @@ -29,20 +29,23 @@ class AnimationDriver { Tag animatedValueTag, std::optional endCallback, folly::dynamic config, - NativeAnimatedNodesManager* manager); + NativeAnimatedNodesManager *manager); virtual ~AnimationDriver() = default; void startAnimation(); void stopAnimation(bool ignoreCompletedHandlers = false); - inline int getId() const noexcept { + inline int getId() const noexcept + { return id_; } - inline Tag getAnimatedValueTag() const noexcept { + inline Tag getAnimatedValueTag() const noexcept + { return animatedValueTag_; } - bool getIsComplete() const noexcept { + bool getIsComplete() const noexcept + { return isComplete_; } @@ -51,21 +54,22 @@ class AnimationDriver { virtual void updateConfig(folly::dynamic config); #ifdef REACT_NATIVE_DEBUG - std::string debugID() const { - return (config_.count("debugID") != 0u) ? config_["debugID"].asString() - : ""; + std::string debugID() const + { + return (config_.count("debugID") != 0u) ? config_["debugID"].asString() : ""; } #endif - static std::optional getDriverTypeByName( - const std::string& driverTypeName); + static std::optional getDriverTypeByName(const std::string &driverTypeName); protected: - virtual bool update(double /*timeDeltaMs*/, bool /*restarting*/) { + virtual bool update(double /*timeDeltaMs*/, bool /*restarting*/) + { return true; } - void markNodeUpdated(Tag tag) { + void markNodeUpdated(Tag tag) + { manager_->updatedNodeTags_.insert(tag); } @@ -73,7 +77,7 @@ class AnimationDriver { int id_{0}; Tag animatedValueTag_{}; // Tag of a ValueAnimatedNode int iterations_{0}; - NativeAnimatedNodesManager* manager_; + NativeAnimatedNodesManager *manager_; bool isComplete_{false}; int currentIteration_{0}; diff --git a/packages/react-native/ReactCommon/react/renderer/animated/drivers/AnimationDriverUtils.h b/packages/react-native/ReactCommon/react/renderer/animated/drivers/AnimationDriverUtils.h index f99a74857c3..4fb5b97bd66 100644 --- a/packages/react-native/ReactCommon/react/renderer/animated/drivers/AnimationDriverUtils.h +++ b/packages/react-native/ReactCommon/react/renderer/animated/drivers/AnimationDriverUtils.h @@ -30,7 +30,8 @@ inline double interpolate( double outputMin, double outputMax, std::string_view extrapolateLeft, - std::string_view extrapolateRight) { + std::string_view extrapolateRight) +{ auto result = inputValue; // Extrapolate @@ -57,8 +58,7 @@ inline double interpolate( return outputMax; } - return outputMin + - (outputMax - outputMin) * (result - inputMin) / (inputMax - inputMin); + return outputMin + (outputMax - outputMin) * (result - inputMin) / (inputMax - inputMin); } } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/animated/drivers/DecayAnimationDriver.h b/packages/react-native/ReactCommon/react/renderer/animated/drivers/DecayAnimationDriver.h index df94855f587..8991b22664e 100644 --- a/packages/react-native/ReactCommon/react/renderer/animated/drivers/DecayAnimationDriver.h +++ b/packages/react-native/ReactCommon/react/renderer/animated/drivers/DecayAnimationDriver.h @@ -22,7 +22,7 @@ class DecayAnimationDriver : public AnimationDriver { Tag animatedValueTag, std::optional endCallback, folly::dynamic config, - NativeAnimatedNodesManager* manager); + NativeAnimatedNodesManager *manager); protected: bool update(double timeDeltaMs, bool restarting) override; diff --git a/packages/react-native/ReactCommon/react/renderer/animated/drivers/FrameAnimationDriver.h b/packages/react-native/ReactCommon/react/renderer/animated/drivers/FrameAnimationDriver.h index c11c926948d..7bcbc4a0448 100644 --- a/packages/react-native/ReactCommon/react/renderer/animated/drivers/FrameAnimationDriver.h +++ b/packages/react-native/ReactCommon/react/renderer/animated/drivers/FrameAnimationDriver.h @@ -22,7 +22,7 @@ class FrameAnimationDriver : public AnimationDriver { Tag animatedValueTag, std::optional endCallback, folly::dynamic config, - NativeAnimatedNodesManager* manager); + NativeAnimatedNodesManager *manager); protected: bool update(double timeDeltaMs, bool restarting) override; diff --git a/packages/react-native/ReactCommon/react/renderer/animated/drivers/SpringAnimationDriver.h b/packages/react-native/ReactCommon/react/renderer/animated/drivers/SpringAnimationDriver.h index 87fe1e056a5..ce62c9c5fb0 100644 --- a/packages/react-native/ReactCommon/react/renderer/animated/drivers/SpringAnimationDriver.h +++ b/packages/react-native/ReactCommon/react/renderer/animated/drivers/SpringAnimationDriver.h @@ -22,15 +22,14 @@ class SpringAnimationDriver : public AnimationDriver { Tag animatedValueTag, std::optional endCallback, folly::dynamic config, - NativeAnimatedNodesManager* manager); + NativeAnimatedNodesManager *manager); protected: bool update(double timeDeltaMs, bool restarting) override; private: std::tuple getValueAndVelocityForTime(double time) const; - bool isAtRest(double currentVelocity, double currentValue, double endValue) - const; + bool isAtRest(double currentVelocity, double currentValue, double endValue) const; bool isOvershooting(double currentValue) const; double springStiffness_{0}; diff --git a/packages/react-native/ReactCommon/react/renderer/animated/event_drivers/EventAnimationDriver.h b/packages/react-native/ReactCommon/react/renderer/animated/event_drivers/EventAnimationDriver.h index 07a4633a100..97dc65a86c8 100644 --- a/packages/react-native/ReactCommon/react/renderer/animated/event_drivers/EventAnimationDriver.h +++ b/packages/react-native/ReactCommon/react/renderer/animated/event_drivers/EventAnimationDriver.h @@ -22,15 +22,14 @@ namespace facebook::react { class EventAnimationDriver { public: - EventAnimationDriver( - const std::vector& eventPath, - Tag animatedValueTag); + EventAnimationDriver(const std::vector &eventPath, Tag animatedValueTag); ~EventAnimationDriver() = default; - std::optional getValueFromPayload(const EventPayload& eventPayload); + std::optional getValueFromPayload(const EventPayload &eventPayload); - Tag getAnimatedNodeTag() const { + Tag getAnimatedNodeTag() const + { return animatedValueTag_; } @@ -44,8 +43,8 @@ struct EventAnimationDriverKey { Tag viewTag; std::string eventName; - bool operator==( - const facebook::react::EventAnimationDriverKey& rhs) const noexcept { + bool operator==(const facebook::react::EventAnimationDriverKey &rhs) const noexcept + { return viewTag == rhs.viewTag && eventName == rhs.eventName; } }; @@ -55,9 +54,9 @@ struct EventAnimationDriverKey { namespace std { template <> struct hash { - size_t operator()(const facebook::react::EventAnimationDriverKey& key) const { - return std::hash()(key.viewTag) ^ - std::hash()(key.eventName); + size_t operator()(const facebook::react::EventAnimationDriverKey &key) const + { + return std::hash()(key.viewTag) ^ std::hash()(key.eventName); } }; } // namespace std diff --git a/packages/react-native/ReactCommon/react/renderer/animated/internal/AnimatedMountingOverrideDelegate.cpp b/packages/react-native/ReactCommon/react/renderer/animated/internal/AnimatedMountingOverrideDelegate.cpp index d8fd427667d..4aba58cc15c 100644 --- a/packages/react-native/ReactCommon/react/renderer/animated/internal/AnimatedMountingOverrideDelegate.cpp +++ b/packages/react-native/ReactCommon/react/renderer/animated/internal/AnimatedMountingOverrideDelegate.cpp @@ -21,7 +21,7 @@ AnimatedMountingOverrideDelegate::AnimatedMountingOverrideDelegate( const Scheduler& scheduler) : MountingOverrideDelegate(), animatedManager_(&animatedManager), - scheduler_(&scheduler){}; + scheduler_(&scheduler) {}; bool AnimatedMountingOverrideDelegate::shouldOverridePullTransaction() const { if (animatedManager_ != nullptr) { @@ -91,10 +91,11 @@ AnimatedMountingOverrideDelegate::pullTransaction( NullValueStrategy::Override); #endif - filteredMutations.emplace_back(ShadowViewMutation::UpdateMutation( - mutation.oldChildShadowView, - std::move(modifiedNewChildShadowView), - mutation.parentTag)); + filteredMutations.emplace_back( + ShadowViewMutation::UpdateMutation( + mutation.oldChildShadowView, + std::move(modifiedNewChildShadowView), + mutation.parentTag)); } } } diff --git a/packages/react-native/ReactCommon/react/renderer/animated/internal/AnimatedMountingOverrideDelegate.h b/packages/react-native/ReactCommon/react/renderer/animated/internal/AnimatedMountingOverrideDelegate.h index 3cad061ca48..f358227caa6 100644 --- a/packages/react-native/ReactCommon/react/renderer/animated/internal/AnimatedMountingOverrideDelegate.h +++ b/packages/react-native/ReactCommon/react/renderer/animated/internal/AnimatedMountingOverrideDelegate.h @@ -21,22 +21,20 @@ class NativeAnimatedNodesManager; class AnimatedMountingOverrideDelegate : public MountingOverrideDelegate { public: - AnimatedMountingOverrideDelegate( - NativeAnimatedNodesManager& animatedManager, - const Scheduler& scheduler); + AnimatedMountingOverrideDelegate(NativeAnimatedNodesManager &animatedManager, const Scheduler &scheduler); bool shouldOverridePullTransaction() const override; std::optional pullTransaction( SurfaceId surfaceId, MountingTransaction::Number transactionNumber, - const TransactionTelemetry& telemetry, + const TransactionTelemetry &telemetry, ShadowViewMutationList mutations) const override; private: - mutable NativeAnimatedNodesManager* animatedManager_; + mutable NativeAnimatedNodesManager *animatedManager_; - const Scheduler* scheduler_; + const Scheduler *scheduler_; }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/animated/internal/NativeAnimatedAllowlist.h b/packages/react-native/ReactCommon/react/renderer/animated/internal/NativeAnimatedAllowlist.h index a1769d7c617..849f260ce87 100644 --- a/packages/react-native/ReactCommon/react/renderer/animated/internal/NativeAnimatedAllowlist.h +++ b/packages/react-native/ReactCommon/react/renderer/animated/internal/NativeAnimatedAllowlist.h @@ -12,7 +12,8 @@ namespace facebook::react { -inline static std::unordered_set getDirectManipulationAllowlist() { +inline static std::unordered_set getDirectManipulationAllowlist() +{ /** * Direct manipulation eligible styles allowed by the NativeAnimated JS * implementation. Keep in sync with diff --git a/packages/react-native/ReactCommon/react/renderer/animated/nodes/AdditionAnimatedNode.h b/packages/react-native/ReactCommon/react/renderer/animated/nodes/AdditionAnimatedNode.h index 101941e4a32..5167c1c8372 100644 --- a/packages/react-native/ReactCommon/react/renderer/animated/nodes/AdditionAnimatedNode.h +++ b/packages/react-native/ReactCommon/react/renderer/animated/nodes/AdditionAnimatedNode.h @@ -17,11 +17,10 @@ namespace facebook::react { class AdditionAnimatedNode final : public OperatorAnimatedNode { public: - AdditionAnimatedNode( - Tag tag, - const folly::dynamic& config, - NativeAnimatedNodesManager& manager) - : OperatorAnimatedNode(tag, config, manager) {} + AdditionAnimatedNode(Tag tag, const folly::dynamic &config, NativeAnimatedNodesManager &manager) + : OperatorAnimatedNode(tag, config, manager) + { + } void update() override; }; diff --git a/packages/react-native/ReactCommon/react/renderer/animated/nodes/AnimatedNode.h b/packages/react-native/ReactCommon/react/renderer/animated/nodes/AnimatedNode.h index d26b9fae526..fc7e3842f53 100644 --- a/packages/react-native/ReactCommon/react/renderer/animated/nodes/AnimatedNode.h +++ b/packages/react-native/ReactCommon/react/renderer/animated/nodes/AnimatedNode.h @@ -44,18 +44,19 @@ class AnimatedNode { folly::dynamic config, // TODO: T190028913 maybe pass in strongly typed data when constructing // AnimatedNode - NativeAnimatedNodesManager& manager, + NativeAnimatedNodesManager &manager, AnimatedNodeType type); // Detach Node virtual ~AnimatedNode() = default; - AnimatedNode(AnimatedNode&&) noexcept = default; - AnimatedNode& operator=(AnimatedNode&&) noexcept = default; - AnimatedNode(const AnimatedNode&) = default; - AnimatedNode& operator=(const AnimatedNode&) = default; + AnimatedNode(AnimatedNode &&) noexcept = default; + AnimatedNode &operator=(AnimatedNode &&) noexcept = default; + AnimatedNode(const AnimatedNode &) = default; + AnimatedNode &operator=(const AnimatedNode &) = default; - Tag tag() const noexcept { + Tag tag() const noexcept + { return tag_; } @@ -63,23 +64,25 @@ class AnimatedNode { void removeChild(Tag tag); - const std::unordered_set& getChildren() const noexcept { + const std::unordered_set &getChildren() const noexcept + { return children_; } - AnimatedNodeType type() const noexcept { + AnimatedNodeType type() const noexcept + { return type_; } - const folly::dynamic& getConfig() const noexcept { + const folly::dynamic &getConfig() const noexcept + { return config_; } #ifdef REACT_NATIVE_DEBUG - std::string debugID() const { - return (getConfig().count("debugID") != 0u) - ? getConfig()["debugID"].asString() - : ""; + std::string debugID() const + { + return (getConfig().count("debugID") != 0u) ? getConfig()["debugID"].asString() : ""; } #endif @@ -88,8 +91,7 @@ class AnimatedNode { virtual void onDetachedFromNode(Tag /*animatedNodeTag*/) {} virtual void onAttachToNode(Tag /*animatedNodeTag*/) {} - static std::optional getNodeTypeByName( - const std::string& nodeTypeName); + static std::optional getNodeTypeByName(const std::string &nodeTypeName); int activeIncomingNodes = 0; int bfsColor = 0; @@ -97,9 +99,9 @@ class AnimatedNode { static constexpr int INITIAL_BFS_COLOR = 0; protected: - AnimatedNode* getChildNode(Tag tag); + AnimatedNode *getChildNode(Tag tag); Tag tag_{0}; - NativeAnimatedNodesManager* manager_; + NativeAnimatedNodesManager *manager_; AnimatedNodeType type_; std::unordered_set children_{}; diff --git a/packages/react-native/ReactCommon/react/renderer/animated/nodes/ColorAnimatedNode.h b/packages/react-native/ReactCommon/react/renderer/animated/nodes/ColorAnimatedNode.h index 4a9e8c59652..eb04ad931b2 100644 --- a/packages/react-native/ReactCommon/react/renderer/animated/nodes/ColorAnimatedNode.h +++ b/packages/react-native/ReactCommon/react/renderer/animated/nodes/ColorAnimatedNode.h @@ -18,10 +18,7 @@ namespace facebook::react { class ColorAnimatedNode final : public AnimatedNode { public: - ColorAnimatedNode( - Tag tag, - const folly::dynamic& config, - NativeAnimatedNodesManager& manager); + ColorAnimatedNode(Tag tag, const folly::dynamic &config, NativeAnimatedNodesManager &manager); void update() override; diff --git a/packages/react-native/ReactCommon/react/renderer/animated/nodes/DiffClampAnimatedNode.h b/packages/react-native/ReactCommon/react/renderer/animated/nodes/DiffClampAnimatedNode.h index ecf15ba25e0..3be413383a3 100644 --- a/packages/react-native/ReactCommon/react/renderer/animated/nodes/DiffClampAnimatedNode.h +++ b/packages/react-native/ReactCommon/react/renderer/animated/nodes/DiffClampAnimatedNode.h @@ -17,10 +17,7 @@ namespace facebook::react { class DiffClampAnimatedNode final : public ValueAnimatedNode { public: - DiffClampAnimatedNode( - Tag tag, - const folly::dynamic& config, - NativeAnimatedNodesManager& manager); + DiffClampAnimatedNode(Tag tag, const folly::dynamic &config, NativeAnimatedNodesManager &manager); void update() override; diff --git a/packages/react-native/ReactCommon/react/renderer/animated/nodes/DivisionAnimatedNode.h b/packages/react-native/ReactCommon/react/renderer/animated/nodes/DivisionAnimatedNode.h index 63bf599bebb..9227738db4c 100644 --- a/packages/react-native/ReactCommon/react/renderer/animated/nodes/DivisionAnimatedNode.h +++ b/packages/react-native/ReactCommon/react/renderer/animated/nodes/DivisionAnimatedNode.h @@ -17,11 +17,10 @@ namespace facebook::react { class DivisionAnimatedNode final : public OperatorAnimatedNode { public: - DivisionAnimatedNode( - Tag tag, - const folly::dynamic& config, - NativeAnimatedNodesManager& manager) - : OperatorAnimatedNode(tag, config, manager) {} + DivisionAnimatedNode(Tag tag, const folly::dynamic &config, NativeAnimatedNodesManager &manager) + : OperatorAnimatedNode(tag, config, manager) + { + } void update() override; }; diff --git a/packages/react-native/ReactCommon/react/renderer/animated/nodes/InterpolationAnimatedNode.h b/packages/react-native/ReactCommon/react/renderer/animated/nodes/InterpolationAnimatedNode.h index 89130e98ac9..32ad166252c 100644 --- a/packages/react-native/ReactCommon/react/renderer/animated/nodes/InterpolationAnimatedNode.h +++ b/packages/react-native/ReactCommon/react/renderer/animated/nodes/InterpolationAnimatedNode.h @@ -20,10 +20,7 @@ namespace facebook::react { class InterpolationAnimatedNode final : public ValueAnimatedNode { public: - InterpolationAnimatedNode( - Tag tag, - const folly::dynamic& config, - NativeAnimatedNodesManager& manager); + InterpolationAnimatedNode(Tag tag, const folly::dynamic &config, NativeAnimatedNodesManager &manager); void update() override; void onDetachedFromNode(Tag animatedNodeTag) override; diff --git a/packages/react-native/ReactCommon/react/renderer/animated/nodes/ModulusAnimatedNode.h b/packages/react-native/ReactCommon/react/renderer/animated/nodes/ModulusAnimatedNode.h index 78326347fe8..9d0a30c9b22 100644 --- a/packages/react-native/ReactCommon/react/renderer/animated/nodes/ModulusAnimatedNode.h +++ b/packages/react-native/ReactCommon/react/renderer/animated/nodes/ModulusAnimatedNode.h @@ -17,10 +17,7 @@ namespace facebook::react { class ModulusAnimatedNode final : public ValueAnimatedNode { public: - ModulusAnimatedNode( - Tag tag, - const folly::dynamic& config, - NativeAnimatedNodesManager& manager); + ModulusAnimatedNode(Tag tag, const folly::dynamic &config, NativeAnimatedNodesManager &manager); void update() override; diff --git a/packages/react-native/ReactCommon/react/renderer/animated/nodes/MultiplicationAnimatedNode.h b/packages/react-native/ReactCommon/react/renderer/animated/nodes/MultiplicationAnimatedNode.h index e21e40aa592..e402b3069eb 100644 --- a/packages/react-native/ReactCommon/react/renderer/animated/nodes/MultiplicationAnimatedNode.h +++ b/packages/react-native/ReactCommon/react/renderer/animated/nodes/MultiplicationAnimatedNode.h @@ -17,11 +17,10 @@ namespace facebook::react { class MultiplicationAnimatedNode final : public OperatorAnimatedNode { public: - MultiplicationAnimatedNode( - Tag tag, - const folly::dynamic& config, - NativeAnimatedNodesManager& manager) - : OperatorAnimatedNode(tag, config, manager) {} + MultiplicationAnimatedNode(Tag tag, const folly::dynamic &config, NativeAnimatedNodesManager &manager) + : OperatorAnimatedNode(tag, config, manager) + { + } void update() override; }; diff --git a/packages/react-native/ReactCommon/react/renderer/animated/nodes/ObjectAnimatedNode.h b/packages/react-native/ReactCommon/react/renderer/animated/nodes/ObjectAnimatedNode.h index 4be4c7596d9..eaaceaf1064 100644 --- a/packages/react-native/ReactCommon/react/renderer/animated/nodes/ObjectAnimatedNode.h +++ b/packages/react-native/ReactCommon/react/renderer/animated/nodes/ObjectAnimatedNode.h @@ -19,20 +19,15 @@ namespace facebook::react { class ObjectAnimatedNode final : public AnimatedNode { public: - ObjectAnimatedNode( - Tag tag, - const folly::dynamic& config, - NativeAnimatedNodesManager& manager); - void collectViewUpdates(std::string propKey, folly::dynamic& props); + ObjectAnimatedNode(Tag tag, const folly::dynamic &config, NativeAnimatedNodesManager &manager); + void collectViewUpdates(std::string propKey, folly::dynamic &props); private: - folly::dynamic collectViewUpdatesObjectHelper( - const folly::dynamic& value) const; + folly::dynamic collectViewUpdatesObjectHelper(const folly::dynamic &value) const; - folly::dynamic collectViewUpdatesArrayHelper( - const folly::dynamic& value) const; + folly::dynamic collectViewUpdatesArrayHelper(const folly::dynamic &value) const; - folly::dynamic getValueProp(const folly::dynamic& prop) const; + folly::dynamic getValueProp(const folly::dynamic &prop) const; }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/animated/nodes/PropsAnimatedNode.h b/packages/react-native/ReactCommon/react/renderer/animated/nodes/PropsAnimatedNode.h index 29e300b42f8..9d654a33b8e 100644 --- a/packages/react-native/ReactCommon/react/renderer/animated/nodes/PropsAnimatedNode.h +++ b/packages/react-native/ReactCommon/react/renderer/animated/nodes/PropsAnimatedNode.h @@ -19,19 +19,18 @@ namespace facebook::react { class PropsAnimatedNode final : public AnimatedNode { public: - PropsAnimatedNode( - Tag tag, - const folly::dynamic& config, - NativeAnimatedNodesManager& manager); + PropsAnimatedNode(Tag tag, const folly::dynamic &config, NativeAnimatedNodesManager &manager); void connectToView(Tag viewTag); void disconnectFromView(Tag viewTag); void restoreDefaultValues(); - Tag connectedViewTag() const { + Tag connectedViewTag() const + { return connectedViewTag_; } - folly::dynamic props() { + folly::dynamic props() + { std::lock_guard lock(propsMutex_); return props_; } diff --git a/packages/react-native/ReactCommon/react/renderer/animated/nodes/RoundAnimatedNode.h b/packages/react-native/ReactCommon/react/renderer/animated/nodes/RoundAnimatedNode.h index 6ef2d991237..dc5a03b03dd 100644 --- a/packages/react-native/ReactCommon/react/renderer/animated/nodes/RoundAnimatedNode.h +++ b/packages/react-native/ReactCommon/react/renderer/animated/nodes/RoundAnimatedNode.h @@ -23,10 +23,7 @@ namespace facebook::react { */ class RoundAnimatedNode : public ValueAnimatedNode { public: - RoundAnimatedNode( - Tag tag, - const folly::dynamic& config, - NativeAnimatedNodesManager& manager); + RoundAnimatedNode(Tag tag, const folly::dynamic &config, NativeAnimatedNodesManager &manager); void update() override; diff --git a/packages/react-native/ReactCommon/react/renderer/animated/nodes/StyleAnimatedNode.h b/packages/react-native/ReactCommon/react/renderer/animated/nodes/StyleAnimatedNode.h index 20883209f94..5e8031e0556 100644 --- a/packages/react-native/ReactCommon/react/renderer/animated/nodes/StyleAnimatedNode.h +++ b/packages/react-native/ReactCommon/react/renderer/animated/nodes/StyleAnimatedNode.h @@ -18,13 +18,11 @@ namespace facebook::react { class StyleAnimatedNode final : public AnimatedNode { public: - StyleAnimatedNode( - Tag tag, - const folly::dynamic& config, - NativeAnimatedNodesManager& manager); - void collectViewUpdates(folly::dynamic& props); + StyleAnimatedNode(Tag tag, const folly::dynamic &config, NativeAnimatedNodesManager &manager); + void collectViewUpdates(folly::dynamic &props); - bool isLayoutStyleUpdated() const noexcept { + bool isLayoutStyleUpdated() const noexcept + { return layoutStyleUpdated_; } diff --git a/packages/react-native/ReactCommon/react/renderer/animated/nodes/SubtractionAnimatedNode.h b/packages/react-native/ReactCommon/react/renderer/animated/nodes/SubtractionAnimatedNode.h index 6a6159035ad..04e418b88f4 100644 --- a/packages/react-native/ReactCommon/react/renderer/animated/nodes/SubtractionAnimatedNode.h +++ b/packages/react-native/ReactCommon/react/renderer/animated/nodes/SubtractionAnimatedNode.h @@ -18,11 +18,10 @@ namespace facebook::react { class SubtractionAnimatedNode final : public OperatorAnimatedNode { public: - SubtractionAnimatedNode( - Tag tag, - const folly::dynamic& config, - NativeAnimatedNodesManager& manager) - : OperatorAnimatedNode(tag, config, manager) {} + SubtractionAnimatedNode(Tag tag, const folly::dynamic &config, NativeAnimatedNodesManager &manager) + : OperatorAnimatedNode(tag, config, manager) + { + } void update() override; }; diff --git a/packages/react-native/ReactCommon/react/renderer/animated/nodes/TrackingAnimatedNode.h b/packages/react-native/ReactCommon/react/renderer/animated/nodes/TrackingAnimatedNode.h index e60a3bbed6c..d147ced26da 100644 --- a/packages/react-native/ReactCommon/react/renderer/animated/nodes/TrackingAnimatedNode.h +++ b/packages/react-native/ReactCommon/react/renderer/animated/nodes/TrackingAnimatedNode.h @@ -17,10 +17,7 @@ namespace facebook::react { class TrackingAnimatedNode final : public AnimatedNode { public: - TrackingAnimatedNode( - Tag tag, - const folly::dynamic& config, - NativeAnimatedNodesManager& manager); + TrackingAnimatedNode(Tag tag, const folly::dynamic &config, NativeAnimatedNodesManager &manager); void update() override; diff --git a/packages/react-native/ReactCommon/react/renderer/animated/nodes/TransformAnimatedNode.h b/packages/react-native/ReactCommon/react/renderer/animated/nodes/TransformAnimatedNode.h index dc587df1d05..7cc6d1537ab 100644 --- a/packages/react-native/ReactCommon/react/renderer/animated/nodes/TransformAnimatedNode.h +++ b/packages/react-native/ReactCommon/react/renderer/animated/nodes/TransformAnimatedNode.h @@ -24,11 +24,8 @@ struct TransformConfig { class TransformAnimatedNode final : public AnimatedNode { public: - TransformAnimatedNode( - Tag tag, - const folly::dynamic& config, - NativeAnimatedNodesManager& manager); + TransformAnimatedNode(Tag tag, const folly::dynamic &config, NativeAnimatedNodesManager &manager); - void collectViewUpdates(folly::dynamic& props); + void collectViewUpdates(folly::dynamic &props); }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/animated/nodes/ValueAnimatedNode.h b/packages/react-native/ReactCommon/react/renderer/animated/nodes/ValueAnimatedNode.h index 930bdf70174..e97a2ea5d26 100644 --- a/packages/react-native/ReactCommon/react/renderer/animated/nodes/ValueAnimatedNode.h +++ b/packages/react-native/ReactCommon/react/renderer/animated/nodes/ValueAnimatedNode.h @@ -21,10 +21,7 @@ using ValueListenerCallback = std::function; class ValueAnimatedNode : public AnimatedNode { public: - ValueAnimatedNode( - Tag tag, - const folly::dynamic& config, - NativeAnimatedNodesManager& manager); + ValueAnimatedNode(Tag tag, const folly::dynamic &config, NativeAnimatedNodesManager &manager); double getValue() const noexcept; double getRawValue() const noexcept; bool setRawValue(double value) noexcept; @@ -32,9 +29,10 @@ class ValueAnimatedNode : public AnimatedNode { bool setOffset(double offset) noexcept; void flattenOffset() noexcept; void extractOffset() noexcept; - void setValueListener(ValueListenerCallback&& callback) noexcept; + void setValueListener(ValueListenerCallback &&callback) noexcept; - bool getIsColorValue() const noexcept { + bool getIsColorValue() const noexcept + { return isColorValue_; } @@ -51,10 +49,7 @@ class ValueAnimatedNode : public AnimatedNode { class OperatorAnimatedNode : public ValueAnimatedNode { public: - OperatorAnimatedNode( - Tag tag, - const folly::dynamic& config, - NativeAnimatedNodesManager& manager); + OperatorAnimatedNode(Tag tag, const folly::dynamic &config, NativeAnimatedNodesManager &manager); protected: std::vector inputNodes_{}; diff --git a/packages/react-native/ReactCommon/react/renderer/animated/tests/AnimationTestsBase.h b/packages/react-native/ReactCommon/react/renderer/animated/tests/AnimationTestsBase.h index 1ff54930e68..2463b69d72e 100644 --- a/packages/react-native/ReactCommon/react/renderer/animated/tests/AnimationTestsBase.h +++ b/packages/react-native/ReactCommon/react/renderer/animated/tests/AnimationTestsBase.h @@ -22,14 +22,15 @@ class AnimationTestsBase : public testing::Test { AnimationTestsBase() = default; protected: - void initNodesManager() noexcept { + void initNodesManager() noexcept + { nodesManager_.reset(); nodesManager_ = std::make_shared( - [this](Tag reactTag, const folly::dynamic& changedProps) { + [this](Tag reactTag, const folly::dynamic &changedProps) { lastUpdatedNodeTag = reactTag; lastCommittedProps = changedProps; }, - [this](const std::unordered_map& nodesProps) { + [this](const std::unordered_map &nodesProps) { if (!nodesProps.empty()) { lastUpdatedNodeTag = nodesProps.begin()->first; lastCommittedProps = nodesProps.begin()->second; @@ -38,11 +39,13 @@ class AnimationTestsBase : public testing::Test { NativeAnimatedNodesManager::isOnRenderThread_ = true; } - bool nodeNeedsUpdate(Tag nodeTag) const { + bool nodeNeedsUpdate(Tag nodeTag) const + { return nodesManager_->updatedNodeTags_.contains(nodeTag); } - void runAnimationFrame(double timestamp) { + void runAnimationFrame(double timestamp) + { nodesManager_->onAnimationFrame(timestamp); } diff --git a/packages/react-native/ReactCommon/react/renderer/animationbackend/AnimatedProps.h b/packages/react-native/ReactCommon/react/renderer/animationbackend/AnimatedProps.h index 76d6eaaeeb0..d65411a812c 100644 --- a/packages/react-native/ReactCommon/react/renderer/animationbackend/AnimatedProps.h +++ b/packages/react-native/ReactCommon/react/renderer/animationbackend/AnimatedProps.h @@ -24,13 +24,13 @@ template struct AnimatedProp : AnimatedPropBase { T value; AnimatedProp() = default; - AnimatedProp(PropName propName, const T& value) - : AnimatedPropBase{propName}, value(std::move(value)) {} + AnimatedProp(PropName propName, const T &value) : AnimatedPropBase{propName}, value(std::move(value)) {} }; template -T get(const std::unique_ptr& animatedProp) { - return static_cast*>(animatedProp.get())->value; +T get(const std::unique_ptr &animatedProp) +{ + return static_cast *>(animatedProp.get())->value; } struct AnimatedProps { diff --git a/packages/react-native/ReactCommon/react/renderer/animationbackend/AnimatedPropsBuilder.h b/packages/react-native/ReactCommon/react/renderer/animationbackend/AnimatedPropsBuilder.h index e7a4d4ef11f..e52b73bc78d 100644 --- a/packages/react-native/ReactCommon/react/renderer/animationbackend/AnimatedPropsBuilder.h +++ b/packages/react-native/ReactCommon/react/renderer/animationbackend/AnimatedPropsBuilder.h @@ -15,32 +15,36 @@ struct AnimatedPropsBuilder { std::vector> props; std::unique_ptr rawProps; - void setOpacity(Float value) { + void setOpacity(Float value) + { props.push_back(std::make_unique>(OPACITY, value)); } - void setWidth(yoga::Style::SizeLength value) { - props.push_back( - std::make_unique>(WIDTH, value)); + void setWidth(yoga::Style::SizeLength value) + { + props.push_back(std::make_unique>(WIDTH, value)); } - void setHeight(yoga::Style::SizeLength value) { - props.push_back( - std::make_unique>(HEIGHT, value)); + void setHeight(yoga::Style::SizeLength value) + { + props.push_back(std::make_unique>(HEIGHT, value)); } - void setBorderRadii(CascadedBorderRadii& value) { - props.push_back(std::make_unique>( - BORDER_RADII, value)); + void setBorderRadii(CascadedBorderRadii &value) + { + props.push_back(std::make_unique>(BORDER_RADII, value)); } - void setTransform(Transform& t) { - props.push_back( - std::make_unique>(TRANSFORM, std::move(t))); + void setTransform(Transform &t) + { + props.push_back(std::make_unique>(TRANSFORM, std::move(t))); } - void storeDynamic(folly::dynamic& d) { + void storeDynamic(folly::dynamic &d) + { rawProps = std::make_unique(std::move(d)); } - void storeJSI(jsi::Runtime& runtime, jsi::Value& value) { + void storeJSI(jsi::Runtime &runtime, jsi::Value &value) + { rawProps = std::make_unique(runtime, value); } - AnimatedProps get() { + AnimatedProps get() + { return AnimatedProps{std::move(props), std::move(rawProps)}; } }; diff --git a/packages/react-native/ReactCommon/react/renderer/animationbackend/AnimationBackend.h b/packages/react-native/ReactCommon/react/renderer/animationbackend/AnimationBackend.h index 31e94b93586..9236370c382 100644 --- a/packages/react-native/ReactCommon/react/renderer/animationbackend/AnimationBackend.h +++ b/packages/react-native/ReactCommon/react/renderer/animationbackend/AnimationBackend.h @@ -20,7 +20,7 @@ namespace facebook::react { struct AnimationMutation { Tag tag; - const ShadowNodeFamily* family; + const ShadowNodeFamily *family; AnimatedProps props; }; @@ -29,35 +29,31 @@ using AnimationMutations = std::vector; class AnimationBackend : public UIManagerAnimationBackend { public: using Callback = std::function; - using StartOnRenderCallback = - std::function&&, bool /* isAsync */)>; + using StartOnRenderCallback = std::function &&, bool /* isAsync */)>; using StopOnRenderCallback = std::function; - using DirectManipulationCallback = - std::function; - using FabricCommitCallback = - std::function&)>; + using DirectManipulationCallback = std::function; + using FabricCommitCallback = std::function &)>; std::vector callbacks; const StartOnRenderCallback startOnRenderCallback_; const StopOnRenderCallback stopOnRenderCallback_; const DirectManipulationCallback directManipulationCallback_; const FabricCommitCallback fabricCommitCallback_; - UIManager* uiManager_; + UIManager *uiManager_; AnimationBackend( - StartOnRenderCallback&& startOnRenderCallback, - StopOnRenderCallback&& stopOnRenderCallback, - DirectManipulationCallback&& directManipulationCallback, - FabricCommitCallback&& fabricCommitCallback, - UIManager* uiManager); + StartOnRenderCallback &&startOnRenderCallback, + StopOnRenderCallback &&stopOnRenderCallback, + DirectManipulationCallback &&directManipulationCallback, + FabricCommitCallback &&fabricCommitCallback, + UIManager *uiManager); void commitUpdatesWithFamilies( - const std::unordered_set& families, - std::unordered_map& updates); - void synchronouslyUpdateProps( - const std::unordered_map& updates); + const std::unordered_set &families, + std::unordered_map &updates); + void synchronouslyUpdateProps(const std::unordered_map &updates); void onAnimationFrame(double timestamp) override; - void start(const Callback& callback, bool isAsync); + void start(const Callback &callback, bool isAsync); void stop(bool isAsync) override; }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/animations/LayoutAnimationCallbackWrapper.h b/packages/react-native/ReactCommon/react/renderer/animations/LayoutAnimationCallbackWrapper.h index 64c52d42615..53ba7915c49 100644 --- a/packages/react-native/ReactCommon/react/renderer/animations/LayoutAnimationCallbackWrapper.h +++ b/packages/react-native/ReactCommon/react/renderer/animations/LayoutAnimationCallbackWrapper.h @@ -14,11 +14,14 @@ namespace facebook::react { class LayoutAnimationCallbackWrapper { public: - LayoutAnimationCallbackWrapper(jsi::Function&& callback) - : callback_(std::make_shared(std::move(callback))) {} + LayoutAnimationCallbackWrapper(jsi::Function &&callback) + : callback_(std::make_shared(std::move(callback))) + { + } LayoutAnimationCallbackWrapper() : callback_(nullptr) {} - void call(jsi::Runtime& runtime) const { + void call(jsi::Runtime &runtime) const + { if (callback_) { callback_->call(runtime); callback_.reset(); diff --git a/packages/react-native/ReactCommon/react/renderer/animations/LayoutAnimationDriver.cpp b/packages/react-native/ReactCommon/react/renderer/animations/LayoutAnimationDriver.cpp index 3f70b7aeffc..5b634bfba16 100644 --- a/packages/react-native/ReactCommon/react/renderer/animations/LayoutAnimationDriver.cpp +++ b/packages/react-native/ReactCommon/react/renderer/animations/LayoutAnimationDriver.cpp @@ -55,8 +55,9 @@ void LayoutAnimationDriver::animationMutationsForFrame( animationInterpolationFactor, baselineShadowView, finalShadowView); // Create the mutation instruction - mutationsList.emplace_back(ShadowViewMutation::UpdateMutation( - keyframe.viewPrev, mutatedShadowView, keyframe.parentTag)); + mutationsList.emplace_back( + ShadowViewMutation::UpdateMutation( + keyframe.viewPrev, mutatedShadowView, keyframe.parentTag)); PrintMutationInstruction("Animation Progress:", mutationsList.back()); diff --git a/packages/react-native/ReactCommon/react/renderer/animations/LayoutAnimationDriver.h b/packages/react-native/ReactCommon/react/renderer/animations/LayoutAnimationDriver.h index 3ddbc0884d4..7e22dfe8d15 100644 --- a/packages/react-native/ReactCommon/react/renderer/animations/LayoutAnimationDriver.h +++ b/packages/react-native/ReactCommon/react/renderer/animations/LayoutAnimationDriver.h @@ -17,18 +17,15 @@ class LayoutAnimationDriver : public LayoutAnimationKeyFrameManager { public: LayoutAnimationDriver( RuntimeExecutor runtimeExecutor, - std::shared_ptr& contextContainer, - LayoutAnimationStatusDelegate* delegate) - : LayoutAnimationKeyFrameManager( - runtimeExecutor, - contextContainer, - delegate) {} + std::shared_ptr &contextContainer, + LayoutAnimationStatusDelegate *delegate) + : LayoutAnimationKeyFrameManager(runtimeExecutor, contextContainer, delegate) + { + } protected: - virtual void animationMutationsForFrame( - SurfaceId surfaceId, - ShadowViewMutation::List& mutationsList, - uint64_t now) const override; + virtual void animationMutationsForFrame(SurfaceId surfaceId, ShadowViewMutation::List &mutationsList, uint64_t now) + const override; }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/animations/LayoutAnimationKeyFrameManager.cpp b/packages/react-native/ReactCommon/react/renderer/animations/LayoutAnimationKeyFrameManager.cpp index 22562fd67bf..a71b4fb06a9 100644 --- a/packages/react-native/ReactCommon/react/renderer/animations/LayoutAnimationKeyFrameManager.cpp +++ b/packages/react-native/ReactCommon/react/renderer/animations/LayoutAnimationKeyFrameManager.cpp @@ -122,14 +122,15 @@ void LayoutAnimationKeyFrameManager::uiManagerDidConfigureNextLayoutAnimation( if (layoutAnimationConfig) { std::scoped_lock lock(currentAnimationMutex_); - uiManagerDidConfigureNextLayoutAnimation(LayoutAnimation{ - .surfaceId = -1, - .startTime = 0, - .completed = false, - .layoutAnimationConfig = *layoutAnimationConfig, - .successCallback = successCallback, - .failureCallback = failureCallback, - .keyFrames = {}}); + uiManagerDidConfigureNextLayoutAnimation( + LayoutAnimation{ + .surfaceId = -1, + .startTime = 0, + .completed = false, + .layoutAnimationConfig = *layoutAnimationConfig, + .successCallback = successCallback, + .failureCallback = failureCallback, + .keyFrames = {}}); } else { LOG(ERROR) << "Parsing LayoutAnimationConfig failed: " << (folly::dynamic)config; @@ -1175,25 +1176,31 @@ void LayoutAnimationKeyFrameManager::queueFinalMutationsForCompletedKeyFrame( // For CREATE/INSERT this will contain CREATE, INSERT in that order. // For REMOVE/DELETE, same. case ShadowViewMutation::Type::Create: - mutationsList.push_back(ShadowViewMutation::CreateMutation( - finalMutation.newChildShadowView)); + mutationsList.push_back( + ShadowViewMutation::CreateMutation( + finalMutation.newChildShadowView)); break; case ShadowViewMutation::Type::Delete: mutationsList.push_back(ShadowViewMutation::DeleteMutation(prev)); break; case ShadowViewMutation::Type::Insert: - mutationsList.push_back(ShadowViewMutation::InsertMutation( - finalMutation.parentTag, - finalMutation.newChildShadowView, - finalMutation.index)); + mutationsList.push_back( + ShadowViewMutation::InsertMutation( + finalMutation.parentTag, + finalMutation.newChildShadowView, + finalMutation.index)); break; case ShadowViewMutation::Type::Remove: - mutationsList.push_back(ShadowViewMutation::RemoveMutation( - finalMutation.parentTag, prev, finalMutation.index)); + mutationsList.push_back( + ShadowViewMutation::RemoveMutation( + finalMutation.parentTag, prev, finalMutation.index)); break; case ShadowViewMutation::Type::Update: - mutationsList.push_back(ShadowViewMutation::UpdateMutation( - prev, finalMutation.newChildShadowView, finalMutation.parentTag)); + mutationsList.push_back( + ShadowViewMutation::UpdateMutation( + prev, + finalMutation.newChildShadowView, + finalMutation.parentTag)); break; } if (finalMutation.newChildShadowView.tag > 0) { diff --git a/packages/react-native/ReactCommon/react/renderer/animations/LayoutAnimationKeyFrameManager.h b/packages/react-native/ReactCommon/react/renderer/animations/LayoutAnimationKeyFrameManager.h index 1de8349848d..977be17b0a4 100644 --- a/packages/react-native/ReactCommon/react/renderer/animations/LayoutAnimationKeyFrameManager.h +++ b/packages/react-native/ReactCommon/react/renderer/animations/LayoutAnimationKeyFrameManager.h @@ -24,36 +24,32 @@ namespace facebook::react { #ifdef LAYOUT_ANIMATION_VERBOSE_LOGGING -void PrintMutationInstruction( - std::string message, - const ShadowViewMutation& mutation); +void PrintMutationInstruction(std::string message, const ShadowViewMutation &mutation); void PrintMutationInstructionRelative( std::string message, - const ShadowViewMutation& mutation, - const ShadowViewMutation& relativeMutation); + const ShadowViewMutation &mutation, + const ShadowViewMutation &relativeMutation); #else #define PrintMutationInstruction(a, b) #define PrintMutationInstructionRelative(a, b, c) #endif -class LayoutAnimationKeyFrameManager : public UIManagerAnimationDelegate, - public MountingOverrideDelegate { +class LayoutAnimationKeyFrameManager : public UIManagerAnimationDelegate, public MountingOverrideDelegate { public: LayoutAnimationKeyFrameManager( RuntimeExecutor runtimeExecutor, - std::shared_ptr& contextContainer, - LayoutAnimationStatusDelegate* delegate); + std::shared_ptr &contextContainer, + LayoutAnimationStatusDelegate *delegate); #pragma mark - UIManagerAnimationDelegate methods void uiManagerDidConfigureNextLayoutAnimation( - jsi::Runtime& runtime, - const RawValue& config, - const jsi::Value& successCallbackValue, - const jsi::Value& failureCallbackValue) const override; + jsi::Runtime &runtime, + const RawValue &config, + const jsi::Value &successCallbackValue, + const jsi::Value &failureCallbackValue) const override; - void setComponentDescriptorRegistry(const SharedComponentDescriptorRegistry& - componentDescriptorRegistry) override; + void setComponentDescriptorRegistry(const SharedComponentDescriptorRegistry &componentDescriptorRegistry) override; // TODO: add SurfaceId to this API as well bool shouldAnimateFrame() const override; @@ -70,20 +66,18 @@ class LayoutAnimationKeyFrameManager : public UIManagerAnimationDelegate, std::optional pullTransaction( SurfaceId surfaceId, MountingTransaction::Number number, - const TransactionTelemetry& telemetry, + const TransactionTelemetry &telemetry, ShadowViewMutationList mutations) const override; // Exposed for testing. - void uiManagerDidConfigureNextLayoutAnimation( - LayoutAnimation layoutAnimation) const; + void uiManagerDidConfigureNextLayoutAnimation(LayoutAnimation layoutAnimation) const; // LayoutAnimationStatusDelegate - this is for the platform to get // signal when animations start and complete. Setting and resetting this // delegate is protected by a mutex; ALL method calls into this delegate are // also protected by the mutex! The only way to set this without a mutex is // via a constructor. - void setLayoutAnimationStatusDelegate( - LayoutAnimationStatusDelegate* delegate) const; + void setLayoutAnimationStatusDelegate(LayoutAnimationStatusDelegate *delegate) const; void setClockNow(std::function now); @@ -100,9 +94,8 @@ class LayoutAnimationKeyFrameManager : public UIManagerAnimationDelegate, */ mutable std::vector inflightAnimations_{}; - bool hasComponentDescriptorForShadowView(const ShadowView& shadowView) const; - const ComponentDescriptor& getComponentDescriptorForShadowView( - const ShadowView& shadowView) const; + bool hasComponentDescriptorForShadowView(const ShadowView &shadowView) const; + const ComponentDescriptor &getComponentDescriptorForShadowView(const ShadowView &shadowView) const; /** * Given a `progress` between 0 and 1, a mutation and LayoutAnimation config, @@ -113,34 +106,30 @@ class LayoutAnimationKeyFrameManager : public UIManagerAnimationDelegate, * @param finalView the final configuration of the ShadowView * @return the current ShadowView */ - ShadowView createInterpolatedShadowView( - Float progress, - const ShadowView& startingView, - const ShadowView& finalView) const; + ShadowView createInterpolatedShadowView(Float progress, const ShadowView &startingView, const ShadowView &finalView) + const; - void callCallback(const LayoutAnimationCallbackWrapper& callback) const; + void callCallback(const LayoutAnimationCallbackWrapper &callback) const; - virtual void animationMutationsForFrame( - SurfaceId surfaceId, - ShadowViewMutation::List& mutationsList, - uint64_t now) const = 0; + virtual void animationMutationsForFrame(SurfaceId surfaceId, ShadowViewMutation::List &mutationsList, uint64_t now) + const = 0; /** * Queue (and potentially synthesize) final mutations for a finished keyframe. * Keyframe animation may have timed-out, or be canceled due to a conflict. */ void queueFinalMutationsForCompletedKeyFrame( - const AnimationKeyFrame& keyframe, - ShadowViewMutation::List& mutationsList, + const AnimationKeyFrame &keyframe, + ShadowViewMutation::List &mutationsList, bool interrupted, - const std::string& logPrefix) const; + const std::string &logPrefix) const; private: RuntimeExecutor runtimeExecutor_; std::shared_ptr contextContainer_; mutable std::mutex layoutAnimationStatusDelegateMutex_; - mutable LayoutAnimationStatusDelegate* layoutAnimationStatusDelegate_{}; + mutable LayoutAnimationStatusDelegate *layoutAnimationStatusDelegate_{}; mutable std::mutex surfaceIdsToStopMutex_; mutable std::unordered_set surfaceIdsToStop_{}; @@ -149,38 +138,37 @@ class LayoutAnimationKeyFrameManager : public UIManagerAnimationDelegate, void adjustImmediateMutationIndicesForDelayedMutations( SurfaceId surfaceId, - ShadowViewMutation& mutation, + ShadowViewMutation &mutation, bool skipLastAnimation = false, bool lastAnimationOnly = false) const; void adjustDelayedMutationIndicesForMutation( SurfaceId surfaceId, - const ShadowViewMutation& mutation, + const ShadowViewMutation &mutation, bool skipLastAnimation = false) const; void getAndEraseConflictingAnimations( SurfaceId surfaceId, - const ShadowViewMutationList& mutations, - std::vector& conflictingAnimations) const; + const ShadowViewMutationList &mutations, + std::vector &conflictingAnimations) const; /* * Removes animations from `inflightAnimations_` for stopped surfaces. */ void deleteAnimationsForStoppedSurfaces() const; - void simulateImagePropsMemoryAccess( - const ShadowViewMutationList& mutations) const; + void simulateImagePropsMemoryAccess(const ShadowViewMutationList &mutations) const; /** * Interpolates the props values. */ Props::Shared interpolateProps( - const ComponentDescriptor& componentDescriptor, - const PropsParserContext& context, + const ComponentDescriptor &componentDescriptor, + const PropsParserContext &context, Float animationProgress, - const Props::Shared& props, - const Props::Shared& newProps, - const Size& size) const; + const Props::Shared &props, + const Props::Shared &newProps, + const Size &size) const; }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/animations/conversions.h b/packages/react-native/ReactCommon/react/renderer/animations/conversions.h index 2dd7cbc23e3..1eb38ae2822 100644 --- a/packages/react-native/ReactCommon/react/renderer/animations/conversions.h +++ b/packages/react-native/ReactCommon/react/renderer/animations/conversions.h @@ -14,8 +14,8 @@ namespace facebook::react { -static inline std::optional parseAnimationType( - std::string param) { +static inline std::optional parseAnimationType(std::string param) +{ if (param == "spring") { return AnimationType::Spring; } @@ -39,8 +39,8 @@ static inline std::optional parseAnimationType( return {}; } -static inline std::optional parseAnimationProperty( - std::string param) { +static inline std::optional parseAnimationProperty(std::string param) +{ if (param == "opacity") { return AnimationProperty::Opacity; } @@ -58,10 +58,9 @@ static inline std::optional parseAnimationProperty( return {}; } -static inline std::optional parseAnimationConfig( - const folly::dynamic& config, - double defaultDuration, - bool parsePropertyType) { +static inline std::optional +parseAnimationConfig(const folly::dynamic &config, double defaultDuration, bool parsePropertyType) +{ if (config.empty() || !config.isObject()) { return AnimationConfig{ .animationType = AnimationType::Linear, @@ -79,14 +78,12 @@ static inline std::optional parseAnimationConfig( } const auto animationTypeParam = typeIt->second; if (animationTypeParam.empty() || !animationTypeParam.isString()) { - LOG(ERROR) - << "Error parsing animation config: could not unwrap field `type`"; + LOG(ERROR) << "Error parsing animation config: could not unwrap field `type`"; return {}; } const auto animationType = parseAnimationType(animationTypeParam.asString()); if (!animationType) { - LOG(ERROR) - << "Error parsing animation config: could not parse field `type`"; + LOG(ERROR) << "Error parsing animation config: could not parse field `type`"; return {}; } @@ -94,21 +91,17 @@ static inline std::optional parseAnimationConfig( if (parsePropertyType) { const auto propertyIt = config.find("property"); if (propertyIt == config.items().end()) { - LOG(ERROR) - << "Error parsing animation config: could not find field `property`"; + LOG(ERROR) << "Error parsing animation config: could not find field `property`"; return {}; } const auto animationPropertyParam = propertyIt->second; if (animationPropertyParam.empty() || !animationPropertyParam.isString()) { - LOG(ERROR) - << "Error parsing animation config: could not unwrap field `property`"; + LOG(ERROR) << "Error parsing animation config: could not unwrap field `property`"; return {}; } - const auto animationPropertyParsed = - parseAnimationProperty(animationPropertyParam.asString()); + const auto animationPropertyParsed = parseAnimationProperty(animationPropertyParam.asString()); if (!animationPropertyParsed) { - LOG(ERROR) - << "Error parsing animation config: could not parse field `property`"; + LOG(ERROR) << "Error parsing animation config: could not parse field `property`"; return {}; } animationProperty = *animationPropertyParsed; @@ -124,8 +117,7 @@ static inline std::optional parseAnimationConfig( if (durationIt->second.isDouble()) { duration = durationIt->second.asDouble(); } else { - LOG(ERROR) - << "Error parsing animation config: field `duration` must be a number"; + LOG(ERROR) << "Error parsing animation config: field `duration` must be a number"; return {}; } } @@ -135,20 +127,17 @@ static inline std::optional parseAnimationConfig( if (delayIt->second.isDouble()) { delay = delayIt->second.asDouble(); } else { - LOG(ERROR) - << "Error parsing animation config: field `delay` must be a number"; + LOG(ERROR) << "Error parsing animation config: field `delay` must be a number"; return {}; } } const auto springDampingIt = config.find("springDamping"); - if (springDampingIt != config.items().end() && - springDampingIt->second.isDouble()) { + if (springDampingIt != config.items().end() && springDampingIt->second.isDouble()) { if (springDampingIt->second.isDouble()) { springDamping = (Float)springDampingIt->second.asDouble(); } else { - LOG(ERROR) - << "Error parsing animation config: field `springDamping` must be a number"; + LOG(ERROR) << "Error parsing animation config: field `springDamping` must be a number"; return {}; } } @@ -158,8 +147,7 @@ static inline std::optional parseAnimationConfig( if (initialVelocityIt->second.isDouble()) { initialVelocity = (Float)initialVelocityIt->second.asDouble(); } else { - LOG(ERROR) - << "Error parsing animation config: field `initialVelocity` must be a number"; + LOG(ERROR) << "Error parsing animation config: field `initialVelocity` must be a number"; return {}; } } @@ -174,8 +162,8 @@ static inline std::optional parseAnimationConfig( } // Parse animation config from JS -static inline std::optional parseLayoutAnimationConfig( - const folly::dynamic& config) { +static inline std::optional parseLayoutAnimationConfig(const folly::dynamic &config) +{ if (config.empty() || !config.isObject()) { return {}; } diff --git a/packages/react-native/ReactCommon/react/renderer/animations/primitives.h b/packages/react-native/ReactCommon/react/renderer/animations/primitives.h index 7793de3bd18..b43c53474fb 100644 --- a/packages/react-native/ReactCommon/react/renderer/animations/primitives.h +++ b/packages/react-native/ReactCommon/react/renderer/animations/primitives.h @@ -27,20 +27,13 @@ enum class AnimationType { Keyboard = 32 }; -enum class AnimationProperty { - NotApplicable = 0, - Opacity = 1, - ScaleX = 2, - ScaleY = 4, - ScaleXY = 8 -}; +enum class AnimationProperty { NotApplicable = 0, Opacity = 1, ScaleX = 2, ScaleY = 4, ScaleXY = 8 }; // This corresponds exactly with JS. struct AnimationConfig { AnimationType animationType = AnimationType::None; AnimationProperty animationProperty = AnimationProperty::NotApplicable; - double duration = - 0; // these are perhaps better represented as uint64_t, but they + double duration = 0; // these are perhaps better represented as uint64_t, but they // come from JS as doubles double delay = 0; Float springDamping = 0; diff --git a/packages/react-native/ReactCommon/react/renderer/animations/tests/LayoutAnimationTest.cpp b/packages/react-native/ReactCommon/react/renderer/animations/tests/LayoutAnimationTest.cpp index 2eeb5c3ecb6..f5a7efd2ed0 100644 --- a/packages/react-native/ReactCommon/react/renderer/animations/tests/LayoutAnimationTest.cpp +++ b/packages/react-native/ReactCommon/react/renderer/animations/tests/LayoutAnimationTest.cpp @@ -124,12 +124,13 @@ static void testShadowNodeTreeLifeCycleLayoutAnimations( // Injecting a tree into the root node. auto currentRootNode = std::static_pointer_cast( - emptyRootNode->ShadowNode::clone(ShadowNodeFragment{ - .props = ShadowNodeFragment::propsPlaceholder(), - .children = std::make_shared< - std::vector>>( - std::vector>{ - singleRootChildNode})})); + emptyRootNode->ShadowNode::clone( + ShadowNodeFragment{ + .props = ShadowNodeFragment::propsPlaceholder(), + .children = std::make_shared< + std::vector>>( + std::vector>{ + singleRootChildNode})})); // Building an initial view hierarchy. auto viewTree = StubViewTree(ShadowView(*emptyRootNode)); diff --git a/packages/react-native/ReactCommon/react/renderer/animations/utils.h b/packages/react-native/ReactCommon/react/renderer/animations/utils.h index af238c19d00..890a0906d82 100644 --- a/packages/react-native/ReactCommon/react/renderer/animations/utils.h +++ b/packages/react-native/ReactCommon/react/renderer/animations/utils.h @@ -14,21 +14,20 @@ namespace facebook::react { static inline bool shouldFirstComeBeforeSecondRemovesOnly( - const ShadowViewMutation& lhs, - const ShadowViewMutation& rhs) noexcept { + const ShadowViewMutation &lhs, + const ShadowViewMutation &rhs) noexcept +{ // Make sure that removes on the same level are sorted - highest indices must // come first. - return (lhs.type == ShadowViewMutation::Type::Remove && - lhs.type == rhs.type) && - (lhs.parentTag == rhs.parentTag) && (lhs.index > rhs.index); + return (lhs.type == ShadowViewMutation::Type::Remove && lhs.type == rhs.type) && (lhs.parentTag == rhs.parentTag) && + (lhs.index > rhs.index); } -static inline void handleShouldFirstComeBeforeSecondRemovesOnly( - ShadowViewMutation::List& list) noexcept { - std::unordered_map> - removeMutationsByTag; +static inline void handleShouldFirstComeBeforeSecondRemovesOnly(ShadowViewMutation::List &list) noexcept +{ + std::unordered_map> removeMutationsByTag; ShadowViewMutation::List finalList; - for (auto& mutation : list) { + for (auto &mutation : list) { if (mutation.type == ShadowViewMutation::Type::Remove) { auto key = std::to_string(mutation.parentTag); removeMutationsByTag[key].push_back(mutation); @@ -41,25 +40,21 @@ static inline void handleShouldFirstComeBeforeSecondRemovesOnly( return; } - for (auto& mutationsPair : removeMutationsByTag) { + for (auto &mutationsPair : removeMutationsByTag) { if (mutationsPair.second.size() > 1) { std::stable_sort( - mutationsPair.second.begin(), - mutationsPair.second.end(), - &shouldFirstComeBeforeSecondRemovesOnly); + mutationsPair.second.begin(), mutationsPair.second.end(), &shouldFirstComeBeforeSecondRemovesOnly); } - finalList.insert( - finalList.begin(), - mutationsPair.second.begin(), - mutationsPair.second.end()); + finalList.insert(finalList.begin(), mutationsPair.second.begin(), mutationsPair.second.end()); } list = finalList; } static inline bool shouldFirstComeBeforeSecondMutation( - const ShadowViewMutation& lhs, - const ShadowViewMutation& rhs) noexcept { + const ShadowViewMutation &lhs, + const ShadowViewMutation &rhs) noexcept +{ if (lhs.type != rhs.type) { // Deletes always come last if (lhs.type == ShadowViewMutation::Type::Delete) { @@ -70,40 +65,33 @@ static inline bool shouldFirstComeBeforeSecondMutation( } // Remove comes before insert - if (lhs.type == ShadowViewMutation::Type::Remove && - rhs.type == ShadowViewMutation::Type::Insert) { + if (lhs.type == ShadowViewMutation::Type::Remove && rhs.type == ShadowViewMutation::Type::Insert) { return true; } - if (rhs.type == ShadowViewMutation::Type::Remove && - lhs.type == ShadowViewMutation::Type::Insert) { + if (rhs.type == ShadowViewMutation::Type::Remove && lhs.type == ShadowViewMutation::Type::Insert) { return false; } // Create comes before insert - if (lhs.type == ShadowViewMutation::Type::Create && - rhs.type == ShadowViewMutation::Type::Insert) { + if (lhs.type == ShadowViewMutation::Type::Create && rhs.type == ShadowViewMutation::Type::Insert) { return true; } - if (rhs.type == ShadowViewMutation::Type::Create && - lhs.type == ShadowViewMutation::Type::Insert) { + if (rhs.type == ShadowViewMutation::Type::Create && lhs.type == ShadowViewMutation::Type::Insert) { return false; } // Remove comes before Update - if (lhs.type == ShadowViewMutation::Type::Remove && - rhs.type == ShadowViewMutation::Type::Update) { + if (lhs.type == ShadowViewMutation::Type::Remove && rhs.type == ShadowViewMutation::Type::Update) { return true; } - if (rhs.type == ShadowViewMutation::Type::Remove && - lhs.type == ShadowViewMutation::Type::Update) { + if (rhs.type == ShadowViewMutation::Type::Remove && lhs.type == ShadowViewMutation::Type::Update) { return false; } } else { // Make sure that removes on the same level are sorted - highest indices // must come first. - if (lhs.type == ShadowViewMutation::Type::Remove && - lhs.parentTag == rhs.parentTag) { + if (lhs.type == ShadowViewMutation::Type::Remove && lhs.parentTag == rhs.parentTag) { return lhs.index > rhs.index; } } @@ -111,9 +99,7 @@ static inline bool shouldFirstComeBeforeSecondMutation( return &lhs < &rhs; } -std::pair calculateAnimationProgress( - uint64_t now, - const LayoutAnimation& animation, - const AnimationConfig& mutationConfig); +std::pair +calculateAnimationProgress(uint64_t now, const LayoutAnimation &animation, const AnimationConfig &mutationConfig); } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/attributedstring/AttributedString.cpp b/packages/react-native/ReactCommon/react/renderer/attributedstring/AttributedString.cpp index 9b74d2a76b5..73acd016441 100644 --- a/packages/react-native/ReactCommon/react/renderer/attributedstring/AttributedString.cpp +++ b/packages/react-native/ReactCommon/react/renderer/attributedstring/AttributedString.cpp @@ -137,11 +137,12 @@ SharedDebugStringConvertibleList AttributedString::getDebugChildren() const { auto propsList = fragment.textAttributes.DebugStringConvertible::getDebugProps(); - list.push_back(std::make_shared( - "Fragment", - fragment.string, - SharedDebugStringConvertibleList(), - propsList)); + list.push_back( + std::make_shared( + "Fragment", + fragment.string, + SharedDebugStringConvertibleList(), + propsList)); } return list; diff --git a/packages/react-native/ReactCommon/react/renderer/attributedstring/AttributedString.h b/packages/react-native/ReactCommon/react/renderer/attributedstring/AttributedString.h index a2b8d2d4f24..85367a4e786 100644 --- a/packages/react-native/ReactCommon/react/renderer/attributedstring/AttributedString.h +++ b/packages/react-native/ReactCommon/react/renderer/attributedstring/AttributedString.h @@ -42,9 +42,9 @@ class AttributedString : public Sealable, public DebugStringConvertible { * Returns whether the underlying text and attributes are equal, * disregarding layout or other information. */ - bool isContentEqual(const Fragment& rhs) const; + bool isContentEqual(const Fragment &rhs) const; - bool operator==(const Fragment& rhs) const; + bool operator==(const Fragment &rhs) const; }; class Range { @@ -58,31 +58,31 @@ class AttributedString : public Sealable, public DebugStringConvertible { /* * Appends and prepends a `fragment` to the string. */ - void appendFragment(Fragment&& fragment); - void prependFragment(Fragment&& fragment); + void appendFragment(Fragment &&fragment); + void prependFragment(Fragment &&fragment); /* * Sets attributes which would apply to hypothetical text not included in the * AttributedString. */ - void setBaseTextAttributes(const TextAttributes& defaultAttributes); + void setBaseTextAttributes(const TextAttributes &defaultAttributes); /* * Returns a read-only reference to a list of fragments. */ - const Fragments& getFragments() const; + const Fragments &getFragments() const; /* * Returns a reference to a list of fragments. */ - Fragments& getFragments(); + Fragments &getFragments(); /* * Returns a string constructed from all strings in all fragments. */ std::string getString() const; - const TextAttributes& getBaseTextAttributes() const; + const TextAttributes &getBaseTextAttributes() const; /* * Returns `true` if the string is empty (has no any fragments). @@ -92,11 +92,11 @@ class AttributedString : public Sealable, public DebugStringConvertible { /** * Compares equality of TextAttributes of all Fragments on both sides. */ - bool compareTextAttributesWithoutFrame(const AttributedString& rhs) const; + bool compareTextAttributesWithoutFrame(const AttributedString &rhs) const; - bool isContentEqual(const AttributedString& rhs) const; + bool isContentEqual(const AttributedString &rhs) const; - bool operator==(const AttributedString& rhs) const; + bool operator==(const AttributedString &rhs) const; #pragma mark - DebugStringConvertible @@ -114,8 +114,8 @@ class AttributedString : public Sealable, public DebugStringConvertible { namespace std { template <> struct hash { - size_t operator()( - const facebook::react::AttributedString::Fragment& fragment) const { + size_t operator()(const facebook::react::AttributedString::Fragment &fragment) const + { return facebook::react::hash_combine( fragment.string, fragment.textAttributes, @@ -126,13 +126,12 @@ struct hash { template <> struct hash { - size_t operator()( - const facebook::react::AttributedString& attributedString) const { + size_t operator()(const facebook::react::AttributedString &attributedString) const + { auto seed = size_t{0}; - facebook::react::hash_combine( - seed, attributedString.getBaseTextAttributes()); - for (const auto& fragment : attributedString.getFragments()) { + facebook::react::hash_combine(seed, attributedString.getBaseTextAttributes()); + for (const auto &fragment : attributedString.getFragments()) { facebook::react::hash_combine(seed, fragment); } diff --git a/packages/react-native/ReactCommon/react/renderer/attributedstring/AttributedStringBox.cpp b/packages/react-native/ReactCommon/react/renderer/attributedstring/AttributedStringBox.cpp index be3552ff66d..430f8d3ad6a 100644 --- a/packages/react-native/ReactCommon/react/renderer/attributedstring/AttributedStringBox.cpp +++ b/packages/react-native/ReactCommon/react/renderer/attributedstring/AttributedStringBox.cpp @@ -16,12 +16,12 @@ namespace facebook::react { AttributedStringBox::AttributedStringBox() : mode_(Mode::Value), value_(std::make_shared(AttributedString{})), - opaquePointer_({}){}; + opaquePointer_({}) {}; AttributedStringBox::AttributedStringBox(const AttributedString& value) : mode_(Mode::Value), value_(std::make_shared(value)), - opaquePointer_({}){}; + opaquePointer_({}) {}; AttributedStringBox::AttributedStringBox(std::shared_ptr opaquePointer) : mode_(Mode::OpaquePointer), diff --git a/packages/react-native/ReactCommon/react/renderer/attributedstring/AttributedStringBox.h b/packages/react-native/ReactCommon/react/renderer/attributedstring/AttributedStringBox.h index 026ff61ec07..9f8a72b61c6 100644 --- a/packages/react-native/ReactCommon/react/renderer/attributedstring/AttributedStringBox.h +++ b/packages/react-native/ReactCommon/react/renderer/attributedstring/AttributedStringBox.h @@ -33,22 +33,22 @@ class AttributedStringBox final { /* * Custom explicit constructors. */ - explicit AttributedStringBox(const AttributedString& value); + explicit AttributedStringBox(const AttributedString &value); explicit AttributedStringBox(std::shared_ptr opaquePointer); /* * Movable, Copyable, Assignable. */ - AttributedStringBox(const AttributedStringBox& other) = default; - AttributedStringBox(AttributedStringBox&& other) noexcept; - AttributedStringBox& operator=(const AttributedStringBox& other) = default; - AttributedStringBox& operator=(AttributedStringBox&& other) noexcept; + AttributedStringBox(const AttributedStringBox &other) = default; + AttributedStringBox(AttributedStringBox &&other) noexcept; + AttributedStringBox &operator=(const AttributedStringBox &other) = default; + AttributedStringBox &operator=(AttributedStringBox &&other) noexcept; /* * Getters. */ Mode getMode() const; - const AttributedString& getValue() const; + const AttributedString &getValue() const; std::shared_ptr getOpaquePointer() const; private: @@ -57,22 +57,20 @@ class AttributedStringBox final { std::shared_ptr opaquePointer_; }; -bool operator==(const AttributedStringBox& lhs, const AttributedStringBox& rhs); -bool operator!=(const AttributedStringBox& lhs, const AttributedStringBox& rhs); +bool operator==(const AttributedStringBox &lhs, const AttributedStringBox &rhs); +bool operator!=(const AttributedStringBox &lhs, const AttributedStringBox &rhs); } // namespace facebook::react template <> struct std::hash { - size_t operator()( - const facebook::react::AttributedStringBox& attributedStringBox) const { + size_t operator()(const facebook::react::AttributedStringBox &attributedStringBox) const + { switch (attributedStringBox.getMode()) { case facebook::react::AttributedStringBox::Mode::Value: - return std::hash()( - attributedStringBox.getValue()); + return std::hash()(attributedStringBox.getValue()); case facebook::react::AttributedStringBox::Mode::OpaquePointer: - return std::hash>()( - attributedStringBox.getOpaquePointer()); + return std::hash>()(attributedStringBox.getOpaquePointer()); } } }; diff --git a/packages/react-native/ReactCommon/react/renderer/attributedstring/ParagraphAttributes.h b/packages/react-native/ReactCommon/react/renderer/attributedstring/ParagraphAttributes.h index 35ec7a71291..c233c4d8f17 100644 --- a/packages/react-native/ReactCommon/react/renderer/attributedstring/ParagraphAttributes.h +++ b/packages/react-native/ReactCommon/react/renderer/attributedstring/ParagraphAttributes.h @@ -82,8 +82,8 @@ class ParagraphAttributes : public DebugStringConvertible { */ std::optional textAlignVertical{}; - bool operator==(const ParagraphAttributes& rhs) const; - bool operator!=(const ParagraphAttributes& rhs) const; + bool operator==(const ParagraphAttributes &rhs) const; + bool operator!=(const ParagraphAttributes &rhs) const; #pragma mark - DebugStringConvertible @@ -98,8 +98,8 @@ namespace std { template <> struct hash { - size_t operator()( - const facebook::react::ParagraphAttributes& attributes) const { + size_t operator()(const facebook::react::ParagraphAttributes &attributes) const + { return facebook::react::hash_combine( attributes.maximumNumberOfLines, attributes.ellipsizeMode, diff --git a/packages/react-native/ReactCommon/react/renderer/attributedstring/PlaceholderAttributedString.h b/packages/react-native/ReactCommon/react/renderer/attributedstring/PlaceholderAttributedString.h index 3b8329eb653..fdf10451752 100644 --- a/packages/react-native/ReactCommon/react/renderer/attributedstring/PlaceholderAttributedString.h +++ b/packages/react-native/ReactCommon/react/renderer/attributedstring/PlaceholderAttributedString.h @@ -17,14 +17,12 @@ namespace facebook::react { * during measurement. Usages of this function should be replaced with * formatting based off of baseTextAttributes. */ -inline AttributedString ensurePlaceholderIfEmpty_DO_NOT_USE( - const AttributedString& attributedString) { +inline AttributedString ensurePlaceholderIfEmpty_DO_NOT_USE(const AttributedString &attributedString) +{ if (attributedString.isEmpty()) { AttributedString placeholder{attributedString}; placeholder.appendFragment( - {.string = "I", - .textAttributes = attributedString.getBaseTextAttributes(), - .parentShadowView = {}}); + {.string = "I", .textAttributes = attributedString.getBaseTextAttributes(), .parentShadowView = {}}); return placeholder; } diff --git a/packages/react-native/ReactCommon/react/renderer/attributedstring/TextAttributes.h b/packages/react-native/ReactCommon/react/renderer/attributedstring/TextAttributes.h index 8a7e26c57b6..b66452408b7 100644 --- a/packages/react-native/ReactCommon/react/renderer/attributedstring/TextAttributes.h +++ b/packages/react-native/ReactCommon/react/renderer/attributedstring/TextAttributes.h @@ -92,7 +92,7 @@ class TextAttributes : public DebugStringConvertible { #pragma mark - Operators - bool operator==(const TextAttributes& rhs) const; + bool operator==(const TextAttributes &rhs) const; #pragma mark - DebugStringConvertible @@ -107,8 +107,8 @@ namespace std { template <> struct hash { - size_t operator()( - const facebook::react::TextAttributes& textAttributes) const { + size_t operator()(const facebook::react::TextAttributes &textAttributes) const + { return facebook::react::hash_combine( textAttributes.foregroundColor, textAttributes.backgroundColor, diff --git a/packages/react-native/ReactCommon/react/renderer/attributedstring/conversions.h b/packages/react-native/ReactCommon/react/renderer/attributedstring/conversions.h index 0923e85b2c3..f771236e787 100644 --- a/packages/react-native/ReactCommon/react/renderer/attributedstring/conversions.h +++ b/packages/react-native/ReactCommon/react/renderer/attributedstring/conversions.h @@ -32,7 +32,8 @@ namespace facebook::react { -inline std::string toString(const DynamicTypeRamp& dynamicTypeRamp) { +inline std::string toString(const DynamicTypeRamp &dynamicTypeRamp) +{ switch (dynamicTypeRamp) { case DynamicTypeRamp::Caption2: return "caption2"; @@ -65,10 +66,8 @@ inline std::string toString(const DynamicTypeRamp& dynamicTypeRamp) { return "body"; } -inline void fromRawValue( - const PropsParserContext& context, - const RawValue& value, - DynamicTypeRamp& result) { +inline void fromRawValue(const PropsParserContext &context, const RawValue &value, DynamicTypeRamp &result) +{ react_native_expect(value.hasType()); if (value.hasType()) { auto string = (std::string)value; @@ -110,7 +109,8 @@ inline void fromRawValue( result = DynamicTypeRamp::Body; } -inline std::string toString(const EllipsizeMode& ellipsisMode) { +inline std::string toString(const EllipsizeMode &ellipsisMode) +{ switch (ellipsisMode) { case EllipsizeMode::Clip: return "clip"; @@ -129,10 +129,8 @@ inline std::string toString(const EllipsizeMode& ellipsisMode) { return "tail"; } -inline void fromRawValue( - const PropsParserContext& context, - const RawValue& value, - EllipsizeMode& result) { +inline void fromRawValue(const PropsParserContext &context, const RawValue &value, EllipsizeMode &result) +{ react_native_expect(value.hasType()); if (value.hasType()) { auto string = (std::string)value; @@ -160,7 +158,8 @@ inline void fromRawValue( result = EllipsizeMode::Tail; } -inline std::string toString(const TextBreakStrategy& textBreakStrategy) { +inline std::string toString(const TextBreakStrategy &textBreakStrategy) +{ switch (textBreakStrategy) { case TextBreakStrategy::Simple: return "simple"; @@ -175,10 +174,8 @@ inline std::string toString(const TextBreakStrategy& textBreakStrategy) { return "highQuality"; } -inline void fromRawValue( - const PropsParserContext& context, - const RawValue& value, - TextBreakStrategy& result) { +inline void fromRawValue(const PropsParserContext &context, const RawValue &value, TextBreakStrategy &result) +{ react_native_expect(value.hasType()); if (value.hasType()) { auto string = (std::string)value; @@ -202,10 +199,8 @@ inline void fromRawValue( result = TextBreakStrategy::HighQuality; } -inline void fromRawValue( - const PropsParserContext& context, - const RawValue& value, - FontWeight& result) { +inline void fromRawValue(const PropsParserContext &context, const RawValue &value, FontWeight &result) +{ react_native_expect(value.hasType() || value.hasType()); if (value.hasType()) { auto string = (std::string)value; @@ -274,14 +269,13 @@ inline void fromRawValue( result = FontWeight::Regular; } -inline std::string toString(const FontWeight& fontWeight) { +inline std::string toString(const FontWeight &fontWeight) +{ return std::to_string((int)fontWeight); } -inline void fromRawValue( - const PropsParserContext& context, - const RawValue& value, - FontStyle& result) { +inline void fromRawValue(const PropsParserContext &context, const RawValue &value, FontStyle &result) +{ react_native_expect(value.hasType()); if (value.hasType()) { auto string = (std::string)value; @@ -306,7 +300,8 @@ inline void fromRawValue( result = FontStyle::Normal; } -inline std::string toString(const FontStyle& fontStyle) { +inline std::string toString(const FontStyle &fontStyle) +{ switch (fontStyle) { case FontStyle::Normal: return "normal"; @@ -322,15 +317,13 @@ inline std::string toString(const FontStyle& fontStyle) { return "normal"; } -inline void fromRawValue( - const PropsParserContext& context, - const RawValue& value, - FontVariant& result) { +inline void fromRawValue(const PropsParserContext &context, const RawValue &value, FontVariant &result) +{ result = FontVariant::Default; react_native_expect(value.hasType>()); if (value.hasType>()) { auto items = std::vector{value}; - for (const auto& item : items) { + for (const auto &item : items) { if (item == "small-caps") { result = (FontVariant)((int)result | (int)FontVariant::SmallCaps); } else if (item == "oldstyle-nums") { @@ -340,8 +333,7 @@ inline void fromRawValue( } else if (item == "tabular-nums") { result = (FontVariant)((int)result | (int)FontVariant::TabularNums); } else if (item == "proportional-nums") { - result = - (FontVariant)((int)result | (int)FontVariant::ProportionalNums); + result = (FontVariant)((int)result | (int)FontVariant::ProportionalNums); } else if (item == "stylistic-one") { result = (FontVariant)((int)result | (int)FontVariant::StylisticOne); } else if (item == "stylistic-two") { @@ -367,26 +359,19 @@ inline void fromRawValue( } else if (item == "stylistic-twelve") { result = (FontVariant)((int)result | (int)FontVariant::StylisticTwelve); } else if (item == "stylistic-thirteen") { - result = - (FontVariant)((int)result | (int)FontVariant::StylisticThirteen); + result = (FontVariant)((int)result | (int)FontVariant::StylisticThirteen); } else if (item == "stylistic-fourteen") { - result = - (FontVariant)((int)result | (int)FontVariant::StylisticFourteen); + result = (FontVariant)((int)result | (int)FontVariant::StylisticFourteen); } else if (item == "stylistic-fifteen") { - result = - (FontVariant)((int)result | (int)FontVariant::StylisticFifteen); + result = (FontVariant)((int)result | (int)FontVariant::StylisticFifteen); } else if (item == "stylistic-sixteen") { - result = - (FontVariant)((int)result | (int)FontVariant::StylisticSixteen); + result = (FontVariant)((int)result | (int)FontVariant::StylisticSixteen); } else if (item == "stylistic-seventeen") { - result = - (FontVariant)((int)result | (int)FontVariant::StylisticSeventeen); + result = (FontVariant)((int)result | (int)FontVariant::StylisticSeventeen); } else if (item == "stylistic-eighteen") { - result = - (FontVariant)((int)result | (int)FontVariant::StylisticEighteen); + result = (FontVariant)((int)result | (int)FontVariant::StylisticEighteen); } else if (item == "stylistic-nineteen") { - result = - (FontVariant)((int)result | (int)FontVariant::StylisticNineteen); + result = (FontVariant)((int)result | (int)FontVariant::StylisticNineteen); } else if (item == "stylistic-twenty") { result = (FontVariant)((int)result | (int)FontVariant::StylisticTwenty); } else { @@ -399,7 +384,8 @@ inline void fromRawValue( } } -inline std::string toString(const FontVariant& fontVariant) { +inline std::string toString(const FontVariant &fontVariant) +{ auto result = std::string{}; auto separator = std::string{", "}; if (((int)fontVariant & (int)FontVariant::SmallCaps) != 0) { @@ -485,10 +471,8 @@ inline std::string toString(const FontVariant& fontVariant) { return result; } -inline void fromRawValue( - const PropsParserContext& context, - const RawValue& value, - TextTransform& result) { +inline void fromRawValue(const PropsParserContext &context, const RawValue &value, TextTransform &result) +{ react_native_expect(value.hasType()); if (value.hasType()) { auto string = (std::string)value; @@ -517,7 +501,8 @@ inline void fromRawValue( result = TextTransform::None; } -inline std::string toString(const TextTransform& textTransform) { +inline std::string toString(const TextTransform &textTransform) +{ switch (textTransform) { case TextTransform::None: return "none"; @@ -537,10 +522,8 @@ inline std::string toString(const TextTransform& textTransform) { return "none"; } -inline void fromRawValue( - const PropsParserContext& context, - const RawValue& value, - TextAlignment& result) { +inline void fromRawValue(const PropsParserContext &context, const RawValue &value, TextAlignment &result) +{ react_native_expect(value.hasType()); if (value.hasType()) { auto string = (std::string)value; @@ -567,7 +550,8 @@ inline void fromRawValue( result = TextAlignment::Natural; } -inline std::string toString(const TextAlignment& textAlignment) { +inline std::string toString(const TextAlignment &textAlignment) +{ switch (textAlignment) { case TextAlignment::Natural: return "auto"; @@ -586,10 +570,8 @@ inline std::string toString(const TextAlignment& textAlignment) { return "auto"; } -inline void fromRawValue( - const PropsParserContext& /*context*/, - const RawValue& value, - TextAlignmentVertical& result) { +inline void fromRawValue(const PropsParserContext & /*context*/, const RawValue &value, TextAlignmentVertical &result) +{ react_native_expect(value.hasType()); if (value.hasType()) { auto string = (std::string)value; @@ -615,7 +597,8 @@ inline void fromRawValue( result = TextAlignmentVertical::Auto; } -inline std::string toString(const TextAlignmentVertical& textAlignment) { +inline std::string toString(const TextAlignmentVertical &textAlignment) +{ switch (textAlignment) { case TextAlignmentVertical::Auto: return "auto"; @@ -632,10 +615,8 @@ inline std::string toString(const TextAlignmentVertical& textAlignment) { return "auto"; } -inline void fromRawValue( - const PropsParserContext& context, - const RawValue& value, - WritingDirection& result) { +inline void fromRawValue(const PropsParserContext &context, const RawValue &value, WritingDirection &result) +{ react_native_expect(value.hasType()); if (value.hasType()) { auto string = (std::string)value; @@ -659,7 +640,8 @@ inline void fromRawValue( result = WritingDirection::Natural; } -inline std::string toString(const WritingDirection& writingDirection) { +inline std::string toString(const WritingDirection &writingDirection) +{ switch (writingDirection) { case WritingDirection::Natural: return "auto"; @@ -674,10 +656,8 @@ inline std::string toString(const WritingDirection& writingDirection) { return "auto"; } -inline void fromRawValue( - const PropsParserContext& context, - const RawValue& value, - LineBreakStrategy& result) { +inline void fromRawValue(const PropsParserContext &context, const RawValue &value, LineBreakStrategy &result) +{ react_native_expect(value.hasType()); if (value.hasType()) { auto string = (std::string)value; @@ -703,7 +683,8 @@ inline void fromRawValue( result = LineBreakStrategy::None; } -inline std::string toString(const LineBreakStrategy& lineBreakStrategy) { +inline std::string toString(const LineBreakStrategy &lineBreakStrategy) +{ switch (lineBreakStrategy) { case LineBreakStrategy::None: return "none"; @@ -720,10 +701,8 @@ inline std::string toString(const LineBreakStrategy& lineBreakStrategy) { return "none"; } -inline void fromRawValue( - const PropsParserContext& /*context*/, - const RawValue& value, - LineBreakMode& result) { +inline void fromRawValue(const PropsParserContext & /*context*/, const RawValue &value, LineBreakMode &result) +{ react_native_expect(value.hasType()); if (value.hasType()) { auto string = (std::string)value; @@ -753,7 +732,8 @@ inline void fromRawValue( result = LineBreakMode::Word; } -inline std::string toString(const LineBreakMode& lineBreakMode) { +inline std::string toString(const LineBreakMode &lineBreakMode) +{ switch (lineBreakMode) { case LineBreakMode::Word: return "wordWrapping"; @@ -774,10 +754,8 @@ inline std::string toString(const LineBreakMode& lineBreakMode) { return "wordWrapping"; } -inline void fromRawValue( - const PropsParserContext& context, - const RawValue& value, - TextDecorationLineType& result) { +inline void fromRawValue(const PropsParserContext &context, const RawValue &value, TextDecorationLineType &result) +{ react_native_expect(value.hasType()); if (value.hasType()) { auto string = (std::string)value; @@ -788,9 +766,7 @@ inline void fromRawValue( } else if (string == "strikethrough" || string == "line-through") { // TODO: remove "line-through" after deprecation result = TextDecorationLineType::Strikethrough; - } else if ( - string == "underline-strikethrough" || - string == "underline line-through") { + } else if (string == "underline-strikethrough" || string == "underline line-through") { // TODO: remove "underline line-through" after "line-through" deprecation result = TextDecorationLineType::UnderlineStrikethrough; } else { @@ -807,8 +783,8 @@ inline void fromRawValue( result = TextDecorationLineType::None; } -inline std::string toString( - const TextDecorationLineType& textDecorationLineType) { +inline std::string toString(const TextDecorationLineType &textDecorationLineType) +{ switch (textDecorationLineType) { case TextDecorationLineType::None: return "none"; @@ -826,10 +802,8 @@ inline std::string toString( return "none"; } -inline void fromRawValue( - const PropsParserContext& context, - const RawValue& value, - TextDecorationStyle& result) { +inline void fromRawValue(const PropsParserContext &context, const RawValue &value, TextDecorationStyle &result) +{ react_native_expect(value.hasType()); if (value.hasType()) { auto string = (std::string)value; @@ -855,7 +829,8 @@ inline void fromRawValue( result = TextDecorationStyle::Solid; } -inline std::string toString(const TextDecorationStyle& textDecorationStyle) { +inline std::string toString(const TextDecorationStyle &textDecorationStyle) +{ switch (textDecorationStyle) { case TextDecorationStyle::Solid: return "solid"; @@ -873,7 +848,8 @@ inline std::string toString(const TextDecorationStyle& textDecorationStyle) { return "solid"; } -inline std::string toString(const HyphenationFrequency& hyphenationFrequency) { +inline std::string toString(const HyphenationFrequency &hyphenationFrequency) +{ switch (hyphenationFrequency) { case HyphenationFrequency::None: return "none"; @@ -888,10 +864,8 @@ inline std::string toString(const HyphenationFrequency& hyphenationFrequency) { return "none"; } -inline void fromRawValue( - const PropsParserContext& context, - const RawValue& value, - HyphenationFrequency& result) { +inline void fromRawValue(const PropsParserContext &context, const RawValue &value, HyphenationFrequency &result) +{ react_native_expect(value.hasType()); if (value.hasType()) { auto string = (std::string)value; @@ -916,10 +890,11 @@ inline void fromRawValue( } inline ParagraphAttributes convertRawProp( - const PropsParserContext& context, - const RawProps& rawProps, - const ParagraphAttributes& sourceParagraphAttributes, - const ParagraphAttributes& defaultParagraphAttributes) { + const PropsParserContext &context, + const RawProps &rawProps, + const ParagraphAttributes &sourceParagraphAttributes, + const ParagraphAttributes &defaultParagraphAttributes) +{ auto paragraphAttributes = ParagraphAttributes{}; paragraphAttributes.maximumNumberOfLines = convertRawProp( @@ -986,10 +961,8 @@ inline ParagraphAttributes convertRawProp( return paragraphAttributes; } -inline void fromRawValue( - const PropsParserContext& context, - const RawValue& value, - AttributedString::Range& result) { +inline void fromRawValue(const PropsParserContext &context, const RawValue &value, AttributedString::Range &result) +{ auto map = (std::unordered_map)value; auto start = map.find("start"); @@ -1002,9 +975,9 @@ inline void fromRawValue( } } -inline std::string toString(const AttributedString::Range& range) { - return "{location: " + std::to_string(range.location) + - ", length: " + std::to_string(range.length) + "}"; +inline std::string toString(const AttributedString::Range &range) +{ + return "{location: " + std::to_string(range.location) + ", length: " + std::to_string(range.length) + "}"; } #ifdef RN_SERIALIZABLE_STATE @@ -1066,36 +1039,26 @@ constexpr static MapBuffer::Key PA_KEY_MINIMUM_FONT_SIZE = 6; constexpr static MapBuffer::Key PA_KEY_MAXIMUM_FONT_SIZE = 7; constexpr static MapBuffer::Key PA_KEY_TEXT_ALIGN_VERTICAL = 8; -inline MapBuffer toMapBuffer(const ParagraphAttributes& paragraphAttributes) { +inline MapBuffer toMapBuffer(const ParagraphAttributes ¶graphAttributes) +{ auto builder = MapBufferBuilder(); - builder.putInt( - PA_KEY_MAX_NUMBER_OF_LINES, paragraphAttributes.maximumNumberOfLines); - builder.putString( - PA_KEY_ELLIPSIZE_MODE, toString(paragraphAttributes.ellipsizeMode)); - builder.putString( - PA_KEY_TEXT_BREAK_STRATEGY, - toString(paragraphAttributes.textBreakStrategy)); - builder.putBool( - PA_KEY_ADJUST_FONT_SIZE_TO_FIT, paragraphAttributes.adjustsFontSizeToFit); - builder.putBool( - PA_KEY_INCLUDE_FONT_PADDING, paragraphAttributes.includeFontPadding); - builder.putString( - PA_KEY_HYPHENATION_FREQUENCY, - toString(paragraphAttributes.android_hyphenationFrequency)); + builder.putInt(PA_KEY_MAX_NUMBER_OF_LINES, paragraphAttributes.maximumNumberOfLines); + builder.putString(PA_KEY_ELLIPSIZE_MODE, toString(paragraphAttributes.ellipsizeMode)); + builder.putString(PA_KEY_TEXT_BREAK_STRATEGY, toString(paragraphAttributes.textBreakStrategy)); + builder.putBool(PA_KEY_ADJUST_FONT_SIZE_TO_FIT, paragraphAttributes.adjustsFontSizeToFit); + builder.putBool(PA_KEY_INCLUDE_FONT_PADDING, paragraphAttributes.includeFontPadding); + builder.putString(PA_KEY_HYPHENATION_FREQUENCY, toString(paragraphAttributes.android_hyphenationFrequency)); if (paragraphAttributes.textAlignVertical.has_value()) { - builder.putString( - PA_KEY_TEXT_ALIGN_VERTICAL, - toString(*paragraphAttributes.textAlignVertical)); + builder.putString(PA_KEY_TEXT_ALIGN_VERTICAL, toString(*paragraphAttributes.textAlignVertical)); } - builder.putDouble( - PA_KEY_MINIMUM_FONT_SIZE, paragraphAttributes.minimumFontSize); - builder.putDouble( - PA_KEY_MAXIMUM_FONT_SIZE, paragraphAttributes.maximumFontSize); + builder.putDouble(PA_KEY_MINIMUM_FONT_SIZE, paragraphAttributes.minimumFontSize); + builder.putDouble(PA_KEY_MAXIMUM_FONT_SIZE, paragraphAttributes.maximumFontSize); return builder.build(); } -inline MapBuffer toMapBuffer(const FontVariant& fontVariant) { +inline MapBuffer toMapBuffer(const FontVariant &fontVariant) +{ auto builder = MapBufferBuilder(); int index = 0; if ((int)fontVariant & (int)FontVariant::SmallCaps) { @@ -1117,15 +1080,14 @@ inline MapBuffer toMapBuffer(const FontVariant& fontVariant) { return builder.build(); } -inline MapBuffer toMapBuffer(const TextAttributes& textAttributes) { +inline MapBuffer toMapBuffer(const TextAttributes &textAttributes) +{ auto builder = MapBufferBuilder(); if (textAttributes.foregroundColor) { - builder.putInt( - TA_KEY_FOREGROUND_COLOR, toAndroidRepr(textAttributes.foregroundColor)); + builder.putInt(TA_KEY_FOREGROUND_COLOR, toAndroidRepr(textAttributes.foregroundColor)); } if (textAttributes.backgroundColor) { - builder.putInt( - TA_KEY_BACKGROUND_COLOR, toAndroidRepr(textAttributes.backgroundColor)); + builder.putInt(TA_KEY_BACKGROUND_COLOR, toAndroidRepr(textAttributes.backgroundColor)); } if (!std::isnan(textAttributes.opacity)) { builder.putDouble(TA_KEY_OPACITY, textAttributes.opacity); @@ -1137,8 +1099,7 @@ inline MapBuffer toMapBuffer(const TextAttributes& textAttributes) { builder.putDouble(TA_KEY_FONT_SIZE, textAttributes.fontSize); } if (!std::isnan(textAttributes.fontSizeMultiplier)) { - builder.putDouble( - TA_KEY_FONT_SIZE_MULTIPLIER, textAttributes.fontSizeMultiplier); + builder.putDouble(TA_KEY_FONT_SIZE_MULTIPLIER, textAttributes.fontSizeMultiplier); } if (textAttributes.fontWeight.has_value()) { builder.putString(TA_KEY_FONT_WEIGHT, toString(*textAttributes.fontWeight)); @@ -1151,12 +1112,10 @@ inline MapBuffer toMapBuffer(const TextAttributes& textAttributes) { builder.putMapBuffer(TA_KEY_FONT_VARIANT, fontVariantMap); } if (textAttributes.allowFontScaling.has_value()) { - builder.putBool( - TA_KEY_ALLOW_FONT_SCALING, *textAttributes.allowFontScaling); + builder.putBool(TA_KEY_ALLOW_FONT_SCALING, *textAttributes.allowFontScaling); } if (!std::isnan(textAttributes.maxFontSizeMultiplier)) { - builder.putDouble( - TA_KEY_MAX_FONT_SIZE_MULTIPLIER, textAttributes.maxFontSizeMultiplier); + builder.putDouble(TA_KEY_MAX_FONT_SIZE_MULTIPLIER, textAttributes.maxFontSizeMultiplier); } if (!std::isnan(textAttributes.letterSpacing)) { builder.putDouble(TA_KEY_LETTER_SPACING, textAttributes.letterSpacing); @@ -1168,64 +1127,46 @@ inline MapBuffer toMapBuffer(const TextAttributes& textAttributes) { builder.putString(TA_KEY_ALIGNMENT, toString(*textAttributes.alignment)); } if (textAttributes.baseWritingDirection.has_value()) { - builder.putString( - TA_KEY_BEST_WRITING_DIRECTION, - toString(*textAttributes.baseWritingDirection)); + builder.putString(TA_KEY_BEST_WRITING_DIRECTION, toString(*textAttributes.baseWritingDirection)); } if (textAttributes.lineBreakStrategy.has_value()) { - builder.putString( - TA_KEY_LINE_BREAK_STRATEGY, - toString(*textAttributes.lineBreakStrategy)); + builder.putString(TA_KEY_LINE_BREAK_STRATEGY, toString(*textAttributes.lineBreakStrategy)); } if (textAttributes.textTransform.has_value()) { - builder.putString( - TA_KEY_TEXT_TRANSFORM, toString(*textAttributes.textTransform)); + builder.putString(TA_KEY_TEXT_TRANSFORM, toString(*textAttributes.textTransform)); } // Decoration if (textAttributes.textDecorationColor) { - builder.putInt( - TA_KEY_TEXT_DECORATION_COLOR, - toAndroidRepr(textAttributes.textDecorationColor)); + builder.putInt(TA_KEY_TEXT_DECORATION_COLOR, toAndroidRepr(textAttributes.textDecorationColor)); } if (textAttributes.textDecorationLineType.has_value()) { - builder.putString( - TA_KEY_TEXT_DECORATION_LINE, - toString(*textAttributes.textDecorationLineType)); + builder.putString(TA_KEY_TEXT_DECORATION_LINE, toString(*textAttributes.textDecorationLineType)); } if (textAttributes.textDecorationStyle.has_value()) { - builder.putString( - TA_KEY_TEXT_DECORATION_STYLE, - toString(*textAttributes.textDecorationStyle)); + builder.putString(TA_KEY_TEXT_DECORATION_STYLE, toString(*textAttributes.textDecorationStyle)); } // Shadow if (!std::isnan(textAttributes.textShadowRadius)) { - builder.putDouble( - TA_KEY_TEXT_SHADOW_RADIUS, textAttributes.textShadowRadius); + builder.putDouble(TA_KEY_TEXT_SHADOW_RADIUS, textAttributes.textShadowRadius); } if (textAttributes.textShadowColor) { - builder.putInt( - TA_KEY_TEXT_SHADOW_COLOR, - toAndroidRepr(textAttributes.textShadowColor)); + builder.putInt(TA_KEY_TEXT_SHADOW_COLOR, toAndroidRepr(textAttributes.textShadowColor)); } if (textAttributes.textShadowOffset) { - builder.putDouble( - TA_KEY_TEXT_SHADOW_OFFSET_DX, textAttributes.textShadowOffset->width); - builder.putDouble( - TA_KEY_TEXT_SHADOW_OFFSET_DY, textAttributes.textShadowOffset->height); + builder.putDouble(TA_KEY_TEXT_SHADOW_OFFSET_DX, textAttributes.textShadowOffset->width); + builder.putDouble(TA_KEY_TEXT_SHADOW_OFFSET_DY, textAttributes.textShadowOffset->height); } // Special if (textAttributes.isHighlighted.has_value()) { builder.putBool(TA_KEY_IS_HIGHLIGHTED, *textAttributes.isHighlighted); } if (textAttributes.layoutDirection.has_value()) { - builder.putString( - TA_KEY_LAYOUT_DIRECTION, toString(*textAttributes.layoutDirection)); + builder.putString(TA_KEY_LAYOUT_DIRECTION, toString(*textAttributes.layoutDirection)); } if (textAttributes.accessibilityRole.has_value()) { - builder.putString( - TA_KEY_ACCESSIBILITY_ROLE, toString(*textAttributes.accessibilityRole)); + builder.putString(TA_KEY_ACCESSIBILITY_ROLE, toString(*textAttributes.accessibilityRole)); } if (textAttributes.role.has_value()) { builder.putInt(TA_KEY_ROLE, static_cast(*textAttributes.role)); @@ -1233,7 +1174,8 @@ inline MapBuffer toMapBuffer(const TextAttributes& textAttributes) { return builder.build(); } -inline MapBuffer toMapBuffer(const AttributedString::Fragment& fragment) { +inline MapBuffer toMapBuffer(const AttributedString::Fragment &fragment) +{ auto builder = MapBufferBuilder(); builder.putString(FR_KEY_STRING, fragment.string); @@ -1242,11 +1184,8 @@ inline MapBuffer toMapBuffer(const AttributedString::Fragment& fragment) { } if (fragment.isAttachment()) { builder.putBool(FR_KEY_IS_ATTACHMENT, true); - builder.putDouble( - FR_KEY_WIDTH, fragment.parentShadowView.layoutMetrics.frame.size.width); - builder.putDouble( - FR_KEY_HEIGHT, - fragment.parentShadowView.layoutMetrics.frame.size.height); + builder.putDouble(FR_KEY_WIDTH, fragment.parentShadowView.layoutMetrics.frame.size.width); + builder.putDouble(FR_KEY_HEIGHT, fragment.parentShadowView.layoutMetrics.frame.size.height); } auto textAttributesMap = toMapBuffer(fragment.textAttributes); builder.putMapBuffer(FR_KEY_TEXT_ATTRIBUTES, textAttributesMap); @@ -1254,7 +1193,8 @@ inline MapBuffer toMapBuffer(const AttributedString::Fragment& fragment) { return builder.build(); } -inline MapBuffer toMapBuffer(const AttributedString& attributedString) { +inline MapBuffer toMapBuffer(const AttributedString &attributedString) +{ auto fragmentsBuilder = MapBufferBuilder(); int index = 0; @@ -1263,14 +1203,11 @@ inline MapBuffer toMapBuffer(const AttributedString& attributedString) { } auto builder = MapBufferBuilder(); - size_t hash = - std::hash{}(attributedString); + size_t hash = std::hash{}(attributedString); // TODO: This truncates half the hash builder.putInt(AS_KEY_HASH, static_cast(hash)); builder.putString(AS_KEY_STRING, attributedString.getString()); - builder.putMapBuffer( - AS_KEY_BASE_ATTRIBUTES, - toMapBuffer(attributedString.getBaseTextAttributes())); + builder.putMapBuffer(AS_KEY_BASE_ATTRIBUTES, toMapBuffer(attributedString.getBaseTextAttributes())); auto fragmentsMap = fragmentsBuilder.build(); builder.putMapBuffer(AS_KEY_FRAGMENTS, fragmentsMap); return builder.build(); diff --git a/packages/react-native/ReactCommon/react/renderer/attributedstring/primitives.h b/packages/react-native/ReactCommon/react/renderer/attributedstring/primitives.h index 32db227b527..d23104518c7 100644 --- a/packages/react-native/ReactCommon/react/renderer/attributedstring/primitives.h +++ b/packages/react-native/ReactCommon/react/renderer/attributedstring/primitives.h @@ -132,12 +132,7 @@ enum class LineBreakMode { Tail // Truncate at tail of line: "abcd..." }; -enum class TextDecorationLineType { - None, - Underline, - Strikethrough, - UnderlineStrikethrough -}; +enum class TextDecorationLineType { None, Underline, Strikethrough, UnderlineStrikethrough }; enum class TextDecorationStyle { Solid, Double, Dotted, Dashed }; diff --git a/packages/react-native/ReactCommon/react/renderer/bridging/bridging.h b/packages/react-native/ReactCommon/react/renderer/bridging/bridging.h index bd17c323456..38da825acdd 100644 --- a/packages/react-native/ReactCommon/react/renderer/bridging/bridging.h +++ b/packages/react-native/ReactCommon/react/renderer/bridging/bridging.h @@ -15,9 +15,8 @@ namespace facebook::react { template <> struct Bridging> { - static std::shared_ptr fromJs( - jsi::Runtime& rt, - const jsi::Value& jsiValue) { + static std::shared_ptr fromJs(jsi::Runtime &rt, const jsi::Value &jsiValue) + { auto object = jsiValue.asObject(rt); // Using `jsi::NativeState` instead of `ShadowNodeWrapper` to avoid doing a @@ -29,20 +28,16 @@ struct Bridging> { } auto nativeState = object.getNativeState(rt); - auto shadowNodeWrapper = - std::dynamic_pointer_cast(nativeState); - if (shadowNodeWrapper == nullptr || - shadowNodeWrapper->shadowNode == nullptr) { - throw jsi::JSINativeException( - "Value state is nullptr, expected a ShadowNode reference"); + auto shadowNodeWrapper = std::dynamic_pointer_cast(nativeState); + if (shadowNodeWrapper == nullptr || shadowNodeWrapper->shadowNode == nullptr) { + throw jsi::JSINativeException("Value state is nullptr, expected a ShadowNode reference"); } return shadowNodeWrapper->shadowNode; } - static jsi::Value toJs( - jsi::Runtime& rt, - const std::shared_ptr& value) { + static jsi::Value toJs(jsi::Runtime &rt, const std::shared_ptr &value) + { jsi::Object obj(rt); obj.setNativeState(rt, std::make_shared(value)); return obj; diff --git a/packages/react-native/ReactCommon/react/renderer/componentregistry/ComponentDescriptorFactory.h b/packages/react-native/ReactCommon/react/renderer/componentregistry/ComponentDescriptorFactory.h index d10ea3536da..ef0bbc50ecd 100644 --- a/packages/react-native/ReactCommon/react/renderer/componentregistry/ComponentDescriptorFactory.h +++ b/packages/react-native/ReactCommon/react/renderer/componentregistry/ComponentDescriptorFactory.h @@ -22,10 +22,9 @@ namespace facebook::react { * Each app must provide an implementation of the static class method which * should register its specific set of supported components. */ -using ComponentRegistryFactory = - std::function& contextContainer)>; +using ComponentRegistryFactory = std::function &contextContainer)>; ComponentRegistryFactory getDefaultComponentRegistryFactory(); diff --git a/packages/react-native/ReactCommon/react/renderer/componentregistry/ComponentDescriptorProvider.h b/packages/react-native/ReactCommon/react/renderer/componentregistry/ComponentDescriptorProvider.h index 175d9bd6e7d..f1e6c7a4010 100644 --- a/packages/react-native/ReactCommon/react/renderer/componentregistry/ComponentDescriptorProvider.h +++ b/packages/react-native/ReactCommon/react/renderer/componentregistry/ComponentDescriptorProvider.h @@ -18,8 +18,7 @@ namespace facebook::react { * constructor. The callable returns a unique pointer conveniently represents an * abstract type and ownership of the newly created object. */ -using ComponentDescriptorConstructor = ComponentDescriptor::Unique( - const ComponentDescriptorParameters& parameters); +using ComponentDescriptorConstructor = ComponentDescriptor::Unique(const ComponentDescriptorParameters ¶meters); /* * Represents a unified way to construct an instance of a particular stored @@ -36,15 +35,15 @@ class ComponentDescriptorProvider final { ComponentHandle handle; ComponentName name; ComponentDescriptor::Flavor flavor; - ComponentDescriptorConstructor* constructor; + ComponentDescriptorConstructor *constructor; }; /* * Creates a `ComponentDescriptor` for given `ComponentDescriptorParameters`. */ template -ComponentDescriptor::Unique concreteComponentDescriptorConstructor( - const ComponentDescriptorParameters& parameters) { +ComponentDescriptor::Unique concreteComponentDescriptorConstructor(const ComponentDescriptorParameters ¶meters) +{ static_assert( std::is_base_of::value, "ComponentDescriptorT must be a descendant of ComponentDescriptor"); @@ -57,7 +56,8 @@ ComponentDescriptor::Unique concreteComponentDescriptorConstructor( * class. */ template -ComponentDescriptorProvider concreteComponentDescriptorProvider() { +ComponentDescriptorProvider concreteComponentDescriptorProvider() +{ static_assert( std::is_base_of::value, "ComponentDescriptorT must be a descendant of ComponentDescriptor"); diff --git a/packages/react-native/ReactCommon/react/renderer/componentregistry/ComponentDescriptorProviderRegistry.h b/packages/react-native/ReactCommon/react/renderer/componentregistry/ComponentDescriptorProviderRegistry.h index 1a23997add0..9d9bad36945 100644 --- a/packages/react-native/ReactCommon/react/renderer/componentregistry/ComponentDescriptorProviderRegistry.h +++ b/packages/react-native/ReactCommon/react/renderer/componentregistry/ComponentDescriptorProviderRegistry.h @@ -16,8 +16,7 @@ namespace facebook::react { -using ComponentDescriptorProviderRequest = - std::function; +using ComponentDescriptorProviderRequest = std::function; /* * Registry of `ComponentDescriptorProvider`s (and managed @@ -32,7 +31,7 @@ class ComponentDescriptorProviderRegistry final { * `ComponentDescriptorRegistry`s accordingly. * The methods can be called on any thread. */ - void add(const ComponentDescriptorProvider& provider) const; + void add(const ComponentDescriptorProvider &provider) const; /* * ComponenDescriptorRegistry will call the `request` in case if a component @@ -42,8 +41,7 @@ class ComponentDescriptorProviderRegistry final { * The request can be called on any thread. * The methods can be called on any thread. */ - void setComponentDescriptorProviderRequest( - ComponentDescriptorProviderRequest request) const; + void setComponentDescriptorProviderRequest(ComponentDescriptorProviderRequest request) const; /* * Creates managed `ComponentDescriptorRegistry` based on a stored list of @@ -51,7 +49,7 @@ class ComponentDescriptorProviderRegistry final { * The methods can be called on any thread. */ ComponentDescriptorRegistry::Shared createComponentDescriptorRegistry( - const ComponentDescriptorParameters& parameters) const; + const ComponentDescriptorParameters ¶meters) const; private: friend class ComponentDescriptorRegistry; @@ -59,12 +57,9 @@ class ComponentDescriptorProviderRegistry final { void request(ComponentName componentName) const; mutable std::shared_mutex mutex_; - mutable std::vector> - componentDescriptorRegistries_; - mutable std::unordered_map - componentDescriptorProviders_; - mutable ComponentDescriptorProviderRequest - componentDescriptorProviderRequest_{}; + mutable std::vector> componentDescriptorRegistries_; + mutable std::unordered_map componentDescriptorProviders_; + mutable ComponentDescriptorProviderRequest componentDescriptorProviderRequest_{}; }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/componentregistry/ComponentDescriptorRegistry.h b/packages/react-native/ReactCommon/react/renderer/componentregistry/ComponentDescriptorRegistry.h index 641a99c384f..54e5ff55259 100644 --- a/packages/react-native/ReactCommon/react/renderer/componentregistry/ComponentDescriptorRegistry.h +++ b/packages/react-native/ReactCommon/react/renderer/componentregistry/ComponentDescriptorRegistry.h @@ -21,8 +21,7 @@ namespace facebook::react { class ComponentDescriptorProviderRegistry; class ComponentDescriptorRegistry; -using SharedComponentDescriptorRegistry = - std::shared_ptr; +using SharedComponentDescriptorRegistry = std::shared_ptr; /* * Registry of particular `ComponentDescriptor`s. @@ -37,7 +36,7 @@ class ComponentDescriptorRegistry { */ ComponentDescriptorRegistry( ComponentDescriptorParameters parameters, - const ComponentDescriptorProviderRegistry& providerRegistry, + const ComponentDescriptorProviderRegistry &providerRegistry, std::shared_ptr contextContainer); /* @@ -45,24 +44,21 @@ class ComponentDescriptorRegistry { * If you requesting a ComponentDescriptor and unsure that it's there, you are * doing something wrong. */ - const ComponentDescriptor* - findComponentDescriptorByHandle_DO_NOT_USE_THIS_IS_BROKEN( + const ComponentDescriptor *findComponentDescriptorByHandle_DO_NOT_USE_THIS_IS_BROKEN( ComponentHandle componentHandle) const; - const ComponentDescriptor& at(const std::string& componentName) const; - const ComponentDescriptor& at(ComponentHandle componentHandle) const; + const ComponentDescriptor &at(const std::string &componentName) const; + const ComponentDescriptor &at(ComponentHandle componentHandle) const; bool hasComponentDescriptorAt(ComponentHandle componentHandle) const; - void setFallbackComponentDescriptor( - const SharedComponentDescriptor& descriptor); + void setFallbackComponentDescriptor(const SharedComponentDescriptor &descriptor); ComponentDescriptor::Shared getFallbackComponentDescriptor() const; private: friend class ComponentDescriptorProviderRegistry; - void registerComponentDescriptor( - const SharedComponentDescriptor& componentDescriptor) const; + void registerComponentDescriptor(const SharedComponentDescriptor &componentDescriptor) const; /* * Creates a `ComponentDescriptor` using specified @@ -71,17 +67,14 @@ class ComponentDescriptorRegistry { * To be used by `ComponentDescriptorProviderRegistry` only. * Thread safe. */ - void add( - const ComponentDescriptorProvider& componentDescriptorProvider) const; + void add(const ComponentDescriptorProvider &componentDescriptorProvider) const; mutable std::shared_mutex mutex_; - mutable std::unordered_map - _registryByHandle; - mutable std::unordered_map - _registryByName; + mutable std::unordered_map _registryByHandle; + mutable std::unordered_map _registryByName; ComponentDescriptor::Shared _fallbackComponentDescriptor; ComponentDescriptorParameters parameters_{}; - const ComponentDescriptorProviderRegistry& providerRegistry_; + const ComponentDescriptorProviderRegistry &providerRegistry_; std::shared_ptr contextContainer_; }; diff --git a/packages/react-native/ReactCommon/react/renderer/componentregistry/native/NativeComponentRegistryBinding.h b/packages/react-native/ReactCommon/react/renderer/componentregistry/native/NativeComponentRegistryBinding.h index e0c9d23463e..1b2bbaf005d 100644 --- a/packages/react-native/ReactCommon/react/renderer/componentregistry/native/NativeComponentRegistryBinding.h +++ b/packages/react-native/ReactCommon/react/renderer/componentregistry/native/NativeComponentRegistryBinding.h @@ -17,15 +17,12 @@ namespace facebook::react { * An app/platform-specific provider function to determine if a component * is registered in the native platform. */ -using HasComponentProviderFunctionType = - std::function; +using HasComponentProviderFunctionType = std::function; /* * Installs HasComponentProviderFunction into JavaScript runtime. * Thread synchronization must be enforced externally. */ -void bindHasComponentProvider( - jsi::Runtime& runtime, - HasComponentProviderFunctionType&& provider); +void bindHasComponentProvider(jsi::Runtime &runtime, HasComponentProviderFunctionType &&provider); } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/components/image/ImageComponentDescriptor.cpp b/packages/react-native/ReactCommon/react/renderer/components/image/ImageComponentDescriptor.cpp index 6049bbb2a52..9067689fd1f 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/image/ImageComponentDescriptor.cpp +++ b/packages/react-native/ReactCommon/react/renderer/components/image/ImageComponentDescriptor.cpp @@ -16,7 +16,8 @@ ImageComponentDescriptor::ImageComponentDescriptor( const ComponentDescriptorParameters& parameters) : ConcreteComponentDescriptor(parameters), imageManager_( - getManagerByName(contextContainer_, ImageManagerKey)){}; + getManagerByName(contextContainer_, ImageManagerKey)) { + }; void ImageComponentDescriptor::adopt(ShadowNode& shadowNode) const { ConcreteComponentDescriptor::adopt(shadowNode); diff --git a/packages/react-native/ReactCommon/react/renderer/components/image/ImageComponentDescriptor.h b/packages/react-native/ReactCommon/react/renderer/components/image/ImageComponentDescriptor.h index 35bce183c02..ff6417774db 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/image/ImageComponentDescriptor.h +++ b/packages/react-native/ReactCommon/react/renderer/components/image/ImageComponentDescriptor.h @@ -19,13 +19,11 @@ extern const char ImageManagerKey[]; /* * Descriptor for component. */ -class ImageComponentDescriptor final - : public ConcreteComponentDescriptor { +class ImageComponentDescriptor final : public ConcreteComponentDescriptor { public: - explicit ImageComponentDescriptor( - const ComponentDescriptorParameters& parameters); + explicit ImageComponentDescriptor(const ComponentDescriptorParameters ¶meters); - void adopt(ShadowNode& shadowNode) const override; + void adopt(ShadowNode &shadowNode) const override; private: const std::shared_ptr imageManager_; diff --git a/packages/react-native/ReactCommon/react/renderer/components/image/ImageEventEmitter.h b/packages/react-native/ReactCommon/react/renderer/components/image/ImageEventEmitter.h index 67ab60bb9a9..b995bfad3fb 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/image/ImageEventEmitter.h +++ b/packages/react-native/ReactCommon/react/renderer/components/image/ImageEventEmitter.h @@ -17,10 +17,10 @@ class ImageEventEmitter : public ViewEventEmitter { using ViewEventEmitter::ViewEventEmitter; void onLoadStart() const; - void onLoad(const ImageSource& source) const; + void onLoad(const ImageSource &source) const; void onLoadEnd() const; void onProgress(double progress, int64_t loaded, int64_t total) const; - void onError(const ImageErrorInfo& error) const; + void onError(const ImageErrorInfo &error) const; void onPartialLoad() const; }; diff --git a/packages/react-native/ReactCommon/react/renderer/components/image/ImageProps.h b/packages/react-native/ReactCommon/react/renderer/components/image/ImageProps.h index 43cdc51ac5b..7a533838ea9 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/image/ImageProps.h +++ b/packages/react-native/ReactCommon/react/renderer/components/image/ImageProps.h @@ -18,16 +18,10 @@ namespace facebook::react { class ImageProps final : public ViewProps { public: ImageProps() = default; - ImageProps( - const PropsParserContext& context, - const ImageProps& sourceProps, - const RawProps& rawProps); + ImageProps(const PropsParserContext &context, const ImageProps &sourceProps, const RawProps &rawProps); - void setProp( - const PropsParserContext& context, - RawPropsPropNameHash hash, - const char* propName, - const RawValue& value); + void + setProp(const PropsParserContext &context, RawPropsPropNameHash hash, const char *propName, const RawValue &value); #pragma mark - Props @@ -48,7 +42,7 @@ class ImageProps final : public ViewProps { #ifdef RN_SERIALIZABLE_STATE ComponentName getDiffPropsImplementationTarget() const override; - folly::dynamic getDiffProps(const Props* prevProps) const override; + folly::dynamic getDiffProps(const Props *prevProps) const override; #endif #if RN_DEBUG_STRING_CONVERTIBLE diff --git a/packages/react-native/ReactCommon/react/renderer/components/image/ImageShadowNode.h b/packages/react-native/ReactCommon/react/renderer/components/image/ImageShadowNode.h index 1bcb0d81310..3ecd4672d12 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/image/ImageShadowNode.h +++ b/packages/react-native/ReactCommon/react/renderer/components/image/ImageShadowNode.h @@ -22,15 +22,13 @@ extern const char ImageComponentName[]; /* * `ShadowNode` for component. */ -class ImageShadowNode final : public ConcreteViewShadowNode< - ImageComponentName, - ImageProps, - ImageEventEmitter, - ImageState> { +class ImageShadowNode final + : public ConcreteViewShadowNode { public: using ConcreteViewShadowNode::ConcreteViewShadowNode; - static ShadowNodeTraits BaseTraits() { + static ShadowNodeTraits BaseTraits() + { auto traits = ConcreteViewShadowNode::BaseTraits(); traits.set(ShadowNodeTraits::Trait::LeafYogaNode); return traits; @@ -39,12 +37,13 @@ class ImageShadowNode final : public ConcreteViewShadowNode< /* * Associates a shared `ImageManager` with the node. */ - void setImageManager(const std::shared_ptr& imageManager); + void setImageManager(const std::shared_ptr &imageManager); static ImageState initialStateData( - const Props::Shared& props, - const ShadowNodeFamily::Shared& /*family*/, - const ComponentDescriptor& componentDescriptor) { + const Props::Shared &props, + const ShadowNodeFamily::Shared & /*family*/, + const ComponentDescriptor &componentDescriptor) + { auto imageSource = ImageSource{ImageSource::Type::Invalid}; return {imageSource, {imageSource, nullptr}, {}}; } diff --git a/packages/react-native/ReactCommon/react/renderer/components/image/ImageState.h b/packages/react-native/ReactCommon/react/renderer/components/image/ImageState.h index fac7d154b57..718dd12620b 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/image/ImageState.h +++ b/packages/react-native/ReactCommon/react/renderer/components/image/ImageState.h @@ -24,13 +24,12 @@ namespace facebook::react { */ class ImageState final { public: - ImageState( - const ImageSource& imageSource, - ImageRequest imageRequest, - const ImageRequestParams& imageRequestParams) + ImageState(const ImageSource &imageSource, ImageRequest imageRequest, const ImageRequestParams &imageRequestParams) : imageSource_(imageSource), imageRequest_(std::make_shared(std::move(imageRequest))), - imageRequestParams_(imageRequestParams) {} + imageRequestParams_(imageRequestParams) + { + } /* * Returns stored ImageSource object. @@ -41,20 +40,20 @@ class ImageState final { * Exposes for reading stored `ImageRequest` object. * `ImageRequest` object cannot be copied or moved from `ImageLocalData`. */ - const ImageRequest& getImageRequest() const; + const ImageRequest &getImageRequest() const; /* * Returns stored ImageRequestParams object. */ - const ImageRequestParams& getImageRequestParams() const; + const ImageRequestParams &getImageRequestParams() const; #ifdef ANDROID - ImageState(const ImageState& previousState, folly::dynamic data) - : imageRequestParams_{} {}; + ImageState(const ImageState &previousState, folly::dynamic data) : imageRequestParams_{} {}; /* * Empty implementation for Android because it doesn't use this class. */ - folly::dynamic getDynamic() const { + folly::dynamic getDynamic() const + { return {}; }; #endif diff --git a/packages/react-native/ReactCommon/react/renderer/components/image/conversions.h b/packages/react-native/ReactCommon/react/renderer/components/image/conversions.h index 2803206c792..2f59ab63dd7 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/image/conversions.h +++ b/packages/react-native/ReactCommon/react/renderer/components/image/conversions.h @@ -18,10 +18,8 @@ namespace facebook::react { -inline void fromRawValue( - const PropsParserContext& context, - const RawValue& value, - ImageSource& result) { +inline void fromRawValue(const PropsParserContext &context, const RawValue &value, ImageSource &result) +{ if (value.hasType()) { result = { /* .type = */ ImageSource::Type::Remote, @@ -40,12 +38,10 @@ inline void fromRawValue( result.type = ImageSource::Type::Local; } - if (items.find("width") != items.end() && - items.find("height") != items.end() && + if (items.find("width") != items.end() && items.find("height") != items.end() && // The following checks have to be removed after codegen is shipped. // See T45151459. - items.at("width").hasType() && - items.at("height").hasType()) { + items.at("width").hasType() && items.at("height").hasType()) { result.size = {(Float)items.at("width"), (Float)items.at("height")}; } @@ -81,27 +77,22 @@ inline void fromRawValue( } if (items.find("headers") != items.end() && - items.at("headers") - .hasType>()) { - auto headers = - (std::unordered_map)items.at("headers"); - for (const auto& header : headers) { + items.at("headers").hasType>()) { + auto headers = (std::unordered_map)items.at("headers"); + for (const auto &header : headers) { result.headers.push_back(header); } } - if (items.find("body") != items.end() && - items.at("body").hasType()) { + if (items.find("body") != items.end() && items.at("body").hasType()) { result.body = (std::string)items.at("body"); } - if (items.find("method") != items.end() && - items.at("method").hasType()) { + if (items.find("method") != items.end() && items.at("method").hasType()) { result.method = (std::string)items.at("method"); } - if (items.find("cache") != items.end() && - items.at("cache").hasType()) { + if (items.find("cache") != items.end() && items.at("cache").hasType()) { auto cache = (std::string)items.at("cache"); if (cache == "reload") { result.cache = ImageSource::CacheStategy::Reload; @@ -121,14 +112,13 @@ inline void fromRawValue( result.type = ImageSource::Type::Invalid; } -inline std::string toString(const ImageSource& value) { +inline std::string toString(const ImageSource &value) +{ return "{uri: " + value.uri + "}"; } -inline void fromRawValue( - const PropsParserContext& context, - const RawValue& value, - ImageResizeMode& result) { +inline void fromRawValue(const PropsParserContext &context, const RawValue &value, ImageResizeMode &result) +{ react_native_expect(value.hasType()); if (!value.hasType()) { LOG(ERROR) << "Unsupported ImageResizeMode type"; @@ -158,7 +148,8 @@ inline void fromRawValue( } } -inline std::string toString(const ImageResizeMode& value) { +inline std::string toString(const ImageResizeMode &value) +{ switch (value) { case ImageResizeMode::Cover: return "cover"; diff --git a/packages/react-native/ReactCommon/react/renderer/components/inputaccessory/InputAccessoryComponentDescriptor.h b/packages/react-native/ReactCommon/react/renderer/components/inputaccessory/InputAccessoryComponentDescriptor.h index fb252fd4652..1f524310d8c 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/inputaccessory/InputAccessoryComponentDescriptor.h +++ b/packages/react-native/ReactCommon/react/renderer/components/inputaccessory/InputAccessoryComponentDescriptor.h @@ -16,23 +16,17 @@ namespace facebook::react { /* * Descriptor for component. */ -class InputAccessoryComponentDescriptor final - : public ConcreteComponentDescriptor { +class InputAccessoryComponentDescriptor final : public ConcreteComponentDescriptor { public: using ConcreteComponentDescriptor::ConcreteComponentDescriptor; - void adopt(ShadowNode& shadowNode) const override { - auto& layoutableShadowNode = - static_cast(shadowNode); + void adopt(ShadowNode &shadowNode) const override + { + auto &layoutableShadowNode = static_cast(shadowNode); - auto& stateData = - static_cast( - *shadowNode.getState()) - .getData(); + auto &stateData = static_cast(*shadowNode.getState()).getData(); - layoutableShadowNode.setSize(Size{ - .width = stateData.viewportSize.width, - .height = stateData.viewportSize.height}); + layoutableShadowNode.setSize(Size{.width = stateData.viewportSize.width, .height = stateData.viewportSize.height}); layoutableShadowNode.setPositionType(YGPositionTypeAbsolute); ConcreteComponentDescriptor::adopt(shadowNode); diff --git a/packages/react-native/ReactCommon/react/renderer/components/inputaccessory/InputAccessoryShadowNode.h b/packages/react-native/ReactCommon/react/renderer/components/inputaccessory/InputAccessoryShadowNode.h index 15cbea43434..5de0b82ea0c 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/inputaccessory/InputAccessoryShadowNode.h +++ b/packages/react-native/ReactCommon/react/renderer/components/inputaccessory/InputAccessoryShadowNode.h @@ -27,7 +27,8 @@ class InputAccessoryShadowNode final : public ConcreteViewShadowNode< public: using ConcreteViewShadowNode::ConcreteViewShadowNode; - static ShadowNodeTraits BaseTraits() { + static ShadowNodeTraits BaseTraits() + { auto traits = ConcreteViewShadowNode::BaseTraits(); traits.set(ShadowNodeTraits::Trait::RootNodeKind); return traits; diff --git a/packages/react-native/ReactCommon/react/renderer/components/inputaccessory/InputAccessoryState.h b/packages/react-native/ReactCommon/react/renderer/components/inputaccessory/InputAccessoryState.h index e415c67681e..75e5c9ca0b3 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/inputaccessory/InputAccessoryState.h +++ b/packages/react-native/ReactCommon/react/renderer/components/inputaccessory/InputAccessoryState.h @@ -17,8 +17,8 @@ namespace facebook::react { */ class InputAccessoryState final { public: - InputAccessoryState(){}; - InputAccessoryState(Size viewportSize_) : viewportSize(viewportSize_){}; + InputAccessoryState() {}; + InputAccessoryState(Size viewportSize_) : viewportSize(viewportSize_) {}; const Size viewportSize{}; }; diff --git a/packages/react-native/ReactCommon/react/renderer/components/legacyviewmanagerinterop/LegacyViewManagerInteropComponentDescriptor.h b/packages/react-native/ReactCommon/react/renderer/components/legacyviewmanagerinterop/LegacyViewManagerInteropComponentDescriptor.h index a59365e4031..953c5f8dceb 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/legacyviewmanagerinterop/LegacyViewManagerInteropComponentDescriptor.h +++ b/packages/react-native/ReactCommon/react/renderer/components/legacyviewmanagerinterop/LegacyViewManagerInteropComponentDescriptor.h @@ -17,8 +17,7 @@ class LegacyViewManagerInteropComponentDescriptor final public: using ConcreteComponentDescriptor::ConcreteComponentDescriptor; - LegacyViewManagerInteropComponentDescriptor( - const ComponentDescriptorParameters& parameters); + LegacyViewManagerInteropComponentDescriptor(const ComponentDescriptorParameters ¶meters); /* * Returns `name` and `handle` based on a `flavor`, not on static data from * `LegacyViewManagerInteropShadowNode`. @@ -27,7 +26,7 @@ class LegacyViewManagerInteropComponentDescriptor final ComponentName getComponentName() const override; protected: - void adopt(ShadowNode& shadowNode) const override; + void adopt(ShadowNode &shadowNode) const override; private: const std::shared_ptr _coordinator; diff --git a/packages/react-native/ReactCommon/react/renderer/components/legacyviewmanagerinterop/LegacyViewManagerInteropViewProps.h b/packages/react-native/ReactCommon/react/renderer/components/legacyviewmanagerinterop/LegacyViewManagerInteropViewProps.h index 4decba7e802..6b564ecc36f 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/legacyviewmanagerinterop/LegacyViewManagerInteropViewProps.h +++ b/packages/react-native/ReactCommon/react/renderer/components/legacyviewmanagerinterop/LegacyViewManagerInteropViewProps.h @@ -16,9 +16,9 @@ class LegacyViewManagerInteropViewProps final : public ViewProps { public: LegacyViewManagerInteropViewProps() = default; LegacyViewManagerInteropViewProps( - const PropsParserContext& context, - const LegacyViewManagerInteropViewProps& sourceProps, - const RawProps& rawProps); + const PropsParserContext &context, + const LegacyViewManagerInteropViewProps &sourceProps, + const RawProps &rawProps); #pragma mark - Props diff --git a/packages/react-native/ReactCommon/react/renderer/components/legacyviewmanagerinterop/UnstableLegacyViewManagerAutomaticComponentDescriptor.h b/packages/react-native/ReactCommon/react/renderer/components/legacyviewmanagerinterop/UnstableLegacyViewManagerAutomaticComponentDescriptor.h index 24458840edc..0f9dd1aabe3 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/legacyviewmanagerinterop/UnstableLegacyViewManagerAutomaticComponentDescriptor.h +++ b/packages/react-native/ReactCommon/react/renderer/components/legacyviewmanagerinterop/UnstableLegacyViewManagerAutomaticComponentDescriptor.h @@ -15,16 +15,16 @@ namespace facebook::react { class UnstableLegacyViewManagerAutomaticComponentDescriptor final - : public ConcreteComponentDescriptor< - LegacyViewManagerAndroidInteropShadowNode> { + : public ConcreteComponentDescriptor { public: using ConcreteComponentDescriptor::ConcreteComponentDescriptor; UnstableLegacyViewManagerAutomaticComponentDescriptor( - const ComponentDescriptorParameters& parameters, + const ComponentDescriptorParameters ¶meters, std::string legacyComponentName) - : ConcreteComponentDescriptor(parameters), - legacyComponentName_(std::move(legacyComponentName)) {} + : ConcreteComponentDescriptor(parameters), legacyComponentName_(std::move(legacyComponentName)) + { + } ComponentHandle getComponentHandle() const override; ComponentName getComponentName() const override; diff --git a/packages/react-native/ReactCommon/react/renderer/components/legacyviewmanagerinterop/UnstableLegacyViewManagerAutomaticShadowNode.h b/packages/react-native/ReactCommon/react/renderer/components/legacyviewmanagerinterop/UnstableLegacyViewManagerAutomaticShadowNode.h index 59081e6b00f..6fb431f0d99 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/legacyviewmanagerinterop/UnstableLegacyViewManagerAutomaticShadowNode.h +++ b/packages/react-native/ReactCommon/react/renderer/components/legacyviewmanagerinterop/UnstableLegacyViewManagerAutomaticShadowNode.h @@ -14,8 +14,7 @@ namespace facebook::react { extern const char LegacyViewManagerAndroidInteropComponentName[]; -using LegacyViewManagerAndroidInteropShadowNode = ConcreteViewShadowNode< - LegacyViewManagerAndroidInteropComponentName, - LegacyViewManagerInteropViewProps>; +using LegacyViewManagerAndroidInteropShadowNode = + ConcreteViewShadowNode; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/components/legacyviewmanagerinterop/UnstableLegacyViewManagerInteropComponentDescriptor.h b/packages/react-native/ReactCommon/react/renderer/components/legacyviewmanagerinterop/UnstableLegacyViewManagerInteropComponentDescriptor.h index 6f7ed1a5ba4..9d9d0ff739b 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/legacyviewmanagerinterop/UnstableLegacyViewManagerInteropComponentDescriptor.h +++ b/packages/react-native/ReactCommon/react/renderer/components/legacyviewmanagerinterop/UnstableLegacyViewManagerInteropComponentDescriptor.h @@ -19,16 +19,15 @@ namespace facebook::react { * This component is part of the Fabric Interop Layer and is subject to future * changes (hence the "Unstable" prefix). */ -template +template class UnstableLegacyViewManagerInteropComponentDescriptor - : public ConcreteComponentDescriptor< - ConcreteViewShadowNode> { + : public ConcreteComponentDescriptor> { public: UnstableLegacyViewManagerInteropComponentDescriptor( - const ComponentDescriptorParameters& parameters) - : ConcreteComponentDescriptor< - ConcreteViewShadowNode>( - parameters) {} + const ComponentDescriptorParameters ¶meters) + : ConcreteComponentDescriptor>(parameters) + { + } private: }; diff --git a/packages/react-native/ReactCommon/react/renderer/components/modal/ModalHostViewComponentDescriptor.h b/packages/react-native/ReactCommon/react/renderer/components/modal/ModalHostViewComponentDescriptor.h index 51f60b9c503..f48c41fb114 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/modal/ModalHostViewComponentDescriptor.h +++ b/packages/react-native/ReactCommon/react/renderer/components/modal/ModalHostViewComponentDescriptor.h @@ -17,36 +17,27 @@ namespace facebook::react { * Descriptor for component. */ -class ModalHostViewComponentDescriptor final - : public ConcreteComponentDescriptor { +class ModalHostViewComponentDescriptor final : public ConcreteComponentDescriptor { public: using ConcreteComponentDescriptor::ConcreteComponentDescriptor; - void adopt(ShadowNode& shadowNode) const override { - auto& layoutableShadowNode = - static_cast(shadowNode); - auto& stateData = - static_cast( - *shadowNode.getState()) - .getData(); + void adopt(ShadowNode &shadowNode) const override + { + auto &layoutableShadowNode = static_cast(shadowNode); + auto &stateData = static_cast(*shadowNode.getState()).getData(); - layoutableShadowNode.setSize(Size{ - .width = stateData.screenSize.width, - .height = stateData.screenSize.height}); + layoutableShadowNode.setSize(Size{.width = stateData.screenSize.width, .height = stateData.screenSize.height}); layoutableShadowNode.setPositionType(YGPositionTypeAbsolute); ConcreteComponentDescriptor::adopt(shadowNode); } #ifdef ANDROID - State::Shared createInitialState( - const Props::Shared& props, - const ShadowNodeFamily::Shared& family) const override; + State::Shared createInitialState(const Props::Shared &props, const ShadowNodeFamily::Shared &family) const override; #endif // ANDROID private: - constexpr static auto UIManagerJavaDescriptor = - "com/facebook/react/fabric/FabricUIManager"; + constexpr static auto UIManagerJavaDescriptor = "com/facebook/react/fabric/FabricUIManager"; }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/components/modal/ModalHostViewShadowNode.h b/packages/react-native/ReactCommon/react/renderer/components/modal/ModalHostViewShadowNode.h index 7a37ba1885f..3964dee4b93 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/modal/ModalHostViewShadowNode.h +++ b/packages/react-native/ReactCommon/react/renderer/components/modal/ModalHostViewShadowNode.h @@ -27,7 +27,8 @@ class ModalHostViewShadowNode final : public ConcreteViewShadowNode< public: using ConcreteViewShadowNode::ConcreteViewShadowNode; - static ShadowNodeTraits BaseTraits() { + static ShadowNodeTraits BaseTraits() + { auto traits = ConcreteViewShadowNode::BaseTraits(); traits.set(ShadowNodeTraits::Trait::RootNodeKind); // has a side effect of showing the modal overlay and diff --git a/packages/react-native/ReactCommon/react/renderer/components/modal/ModalHostViewState.h b/packages/react-native/ReactCommon/react/renderer/components/modal/ModalHostViewState.h index 76879cf7347..eec349a35fb 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/modal/ModalHostViewState.h +++ b/packages/react-native/ReactCommon/react/renderer/components/modal/ModalHostViewState.h @@ -25,15 +25,13 @@ class ModalHostViewState final { using Shared = std::shared_ptr; ModalHostViewState() : screenSize(ModalHostViewScreenSize()) {} - ModalHostViewState(Size screenSize_) : screenSize(screenSize_){}; + ModalHostViewState(Size screenSize_) : screenSize(screenSize_) {}; #ifdef RN_SERIALIZABLE_STATE - ModalHostViewState( - const ModalHostViewState& previousState, - folly::dynamic data) - : screenSize(Size{ - .width = (Float)data["screenWidth"].getDouble(), - .height = (Float)data["screenHeight"].getDouble()}){}; + ModalHostViewState(const ModalHostViewState &previousState, folly::dynamic data) + : screenSize( + Size{.width = (Float)data["screenWidth"].getDouble(), .height = (Float)data["screenHeight"].getDouble()}) { + }; #endif const Size screenSize{}; diff --git a/packages/react-native/ReactCommon/react/renderer/components/progressbar/android/react/renderer/components/progressbar/AndroidProgressBarComponentDescriptor.h b/packages/react-native/ReactCommon/react/renderer/components/progressbar/android/react/renderer/components/progressbar/AndroidProgressBarComponentDescriptor.h index 5de41780635..5806aa51093 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/progressbar/android/react/renderer/components/progressbar/AndroidProgressBarComponentDescriptor.h +++ b/packages/react-native/ReactCommon/react/renderer/components/progressbar/android/react/renderer/components/progressbar/AndroidProgressBarComponentDescriptor.h @@ -16,31 +16,27 @@ namespace facebook::react { /* * Descriptor for component. */ -class AndroidProgressBarComponentDescriptor final - : public ConcreteComponentDescriptor { +class AndroidProgressBarComponentDescriptor final : public ConcreteComponentDescriptor { public: - AndroidProgressBarComponentDescriptor( - const ComponentDescriptorParameters& parameters) + AndroidProgressBarComponentDescriptor(const ComponentDescriptorParameters ¶meters) : ConcreteComponentDescriptor(parameters), - measurementsManager_( - std::make_shared( - contextContainer_)) {} + measurementsManager_(std::make_shared(contextContainer_)) + { + } - void adopt(ShadowNode& shadowNode) const override { + void adopt(ShadowNode &shadowNode) const override + { ConcreteComponentDescriptor::adopt(shadowNode); - auto& androidProgressBarShadowNode = - static_cast(shadowNode); + auto &androidProgressBarShadowNode = static_cast(shadowNode); // `AndroidProgressBarShadowNode` uses // `AndroidProgressBarMeasurementsManager` to provide measurements to Yoga. - androidProgressBarShadowNode.setAndroidProgressBarMeasurementsManager( - measurementsManager_); + androidProgressBarShadowNode.setAndroidProgressBarMeasurementsManager(measurementsManager_); } private: - const std::shared_ptr - measurementsManager_; + const std::shared_ptr measurementsManager_; }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/components/progressbar/android/react/renderer/components/progressbar/AndroidProgressBarMeasurementsManager.h b/packages/react-native/ReactCommon/react/renderer/components/progressbar/android/react/renderer/components/progressbar/AndroidProgressBarMeasurementsManager.h index 9eeb3bee3c4..d9aa7a46a68 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/progressbar/android/react/renderer/components/progressbar/AndroidProgressBarMeasurementsManager.h +++ b/packages/react-native/ReactCommon/react/renderer/components/progressbar/android/react/renderer/components/progressbar/AndroidProgressBarMeasurementsManager.h @@ -16,14 +16,12 @@ namespace facebook::react { class AndroidProgressBarMeasurementsManager { public: - AndroidProgressBarMeasurementsManager( - const std::shared_ptr& contextContainer) - : contextContainer_(contextContainer) {} + AndroidProgressBarMeasurementsManager(const std::shared_ptr &contextContainer) + : contextContainer_(contextContainer) + { + } - Size measure( - SurfaceId surfaceId, - const AndroidProgressBarProps& props, - LayoutConstraints layoutConstraints) const; + Size measure(SurfaceId surfaceId, const AndroidProgressBarProps &props, LayoutConstraints layoutConstraints) const; private: const std::shared_ptr contextContainer_; diff --git a/packages/react-native/ReactCommon/react/renderer/components/progressbar/android/react/renderer/components/progressbar/AndroidProgressBarShadowNode.h b/packages/react-native/ReactCommon/react/renderer/components/progressbar/android/react/renderer/components/progressbar/AndroidProgressBarShadowNode.h index 7b28d992ba6..92b4dc61f8b 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/progressbar/android/react/renderer/components/progressbar/AndroidProgressBarShadowNode.h +++ b/packages/react-native/ReactCommon/react/renderer/components/progressbar/android/react/renderer/components/progressbar/AndroidProgressBarShadowNode.h @@ -26,7 +26,8 @@ class AndroidProgressBarShadowNode final : public ConcreteViewShadowNode< public: using ConcreteViewShadowNode::ConcreteViewShadowNode; - static ShadowNodeTraits BaseTraits() { + static ShadowNodeTraits BaseTraits() + { auto traits = ConcreteViewShadowNode::BaseTraits(); traits.set(ShadowNodeTraits::Trait::LeafYogaNode); traits.set(ShadowNodeTraits::Trait::MeasurableYogaNode); @@ -35,14 +36,11 @@ class AndroidProgressBarShadowNode final : public ConcreteViewShadowNode< // Associates a shared `AndroidProgressBarMeasurementsManager` with the node. void setAndroidProgressBarMeasurementsManager( - const std::shared_ptr& - measurementsManager); + const std::shared_ptr &measurementsManager); #pragma mark - LayoutableShadowNode - Size measureContent( - const LayoutContext& layoutContext, - const LayoutConstraints& layoutConstraints) const override; + Size measureContent(const LayoutContext &layoutContext, const LayoutConstraints &layoutConstraints) const override; private: std::shared_ptr measurementsManager_; diff --git a/packages/react-native/ReactCommon/react/renderer/components/progressbar/android/react/renderer/components/progressbar/conversions.h b/packages/react-native/ReactCommon/react/renderer/components/progressbar/android/react/renderer/components/progressbar/conversions.h index 8d636a7019f..92f0201a2ca 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/progressbar/android/react/renderer/components/progressbar/conversions.h +++ b/packages/react-native/ReactCommon/react/renderer/components/progressbar/android/react/renderer/components/progressbar/conversions.h @@ -14,7 +14,8 @@ namespace facebook::react { #ifdef RN_SERIALIZABLE_STATE -inline folly::dynamic toDynamic(const AndroidProgressBarProps& props) { +inline folly::dynamic toDynamic(const AndroidProgressBarProps &props) +{ folly::dynamic serializedProps = folly::dynamic::object(); serializedProps["styleAttr"] = props.styleAttr; serializedProps["typeAttr"] = props.typeAttr; diff --git a/packages/react-native/ReactCommon/react/renderer/components/root/RootProps.cpp b/packages/react-native/ReactCommon/react/renderer/components/root/RootProps.cpp index d1ef9a0b154..72f984ba22c 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/root/RootProps.cpp +++ b/packages/react-native/ReactCommon/react/renderer/components/root/RootProps.cpp @@ -31,6 +31,6 @@ RootProps::RootProps( const LayoutContext& layoutContext) : ViewProps(), layoutConstraints(layoutConstraints), - layoutContext(layoutContext){}; + layoutContext(layoutContext) {}; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/components/root/RootProps.h b/packages/react-native/ReactCommon/react/renderer/components/root/RootProps.h index 57423128c5f..1003f5202f8 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/root/RootProps.h +++ b/packages/react-native/ReactCommon/react/renderer/components/root/RootProps.h @@ -19,15 +19,12 @@ namespace facebook::react { class RootProps final : public ViewProps { public: RootProps() = default; + RootProps(const PropsParserContext &context, const RootProps &sourceProps, const RawProps &rawProps); RootProps( - const PropsParserContext& context, - const RootProps& sourceProps, - const RawProps& rawProps); - RootProps( - const PropsParserContext& context, - const RootProps& sourceProps, - const LayoutConstraints& layoutConstraints, - const LayoutContext& layoutContext); + const PropsParserContext &context, + const RootProps &sourceProps, + const LayoutConstraints &layoutConstraints, + const LayoutContext &layoutContext); #pragma mark - Props diff --git a/packages/react-native/ReactCommon/react/renderer/components/root/RootShadowNode.h b/packages/react-native/ReactCommon/react/renderer/components/root/RootShadowNode.h index fce4754d52c..2676a130768 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/root/RootShadowNode.h +++ b/packages/react-native/ReactCommon/react/renderer/components/root/RootShadowNode.h @@ -26,15 +26,15 @@ extern const char RootComponentName[]; * props which represent external layout constraints and context of the * shadow tree. */ -class RootShadowNode final - : public ConcreteViewShadowNode { +class RootShadowNode final : public ConcreteViewShadowNode { public: using ConcreteViewShadowNode::ConcreteViewShadowNode; using Shared = std::shared_ptr; using Unshared = std::shared_ptr; - static ShadowNodeTraits BaseTraits() { + static ShadowNodeTraits BaseTraits() + { auto traits = ConcreteViewShadowNode::BaseTraits(); traits.set(ShadowNodeTraits::Trait::RootNodeKind); return traits; @@ -44,16 +44,15 @@ class RootShadowNode final * Layouts the shadow tree if needed. * Returns `false` if the three is already laid out. */ - bool layoutIfNeeded( - std::vector* affectedNodes = {}); + bool layoutIfNeeded(std::vector *affectedNodes = {}); /* * Clones the node with given `layoutConstraints` and `layoutContext`. */ RootShadowNode::Unshared clone( - const PropsParserContext& propsParserContext, - const LayoutConstraints& layoutConstraints, - const LayoutContext& layoutContext) const; + const PropsParserContext &propsParserContext, + const LayoutConstraints &layoutConstraints, + const LayoutContext &layoutContext) const; Transform getTransform() const override; diff --git a/packages/react-native/ReactCommon/react/renderer/components/safeareaview/SafeAreaViewComponentDescriptor.h b/packages/react-native/ReactCommon/react/renderer/components/safeareaview/SafeAreaViewComponentDescriptor.h index f8a39157044..a03c7c968d2 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/safeareaview/SafeAreaViewComponentDescriptor.h +++ b/packages/react-native/ReactCommon/react/renderer/components/safeareaview/SafeAreaViewComponentDescriptor.h @@ -15,15 +15,12 @@ namespace facebook::react { /* * Descriptor for component. */ -class SafeAreaViewComponentDescriptor final - : public ConcreteComponentDescriptor { +class SafeAreaViewComponentDescriptor final : public ConcreteComponentDescriptor { using ConcreteComponentDescriptor::ConcreteComponentDescriptor; - void adopt(ShadowNode& shadowNode) const override { - auto& layoutableShadowNode = - static_cast(shadowNode); - auto& stateData = static_cast( - *shadowNode.getState()) - .getData(); + void adopt(ShadowNode &shadowNode) const override + { + auto &layoutableShadowNode = static_cast(shadowNode); + auto &stateData = static_cast(*shadowNode.getState()).getData(); layoutableShadowNode.setPadding(stateData.padding); ConcreteComponentDescriptor::adopt(shadowNode); diff --git a/packages/react-native/ReactCommon/react/renderer/components/safeareaview/SafeAreaViewShadowNode.h b/packages/react-native/ReactCommon/react/renderer/components/safeareaview/SafeAreaViewShadowNode.h index 43c9f132055..ed073709833 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/safeareaview/SafeAreaViewShadowNode.h +++ b/packages/react-native/ReactCommon/react/renderer/components/safeareaview/SafeAreaViewShadowNode.h @@ -20,11 +20,8 @@ extern const char SafeAreaViewComponentName[]; /* * `ShadowNode` for component. */ -class SafeAreaViewShadowNode final : public ConcreteViewShadowNode< - SafeAreaViewComponentName, - SafeAreaViewProps, - ViewEventEmitter, - SafeAreaViewState> { +class SafeAreaViewShadowNode final + : public ConcreteViewShadowNode { using ConcreteViewShadowNode::ConcreteViewShadowNode; }; diff --git a/packages/react-native/ReactCommon/react/renderer/components/safeareaview/SafeAreaViewState.h b/packages/react-native/ReactCommon/react/renderer/components/safeareaview/SafeAreaViewState.h index 35544087532..7ca383fdb51 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/safeareaview/SafeAreaViewState.h +++ b/packages/react-native/ReactCommon/react/renderer/components/safeareaview/SafeAreaViewState.h @@ -23,15 +23,14 @@ class SafeAreaViewState final { #ifdef ANDROID SafeAreaViewState() = default; - SafeAreaViewState( - const SafeAreaViewState& /*previousState*/, - folly::dynamic data) - : padding(EdgeInsets{ - (Float)data["left"].getDouble(), - (Float)data["top"].getDouble(), - (Float)data["right"].getDouble(), - (Float)data["bottom"].getDouble(), - }){}; + SafeAreaViewState(const SafeAreaViewState & /*previousState*/, folly::dynamic data) + : padding( + EdgeInsets{ + (Float)data["left"].getDouble(), + (Float)data["top"].getDouble(), + (Float)data["right"].getDouble(), + (Float)data["bottom"].getDouble(), + }) {}; folly::dynamic getDynamic() const; #endif diff --git a/packages/react-native/ReactCommon/react/renderer/components/scrollview/BaseScrollViewProps.h b/packages/react-native/ReactCommon/react/renderer/components/scrollview/BaseScrollViewProps.h index 0ea853b9b36..f6de1cd07fd 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/scrollview/BaseScrollViewProps.h +++ b/packages/react-native/ReactCommon/react/renderer/components/scrollview/BaseScrollViewProps.h @@ -20,15 +20,12 @@ class BaseScrollViewProps : public ViewProps { public: BaseScrollViewProps() = default; BaseScrollViewProps( - const PropsParserContext& context, - const BaseScrollViewProps& sourceProps, - const RawProps& rawProps); + const PropsParserContext &context, + const BaseScrollViewProps &sourceProps, + const RawProps &rawProps); - void setProp( - const PropsParserContext& context, - RawPropsPropNameHash hash, - const char* propName, - const RawValue& value); + void + setProp(const PropsParserContext &context, RawPropsPropNameHash hash, const char *propName, const RawValue &value); #pragma mark - Props @@ -46,8 +43,7 @@ class BaseScrollViewProps : public ViewProps { bool directionalLockEnabled{}; ScrollViewIndicatorStyle indicatorStyle{}; ScrollViewKeyboardDismissMode keyboardDismissMode{}; - std::optional - maintainVisibleContentPosition{}; + std::optional maintainVisibleContentPosition{}; Float maximumZoomScale{1.0f}; Float minimumZoomScale{1.0f}; bool scrollEnabled{true}; @@ -69,8 +65,7 @@ class BaseScrollViewProps : public ViewProps { std::vector snapToOffsets{}; bool snapToStart{true}; bool snapToEnd{true}; - ContentInsetAdjustmentBehavior contentInsetAdjustmentBehavior{ - ContentInsetAdjustmentBehavior::Never}; + ContentInsetAdjustmentBehavior contentInsetAdjustmentBehavior{ContentInsetAdjustmentBehavior::Never}; bool scrollToOverflowEnabled{false}; bool isInvertedVirtualizedList{false}; diff --git a/packages/react-native/ReactCommon/react/renderer/components/scrollview/ScrollEvent.h b/packages/react-native/ReactCommon/react/renderer/components/scrollview/ScrollEvent.h index a9fccb459a6..fb2cd8b44fd 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/scrollview/ScrollEvent.h +++ b/packages/react-native/ReactCommon/react/renderer/components/scrollview/ScrollEvent.h @@ -34,11 +34,10 @@ struct ScrollEvent : public EventPayload { /* * EventPayload implementations */ - jsi::Value asJSIValue(jsi::Runtime& runtime) const override; + jsi::Value asJSIValue(jsi::Runtime &runtime) const override; EventPayloadType getType() const override; - std::optional extractValue( - const std::vector& path) const override; + std::optional extractValue(const std::vector &path) const override; }; struct ScrollEndDragEvent : public ScrollEvent { @@ -47,22 +46,23 @@ struct ScrollEndDragEvent : public ScrollEvent { ScrollEndDragEvent() = default; - ScrollEndDragEvent(const ScrollEvent& scrollEvent) - : ScrollEvent(scrollEvent), targetContentOffset({}), velocity({}) {} + ScrollEndDragEvent(const ScrollEvent &scrollEvent) : ScrollEvent(scrollEvent), targetContentOffset({}), velocity({}) + { + } folly::dynamic asDynamic() const; /* * EventPayload implementations */ - jsi::Value asJSIValue(jsi::Runtime& runtime) const override; + jsi::Value asJSIValue(jsi::Runtime &runtime) const override; }; #if RN_DEBUG_STRING_CONVERTIBLE -std::string getDebugName(const ScrollEvent& scrollEvent); +std::string getDebugName(const ScrollEvent &scrollEvent); std::vector getDebugProps( - const ScrollEvent& scrollEvent, + const ScrollEvent &scrollEvent, DebugStringConvertibleOptions options); #endif diff --git a/packages/react-native/ReactCommon/react/renderer/components/scrollview/ScrollViewComponentDescriptor.h b/packages/react-native/ReactCommon/react/renderer/components/scrollview/ScrollViewComponentDescriptor.h index bde164951fa..84415e8fd37 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/scrollview/ScrollViewComponentDescriptor.h +++ b/packages/react-native/ReactCommon/react/renderer/components/scrollview/ScrollViewComponentDescriptor.h @@ -12,7 +12,6 @@ namespace facebook::react { -using ScrollViewComponentDescriptor = - ConcreteComponentDescriptor; +using ScrollViewComponentDescriptor = ConcreteComponentDescriptor; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/components/scrollview/ScrollViewEventEmitter.h b/packages/react-native/ReactCommon/react/renderer/components/scrollview/ScrollViewEventEmitter.h index 2742244bc4f..1879f155064 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/scrollview/ScrollViewEventEmitter.h +++ b/packages/react-native/ReactCommon/react/renderer/components/scrollview/ScrollViewEventEmitter.h @@ -23,16 +23,15 @@ class ScrollViewEventEmitter : public ViewEventEmitter { using Metrics = ScrollEvent; using EndDragMetrics = ScrollEndDragEvent; - void onScroll(const ScrollEvent& scrollEvent) const; - void onScrollBeginDrag(const ScrollEvent& scrollEvent) const; - void onScrollEndDrag(const ScrollEndDragEvent& scrollEvent) const; - void onMomentumScrollBegin(const ScrollEvent& scrollEvent) const; - void onMomentumScrollEnd(const ScrollEvent& scrollEvent) const; - void onScrollToTop(const ScrollEvent& scrollEvent) const; + void onScroll(const ScrollEvent &scrollEvent) const; + void onScrollBeginDrag(const ScrollEvent &scrollEvent) const; + void onScrollEndDrag(const ScrollEndDragEvent &scrollEvent) const; + void onMomentumScrollBegin(const ScrollEvent &scrollEvent) const; + void onMomentumScrollEnd(const ScrollEvent &scrollEvent) const; + void onScrollToTop(const ScrollEvent &scrollEvent) const; private: - void dispatchScrollViewEvent(std::string name, const ScrollEvent& scrollEvent) - const; + void dispatchScrollViewEvent(std::string name, const ScrollEvent &scrollEvent) const; }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/components/scrollview/ScrollViewShadowNode.h b/packages/react-native/ReactCommon/react/renderer/components/scrollview/ScrollViewShadowNode.h index a0fbcf4ca1e..0362662ccf5 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/scrollview/ScrollViewShadowNode.h +++ b/packages/react-native/ReactCommon/react/renderer/components/scrollview/ScrollViewShadowNode.h @@ -21,18 +21,15 @@ extern const char ScrollViewComponentName[]; /* * `ShadowNode` for component. */ -class ScrollViewShadowNode final : public ConcreteViewShadowNode< - ScrollViewComponentName, - ScrollViewProps, - ScrollViewEventEmitter, - ScrollViewState> { +class ScrollViewShadowNode final + : public ConcreteViewShadowNode { public: using ConcreteViewShadowNode::ConcreteViewShadowNode; static ScrollViewState initialStateData( - const Props::Shared& props, - const ShadowNodeFamily::Shared& family, - const ComponentDescriptor& componentDescriptor); + const Props::Shared &props, + const ShadowNodeFamily::Shared &family, + const ComponentDescriptor &componentDescriptor); #pragma mark - LayoutableShadowNode diff --git a/packages/react-native/ReactCommon/react/renderer/components/scrollview/ScrollViewState.h b/packages/react-native/ReactCommon/react/renderer/components/scrollview/ScrollViewState.h index e4a53e61704..25a02f60fdb 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/scrollview/ScrollViewState.h +++ b/packages/react-native/ReactCommon/react/renderer/components/scrollview/ScrollViewState.h @@ -23,10 +23,7 @@ namespace facebook::react { */ class ScrollViewState final { public: - ScrollViewState( - Point contentOffset, - Rect contentBoundingRect, - int scrollAwayPaddingTop); + ScrollViewState(Point contentOffset, Rect contentBoundingRect, int scrollAwayPaddingTop); ScrollViewState() = default; Point contentOffset; @@ -47,16 +44,14 @@ class ScrollViewState final { Size getContentSize() const; #ifdef RN_SERIALIZABLE_STATE - ScrollViewState(const ScrollViewState& previousState, folly::dynamic data) - : contentOffset( - {(Float)data["contentOffsetLeft"].getDouble(), - (Float)data["contentOffsetTop"].getDouble()}), + ScrollViewState(const ScrollViewState &previousState, folly::dynamic data) + : contentOffset({(Float)data["contentOffsetLeft"].getDouble(), (Float)data["contentOffsetTop"].getDouble()}), contentBoundingRect({}), - scrollAwayPaddingTop((Float)data["scrollAwayPaddingTop"].getDouble()){}; + scrollAwayPaddingTop((Float)data["scrollAwayPaddingTop"].getDouble()) {}; - folly::dynamic getDynamic() const { - return folly::dynamic::object("contentOffsetLeft", contentOffset.x)( - "contentOffsetTop", contentOffset.y)( + folly::dynamic getDynamic() const + { + return folly::dynamic::object("contentOffsetLeft", contentOffset.x)("contentOffsetTop", contentOffset.y)( "scrollAwayPaddingTop", scrollAwayPaddingTop); }; #endif diff --git a/packages/react-native/ReactCommon/react/renderer/components/scrollview/conversions.h b/packages/react-native/ReactCommon/react/renderer/components/scrollview/conversions.h index 4c2b581dcda..fa0171ae1c1 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/scrollview/conversions.h +++ b/packages/react-native/ReactCommon/react/renderer/components/scrollview/conversions.h @@ -15,10 +15,8 @@ namespace facebook::react { -inline void fromRawValue( - const PropsParserContext& context, - const RawValue& value, - ScrollViewSnapToAlignment& result) { +inline void fromRawValue(const PropsParserContext &context, const RawValue &value, ScrollViewSnapToAlignment &result) +{ auto string = (std::string)value; if (string == "start") { result = ScrollViewSnapToAlignment::Start; @@ -35,10 +33,8 @@ inline void fromRawValue( abort(); } -inline void fromRawValue( - const PropsParserContext& context, - const RawValue& value, - ScrollViewIndicatorStyle& result) { +inline void fromRawValue(const PropsParserContext &context, const RawValue &value, ScrollViewIndicatorStyle &result) +{ auto string = (std::string)value; if (string == "default") { result = ScrollViewIndicatorStyle::Default; @@ -55,10 +51,9 @@ inline void fromRawValue( abort(); } -inline void fromRawValue( - const PropsParserContext& context, - const RawValue& value, - ScrollViewKeyboardDismissMode& result) { +inline void +fromRawValue(const PropsParserContext &context, const RawValue &value, ScrollViewKeyboardDismissMode &result) +{ auto string = (std::string)value; if (string == "none") { result = ScrollViewKeyboardDismissMode::None; @@ -75,10 +70,9 @@ inline void fromRawValue( abort(); } -inline void fromRawValue( - const PropsParserContext& context, - const RawValue& value, - ContentInsetAdjustmentBehavior& result) { +inline void +fromRawValue(const PropsParserContext &context, const RawValue &value, ContentInsetAdjustmentBehavior &result) +{ auto string = (std::string)value; if (string == "never") { result = ContentInsetAdjustmentBehavior::Never; @@ -99,27 +93,23 @@ inline void fromRawValue( abort(); } -inline void fromRawValue( - const PropsParserContext& context, - const RawValue& value, - ScrollViewMaintainVisibleContentPosition& result) { +inline void +fromRawValue(const PropsParserContext &context, const RawValue &value, ScrollViewMaintainVisibleContentPosition &result) +{ auto map = (std::unordered_map)value; auto minIndexForVisible = map.find("minIndexForVisible"); if (minIndexForVisible != map.end()) { - fromRawValue( - context, minIndexForVisible->second, result.minIndexForVisible); + fromRawValue(context, minIndexForVisible->second, result.minIndexForVisible); } auto autoscrollToTopThreshold = map.find("autoscrollToTopThreshold"); if (autoscrollToTopThreshold != map.end()) { - fromRawValue( - context, - autoscrollToTopThreshold->second, - result.autoscrollToTopThreshold); + fromRawValue(context, autoscrollToTopThreshold->second, result.autoscrollToTopThreshold); } } -inline std::string toString(const ScrollViewSnapToAlignment& value) { +inline std::string toString(const ScrollViewSnapToAlignment &value) +{ switch (value) { case ScrollViewSnapToAlignment::Start: return "start"; @@ -132,7 +122,8 @@ inline std::string toString(const ScrollViewSnapToAlignment& value) { #if RN_DEBUG_STRING_CONVERTIBLE -inline std::string toString(const ScrollViewIndicatorStyle& value) { +inline std::string toString(const ScrollViewIndicatorStyle &value) +{ switch (value) { case ScrollViewIndicatorStyle::Default: return "default"; @@ -143,7 +134,8 @@ inline std::string toString(const ScrollViewIndicatorStyle& value) { } } -inline std::string toString(const ScrollViewKeyboardDismissMode& value) { +inline std::string toString(const ScrollViewKeyboardDismissMode &value) +{ switch (value) { case ScrollViewKeyboardDismissMode::None: return "none"; @@ -154,7 +146,8 @@ inline std::string toString(const ScrollViewKeyboardDismissMode& value) { } } -inline std::string toString(const ContentInsetAdjustmentBehavior& value) { +inline std::string toString(const ContentInsetAdjustmentBehavior &value) +{ switch (value) { case ContentInsetAdjustmentBehavior::Never: return "never"; @@ -167,14 +160,13 @@ inline std::string toString(const ContentInsetAdjustmentBehavior& value) { } } -inline std::string toString( - const std::optional& value) { +inline std::string toString(const std::optional &value) +{ if (!value) { return "null"; } return "{minIndexForVisible: " + toString(value.value().minIndexForVisible) + - ", autoscrollToTopThreshold: " + - toString(value.value().autoscrollToTopThreshold) + "}"; + ", autoscrollToTopThreshold: " + toString(value.value().autoscrollToTopThreshold) + "}"; } #endif diff --git a/packages/react-native/ReactCommon/react/renderer/components/scrollview/platform/android/react/renderer/components/scrollview/HostPlatformScrollViewProps.h b/packages/react-native/ReactCommon/react/renderer/components/scrollview/platform/android/react/renderer/components/scrollview/HostPlatformScrollViewProps.h index bd93114bad8..c8f62f28c49 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/scrollview/platform/android/react/renderer/components/scrollview/HostPlatformScrollViewProps.h +++ b/packages/react-native/ReactCommon/react/renderer/components/scrollview/platform/android/react/renderer/components/scrollview/HostPlatformScrollViewProps.h @@ -18,15 +18,12 @@ class HostPlatformScrollViewProps : public BaseScrollViewProps { public: HostPlatformScrollViewProps() = default; HostPlatformScrollViewProps( - const PropsParserContext& context, - const HostPlatformScrollViewProps& sourceProps, - const RawProps& rawProps); + const PropsParserContext &context, + const HostPlatformScrollViewProps &sourceProps, + const RawProps &rawProps); - void setProp( - const PropsParserContext& context, - RawPropsPropNameHash hash, - const char* propName, - const RawValue& value); + void + setProp(const PropsParserContext &context, RawPropsPropNameHash hash, const char *propName, const RawValue &value); #pragma mark - Props @@ -43,7 +40,7 @@ class HostPlatformScrollViewProps : public BaseScrollViewProps { #endif ComponentName getDiffPropsImplementationTarget() const override; - folly::dynamic getDiffProps(const Props* prevProps) const override; + folly::dynamic getDiffProps(const Props *prevProps) const override; }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/components/scrollview/primitives.h b/packages/react-native/ReactCommon/react/renderer/components/scrollview/primitives.h index bb3f4f1a559..32fdefb2e2f 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/scrollview/primitives.h +++ b/packages/react-native/ReactCommon/react/renderer/components/scrollview/primitives.h @@ -18,24 +18,21 @@ enum class ScrollViewIndicatorStyle { Default, Black, White }; enum class ScrollViewKeyboardDismissMode { None, OnDrag, Interactive }; -enum class ContentInsetAdjustmentBehavior { - Never, - Automatic, - ScrollableAxes, - Always -}; +enum class ContentInsetAdjustmentBehavior { Never, Automatic, ScrollableAxes, Always }; class ScrollViewMaintainVisibleContentPosition final { public: int minIndexForVisible{0}; std::optional autoscrollToTopThreshold{}; - bool operator==(const ScrollViewMaintainVisibleContentPosition& rhs) const { + bool operator==(const ScrollViewMaintainVisibleContentPosition &rhs) const + { return std::tie(this->minIndexForVisible, this->autoscrollToTopThreshold) == std::tie(rhs.minIndexForVisible, rhs.autoscrollToTopThreshold); } - bool operator!=(const ScrollViewMaintainVisibleContentPosition& rhs) const { + bool operator!=(const ScrollViewMaintainVisibleContentPosition &rhs) const + { return !(*this == rhs); } }; diff --git a/packages/react-native/ReactCommon/react/renderer/components/switch/androidswitch/react/renderer/components/androidswitch/AndroidSwitchComponentDescriptor.h b/packages/react-native/ReactCommon/react/renderer/components/switch/androidswitch/react/renderer/components/androidswitch/AndroidSwitchComponentDescriptor.h index 841d5be49e0..1f1e2e17742 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/switch/androidswitch/react/renderer/components/androidswitch/AndroidSwitchComponentDescriptor.h +++ b/packages/react-native/ReactCommon/react/renderer/components/switch/androidswitch/react/renderer/components/androidswitch/AndroidSwitchComponentDescriptor.h @@ -17,25 +17,23 @@ namespace facebook::react { /* * Descriptor for component. */ -class AndroidSwitchComponentDescriptor final - : public ConcreteComponentDescriptor { +class AndroidSwitchComponentDescriptor final : public ConcreteComponentDescriptor { public: - AndroidSwitchComponentDescriptor( - const ComponentDescriptorParameters& parameters) + AndroidSwitchComponentDescriptor(const ComponentDescriptorParameters ¶meters) : ConcreteComponentDescriptor(parameters), - measurementsManager_(std::make_shared( - contextContainer_)) {} + measurementsManager_(std::make_shared(contextContainer_)) + { + } - void adopt(ShadowNode& shadowNode) const override { + void adopt(ShadowNode &shadowNode) const override + { ConcreteComponentDescriptor::adopt(shadowNode); - auto& androidSwitchShadowNode = - static_cast(shadowNode); + auto &androidSwitchShadowNode = static_cast(shadowNode); // `AndroidSwitchShadowNode` uses `AndroidSwitchMeasurementsManager` to // provide measurements to Yoga. - androidSwitchShadowNode.setAndroidSwitchMeasurementsManager( - measurementsManager_); + androidSwitchShadowNode.setAndroidSwitchMeasurementsManager(measurementsManager_); } private: diff --git a/packages/react-native/ReactCommon/react/renderer/components/switch/androidswitch/react/renderer/components/androidswitch/AndroidSwitchMeasurementsManager.h b/packages/react-native/ReactCommon/react/renderer/components/switch/androidswitch/react/renderer/components/androidswitch/AndroidSwitchMeasurementsManager.h index 37ea646899c..370aad59a46 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/switch/androidswitch/react/renderer/components/androidswitch/AndroidSwitchMeasurementsManager.h +++ b/packages/react-native/ReactCommon/react/renderer/components/switch/androidswitch/react/renderer/components/androidswitch/AndroidSwitchMeasurementsManager.h @@ -15,9 +15,10 @@ namespace facebook::react { class AndroidSwitchMeasurementsManager { public: - AndroidSwitchMeasurementsManager( - const std::shared_ptr& contextContainer) - : contextContainer_(contextContainer) {} + AndroidSwitchMeasurementsManager(const std::shared_ptr &contextContainer) + : contextContainer_(contextContainer) + { + } Size measure(SurfaceId surfaceId, LayoutConstraints layoutConstraints) const; diff --git a/packages/react-native/ReactCommon/react/renderer/components/switch/androidswitch/react/renderer/components/androidswitch/AndroidSwitchShadowNode.h b/packages/react-native/ReactCommon/react/renderer/components/switch/androidswitch/react/renderer/components/androidswitch/AndroidSwitchShadowNode.h index c79ea2fbf1d..491426f4020 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/switch/androidswitch/react/renderer/components/androidswitch/AndroidSwitchShadowNode.h +++ b/packages/react-native/ReactCommon/react/renderer/components/switch/androidswitch/react/renderer/components/androidswitch/AndroidSwitchShadowNode.h @@ -21,14 +21,13 @@ extern const char AndroidSwitchComponentName[]; /* * `ShadowNode` for component. */ -class AndroidSwitchShadowNode final : public ConcreteViewShadowNode< - AndroidSwitchComponentName, - AndroidSwitchProps, - AndroidSwitchEventEmitter> { +class AndroidSwitchShadowNode final + : public ConcreteViewShadowNode { public: using ConcreteViewShadowNode::ConcreteViewShadowNode; - static ShadowNodeTraits BaseTraits() { + static ShadowNodeTraits BaseTraits() + { auto traits = ConcreteViewShadowNode::BaseTraits(); traits.set(ShadowNodeTraits::Trait::LeafYogaNode); traits.set(ShadowNodeTraits::Trait::MeasurableYogaNode); @@ -37,14 +36,11 @@ class AndroidSwitchShadowNode final : public ConcreteViewShadowNode< // Associates a shared `AndroidSwitchMeasurementsManager` with the node. void setAndroidSwitchMeasurementsManager( - const std::shared_ptr& - measurementsManager); + const std::shared_ptr &measurementsManager); #pragma mark - LayoutableShadowNode - Size measureContent( - const LayoutContext& layoutContext, - const LayoutConstraints& layoutConstraints) const override; + Size measureContent(const LayoutContext &layoutContext, const LayoutConstraints &layoutConstraints) const override; private: std::shared_ptr measurementsManager_; diff --git a/packages/react-native/ReactCommon/react/renderer/components/switch/iosswitch/react/renderer/components/switch/AppleSwitchComponentDescriptor.h b/packages/react-native/ReactCommon/react/renderer/components/switch/iosswitch/react/renderer/components/switch/AppleSwitchComponentDescriptor.h index de4cef29aaa..0d39a055f06 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/switch/iosswitch/react/renderer/components/switch/AppleSwitchComponentDescriptor.h +++ b/packages/react-native/ReactCommon/react/renderer/components/switch/iosswitch/react/renderer/components/switch/AppleSwitchComponentDescriptor.h @@ -16,13 +16,14 @@ namespace facebook::react { /* * Descriptor for component. */ -class SwitchComponentDescriptor final - : public ConcreteComponentDescriptor { +class SwitchComponentDescriptor final : public ConcreteComponentDescriptor { public: - SwitchComponentDescriptor(const ComponentDescriptorParameters& parameters) - : ConcreteComponentDescriptor(parameters) {} + SwitchComponentDescriptor(const ComponentDescriptorParameters ¶meters) : ConcreteComponentDescriptor(parameters) + { + } - void adopt(ShadowNode& shadowNode) const override { + void adopt(ShadowNode &shadowNode) const override + { ConcreteComponentDescriptor::adopt(shadowNode); } }; diff --git a/packages/react-native/ReactCommon/react/renderer/components/switch/iosswitch/react/renderer/components/switch/AppleSwitchShadowNode.h b/packages/react-native/ReactCommon/react/renderer/components/switch/iosswitch/react/renderer/components/switch/AppleSwitchShadowNode.h index 2cffdf139f5..878a2cc8177 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/switch/iosswitch/react/renderer/components/switch/AppleSwitchShadowNode.h +++ b/packages/react-native/ReactCommon/react/renderer/components/switch/iosswitch/react/renderer/components/switch/AppleSwitchShadowNode.h @@ -18,14 +18,13 @@ extern const char AppleSwitchComponentName[]; /* * `ShadowNode` for component. */ -class SwitchShadowNode final : public ConcreteViewShadowNode< - AppleSwitchComponentName, - SwitchProps, - SwitchEventEmitter> { +class SwitchShadowNode final + : public ConcreteViewShadowNode { public: using ConcreteViewShadowNode::ConcreteViewShadowNode; - static ShadowNodeTraits BaseTraits() { + static ShadowNodeTraits BaseTraits() + { auto traits = ConcreteViewShadowNode::BaseTraits(); traits.set(ShadowNodeTraits::Trait::LeafYogaNode); traits.set(ShadowNodeTraits::Trait::MeasurableYogaNode); @@ -34,9 +33,7 @@ class SwitchShadowNode final : public ConcreteViewShadowNode< #pragma mark - LayoutableShadowNode - Size measureContent( - const LayoutContext& layoutContext, - const LayoutConstraints& layoutConstraints) const override; + Size measureContent(const LayoutContext &layoutContext, const LayoutConstraints &layoutConstraints) const override; }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/components/text/BaseParagraphProps.h b/packages/react-native/ReactCommon/react/renderer/components/text/BaseParagraphProps.h index defabb15fa4..72ba6e0fb3d 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/text/BaseParagraphProps.h +++ b/packages/react-native/ReactCommon/react/renderer/components/text/BaseParagraphProps.h @@ -27,15 +27,12 @@ class BaseParagraphProps : public ViewProps, public BaseTextProps { public: BaseParagraphProps() = default; BaseParagraphProps( - const PropsParserContext& context, - const BaseParagraphProps& sourceProps, - const RawProps& rawProps); + const PropsParserContext &context, + const BaseParagraphProps &sourceProps, + const RawProps &rawProps); - void setProp( - const PropsParserContext& context, - RawPropsPropNameHash hash, - const char* propName, - const RawValue& value); + void + setProp(const PropsParserContext &context, RawPropsPropNameHash hash, const char *propName, const RawValue &value); #pragma mark - Props diff --git a/packages/react-native/ReactCommon/react/renderer/components/text/BaseTextProps.cpp b/packages/react-native/ReactCommon/react/renderer/components/text/BaseTextProps.cpp index 01bbdbccdf4..f20cd3c6f98 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/text/BaseTextProps.cpp +++ b/packages/react-native/ReactCommon/react/renderer/components/text/BaseTextProps.cpp @@ -237,7 +237,7 @@ BaseTextProps::BaseTextProps( context, rawProps, sourceProps.textAttributes, - TextAttributes{})){}; + TextAttributes{})) {}; void BaseTextProps::setProp( const PropsParserContext& context, diff --git a/packages/react-native/ReactCommon/react/renderer/components/text/BaseTextProps.h b/packages/react-native/ReactCommon/react/renderer/components/text/BaseTextProps.h index 12d113d6249..732288d87c4 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/text/BaseTextProps.h +++ b/packages/react-native/ReactCommon/react/renderer/components/text/BaseTextProps.h @@ -21,16 +21,10 @@ namespace facebook::react { class BaseTextProps { public: BaseTextProps() = default; - BaseTextProps( - const PropsParserContext& context, - const BaseTextProps& sourceProps, - const RawProps& rawProps); + BaseTextProps(const PropsParserContext &context, const BaseTextProps &sourceProps, const RawProps &rawProps); - void setProp( - const PropsParserContext& context, - RawPropsPropNameHash hash, - const char* propName, - const RawValue& value); + void + setProp(const PropsParserContext &context, RawPropsPropNameHash hash, const char *propName, const RawValue &value); #pragma mark - Props @@ -43,9 +37,7 @@ class BaseTextProps { #endif #ifdef RN_SERIALIZABLE_STATE - void appendTextAttributesProps( - folly::dynamic& result, - const BaseTextProps* prevProps) const; + void appendTextAttributesProps(folly::dynamic &result, const BaseTextProps *prevProps) const; #endif }; diff --git a/packages/react-native/ReactCommon/react/renderer/components/text/BaseTextShadowNode.cpp b/packages/react-native/ReactCommon/react/renderer/components/text/BaseTextShadowNode.cpp index 1d0bd67846c..7050b8406ef 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/text/BaseTextShadowNode.cpp +++ b/packages/react-native/ReactCommon/react/renderer/components/text/BaseTextShadowNode.cpp @@ -76,8 +76,9 @@ void BaseTextShadowNode::buildAttributedString( fragment.parentShadowView = shadowViewFromShadowNode(*childNode); fragment.textAttributes = baseTextAttributes; outAttributedString.appendFragment(std::move(fragment)); - outAttachments.push_back(Attachment{ - childNode.get(), outAttributedString.getFragments().size() - 1}); + outAttachments.push_back( + Attachment{ + childNode.get(), outAttributedString.getFragments().size() - 1}); } } diff --git a/packages/react-native/ReactCommon/react/renderer/components/text/BaseTextShadowNode.h b/packages/react-native/ReactCommon/react/renderer/components/text/BaseTextShadowNode.h index 5d50e92a2c9..09d88b9b3c4 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/text/BaseTextShadowNode.h +++ b/packages/react-native/ReactCommon/react/renderer/components/text/BaseTextShadowNode.h @@ -28,7 +28,7 @@ class BaseTextShadowNode { * Unowning pointer to a `ShadowNode` that represents the attachment. * Cannot be `null`. */ - const ShadowNode* shadowNode; + const ShadowNode *shadowNode; /* * Index of the fragment in `AttributedString` that represents the @@ -52,10 +52,10 @@ class BaseTextShadowNode { * function, or if TextInput should inherit from BaseTextShadowNode. */ static void buildAttributedString( - const TextAttributes& baseTextAttributes, - const ShadowNode& parentNode, - AttributedString& outAttributedString, - Attachments& outAttachments); + const TextAttributes &baseTextAttributes, + const ShadowNode &parentNode, + AttributedString &outAttributedString, + Attachments &outAttachments); }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/components/text/ParagraphComponentDescriptor.h b/packages/react-native/ReactCommon/react/renderer/components/text/ParagraphComponentDescriptor.h index cfcd1cc8984..3ed1a2a7aef 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/text/ParagraphComponentDescriptor.h +++ b/packages/react-native/ReactCommon/react/renderer/components/text/ParagraphComponentDescriptor.h @@ -19,21 +19,20 @@ extern const char TextLayoutManagerKey[]; /* * Descriptor for component. */ -class ParagraphComponentDescriptor final - : public ConcreteComponentDescriptor { +class ParagraphComponentDescriptor final : public ConcreteComponentDescriptor { public: - explicit ParagraphComponentDescriptor( - const ComponentDescriptorParameters& parameters) + explicit ParagraphComponentDescriptor(const ComponentDescriptorParameters ¶meters) : ConcreteComponentDescriptor(parameters), - textLayoutManager_(getManagerByName( - contextContainer_, - TextLayoutManagerKey)) {} + textLayoutManager_(getManagerByName(contextContainer_, TextLayoutManagerKey)) + { + } protected: - void adopt(ShadowNode& shadowNode) const override { + void adopt(ShadowNode &shadowNode) const override + { ConcreteComponentDescriptor::adopt(shadowNode); - auto& paragraphShadowNode = static_cast(shadowNode); + auto ¶graphShadowNode = static_cast(shadowNode); // `ParagraphShadowNode` uses `TextLayoutManager` to measure text content // and communicate text rendering metrics to mounting layer. diff --git a/packages/react-native/ReactCommon/react/renderer/components/text/ParagraphEventEmitter.h b/packages/react-native/ReactCommon/react/renderer/components/text/ParagraphEventEmitter.h index c9af92e99e0..d571b914d87 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/text/ParagraphEventEmitter.h +++ b/packages/react-native/ReactCommon/react/renderer/components/text/ParagraphEventEmitter.h @@ -16,7 +16,7 @@ class ParagraphEventEmitter : public ViewEventEmitter { public: using ViewEventEmitter::ViewEventEmitter; - void onTextLayout(const LinesMeasurements& linesMeasurements) const; + void onTextLayout(const LinesMeasurements &linesMeasurements) const; private: mutable std::mutex linesMeasurementsMutex_; diff --git a/packages/react-native/ReactCommon/react/renderer/components/text/ParagraphShadowNode.cpp b/packages/react-native/ReactCommon/react/renderer/components/text/ParagraphShadowNode.cpp index 5299679a786..059cd5ec866 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/text/ParagraphShadowNode.cpp +++ b/packages/react-native/ReactCommon/react/renderer/components/text/ParagraphShadowNode.cpp @@ -157,11 +157,12 @@ void ParagraphShadowNode::updateStateIfNeeded( return; } - setStateData(ParagraphStateT{ - content.attributedString, - content.paragraphAttributes, - textLayoutManager_, - layout}); + setStateData( + ParagraphStateT{ + content.attributedString, + content.paragraphAttributes, + textLayoutManager_, + layout}); } void ParagraphShadowNode::updateStateIfNeeded(const Content& content) { @@ -174,10 +175,11 @@ void ParagraphShadowNode::updateStateIfNeeded(const Content& content) { return; } - setStateData(ParagraphState{ - content.attributedString, - content.paragraphAttributes, - textLayoutManager_}); + setStateData( + ParagraphState{ + content.attributedString, + content.paragraphAttributes, + textLayoutManager_}); } MeasuredPreparedLayout* ParagraphShadowNode::findUsableLayout() { @@ -248,12 +250,13 @@ Size ParagraphShadowNode::measureContent( auto measurement = tme.measurePreparedLayout( preparedLayout, textLayoutContext, layoutConstraints); - measuredLayouts_.push_back(MeasuredPreparedLayout{ - .layoutConstraints = layoutConstraints, - .measurement = measurement, - // PreparedLayout is not trivially copyable on all platforms - // NOLINTNEXTLINE(performance-move-const-arg) - .preparedLayout = std::move(preparedLayout)}); + measuredLayouts_.push_back( + MeasuredPreparedLayout{ + .layoutConstraints = layoutConstraints, + .measurement = measurement, + // PreparedLayout is not trivially copyable on all platforms + // NOLINTNEXTLINE(performance-move-const-arg) + .preparedLayout = std::move(preparedLayout)}); assert_valid_size(measurement.size, layoutConstraints); return measurement.size; } diff --git a/packages/react-native/ReactCommon/react/renderer/components/text/ParagraphShadowNode.h b/packages/react-native/ReactCommon/react/renderer/components/text/ParagraphShadowNode.h index 7911e94c465..91709d035d0 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/text/ParagraphShadowNode.h +++ b/packages/react-native/ReactCommon/react/renderer/components/text/ParagraphShadowNode.h @@ -26,25 +26,21 @@ extern const char ParagraphComponentName[]; * containing and displaying text. Text content is represented as nested * and components. */ -class ParagraphShadowNode final : public ConcreteViewShadowNode< - ParagraphComponentName, - ParagraphProps, - ParagraphEventEmitter, - ParagraphState>, - public BaseTextShadowNode { +class ParagraphShadowNode final + : public ConcreteViewShadowNode, + public BaseTextShadowNode { public: using ConcreteViewShadowNode::ConcreteViewShadowNode; ParagraphShadowNode( - const ShadowNodeFragment& fragment, - const ShadowNodeFamily::Shared& family, + const ShadowNodeFragment &fragment, + const ShadowNodeFamily::Shared &family, ShadowNodeTraits traits); - ParagraphShadowNode( - const ShadowNode& sourceShadowNode, - const ShadowNodeFragment& fragment); + ParagraphShadowNode(const ShadowNode &sourceShadowNode, const ShadowNodeFragment &fragment); - static ShadowNodeTraits BaseTraits() { + static ShadowNodeTraits BaseTraits() + { auto traits = ConcreteViewShadowNode::BaseTraits(); traits.set(ShadowNodeTraits::Trait::LeafYogaNode); traits.set(ShadowNodeTraits::Trait::MeasurableYogaNode); @@ -66,18 +62,15 @@ class ParagraphShadowNode final : public ConcreteViewShadowNode< * `ParagraphShadowNode` uses the manager to measure text content * and construct `ParagraphState` objects. */ - void setTextLayoutManager( - std::shared_ptr textLayoutManager); + void setTextLayoutManager(std::shared_ptr textLayoutManager); #pragma mark - LayoutableShadowNode void layout(LayoutContext layoutContext) override; - Size measureContent( - const LayoutContext& layoutContext, - const LayoutConstraints& layoutConstraints) const override; + Size measureContent(const LayoutContext &layoutContext, const LayoutConstraints &layoutConstraints) const override; - Float baseline(const LayoutContext& layoutContext, Size size) const override; + Float baseline(const LayoutContext &layoutContext, Size size) const override; /* * Internal representation of the nested content of the node in a format @@ -91,44 +84,41 @@ class ParagraphShadowNode final : public ConcreteViewShadowNode< }; protected: - bool shouldNewRevisionDirtyMeasurement( - const ShadowNode& sourceShadowNode, - const ShadowNodeFragment& fragment) const override; + bool shouldNewRevisionDirtyMeasurement(const ShadowNode &sourceShadowNode, const ShadowNodeFragment &fragment) + const override; private: void initialize() noexcept; /* * Builds (if needed) and returns a reference to a `Content` object. */ - const Content& getContent(const LayoutContext& layoutContext) const; + const Content &getContent(const LayoutContext &layoutContext) const; /* * Builds and returns a `Content` object with given `layoutConstraints`. */ Content getContentWithMeasuredAttachments( - const LayoutContext& layoutContext, - const LayoutConstraints& layoutConstraints) const; + const LayoutContext &layoutContext, + const LayoutConstraints &layoutConstraints) const; /* * Creates a `State` object (with `AttributedText` and * `TextLayoutManager`) if needed. */ template - void updateStateIfNeeded( - const Content& content, - const MeasuredPreparedLayout& layout); + void updateStateIfNeeded(const Content &content, const MeasuredPreparedLayout &layout); /* * Creates a `State` object (with `AttributedText` and * `TextLayoutManager`) if needed. */ - void updateStateIfNeeded(const Content& content); + void updateStateIfNeeded(const Content &content); /** * Returns any previously prepared layout, generated for measurement, which * may be used, given the currently assigned layout to the ShadowNode */ - MeasuredPreparedLayout* findUsableLayout(); + MeasuredPreparedLayout *findUsableLayout(); /** * Returns the final measure of the content frame, before layout rounding diff --git a/packages/react-native/ReactCommon/react/renderer/components/text/RawTextComponentDescriptor.h b/packages/react-native/ReactCommon/react/renderer/components/text/RawTextComponentDescriptor.h index 1f50f7afc44..92a67af3139 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/text/RawTextComponentDescriptor.h +++ b/packages/react-native/ReactCommon/react/renderer/components/text/RawTextComponentDescriptor.h @@ -12,7 +12,6 @@ namespace facebook::react { -using RawTextComponentDescriptor = - ConcreteComponentDescriptor; +using RawTextComponentDescriptor = ConcreteComponentDescriptor; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/components/text/RawTextProps.cpp b/packages/react-native/ReactCommon/react/renderer/components/text/RawTextProps.cpp index bcf58b8de12..938322165b8 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/text/RawTextProps.cpp +++ b/packages/react-native/ReactCommon/react/renderer/components/text/RawTextProps.cpp @@ -17,7 +17,7 @@ RawTextProps::RawTextProps( const RawTextProps& sourceProps, const RawProps& rawProps) : Props(context, sourceProps, rawProps), - text(convertRawProp(context, rawProps, "text", sourceProps.text, {})){}; + text(convertRawProp(context, rawProps, "text", sourceProps.text, {})) {}; #pragma mark - DebugStringConvertible diff --git a/packages/react-native/ReactCommon/react/renderer/components/text/RawTextProps.h b/packages/react-native/ReactCommon/react/renderer/components/text/RawTextProps.h index 4a086254413..fb8cea5dbbc 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/text/RawTextProps.h +++ b/packages/react-native/ReactCommon/react/renderer/components/text/RawTextProps.h @@ -22,10 +22,7 @@ using SharedRawTextProps = std::shared_ptr; class RawTextProps : public Props { public: RawTextProps() = default; - RawTextProps( - const PropsParserContext& context, - const RawTextProps& sourceProps, - const RawProps& rawProps); + RawTextProps(const PropsParserContext &context, const RawTextProps &sourceProps, const RawProps &rawProps); #pragma mark - Props @@ -39,7 +36,7 @@ class RawTextProps : public Props { #ifdef RN_SERIALIZABLE_STATE ComponentName getDiffPropsImplementationTarget() const override; - folly::dynamic getDiffProps(const Props* prevProps) const override; + folly::dynamic getDiffProps(const Props *prevProps) const override; #endif }; diff --git a/packages/react-native/ReactCommon/react/renderer/components/text/RawTextShadowNode.h b/packages/react-native/ReactCommon/react/renderer/components/text/RawTextShadowNode.h index 7d04c781c08..940916f8b48 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/text/RawTextShadowNode.h +++ b/packages/react-native/ReactCommon/react/renderer/components/text/RawTextShadowNode.h @@ -20,10 +20,7 @@ extern const char RawTextComponentName[]; * is represented as ``. * component must not have any children. */ -class RawTextShadowNode : public ConcreteShadowNode< - RawTextComponentName, - ShadowNode, - RawTextProps> { +class RawTextShadowNode : public ConcreteShadowNode { public: using ConcreteShadowNode::ConcreteShadowNode; }; diff --git a/packages/react-native/ReactCommon/react/renderer/components/text/TextProps.cpp b/packages/react-native/ReactCommon/react/renderer/components/text/TextProps.cpp index d013aa04a03..56ba3fbd30d 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/text/TextProps.cpp +++ b/packages/react-native/ReactCommon/react/renderer/components/text/TextProps.cpp @@ -14,7 +14,7 @@ TextProps::TextProps( const TextProps& sourceProps, const RawProps& rawProps) : Props(context, sourceProps, rawProps), - BaseTextProps::BaseTextProps(context, sourceProps, rawProps){}; + BaseTextProps::BaseTextProps(context, sourceProps, rawProps) {}; void TextProps::setProp( const PropsParserContext& context, diff --git a/packages/react-native/ReactCommon/react/renderer/components/text/TextProps.h b/packages/react-native/ReactCommon/react/renderer/components/text/TextProps.h index 2cb00fc39cf..164a8e5358c 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/text/TextProps.h +++ b/packages/react-native/ReactCommon/react/renderer/components/text/TextProps.h @@ -18,16 +18,10 @@ namespace facebook::react { class TextProps : public Props, public BaseTextProps { public: TextProps() = default; - TextProps( - const PropsParserContext& context, - const TextProps& sourceProps, - const RawProps& rawProps); + TextProps(const PropsParserContext &context, const TextProps &sourceProps, const RawProps &rawProps); - void setProp( - const PropsParserContext& context, - RawPropsPropNameHash hash, - const char* propName, - const RawValue& value); + void + setProp(const PropsParserContext &context, RawPropsPropNameHash hash, const char *propName, const RawValue &value); #pragma mark - DebugStringConvertible @@ -37,7 +31,7 @@ class TextProps : public Props, public BaseTextProps { #ifdef RN_SERIALIZABLE_STATE ComponentName getDiffPropsImplementationTarget() const override; - folly::dynamic getDiffProps(const Props* prevProps) const override; + folly::dynamic getDiffProps(const Props *prevProps) const override; #endif }; diff --git a/packages/react-native/ReactCommon/react/renderer/components/text/TextShadowNode.h b/packages/react-native/ReactCommon/react/renderer/components/text/TextShadowNode.h index 695aba56cbc..1fb00e59a25 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/text/TextShadowNode.h +++ b/packages/react-native/ReactCommon/react/renderer/components/text/TextShadowNode.h @@ -20,14 +20,11 @@ extern const char TextComponentName[]; using TextEventEmitter = TouchEventEmitter; -class TextShadowNode : public ConcreteShadowNode< - TextComponentName, - ShadowNode, - TextProps, - TextEventEmitter>, +class TextShadowNode : public ConcreteShadowNode, public BaseTextShadowNode { public: - static ShadowNodeTraits BaseTraits() { + static ShadowNodeTraits BaseTraits() + { auto traits = ConcreteShadowNode::BaseTraits(); #ifdef ANDROID traits.set(ShadowNodeTraits::Trait::FormsView); @@ -38,17 +35,11 @@ class TextShadowNode : public ConcreteShadowNode< using ConcreteShadowNode::ConcreteShadowNode; #ifdef ANDROID - using BaseShadowNode = ConcreteShadowNode< - TextComponentName, - ShadowNode, - TextProps, - TextEventEmitter>; + using BaseShadowNode = ConcreteShadowNode; - TextShadowNode( - const ShadowNodeFragment& fragment, - const ShadowNodeFamily::Shared& family, - ShadowNodeTraits traits) - : BaseShadowNode(fragment, family, traits), BaseTextShadowNode() { + TextShadowNode(const ShadowNodeFragment &fragment, const ShadowNodeFamily::Shared &family, ShadowNodeTraits traits) + : BaseShadowNode(fragment, family, traits), BaseTextShadowNode() + { orderIndex_ = std::numeric_limits::max(); } #endif diff --git a/packages/react-native/ReactCommon/react/renderer/components/text/platform/android/react/renderer/components/text/HostPlatformParagraphProps.cpp b/packages/react-native/ReactCommon/react/renderer/components/text/platform/android/react/renderer/components/text/HostPlatformParagraphProps.cpp index a1019158f66..1862cc1267b 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/text/platform/android/react/renderer/components/text/HostPlatformParagraphProps.cpp +++ b/packages/react-native/ReactCommon/react/renderer/components/text/platform/android/react/renderer/components/text/HostPlatformParagraphProps.cpp @@ -52,7 +52,7 @@ HostPlatformParagraphProps::HostPlatformParagraphProps( sourceProps.dataDetectorType, {})) - {}; +{}; void HostPlatformParagraphProps::setProp( const PropsParserContext& context, diff --git a/packages/react-native/ReactCommon/react/renderer/components/text/platform/android/react/renderer/components/text/HostPlatformParagraphProps.h b/packages/react-native/ReactCommon/react/renderer/components/text/platform/android/react/renderer/components/text/HostPlatformParagraphProps.h index 1082b822b3b..93b6f1002ff 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/text/platform/android/react/renderer/components/text/HostPlatformParagraphProps.h +++ b/packages/react-native/ReactCommon/react/renderer/components/text/platform/android/react/renderer/components/text/HostPlatformParagraphProps.h @@ -28,15 +28,12 @@ class HostPlatformParagraphProps : public BaseParagraphProps { public: HostPlatformParagraphProps() = default; HostPlatformParagraphProps( - const PropsParserContext& context, - const HostPlatformParagraphProps& sourceProps, - const RawProps& rawProps); + const PropsParserContext &context, + const HostPlatformParagraphProps &sourceProps, + const RawProps &rawProps); - void setProp( - const PropsParserContext& context, - RawPropsPropNameHash hash, - const char* propName, - const RawValue& value); + void + setProp(const PropsParserContext &context, RawPropsPropNameHash hash, const char *propName, const RawValue &value); #pragma mark - Props @@ -52,7 +49,7 @@ class HostPlatformParagraphProps : public BaseParagraphProps { #ifdef RN_SERIALIZABLE_STATE ComponentName getDiffPropsImplementationTarget() const override; - folly::dynamic getDiffProps(const Props* prevProps) const override; + folly::dynamic getDiffProps(const Props *prevProps) const override; #endif }; diff --git a/packages/react-native/ReactCommon/react/renderer/components/text/platform/android/react/renderer/components/text/ParagraphState.h b/packages/react-native/ReactCommon/react/renderer/components/text/platform/android/react/renderer/components/text/ParagraphState.h index bab65411e46..8910edec55a 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/text/platform/android/react/renderer/components/text/ParagraphState.h +++ b/packages/react-native/ReactCommon/react/renderer/components/text/platform/android/react/renderer/components/text/ParagraphState.h @@ -65,22 +65,21 @@ class ParagraphState final { : attributedString(std::move(attributedString)), paragraphAttributes(std::move(paragraphAttributes)), layoutManager(std::move(layoutManager)), - measuredLayout(std::move(measuredLayout)) {} + measuredLayout(std::move(measuredLayout)) + { + } ParagraphState( AttributedString attributedString, ParagraphAttributes paragraphAttributes, std::weak_ptr layoutManager) - : ParagraphState( - std::move(attributedString), - std::move(paragraphAttributes), - std::move(layoutManager), - {}) {} + : ParagraphState(std::move(attributedString), std::move(paragraphAttributes), std::move(layoutManager), {}) + { + } ParagraphState() = default; - ParagraphState( - const ParagraphState& /*previousState*/, - const folly::dynamic& /*data*/) { + ParagraphState(const ParagraphState & /*previousState*/, const folly::dynamic & /*data*/) + { react_native_assert(false && "Not supported"); }; diff --git a/packages/react-native/ReactCommon/react/renderer/components/text/platform/android/react/renderer/components/text/conversions.h b/packages/react-native/ReactCommon/react/renderer/components/text/platform/android/react/renderer/components/text/conversions.h index af246ab2b47..5740fa5927b 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/text/platform/android/react/renderer/components/text/conversions.h +++ b/packages/react-native/ReactCommon/react/renderer/components/text/platform/android/react/renderer/components/text/conversions.h @@ -14,10 +14,8 @@ namespace facebook::react { -inline void fromRawValue( - const PropsParserContext& /*context*/, - const RawValue& value, - DataDetectorType& result) { +inline void fromRawValue(const PropsParserContext & /*context*/, const RawValue &value, DataDetectorType &result) +{ auto string = static_cast(value); if (string == "all") { result = DataDetectorType::All; @@ -34,7 +32,8 @@ inline void fromRawValue( } } -inline std::string toString(const DataDetectorType& value) { +inline std::string toString(const DataDetectorType &value) +{ switch (value) { case DataDetectorType::All: return "all"; diff --git a/packages/react-native/ReactCommon/react/renderer/components/text/stateConversions.h b/packages/react-native/ReactCommon/react/renderer/components/text/stateConversions.h index 1f59b74a43a..bc630c073bc 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/text/stateConversions.h +++ b/packages/react-native/ReactCommon/react/renderer/components/text/stateConversions.h @@ -18,7 +18,8 @@ namespace facebook::react { #ifdef RN_SERIALIZABLE_STATE -inline MapBuffer toMapBuffer(const ParagraphState& paragraphState) { +inline MapBuffer toMapBuffer(const ParagraphState ¶graphState) +{ auto builder = MapBufferBuilder(); auto attStringMapBuffer = toMapBuffer(paragraphState.attributedString); builder.putMapBuffer(TX_STATE_KEY_ATTRIBUTED_STRING, attStringMapBuffer); diff --git a/packages/react-native/ReactCommon/react/renderer/components/text/tests/BaseTextShadowNodeTest.cpp b/packages/react-native/ReactCommon/react/renderer/components/text/tests/BaseTextShadowNodeTest.cpp index 6a9e4858d1f..5ac6bc433d9 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/text/tests/BaseTextShadowNodeTest.cpp +++ b/packages/react-native/ReactCommon/react/renderer/components/text/tests/BaseTextShadowNodeTest.cpp @@ -29,26 +29,27 @@ TEST(BaseTextShadowNodeTest, fragmentsWithDifferentAttributes) { PropsParserContext parserContext{-1, contextContainer}; auto builder = simpleComponentBuilder(); - auto shadowNode = builder.build(Element().children({ - Element() - .props([]() { - auto props = std::make_shared(); - props->textAttributes.fontSize = 12; - return props; - }) - .children({ - rawTextElement("First fragment. "), - }), - Element() - .props([]() { - auto props = std::make_shared(); - props->textAttributes.fontSize = 24; - return props; - }) - .children({ - rawTextElement("Second fragment"), - }), - })); + auto shadowNode = builder.build( + Element().children({ + Element() + .props([]() { + auto props = std::make_shared(); + props->textAttributes.fontSize = 12; + return props; + }) + .children({ + rawTextElement("First fragment. "), + }), + Element() + .props([]() { + auto props = std::make_shared(); + props->textAttributes.fontSize = 24; + return props; + }) + .children({ + rawTextElement("Second fragment"), + }), + })); auto baseTextAttributes = TextAttributes::defaultTextAttributes(); AttributedString output; @@ -75,10 +76,11 @@ TEST(BaseTextShadowNodeTest, rawTextIsMerged) { PropsParserContext parserContext{-1, contextContainer}; auto builder = simpleComponentBuilder(); - auto shadowNode = builder.build(Element().children({ - rawTextElement("Hello "), - rawTextElement("World"), - })); + auto shadowNode = builder.build( + Element().children({ + rawTextElement("Hello "), + rawTextElement("World"), + })); auto baseTextAttributes = TextAttributes::defaultTextAttributes(); AttributedString output; diff --git a/packages/react-native/ReactCommon/react/renderer/components/textinput/BaseTextInputProps.h b/packages/react-native/ReactCommon/react/renderer/components/textinput/BaseTextInputProps.h index 5802350a2ee..8994a42231e 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/textinput/BaseTextInputProps.h +++ b/packages/react-native/ReactCommon/react/renderer/components/textinput/BaseTextInputProps.h @@ -22,15 +22,12 @@ class BaseTextInputProps : public ViewProps, public BaseTextProps { public: BaseTextInputProps() = default; BaseTextInputProps( - const PropsParserContext& context, - const BaseTextInputProps& sourceProps, - const RawProps& rawProps); + const PropsParserContext &context, + const BaseTextInputProps &sourceProps, + const RawProps &rawProps); - void setProp( - const PropsParserContext& context, - RawPropsPropNameHash hash, - const char* propName, - const RawValue& value); + void + setProp(const PropsParserContext &context, RawPropsPropNameHash hash, const char *propName, const RawValue &value); SubmitBehavior getNonDefaultSubmitBehavior() const; diff --git a/packages/react-native/ReactCommon/react/renderer/components/textinput/BaseTextInputShadowNode.h b/packages/react-native/ReactCommon/react/renderer/components/textinput/BaseTextInputShadowNode.h index 8c8a225eaa9..984db279df5 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/textinput/BaseTextInputShadowNode.h +++ b/packages/react-native/ReactCommon/react/renderer/components/textinput/BaseTextInputShadowNode.h @@ -28,27 +28,17 @@ namespace facebook::react { /* * Base `ShadowNode` for component. */ -template < - const char* concreteComponentName, - typename ViewPropsT, - typename ViewEventEmitterT, - typename StateDataT> -class BaseTextInputShadowNode : public ConcreteViewShadowNode< - concreteComponentName, - ViewPropsT, - ViewEventEmitterT, - StateDataT>, - public BaseTextShadowNode { +template +class BaseTextInputShadowNode + : public ConcreteViewShadowNode, + public BaseTextShadowNode { public: - using BaseShadowNode = ConcreteViewShadowNode< - concreteComponentName, - ViewPropsT, - ViewEventEmitterT, - StateDataT>; + using BaseShadowNode = ConcreteViewShadowNode; using BaseShadowNode::ConcreteViewShadowNode; - static ShadowNodeTraits BaseTraits() { + static ShadowNodeTraits BaseTraits() + { auto traits = BaseShadowNode::BaseTraits(); traits.set(ShadowNodeTraits::Trait::LeafYogaNode); traits.set(ShadowNodeTraits::Trait::MeasurableYogaNode); @@ -61,17 +51,16 @@ class BaseTextInputShadowNode : public ConcreteViewShadowNode< * `TextInputShadowNode` uses the manager to measure text content * and construct `TextInputState` objects. */ - void setTextLayoutManager( - std::shared_ptr textLayoutManager) { + void setTextLayoutManager(std::shared_ptr textLayoutManager) + { Sealable::ensureUnsealed(); textLayoutManager_ = std::move(textLayoutManager); } protected: - Size measureContent( - const LayoutContext& layoutContext, - const LayoutConstraints& layoutConstraints) const override { - const auto& props = BaseShadowNode::getConcreteProps(); + Size measureContent(const LayoutContext &layoutContext, const LayoutConstraints &layoutConstraints) const override + { + const auto &props = BaseShadowNode::getConcreteProps(); auto textConstraints = getTextConstraints(layoutConstraints); TextLayoutContext textLayoutContext{ @@ -89,13 +78,15 @@ class BaseTextInputShadowNode : public ConcreteViewShadowNode< return layoutConstraints.clamp(textSize); } - void layout(LayoutContext layoutContext) override { + void layout(LayoutContext layoutContext) override + { updateStateIfNeeded(layoutContext); BaseShadowNode::layout(layoutContext); } - Float baseline(const LayoutContext& layoutContext, Size size) const override { - const auto& props = BaseShadowNode::getConcreteProps(); + Float baseline(const LayoutContext &layoutContext, Size size) const override + { + const auto &props = BaseShadowNode::getConcreteProps(); auto attributedString = getAttributedString(layoutContext); if (attributedString.isEmpty()) { @@ -105,22 +96,17 @@ class BaseTextInputShadowNode : public ConcreteViewShadowNode< // Yoga expects a baseline relative to the Node's border-box edge instead of // the content, so we need to adjust by the padding and border widths, which // have already been set by the time of baseline alignment - auto top = YGNodeLayoutGetBorder( - &(YogaLayoutableShadowNode::yogaNode_), YGEdgeTop) + - YGNodeLayoutGetPadding( - &(YogaLayoutableShadowNode::yogaNode_), YGEdgeTop); + auto top = YGNodeLayoutGetBorder(&(YogaLayoutableShadowNode::yogaNode_), YGEdgeTop) + + YGNodeLayoutGetPadding(&(YogaLayoutableShadowNode::yogaNode_), YGEdgeTop); AttributedStringBox attributedStringBox{attributedString}; if constexpr (TextLayoutManagerExtended::supportsLineMeasurement()) { - auto lines = - TextLayoutManagerExtended(*textLayoutManager_) - .measureLines( - attributedStringBox, props.paragraphAttributes, size); + auto lines = TextLayoutManagerExtended(*textLayoutManager_) + .measureLines(attributedStringBox, props.paragraphAttributes, size); return LineMeasurement::baseline(lines) + top; } else { - LOG(WARNING) - << "Baseline alignment is not supported by the current platform"; + LOG(WARNING) << "Baseline alignment is not supported by the current platform"; return top; } } @@ -128,8 +114,8 @@ class BaseTextInputShadowNode : public ConcreteViewShadowNode< /* * Determines the constraints to use while measure the underlying text */ - LayoutConstraints getTextConstraints( - const LayoutConstraints& layoutConstraints) const { + LayoutConstraints getTextConstraints(const LayoutConstraints &layoutConstraints) const + { if (BaseShadowNode::getConcreteProps().multiline) { return layoutConstraints; } else { @@ -155,42 +141,40 @@ class BaseTextInputShadowNode : public ConcreteViewShadowNode< /* * Creates a `State` object if needed. */ - void updateStateIfNeeded(const LayoutContext& layoutContext) { + void updateStateIfNeeded(const LayoutContext &layoutContext) + { Sealable::ensureUnsealed(); - const auto& stateData = BaseShadowNode::getStateData(); - const auto& reactTreeAttributedString = getAttributedString(layoutContext); + const auto &stateData = BaseShadowNode::getStateData(); + const auto &reactTreeAttributedString = getAttributedString(layoutContext); - if (stateData.reactTreeAttributedString.isContentEqual( - reactTreeAttributedString)) { + if (stateData.reactTreeAttributedString.isContentEqual(reactTreeAttributedString)) { return; } - const auto& props = BaseShadowNode::getConcreteProps(); - BaseShadowNode::setStateData(TextInputState{ - AttributedStringBox{reactTreeAttributedString}, - reactTreeAttributedString, - props.paragraphAttributes, - props.mostRecentEventCount}); + const auto &props = BaseShadowNode::getConcreteProps(); + BaseShadowNode::setStateData( + TextInputState{ + AttributedStringBox{reactTreeAttributedString}, + reactTreeAttributedString, + props.paragraphAttributes, + props.mostRecentEventCount}); } /* * Returns a `AttributedString` which represents text content of the node. */ - AttributedString getAttributedString( - const LayoutContext& layoutContext) const { - const auto& props = BaseShadowNode::getConcreteProps(); - const auto textAttributes = - props.getEffectiveTextAttributes(layoutContext.fontSizeMultiplier); + AttributedString getAttributedString(const LayoutContext &layoutContext) const + { + const auto &props = BaseShadowNode::getConcreteProps(); + const auto textAttributes = props.getEffectiveTextAttributes(layoutContext.fontSizeMultiplier); AttributedString attributedString; - attributedString.appendFragment(AttributedString::Fragment{ - .string = props.text, - .textAttributes = textAttributes, - .parentShadowView = ShadowView(*this)}); + attributedString.appendFragment( + AttributedString::Fragment{ + .string = props.text, .textAttributes = textAttributes, .parentShadowView = ShadowView(*this)}); auto attachments = BaseTextShadowNode::Attachments{}; - BaseTextShadowNode::buildAttributedString( - textAttributes, *this, attributedString, attachments); + BaseTextShadowNode::buildAttributedString(textAttributes, *this, attributedString, attachments); attributedString.setBaseTextAttributes(textAttributes); return attributedString; } @@ -200,27 +184,22 @@ class BaseTextInputShadowNode : public ConcreteViewShadowNode< * be used for measuring purposes. It might contain actual text value, * placeholder value or some character that represents the size of the font. */ - AttributedStringBox attributedStringBoxToMeasure( - const LayoutContext& layoutContext) const { + AttributedStringBox attributedStringBoxToMeasure(const LayoutContext &layoutContext) const + { bool meaningfulState = BaseShadowNode::getState() && - BaseShadowNode::getState()->getRevision() != - State::initialRevisionValue && - BaseShadowNode::getStateData() - .reactTreeAttributedString.getBaseTextAttributes() - .fontSizeMultiplier == layoutContext.fontSizeMultiplier; + BaseShadowNode::getState()->getRevision() != State::initialRevisionValue && + BaseShadowNode::getStateData().reactTreeAttributedString.getBaseTextAttributes().fontSizeMultiplier == + layoutContext.fontSizeMultiplier; if (meaningfulState) { - const auto& stateData = BaseShadowNode::getStateData(); + const auto &stateData = BaseShadowNode::getStateData(); auto attributedStringBox = stateData.attributedStringBox; - if (attributedStringBox.getMode() == - AttributedStringBox::Mode::OpaquePointer || + if (attributedStringBox.getMode() == AttributedStringBox::Mode::OpaquePointer || !attributedStringBox.getValue().isEmpty()) { return stateData.attributedStringBox; } } - auto attributedString = meaningfulState - ? AttributedString{} - : getAttributedString(layoutContext); + auto attributedString = meaningfulState ? AttributedString{} : getAttributedString(layoutContext); if (attributedString.isEmpty()) { attributedString = getPlaceholderAttributedString(layoutContext); @@ -228,13 +207,12 @@ class BaseTextInputShadowNode : public ConcreteViewShadowNode< return AttributedStringBox{attributedString}; } - AttributedString getPlaceholderAttributedString( - const LayoutContext& layoutContext) const { - const auto& props = BaseShadowNode::getConcreteProps(); + AttributedString getPlaceholderAttributedString(const LayoutContext &layoutContext) const + { + const auto &props = BaseShadowNode::getConcreteProps(); AttributedString attributedString; - attributedString.setBaseTextAttributes( - props.getEffectiveTextAttributes(layoutContext.fontSizeMultiplier)); + attributedString.setBaseTextAttributes(props.getEffectiveTextAttributes(layoutContext.fontSizeMultiplier)); if (!props.placeholder.empty()) { attributedString.appendFragment( diff --git a/packages/react-native/ReactCommon/react/renderer/components/textinput/TextInputEventEmitter.h b/packages/react-native/ReactCommon/react/renderer/components/textinput/TextInputEventEmitter.h index dbce5751593..a3f2e01c130 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/textinput/TextInputEventEmitter.h +++ b/packages/react-native/ReactCommon/react/renderer/components/textinput/TextInputEventEmitter.h @@ -35,25 +35,23 @@ class TextInputEventEmitter : public ViewEventEmitter { int eventCount; }; - void onFocus(const Metrics& textInputMetrics) const; - void onBlur(const Metrics& textInputMetrics) const; - void onChange(const Metrics& textInputMetrics) const; - void onContentSizeChange(const Metrics& textInputMetrics) const; - void onSelectionChange(const Metrics& textInputMetrics) const; - void onEndEditing(const Metrics& textInputMetrics) const; - void onSubmitEditing(const Metrics& textInputMetrics) const; - void onKeyPress(const KeyPressMetrics& keyPressMetrics) const; - void onScroll(const Metrics& textInputMetrics) const; + void onFocus(const Metrics &textInputMetrics) const; + void onBlur(const Metrics &textInputMetrics) const; + void onChange(const Metrics &textInputMetrics) const; + void onContentSizeChange(const Metrics &textInputMetrics) const; + void onSelectionChange(const Metrics &textInputMetrics) const; + void onEndEditing(const Metrics &textInputMetrics) const; + void onSubmitEditing(const Metrics &textInputMetrics) const; + void onKeyPress(const KeyPressMetrics &keyPressMetrics) const; + void onScroll(const Metrics &textInputMetrics) const; private: void dispatchTextInputEvent( - const std::string& name, - const Metrics& textInputMetrics, + const std::string &name, + const Metrics &textInputMetrics, bool includeSelectionState = false) const; - void dispatchTextInputContentSizeChangeEvent( - const std::string& name, - const Metrics& textInputMetrics) const; + void dispatchTextInputContentSizeChangeEvent(const std::string &name, const Metrics &textInputMetrics) const; }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/components/textinput/TextInputState.h b/packages/react-native/ReactCommon/react/renderer/components/textinput/TextInputState.h index d278f6818b7..9f728d9335f 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/textinput/TextInputState.h +++ b/packages/react-native/ReactCommon/react/renderer/components/textinput/TextInputState.h @@ -28,7 +28,9 @@ class TextInputState final { : attributedStringBox(std::move(attributedStringBox)), reactTreeAttributedString(std::move(reactTreeAttributedString)), paragraphAttributes(std::move(paragraphAttributes)), - mostRecentEventCount(mostRecentEventCount) {} + mostRecentEventCount(mostRecentEventCount) + { + } /* * All content of component. diff --git a/packages/react-native/ReactCommon/react/renderer/components/textinput/baseConversions.h b/packages/react-native/ReactCommon/react/renderer/components/textinput/baseConversions.h index 8acd9781c37..de4bcdc6443 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/textinput/baseConversions.h +++ b/packages/react-native/ReactCommon/react/renderer/components/textinput/baseConversions.h @@ -14,10 +14,8 @@ namespace facebook::react { -inline void fromRawValue( - const PropsParserContext& /*context*/, - const RawValue& value, - SubmitBehavior& result) { +inline void fromRawValue(const PropsParserContext & /*context*/, const RawValue &value, SubmitBehavior &result) +{ auto string = static_cast(value); if (string == "newline") { result = SubmitBehavior::Newline; @@ -30,7 +28,8 @@ inline void fromRawValue( } } -inline folly::dynamic toDynamic(const SubmitBehavior& value) { +inline folly::dynamic toDynamic(const SubmitBehavior &value) +{ switch (value) { case SubmitBehavior::Newline: return "newline"; diff --git a/packages/react-native/ReactCommon/react/renderer/components/textinput/platform/android/react/renderer/components/androidtextinput/AndroidTextInputComponentDescriptor.h b/packages/react-native/ReactCommon/react/renderer/components/textinput/platform/android/react/renderer/components/androidtextinput/AndroidTextInputComponentDescriptor.h index bdb6e7a99a0..fb44034605b 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/textinput/platform/android/react/renderer/components/androidtextinput/AndroidTextInputComponentDescriptor.h +++ b/packages/react-native/ReactCommon/react/renderer/components/textinput/platform/android/react/renderer/components/androidtextinput/AndroidTextInputComponentDescriptor.h @@ -24,102 +24,87 @@ namespace facebook::react { /* * Descriptor for component. */ -class AndroidTextInputComponentDescriptor final - : public ConcreteComponentDescriptor { +class AndroidTextInputComponentDescriptor final : public ConcreteComponentDescriptor { public: - AndroidTextInputComponentDescriptor( - const ComponentDescriptorParameters& parameters) + AndroidTextInputComponentDescriptor(const ComponentDescriptorParameters ¶meters) : ConcreteComponentDescriptor(parameters), - textLayoutManager_( - std::make_shared(contextContainer_)) {} + textLayoutManager_(std::make_shared(contextContainer_)) + { + } - virtual State::Shared createInitialState( - const Props::Shared& props, - const ShadowNodeFamily::Shared& family) const override { + virtual State::Shared createInitialState(const Props::Shared &props, const ShadowNodeFamily::Shared &family) + const override + { int surfaceId = family->getSurfaceId(); ThemePadding theme; // TODO: figure out RTL/start/end/left/right stuff here - if (surfaceIdToThemePaddingMap_.find(surfaceId) != - surfaceIdToThemePaddingMap_.end()) { + if (surfaceIdToThemePaddingMap_.find(surfaceId) != surfaceIdToThemePaddingMap_.end()) { theme = surfaceIdToThemePaddingMap_[surfaceId]; } else { - const jni::global_ref& fabricUIManager = + const jni::global_ref &fabricUIManager = contextContainer_->at>("FabricUIManager"); auto env = jni::Environment::current(); auto defaultTextInputPaddingArray = env->NewFloatArray(4); static auto getThemeData = - jni::findClassStatic(UIManagerJavaDescriptor) - ->getMethod("getThemeData"); + jni::findClassStatic(UIManagerJavaDescriptor)->getMethod("getThemeData"); - if (getThemeData( - fabricUIManager, surfaceId, defaultTextInputPaddingArray) != 0u) { - jfloat* defaultTextInputPadding = - env->GetFloatArrayElements(defaultTextInputPaddingArray, nullptr); + if (getThemeData(fabricUIManager, surfaceId, defaultTextInputPaddingArray) != 0u) { + jfloat *defaultTextInputPadding = env->GetFloatArrayElements(defaultTextInputPaddingArray, nullptr); theme.start = defaultTextInputPadding[0]; theme.end = defaultTextInputPadding[1]; theme.top = defaultTextInputPadding[2]; theme.bottom = defaultTextInputPadding[3]; surfaceIdToThemePaddingMap_.emplace(std::make_pair(surfaceId, theme)); - env->ReleaseFloatArrayElements( - defaultTextInputPaddingArray, defaultTextInputPadding, JNI_ABORT); + env->ReleaseFloatArrayElements(defaultTextInputPaddingArray, defaultTextInputPadding, JNI_ABORT); } env->DeleteLocalRef(defaultTextInputPaddingArray); } return std::make_shared( - std::make_shared( - AndroidTextInputState({}, {}, {}, 0)), - family); + std::make_shared(AndroidTextInputState({}, {}, {}, 0)), family); } protected: - void adopt(ShadowNode& shadowNode) const override { - auto& textInputShadowNode = - static_cast(shadowNode); + void adopt(ShadowNode &shadowNode) const override + { + auto &textInputShadowNode = static_cast(shadowNode); // `TextInputShadowNode` uses `TextLayoutManager` to measure text content // and communicate text rendering metrics to mounting layer. textInputShadowNode.setTextLayoutManager(textLayoutManager_); int surfaceId = textInputShadowNode.getSurfaceId(); - if (surfaceIdToThemePaddingMap_.find(surfaceId) != - surfaceIdToThemePaddingMap_.end()) { - const auto& theme = surfaceIdToThemePaddingMap_[surfaceId]; + if (surfaceIdToThemePaddingMap_.find(surfaceId) != surfaceIdToThemePaddingMap_.end()) { + const auto &theme = surfaceIdToThemePaddingMap_[surfaceId]; - auto& textInputProps = textInputShadowNode.getConcreteProps(); + auto &textInputProps = textInputShadowNode.getConcreteProps(); // Override padding // Node is still unsealed during adoption, before layout is complete // TODO: T62959168 account for RTL and paddingLeft when setting default // paddingStart, and vice-versa with paddingRight/paddingEnd. // For now this assumes no RTL. - auto& style = const_cast(textInputProps.yogaStyle); + auto &style = const_cast(textInputProps.yogaStyle); bool changedPadding = false; - if (!textInputProps.hasPadding && !textInputProps.hasPaddingStart && - !textInputProps.hasPaddingLeft && + if (!textInputProps.hasPadding && !textInputProps.hasPaddingStart && !textInputProps.hasPaddingLeft && !textInputProps.hasPaddingHorizontal) { changedPadding = true; - style.setPadding( - yoga::Edge::Start, yoga::StyleLength::points(theme.start)); + style.setPadding(yoga::Edge::Start, yoga::StyleLength::points(theme.start)); } - if (!textInputProps.hasPadding && !textInputProps.hasPaddingEnd && - !textInputProps.hasPaddingRight && + if (!textInputProps.hasPadding && !textInputProps.hasPaddingEnd && !textInputProps.hasPaddingRight && !textInputProps.hasPaddingHorizontal) { changedPadding = true; style.setPadding(yoga::Edge::End, yoga::StyleLength::points(theme.end)); } - if (!textInputProps.hasPadding && !textInputProps.hasPaddingTop && - !textInputProps.hasPaddingVertical) { + if (!textInputProps.hasPadding && !textInputProps.hasPaddingTop && !textInputProps.hasPaddingVertical) { changedPadding = true; style.setPadding(yoga::Edge::Top, yoga::StyleLength::points(theme.top)); } - if (!textInputProps.hasPadding && !textInputProps.hasPaddingBottom && - !textInputProps.hasPaddingVertical) { + if (!textInputProps.hasPadding && !textInputProps.hasPaddingBottom && !textInputProps.hasPaddingVertical) { changedPadding = true; - style.setPadding( - yoga::Edge::Bottom, yoga::StyleLength::points(theme.bottom)); + style.setPadding(yoga::Edge::Bottom, yoga::StyleLength::points(theme.bottom)); } // If the TextInput initially does not have paddingLeft or paddingStart, a @@ -127,13 +112,11 @@ class AndroidTextInputComponentDescriptor final // paddingLeft update, we must explicitly unset paddingStart... (same with // paddingEnd) // TODO: support RTL - if ((textInputProps.hasPadding || textInputProps.hasPaddingLeft || - textInputProps.hasPaddingHorizontal) && + if ((textInputProps.hasPadding || textInputProps.hasPaddingLeft || textInputProps.hasPaddingHorizontal) && !textInputProps.hasPaddingStart) { style.setPadding(yoga::Edge::Start, yoga::StyleLength::undefined()); } - if ((textInputProps.hasPadding || textInputProps.hasPaddingRight || - textInputProps.hasPaddingHorizontal) && + if ((textInputProps.hasPadding || textInputProps.hasPaddingRight || textInputProps.hasPaddingHorizontal) && !textInputProps.hasPaddingEnd) { style.setPadding(yoga::Edge::End, yoga::StyleLength::undefined()); } @@ -161,8 +144,7 @@ class AndroidTextInputComponentDescriptor final }; // TODO T68526882: Unify with Binding::UIManagerJavaDescriptor - constexpr static auto UIManagerJavaDescriptor = - "com/facebook/react/fabric/FabricUIManager"; + constexpr static auto UIManagerJavaDescriptor = "com/facebook/react/fabric/FabricUIManager"; const std::shared_ptr textLayoutManager_; mutable std::unordered_map surfaceIdToThemePaddingMap_; diff --git a/packages/react-native/ReactCommon/react/renderer/components/textinput/platform/android/react/renderer/components/androidtextinput/AndroidTextInputProps.h b/packages/react-native/ReactCommon/react/renderer/components/textinput/platform/android/react/renderer/components/androidtextinput/AndroidTextInputProps.h index 26753b62d72..d43f97bf811 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/textinput/platform/android/react/renderer/components/androidtextinput/AndroidTextInputProps.h +++ b/packages/react-native/ReactCommon/react/renderer/components/textinput/platform/android/react/renderer/components/androidtextinput/AndroidTextInputProps.h @@ -28,15 +28,15 @@ struct AndroidTextInputTextShadowOffsetStruct { }; inline static bool operator==( - const AndroidTextInputTextShadowOffsetStruct& lhs, - const AndroidTextInputTextShadowOffsetStruct& rhs) { + const AndroidTextInputTextShadowOffsetStruct &lhs, + const AndroidTextInputTextShadowOffsetStruct &rhs) +{ return lhs.width == rhs.width && lhs.height == rhs.height; } -static inline void fromRawValue( - const PropsParserContext& context, - const RawValue& value, - AndroidTextInputTextShadowOffsetStruct& result) { +static inline void +fromRawValue(const PropsParserContext &context, const RawValue &value, AndroidTextInputTextShadowOffsetStruct &result) +{ auto map = (std::unordered_map)value; auto width = map.find("width"); @@ -49,13 +49,13 @@ static inline void fromRawValue( } } -static inline std::string toString( - const AndroidTextInputTextShadowOffsetStruct& value) { +static inline std::string toString(const AndroidTextInputTextShadowOffsetStruct &value) +{ return "[Object AndroidTextInputTextShadowOffsetStruct]"; } -inline folly::dynamic toDynamic( - const AndroidTextInputTextShadowOffsetStruct& value) { +inline folly::dynamic toDynamic(const AndroidTextInputTextShadowOffsetStruct &value) +{ folly::dynamic dynamicValue = folly::dynamic::object(); dynamicValue["width"] = value.width; dynamicValue["height"] = value.height; @@ -66,15 +66,12 @@ class AndroidTextInputProps final : public BaseTextInputProps { public: AndroidTextInputProps() = default; AndroidTextInputProps( - const PropsParserContext& context, - const AndroidTextInputProps& sourceProps, - const RawProps& rawProps); + const PropsParserContext &context, + const AndroidTextInputProps &sourceProps, + const RawProps &rawProps); - void setProp( - const PropsParserContext& context, - RawPropsPropNameHash hash, - const char* propName, - const RawValue& value); + void + setProp(const PropsParserContext &context, RawPropsPropNameHash hash, const char *propName, const RawValue &value); folly::dynamic getDynamic() const; @@ -134,7 +131,7 @@ class AndroidTextInputProps final : public BaseTextInputProps { #endif ComponentName getDiffPropsImplementationTarget() const override; - folly::dynamic getDiffProps(const Props* prevProps) const override; + folly::dynamic getDiffProps(const Props *prevProps) const override; }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/components/textinput/platform/android/react/renderer/components/androidtextinput/AndroidTextInputShadowNode.cpp b/packages/react-native/ReactCommon/react/renderer/components/textinput/platform/android/react/renderer/components/androidtextinput/AndroidTextInputShadowNode.cpp index e559bb76d14..5a09063b9f3 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/textinput/platform/android/react/renderer/components/androidtextinput/AndroidTextInputShadowNode.cpp +++ b/packages/react-native/ReactCommon/react/renderer/components/textinput/platform/android/react/renderer/components/androidtextinput/AndroidTextInputShadowNode.cpp @@ -151,11 +151,12 @@ void AndroidTextInputShadowNode::updateStateIfNeeded( : props.mostRecentEventCount; auto newAttributedString = getMostRecentAttributedString(layoutContext); - setStateData(AndroidTextInputState{ - AttributedStringBox(newAttributedString), - reactTreeAttributedString, - props.paragraphAttributes, - newEventCount}); + setStateData( + AndroidTextInputState{ + AttributedStringBox(newAttributedString), + reactTreeAttributedString, + props.paragraphAttributes, + newEventCount}); } AttributedString AndroidTextInputShadowNode::getAttributedString( diff --git a/packages/react-native/ReactCommon/react/renderer/components/textinput/platform/android/react/renderer/components/androidtextinput/AndroidTextInputShadowNode.h b/packages/react-native/ReactCommon/react/renderer/components/textinput/platform/android/react/renderer/components/androidtextinput/AndroidTextInputShadowNode.h index 97e0b18664f..8a1d6d96990 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/textinput/platform/android/react/renderer/components/androidtextinput/AndroidTextInputShadowNode.h +++ b/packages/react-native/ReactCommon/react/renderer/components/textinput/platform/android/react/renderer/components/androidtextinput/AndroidTextInputShadowNode.h @@ -30,7 +30,8 @@ class AndroidTextInputShadowNode final : public ConcreteViewShadowNode< public: using ConcreteViewShadowNode::ConcreteViewShadowNode; - static ShadowNodeTraits BaseTraits() { + static ShadowNodeTraits BaseTraits() + { auto traits = ConcreteViewShadowNode::BaseTraits(); traits.set(ShadowNodeTraits::Trait::LeafYogaNode); traits.set(ShadowNodeTraits::Trait::MeasurableYogaNode); @@ -43,47 +44,40 @@ class AndroidTextInputShadowNode final : public ConcreteViewShadowNode< * `TextInputShadowNode` uses the manager to measure text content * and construct `TextInputState` objects. */ - void setTextLayoutManager( - std::shared_ptr textLayoutManager); + void setTextLayoutManager(std::shared_ptr textLayoutManager); protected: - Size measureContent( - const LayoutContext& layoutContext, - const LayoutConstraints& layoutConstraints) const override; + Size measureContent(const LayoutContext &layoutContext, const LayoutConstraints &layoutConstraints) const override; void layout(LayoutContext layoutContext) override; - Float baseline(const LayoutContext& layoutContext, Size size) const override; + Float baseline(const LayoutContext &layoutContext, Size size) const override; std::shared_ptr textLayoutManager_; /* * Determines the constraints to use while measure the underlying text */ - LayoutConstraints getTextConstraints( - const LayoutConstraints& layoutConstraints) const; + LayoutConstraints getTextConstraints(const LayoutConstraints &layoutConstraints) const; private: /* * Creates a `State` object (with `AttributedText` and * `TextLayoutManager`) if needed. */ - void updateStateIfNeeded(const LayoutContext& layoutContext); + void updateStateIfNeeded(const LayoutContext &layoutContext); /* * Returns a `AttributedString` which represents text content of the node. */ - AttributedString getAttributedString( - const LayoutContext& layoutContext) const; + AttributedString getAttributedString(const LayoutContext &layoutContext) const; /** * Get the most up-to-date attributed string for measurement and State. */ - AttributedString getMostRecentAttributedString( - const LayoutContext& layoutContext) const; + AttributedString getMostRecentAttributedString(const LayoutContext &layoutContext) const; - AttributedString getPlaceholderAttributedString( - const LayoutContext& layoutContext) const; + AttributedString getPlaceholderAttributedString(const LayoutContext &layoutContext) const; }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/components/textinput/platform/android/react/renderer/components/androidtextinput/AndroidTextInputState.h b/packages/react-native/ReactCommon/react/renderer/components/textinput/platform/android/react/renderer/components/androidtextinput/AndroidTextInputState.h index b5d5eec1522..9655ba81a76 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/textinput/platform/android/react/renderer/components/androidtextinput/AndroidTextInputState.h +++ b/packages/react-native/ReactCommon/react/renderer/components/textinput/platform/android/react/renderer/components/androidtextinput/AndroidTextInputState.h @@ -31,22 +31,18 @@ class AndroidTextInputState final { : attributedStringBox(std::move(attributedStringBox)), reactTreeAttributedString(std::move(reactTreeAttributedString)), paragraphAttributes(std::move(paragraphAttributes)), - mostRecentEventCount(mostRecentEventCount) {} + mostRecentEventCount(mostRecentEventCount) + { + } - AndroidTextInputState( - const AndroidTextInputState& previousState, - const folly::dynamic& data) + AndroidTextInputState(const AndroidTextInputState &previousState, const folly::dynamic &data) : attributedStringBox(previousState.attributedStringBox), reactTreeAttributedString(previousState.reactTreeAttributedString), paragraphAttributes(previousState.paragraphAttributes), - mostRecentEventCount(data.getDefault( - "mostRecentEventCount", - previousState.mostRecentEventCount) - .getInt()), - cachedAttributedStringId(data.getDefault( - "opaqueCacheId", - previousState.cachedAttributedStringId) - .getInt()) {} + mostRecentEventCount(data.getDefault("mostRecentEventCount", previousState.mostRecentEventCount).getInt()), + cachedAttributedStringId(data.getDefault("opaqueCacheId", previousState.cachedAttributedStringId).getInt()) + { + } folly::dynamic getDynamic() const; MapBuffer getMapBuffer() const; diff --git a/packages/react-native/ReactCommon/react/renderer/components/textinput/platform/ios/react/renderer/components/iostextinput/TextInputComponentDescriptor.h b/packages/react-native/ReactCommon/react/renderer/components/textinput/platform/ios/react/renderer/components/iostextinput/TextInputComponentDescriptor.h index c361114f653..4ad058cf7a5 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/textinput/platform/ios/react/renderer/components/iostextinput/TextInputComponentDescriptor.h +++ b/packages/react-native/ReactCommon/react/renderer/components/textinput/platform/ios/react/renderer/components/iostextinput/TextInputComponentDescriptor.h @@ -15,19 +15,20 @@ namespace facebook::react { /* * Descriptor for component. */ -class TextInputComponentDescriptor final - : public ConcreteComponentDescriptor { +class TextInputComponentDescriptor final : public ConcreteComponentDescriptor { public: - TextInputComponentDescriptor(const ComponentDescriptorParameters& parameters) + TextInputComponentDescriptor(const ComponentDescriptorParameters ¶meters) : ConcreteComponentDescriptor(parameters), - textLayoutManager_( - std::make_shared(contextContainer_)) {} + textLayoutManager_(std::make_shared(contextContainer_)) + { + } protected: - void adopt(ShadowNode& shadowNode) const override { + void adopt(ShadowNode &shadowNode) const override + { ConcreteComponentDescriptor::adopt(shadowNode); - auto& concreteShadowNode = static_cast(shadowNode); + auto &concreteShadowNode = static_cast(shadowNode); concreteShadowNode.setTextLayoutManager(textLayoutManager_); } diff --git a/packages/react-native/ReactCommon/react/renderer/components/textinput/platform/ios/react/renderer/components/iostextinput/TextInputProps.cpp b/packages/react-native/ReactCommon/react/renderer/components/textinput/platform/ios/react/renderer/components/iostextinput/TextInputProps.cpp index 4f35234996d..2b598a01cb9 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/textinput/platform/ios/react/renderer/components/iostextinput/TextInputProps.cpp +++ b/packages/react-native/ReactCommon/react/renderer/components/textinput/platform/ios/react/renderer/components/iostextinput/TextInputProps.cpp @@ -50,6 +50,6 @@ TextInputProps::TextInputProps( rawProps, "onChangeSync", sourceProps.onChangeSync, - {})){}; + {})) {}; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/components/textinput/platform/ios/react/renderer/components/iostextinput/TextInputProps.h b/packages/react-native/ReactCommon/react/renderer/components/textinput/platform/ios/react/renderer/components/iostextinput/TextInputProps.h index 40964f33d17..317fff3cbf6 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/textinput/platform/ios/react/renderer/components/iostextinput/TextInputProps.h +++ b/packages/react-native/ReactCommon/react/renderer/components/textinput/platform/ios/react/renderer/components/iostextinput/TextInputProps.h @@ -23,10 +23,7 @@ namespace facebook::react { class TextInputProps final : public BaseTextInputProps { public: TextInputProps() = default; - TextInputProps( - const PropsParserContext& context, - const TextInputProps& sourceProps, - const RawProps& rawProps); + TextInputProps(const PropsParserContext &context, const TextInputProps &sourceProps, const RawProps &rawProps); #pragma mark - Props const TextInputTraits traits{}; diff --git a/packages/react-native/ReactCommon/react/renderer/components/textinput/platform/ios/react/renderer/components/iostextinput/TextInputShadowNode.h b/packages/react-native/ReactCommon/react/renderer/components/textinput/platform/ios/react/renderer/components/iostextinput/TextInputShadowNode.h index af9524b605f..96e9de4525a 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/textinput/platform/ios/react/renderer/components/iostextinput/TextInputShadowNode.h +++ b/packages/react-native/ReactCommon/react/renderer/components/textinput/platform/ios/react/renderer/components/iostextinput/TextInputShadowNode.h @@ -19,11 +19,8 @@ extern const char TextInputComponentName[]; /* * `ShadowNode` for component. */ -class TextInputShadowNode final : public BaseTextInputShadowNode< - TextInputComponentName, - TextInputProps, - TextInputEventEmitter, - TextInputState> { +class TextInputShadowNode final + : public BaseTextInputShadowNode { public: using BaseTextInputShadowNode::BaseTextInputShadowNode; }; diff --git a/packages/react-native/ReactCommon/react/renderer/components/textinput/platform/ios/react/renderer/components/iostextinput/conversions.h b/packages/react-native/ReactCommon/react/renderer/components/textinput/platform/ios/react/renderer/components/iostextinput/conversions.h index bf967317c76..9de9d0e8831 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/textinput/platform/ios/react/renderer/components/iostextinput/conversions.h +++ b/packages/react-native/ReactCommon/react/renderer/components/textinput/platform/ios/react/renderer/components/iostextinput/conversions.h @@ -13,10 +13,8 @@ namespace facebook::react { -inline void fromRawValue( - const PropsParserContext& context, - const RawValue& value, - AutocapitalizationType& result) { +inline void fromRawValue(const PropsParserContext &context, const RawValue &value, AutocapitalizationType &result) +{ auto string = (std::string)value; if (string == "none") { result = AutocapitalizationType::None; @@ -37,10 +35,8 @@ inline void fromRawValue( result = AutocapitalizationType::None; } -inline void fromRawValue( - const PropsParserContext& context, - const RawValue& value, - KeyboardAppearance& result) { +inline void fromRawValue(const PropsParserContext &context, const RawValue &value, KeyboardAppearance &result) +{ auto string = (std::string)value; if (string == "default") { result = KeyboardAppearance::Default; @@ -57,10 +53,8 @@ inline void fromRawValue( result = KeyboardAppearance::Default; } -inline void fromRawValue( - const PropsParserContext& context, - const RawValue& value, - ReturnKeyType& result) { +inline void fromRawValue(const PropsParserContext &context, const RawValue &value, ReturnKeyType &result) +{ auto string = (std::string)value; if (string == "default") { result = ReturnKeyType::Default; @@ -125,10 +119,9 @@ inline void fromRawValue( result = ReturnKeyType::Default; } -inline void fromRawValue( - const PropsParserContext& context, - const RawValue& value, - TextInputAccessoryVisibilityMode& result) { +inline void +fromRawValue(const PropsParserContext &context, const RawValue &value, TextInputAccessoryVisibilityMode &result) +{ auto string = (std::string)value; if (string == "never") { result = TextInputAccessoryVisibilityMode::Never; @@ -149,10 +142,8 @@ inline void fromRawValue( result = TextInputAccessoryVisibilityMode::Never; } -inline void fromRawValue( - const PropsParserContext& context, - const RawValue& value, - KeyboardType& result) { +inline void fromRawValue(const PropsParserContext &context, const RawValue &value, KeyboardType &result) +{ auto string = (std::string)value; if (string == "default") { result = KeyboardType::Default; diff --git a/packages/react-native/ReactCommon/react/renderer/components/textinput/platform/ios/react/renderer/components/iostextinput/primitives.h b/packages/react-native/ReactCommon/react/renderer/components/textinput/platform/ios/react/renderer/components/iostextinput/primitives.h index a5ace05d642..942eeeb8805 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/textinput/platform/ios/react/renderer/components/iostextinput/primitives.h +++ b/packages/react-native/ReactCommon/react/renderer/components/textinput/platform/ios/react/renderer/components/iostextinput/primitives.h @@ -92,8 +92,7 @@ class TextInputTraits final { * iOS & Android * Default value: `Sentences`. */ - AutocapitalizationType autocapitalizationType{ - AutocapitalizationType::Sentences}; + AutocapitalizationType autocapitalizationType{AutocapitalizationType::Sentences}; /* * Can be empty (`null` in JavaScript) which means `default`. @@ -148,8 +147,7 @@ class TextInputTraits final { * iOS-only (implemented only on iOS for now) * Default value: `Never`. */ - TextInputAccessoryVisibilityMode clearButtonMode{ - TextInputAccessoryVisibilityMode::Never}; + TextInputAccessoryVisibilityMode clearButtonMode{TextInputAccessoryVisibilityMode::Never}; /* * iOS-only (implemented only on iOS for now) diff --git a/packages/react-native/ReactCommon/react/renderer/components/textinput/platform/ios/react/renderer/components/iostextinput/propsConversions.h b/packages/react-native/ReactCommon/react/renderer/components/textinput/platform/ios/react/renderer/components/iostextinput/propsConversions.h index 8039fbf56b1..54921b3fca4 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/textinput/platform/ios/react/renderer/components/iostextinput/propsConversions.h +++ b/packages/react-native/ReactCommon/react/renderer/components/textinput/platform/ios/react/renderer/components/iostextinput/propsConversions.h @@ -15,36 +15,20 @@ namespace facebook::react { static TextInputTraits convertRawProp( - const PropsParserContext& context, - const RawProps& rawProps, - const TextInputTraits& sourceTraits, - const TextInputTraits& defaultTraits) { + const PropsParserContext &context, + const RawProps &rawProps, + const TextInputTraits &sourceTraits, + const TextInputTraits &defaultTraits) +{ auto traits = TextInputTraits{}; traits.autocapitalizationType = convertRawProp( - context, - rawProps, - "autoCapitalize", - sourceTraits.autocapitalizationType, - defaultTraits.autocapitalizationType); - traits.autoCorrect = convertRawProp( - context, - rawProps, - "autoCorrect", - sourceTraits.autoCorrect, - defaultTraits.autoCorrect); + context, rawProps, "autoCapitalize", sourceTraits.autocapitalizationType, defaultTraits.autocapitalizationType); + traits.autoCorrect = + convertRawProp(context, rawProps, "autoCorrect", sourceTraits.autoCorrect, defaultTraits.autoCorrect); traits.contextMenuHidden = convertRawProp( - context, - rawProps, - "contextMenuHidden", - sourceTraits.contextMenuHidden, - defaultTraits.contextMenuHidden); - traits.editable = convertRawProp( - context, - rawProps, - "editable", - sourceTraits.editable, - defaultTraits.editable); + context, rawProps, "contextMenuHidden", sourceTraits.contextMenuHidden, defaultTraits.contextMenuHidden); + traits.editable = convertRawProp(context, rawProps, "editable", sourceTraits.editable, defaultTraits.editable); traits.enablesReturnKeyAutomatically = convertRawProp( context, rawProps, @@ -52,107 +36,45 @@ static TextInputTraits convertRawProp( sourceTraits.enablesReturnKeyAutomatically, defaultTraits.enablesReturnKeyAutomatically); traits.keyboardAppearance = convertRawProp( - context, - rawProps, - "keyboardAppearance", - sourceTraits.keyboardAppearance, - defaultTraits.keyboardAppearance); - traits.spellCheck = convertRawProp( - context, - rawProps, - "spellCheck", - sourceTraits.spellCheck, - defaultTraits.spellCheck); - traits.caretHidden = convertRawProp( - context, - rawProps, - "caretHidden", - sourceTraits.caretHidden, - defaultTraits.caretHidden); - traits.clearButtonMode = convertRawProp( - context, - rawProps, - "clearButtonMode", - sourceTraits.clearButtonMode, - defaultTraits.clearButtonMode); - traits.scrollEnabled = convertRawProp( - context, - rawProps, - "scrollEnabled", - sourceTraits.scrollEnabled, - defaultTraits.scrollEnabled); - traits.secureTextEntry = convertRawProp( - context, - rawProps, - "secureTextEntry", - sourceTraits.secureTextEntry, - defaultTraits.secureTextEntry); + context, rawProps, "keyboardAppearance", sourceTraits.keyboardAppearance, defaultTraits.keyboardAppearance); + traits.spellCheck = + convertRawProp(context, rawProps, "spellCheck", sourceTraits.spellCheck, defaultTraits.spellCheck); + traits.caretHidden = + convertRawProp(context, rawProps, "caretHidden", sourceTraits.caretHidden, defaultTraits.caretHidden); + traits.clearButtonMode = + convertRawProp(context, rawProps, "clearButtonMode", sourceTraits.clearButtonMode, defaultTraits.clearButtonMode); + traits.scrollEnabled = + convertRawProp(context, rawProps, "scrollEnabled", sourceTraits.scrollEnabled, defaultTraits.scrollEnabled); + traits.secureTextEntry = + convertRawProp(context, rawProps, "secureTextEntry", sourceTraits.secureTextEntry, defaultTraits.secureTextEntry); traits.clearTextOnFocus = convertRawProp( - context, - rawProps, - "clearTextOnFocus", - sourceTraits.clearTextOnFocus, - defaultTraits.clearTextOnFocus); - traits.keyboardType = convertRawProp( - context, - rawProps, - "keyboardType", - sourceTraits.keyboardType, - defaultTraits.keyboardType); + context, rawProps, "clearTextOnFocus", sourceTraits.clearTextOnFocus, defaultTraits.clearTextOnFocus); + traits.keyboardType = + convertRawProp(context, rawProps, "keyboardType", sourceTraits.keyboardType, defaultTraits.keyboardType); traits.showSoftInputOnFocus = convertRawProp( - context, - rawProps, - "showSoftInputOnFocus", - sourceTraits.showSoftInputOnFocus, - defaultTraits.showSoftInputOnFocus); - traits.returnKeyType = convertRawProp( - context, - rawProps, - "returnKeyType", - sourceTraits.returnKeyType, - defaultTraits.returnKeyType); + context, rawProps, "showSoftInputOnFocus", sourceTraits.showSoftInputOnFocus, defaultTraits.showSoftInputOnFocus); + traits.returnKeyType = + convertRawProp(context, rawProps, "returnKeyType", sourceTraits.returnKeyType, defaultTraits.returnKeyType); traits.selectTextOnFocus = convertRawProp( - context, - rawProps, - "selectTextOnFocus", - sourceTraits.selectTextOnFocus, - defaultTraits.selectTextOnFocus); - traits.textContentType = convertRawProp( - context, - rawProps, - "textContentType", - sourceTraits.textContentType, - defaultTraits.textContentType); - traits.passwordRules = convertRawProp( - context, - rawProps, - "passwordRules", - sourceTraits.passwordRules, - defaultTraits.passwordRules); + context, rawProps, "selectTextOnFocus", sourceTraits.selectTextOnFocus, defaultTraits.selectTextOnFocus); + traits.textContentType = + convertRawProp(context, rawProps, "textContentType", sourceTraits.textContentType, defaultTraits.textContentType); + traits.passwordRules = + convertRawProp(context, rawProps, "passwordRules", sourceTraits.passwordRules, defaultTraits.passwordRules); traits.smartInsertDelete = convertRawProp( - context, - rawProps, - "smartInsertDelete", - sourceTraits.smartInsertDelete, - defaultTraits.smartInsertDelete); + context, rawProps, "smartInsertDelete", sourceTraits.smartInsertDelete, defaultTraits.smartInsertDelete); traits.dataDetectorTypes = convertRawProp( - context, - rawProps, - "dataDetectorTypes", - sourceTraits.dataDetectorTypes, - defaultTraits.dataDetectorTypes); + context, rawProps, "dataDetectorTypes", sourceTraits.dataDetectorTypes, defaultTraits.dataDetectorTypes); return traits; } -inline void fromRawValue( - const PropsParserContext& context, - const RawValue& value, - Selection& result) { +inline void fromRawValue(const PropsParserContext &context, const RawValue &value, Selection &result) +{ if (value.hasType>()) { auto map = (std::unordered_map)value; - for (const auto& pair : map) { + for (const auto &pair : map) { if (pair.first == "start") { result.start = pair.second; } else if (pair.first == "end") { diff --git a/packages/react-native/ReactCommon/react/renderer/components/unimplementedview/UnimplementedViewComponentDescriptor.h b/packages/react-native/ReactCommon/react/renderer/components/unimplementedview/UnimplementedViewComponentDescriptor.h index e73046568de..bd96cf9156b 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/unimplementedview/UnimplementedViewComponentDescriptor.h +++ b/packages/react-native/ReactCommon/react/renderer/components/unimplementedview/UnimplementedViewComponentDescriptor.h @@ -16,8 +16,7 @@ namespace facebook::react { /* * Descriptor for component. */ -class UnimplementedViewComponentDescriptor final - : public ConcreteComponentDescriptor { +class UnimplementedViewComponentDescriptor final : public ConcreteComponentDescriptor { public: using ConcreteComponentDescriptor::ConcreteComponentDescriptor; @@ -32,10 +31,8 @@ class UnimplementedViewComponentDescriptor final * In addition to base implementation, stores a component name inside cloned * `Props` object. */ - Props::Shared cloneProps( - const PropsParserContext& context, - const Props::Shared& props, - RawProps rawProps) const override; + Props::Shared cloneProps(const PropsParserContext &context, const Props::Shared &props, RawProps rawProps) + const override; }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/components/unimplementedview/UnimplementedViewProps.h b/packages/react-native/ReactCommon/react/renderer/components/unimplementedview/UnimplementedViewProps.h index 93a5833fa5b..46490716e4b 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/unimplementedview/UnimplementedViewProps.h +++ b/packages/react-native/ReactCommon/react/renderer/components/unimplementedview/UnimplementedViewProps.h @@ -28,7 +28,7 @@ class UnimplementedViewProps final : public ViewProps { ComponentName getComponentName() const; #ifdef RN_SERIALIZABLE_STATE - folly::dynamic getDiffProps(const Props* prevProps) const override; + folly::dynamic getDiffProps(const Props *prevProps) const override; #endif private: diff --git a/packages/react-native/ReactCommon/react/renderer/components/unimplementedview/UnimplementedViewShadowNode.h b/packages/react-native/ReactCommon/react/renderer/components/unimplementedview/UnimplementedViewShadowNode.h index 405c81e647f..ea9f75a8b35 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/unimplementedview/UnimplementedViewShadowNode.h +++ b/packages/react-native/ReactCommon/react/renderer/components/unimplementedview/UnimplementedViewShadowNode.h @@ -14,8 +14,6 @@ namespace facebook::react { extern const char UnimplementedViewComponentName[]; -using UnimplementedViewShadowNode = ConcreteViewShadowNode< - UnimplementedViewComponentName, - UnimplementedViewProps>; +using UnimplementedViewShadowNode = ConcreteViewShadowNode; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/components/view/AccessibilityPrimitives.h b/packages/react-native/ReactCommon/react/renderer/components/view/AccessibilityPrimitives.h index b5d7010a28b..547bfba956d 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/view/AccessibilityPrimitives.h +++ b/packages/react-native/ReactCommon/react/renderer/components/view/AccessibilityPrimitives.h @@ -36,15 +36,13 @@ enum class AccessibilityTraits : uint32_t { TabBar = (1 << 17), }; -constexpr enum AccessibilityTraits operator|( - const enum AccessibilityTraits lhs, - const enum AccessibilityTraits rhs) { +constexpr enum AccessibilityTraits operator|(const enum AccessibilityTraits lhs, const enum AccessibilityTraits rhs) +{ return (enum AccessibilityTraits)((uint32_t)lhs | (uint32_t)rhs); } -constexpr enum AccessibilityTraits operator&( - const enum AccessibilityTraits lhs, - const enum AccessibilityTraits rhs) { +constexpr enum AccessibilityTraits operator&(const enum AccessibilityTraits lhs, const enum AccessibilityTraits rhs) +{ return (enum AccessibilityTraits)((uint32_t)lhs & (uint32_t)rhs); } @@ -53,15 +51,13 @@ struct AccessibilityAction { std::optional label{}; }; -inline static bool operator==( - const AccessibilityAction& lhs, - const AccessibilityAction& rhs) { +inline static bool operator==(const AccessibilityAction &lhs, const AccessibilityAction &rhs) +{ return lhs.name == rhs.name && lhs.label == rhs.label; } -inline static bool operator!=( - const AccessibilityAction& lhs, - const AccessibilityAction& rhs) { +inline static bool operator!=(const AccessibilityAction &lhs, const AccessibilityAction &rhs) +{ return !(rhs == lhs); } @@ -73,17 +69,14 @@ struct AccessibilityState { enum CheckedState { Unchecked, Checked, Mixed, None } checked{None}; }; -constexpr bool operator==( - const AccessibilityState& lhs, - const AccessibilityState& rhs) { - return lhs.disabled == rhs.disabled && lhs.selected == rhs.selected && - lhs.checked == rhs.checked && lhs.busy == rhs.busy && - lhs.expanded == rhs.expanded; +constexpr bool operator==(const AccessibilityState &lhs, const AccessibilityState &rhs) +{ + return lhs.disabled == rhs.disabled && lhs.selected == rhs.selected && lhs.checked == rhs.checked && + lhs.busy == rhs.busy && lhs.expanded == rhs.expanded; } -constexpr bool operator!=( - const AccessibilityState& lhs, - const AccessibilityState& rhs) { +constexpr bool operator!=(const AccessibilityState &lhs, const AccessibilityState &rhs) +{ return !(rhs == lhs); } @@ -91,15 +84,13 @@ struct AccessibilityLabelledBy { std::vector value{}; }; -inline static bool operator==( - const AccessibilityLabelledBy& lhs, - const AccessibilityLabelledBy& rhs) { +inline static bool operator==(const AccessibilityLabelledBy &lhs, const AccessibilityLabelledBy &rhs) +{ return lhs.value == rhs.value; } -inline static bool operator!=( - const AccessibilityLabelledBy& lhs, - const AccessibilityLabelledBy& rhs) { +inline static bool operator!=(const AccessibilityLabelledBy &lhs, const AccessibilityLabelledBy &rhs) +{ return !(lhs == rhs); } @@ -110,16 +101,13 @@ struct AccessibilityValue { std::optional text{}; }; -constexpr bool operator==( - const AccessibilityValue& lhs, - const AccessibilityValue& rhs) { - return lhs.min == rhs.min && lhs.max == rhs.max && lhs.now == rhs.now && - lhs.text == rhs.text; +constexpr bool operator==(const AccessibilityValue &lhs, const AccessibilityValue &rhs) +{ + return lhs.min == rhs.min && lhs.max == rhs.max && lhs.now == rhs.now && lhs.text == rhs.text; } -constexpr bool operator!=( - const AccessibilityValue& lhs, - const AccessibilityValue& rhs) { +constexpr bool operator!=(const AccessibilityValue &lhs, const AccessibilityValue &rhs) +{ return !(rhs == lhs); } diff --git a/packages/react-native/ReactCommon/react/renderer/components/view/AccessibilityProps.h b/packages/react-native/ReactCommon/react/renderer/components/view/AccessibilityProps.h index 7c798c1cf3e..c664b8461e2 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/view/AccessibilityProps.h +++ b/packages/react-native/ReactCommon/react/renderer/components/view/AccessibilityProps.h @@ -19,15 +19,12 @@ class AccessibilityProps { public: AccessibilityProps() = default; AccessibilityProps( - const PropsParserContext& context, - const AccessibilityProps& sourceProps, - const RawProps& rawProps); + const PropsParserContext &context, + const AccessibilityProps &sourceProps, + const RawProps &rawProps); - void setProp( - const PropsParserContext& context, - RawPropsPropNameHash hash, - const char* propName, - const RawValue& value); + void + setProp(const PropsParserContext &context, RawPropsPropNameHash hash, const char *propName, const RawValue &value); #pragma mark - Props @@ -36,8 +33,7 @@ class AccessibilityProps { std::string accessibilityLabel; std::vector accessibilityOrder{}; AccessibilityLabelledBy accessibilityLabelledBy{}; - AccessibilityLiveRegion accessibilityLiveRegion{ - AccessibilityLiveRegion::None}; + AccessibilityLiveRegion accessibilityLiveRegion{AccessibilityLiveRegion::None}; AccessibilityTraits accessibilityTraits{AccessibilityTraits::None}; std::string accessibilityRole; std::string accessibilityHint; @@ -57,8 +53,7 @@ class AccessibilityProps { bool onAccessibilityMagicTap{}; bool onAccessibilityEscape{}; bool onAccessibilityAction{}; - ImportantForAccessibility importantForAccessibility{ - ImportantForAccessibility::Auto}; + ImportantForAccessibility importantForAccessibility{ImportantForAccessibility::Auto}; Role role{Role::None}; std::string testId; diff --git a/packages/react-native/ReactCommon/react/renderer/components/view/BackgroundImagePropsConversions.cpp b/packages/react-native/ReactCommon/react/renderer/components/view/BackgroundImagePropsConversions.cpp index 56ac84fc5b4..6861ab759ba 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/view/BackgroundImagePropsConversions.cpp +++ b/packages/react-native/ReactCommon/react/renderer/components/view/BackgroundImagePropsConversions.cpp @@ -442,16 +442,18 @@ void fromCSSColorStop( if (colorStop.startPosition.has_value() && colorStop.endPosition.has_value()) { // first stop with start position - colorStops.push_back(ColorStop{ - .color = fromCSSColor(colorStop.color), - .position = - convertLengthPercentageToValueUnit(*colorStop.startPosition)}); + colorStops.push_back( + ColorStop{ + .color = fromCSSColor(colorStop.color), + .position = convertLengthPercentageToValueUnit( + *colorStop.startPosition)}); // second stop with end position (same color) - colorStops.push_back(ColorStop{ - .color = fromCSSColor(colorStop.color), - .position = - convertLengthPercentageToValueUnit(*colorStop.endPosition)}); + colorStops.push_back( + ColorStop{ + .color = fromCSSColor(colorStop.color), + .position = + convertLengthPercentageToValueUnit(*colorStop.endPosition)}); } else { // single color stop ColorStop stop; diff --git a/packages/react-native/ReactCommon/react/renderer/components/view/BackgroundImagePropsConversions.h b/packages/react-native/ReactCommon/react/renderer/components/view/BackgroundImagePropsConversions.h index d33c701c012..aaea4da730d 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/view/BackgroundImagePropsConversions.h +++ b/packages/react-native/ReactCommon/react/renderer/components/view/BackgroundImagePropsConversions.h @@ -15,29 +15,24 @@ namespace facebook::react { void parseProcessedBackgroundImage( - const PropsParserContext& context, - const RawValue& value, - std::vector& result); + const PropsParserContext &context, + const RawValue &value, + std::vector &result); void parseUnprocessedBackgroundImageList( - const PropsParserContext& context, - const std::vector& value, - std::vector& result); + const PropsParserContext &context, + const std::vector &value, + std::vector &result); -void parseUnprocessedBackgroundImageString( - const std::string& value, - std::vector& result); +void parseUnprocessedBackgroundImageString(const std::string &value, std::vector &result); -inline void fromRawValue( - const PropsParserContext& context, - const RawValue& value, - std::vector& result) { +inline void fromRawValue(const PropsParserContext &context, const RawValue &value, std::vector &result) +{ if (ReactNativeFeatureFlags::enableNativeCSSParsing()) { if (value.hasType()) { parseUnprocessedBackgroundImageString((std::string)value, result); } else if (value.hasType>()) { - parseUnprocessedBackgroundImageList( - context, (std::vector)value, result); + parseUnprocessedBackgroundImageList(context, (std::vector)value, result); } else { result = {}; } diff --git a/packages/react-native/ReactCommon/react/renderer/components/view/BaseTouch.h b/packages/react-native/ReactCommon/react/renderer/components/view/BaseTouch.h index 0d658310f27..fdb0a9a8f8d 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/view/BaseTouch.h +++ b/packages/react-native/ReactCommon/react/renderer/components/view/BaseTouch.h @@ -62,29 +62,26 @@ struct BaseTouch { * collections. Because of that they are expressed as separate classes. */ struct Hasher { - size_t operator()(const BaseTouch& touch) const { + size_t operator()(const BaseTouch &touch) const + { return std::hash()(touch.identifier); } }; struct Comparator { - bool operator()(const BaseTouch& lhs, const BaseTouch& rhs) const { + bool operator()(const BaseTouch &lhs, const BaseTouch &rhs) const + { return lhs.identifier == rhs.identifier; } }; }; -void setTouchPayloadOnObject( - jsi::Object& object, - jsi::Runtime& runtime, - const BaseTouch& touch); +void setTouchPayloadOnObject(jsi::Object &object, jsi::Runtime &runtime, const BaseTouch &touch); #if RN_DEBUG_STRING_CONVERTIBLE -std::string getDebugName(const BaseTouch& touch); -std::vector getDebugProps( - const BaseTouch& touch, - DebugStringConvertibleOptions options); +std::string getDebugName(const BaseTouch &touch); +std::vector getDebugProps(const BaseTouch &touch, DebugStringConvertibleOptions options); #endif diff --git a/packages/react-native/ReactCommon/react/renderer/components/view/BaseViewEventEmitter.h b/packages/react-native/ReactCommon/react/renderer/components/view/BaseViewEventEmitter.h index 4b3c59b95bf..e556d1e9754 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/view/BaseViewEventEmitter.h +++ b/packages/react-native/ReactCommon/react/renderer/components/view/BaseViewEventEmitter.h @@ -23,14 +23,14 @@ class BaseViewEventEmitter : public TouchEventEmitter { #pragma mark - Accessibility - void onAccessibilityAction(const std::string& name) const; + void onAccessibilityAction(const std::string &name) const; void onAccessibilityTap() const; void onAccessibilityMagicTap() const; void onAccessibilityEscape() const; #pragma mark - Layout - void onLayout(const LayoutMetrics& layoutMetrics) const; + void onLayout(const LayoutMetrics &layoutMetrics) const; #pragma mark - Focus void onFocus() const; @@ -64,8 +64,7 @@ class BaseViewEventEmitter : public TouchEventEmitter { bool isDispatching{false}; }; - mutable std::shared_ptr layoutEventState_{ - std::make_shared()}; + mutable std::shared_ptr layoutEventState_{std::make_shared()}; }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/components/view/BaseViewProps.h b/packages/react-native/ReactCommon/react/renderer/components/view/BaseViewProps.h index b1c3f33e394..7554ba7cad8 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/view/BaseViewProps.h +++ b/packages/react-native/ReactCommon/react/renderer/components/view/BaseViewProps.h @@ -32,17 +32,13 @@ class BaseViewProps : public YogaStylableProps, public AccessibilityProps { public: BaseViewProps() = default; BaseViewProps( - const PropsParserContext& context, - const BaseViewProps& sourceProps, - const RawProps& rawProps, - const std::function& filterObjectKeys = - nullptr); + const PropsParserContext &context, + const BaseViewProps &sourceProps, + const RawProps &rawProps, + const std::function &filterObjectKeys = nullptr); - void setProp( - const PropsParserContext& context, - RawPropsPropNameHash hash, - const char* propName, - const RawValue& value); + void + setProp(const PropsParserContext &context, RawPropsPropNameHash hash, const char *propName, const RawValue &value); #pragma mark - Props @@ -116,14 +112,12 @@ class BaseViewProps : public YogaStylableProps, public AccessibilityProps { #pragma mark - Convenience Methods CascadedBorderWidths getBorderWidths() const; - BorderMetrics resolveBorderMetrics(const LayoutMetrics& layoutMetrics) const; - Transform resolveTransform(const LayoutMetrics& layoutMetrics) const; + BorderMetrics resolveBorderMetrics(const LayoutMetrics &layoutMetrics) const; + Transform resolveTransform(const LayoutMetrics &layoutMetrics) const; bool getClipsContentToBounds() const; - static Transform resolveTransform( - const Size& frameSize, - const Transform& transform, - const TransformOrigin& transformOrigin); + static Transform + resolveTransform(const Size &frameSize, const Transform &transform, const TransformOrigin &transformOrigin); #if RN_DEBUG_STRING_CONVERTIBLE SharedDebugStringConvertibleList getDebugProps() const override; diff --git a/packages/react-native/ReactCommon/react/renderer/components/view/BoxShadowPropsConversions.h b/packages/react-native/ReactCommon/react/renderer/components/view/BoxShadowPropsConversions.h index 89c7d241375..c3cb5434875 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/view/BoxShadowPropsConversions.h +++ b/packages/react-native/ReactCommon/react/renderer/components/view/BoxShadowPropsConversions.h @@ -22,10 +22,9 @@ namespace facebook::react { -inline void parseProcessedBoxShadow( - const PropsParserContext& context, - const RawValue& value, - std::vector& result) { +inline void +parseProcessedBoxShadow(const PropsParserContext &context, const RawValue &value, std::vector &result) +{ react_native_expect(value.hasType>()); if (!value.hasType>()) { result = {}; @@ -34,9 +33,8 @@ inline void parseProcessedBoxShadow( std::vector boxShadows{}; auto rawBoxShadows = static_cast>(value); - for (const auto& rawBoxShadow : rawBoxShadows) { - bool isMap = - rawBoxShadow.hasType>(); + for (const auto &rawBoxShadow : rawBoxShadows) { + bool isMap = rawBoxShadow.hasType>(); react_native_expect(isMap); if (!isMap) { // If any box shadow is malformed then we should not apply any of them @@ -45,8 +43,7 @@ inline void parseProcessedBoxShadow( return; } - auto rawBoxShadowMap = - static_cast>(rawBoxShadow); + auto rawBoxShadowMap = static_cast>(rawBoxShadow); BoxShadow boxShadow{}; auto offsetX = rawBoxShadowMap.find("offsetX"); react_native_expect(offsetX != rawBoxShadowMap.end()); @@ -106,11 +103,7 @@ inline void parseProcessedBoxShadow( auto color = rawBoxShadowMap.find("color"); if (color != rawBoxShadowMap.end()) { - fromRawValue( - context.contextContainer, - context.surfaceId, - color->second, - boxShadow.color); + fromRawValue(context.contextContainer, context.surfaceId, color->second, boxShadow.color); } boxShadows.push_back(boxShadow); @@ -119,12 +112,11 @@ inline void parseProcessedBoxShadow( result = boxShadows; } -inline std::optional fromCSSShadow(const CSSShadow& cssShadow) { +inline std::optional fromCSSShadow(const CSSShadow &cssShadow) +{ // TODO: handle non-px values - if (cssShadow.offsetX.unit != CSSLengthUnit::Px || - cssShadow.offsetY.unit != CSSLengthUnit::Px || - cssShadow.blurRadius.unit != CSSLengthUnit::Px || - cssShadow.spreadDistance.unit != CSSLengthUnit::Px) { + if (cssShadow.offsetX.unit != CSSLengthUnit::Px || cssShadow.offsetY.unit != CSSLengthUnit::Px || + cssShadow.blurRadius.unit != CSSLengthUnit::Px || cssShadow.spreadDistance.unit != CSSLengthUnit::Px) { return {}; } @@ -138,16 +130,15 @@ inline std::optional fromCSSShadow(const CSSShadow& cssShadow) { }; } -inline void parseUnprocessedBoxShadowString( - std::string&& value, - std::vector& result) { +inline void parseUnprocessedBoxShadowString(std::string &&value, std::vector &result) +{ auto boxShadowList = parseCSSProperty((std::string)value); if (!std::holds_alternative(boxShadowList)) { result = {}; return; } - for (const auto& cssShadow : std::get(boxShadowList)) { + for (const auto &cssShadow : std::get(boxShadowList)) { if (auto boxShadow = fromCSSShadow(cssShadow)) { result.push_back(*boxShadow); } else { @@ -157,9 +148,8 @@ inline void parseUnprocessedBoxShadowString( } } -inline std::optional parseBoxShadowRawValue( - const PropsParserContext& context, - const RawValue& value) { +inline std::optional parseBoxShadowRawValue(const PropsParserContext &context, const RawValue &value) +{ if (!value.hasType>()) { return {}; } @@ -235,10 +225,11 @@ inline std::optional parseBoxShadowRawValue( } inline void parseUnprocessedBoxShadowList( - const PropsParserContext& context, - std::vector&& value, - std::vector& result) { - for (const auto& rawValue : value) { + const PropsParserContext &context, + std::vector &&value, + std::vector &result) +{ + for (const auto &rawValue : value) { if (auto boxShadow = parseBoxShadowRawValue(context, rawValue)) { result.push_back(*boxShadow); } else { @@ -248,24 +239,20 @@ inline void parseUnprocessedBoxShadowList( } } -inline void parseUnprocessedBoxShadow( - const PropsParserContext& context, - const RawValue& value, - std::vector& result) { +inline void +parseUnprocessedBoxShadow(const PropsParserContext &context, const RawValue &value, std::vector &result) +{ if (value.hasType()) { parseUnprocessedBoxShadowString((std::string)value, result); } else if (value.hasType>()) { - parseUnprocessedBoxShadowList( - context, (std::vector)value, result); + parseUnprocessedBoxShadowList(context, (std::vector)value, result); } else { result = {}; } } -inline void fromRawValue( - const PropsParserContext& context, - const RawValue& value, - std::vector& result) { +inline void fromRawValue(const PropsParserContext &context, const RawValue &value, std::vector &result) +{ if (ReactNativeFeatureFlags::enableNativeCSSParsing()) { parseUnprocessedBoxShadow(context, value, result); } else { diff --git a/packages/react-native/ReactCommon/react/renderer/components/view/CSSConversions.h b/packages/react-native/ReactCommon/react/renderer/components/view/CSSConversions.h index 9ed428ae24d..de02ce2016f 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/view/CSSConversions.h +++ b/packages/react-native/ReactCommon/react/renderer/components/view/CSSConversions.h @@ -20,19 +20,19 @@ namespace facebook::react { -inline SharedColor fromCSSColor(const CSSColor& cssColor) { - return hostPlatformColorFromRGBA( - cssColor.r, cssColor.g, cssColor.b, cssColor.a); +inline SharedColor fromCSSColor(const CSSColor &cssColor) +{ + return hostPlatformColorFromRGBA(cssColor.r, cssColor.g, cssColor.b, cssColor.a); } -inline std::optional coerceAmount(const RawValue& value) { +inline std::optional coerceAmount(const RawValue &value) +{ if (value.hasType()) { return (Float)value; } if (value.hasType()) { - auto cssVal = - parseCSSProperty((std::string)value); + auto cssVal = parseCSSProperty((std::string)value); if (std::holds_alternative(cssVal)) { return std::get(cssVal).value; } else if (std::holds_alternative(cssVal)) { @@ -42,7 +42,8 @@ inline std::optional coerceAmount(const RawValue& value) { return {}; } -inline std::optional coerceAngle(const RawValue& value) { +inline std::optional coerceAngle(const RawValue &value) +{ if (value.hasType()) { return (Float)value; } @@ -56,9 +57,8 @@ inline std::optional coerceAngle(const RawValue& value) { return {}; } -inline SharedColor coerceColor( - const RawValue& value, - const PropsParserContext& context) { +inline SharedColor coerceColor(const RawValue &value, const PropsParserContext &context) +{ if (value.hasType()) { auto cssColor = parseCSSProperty((std::string)value); if (!std::holds_alternative(cssColor)) { @@ -72,7 +72,8 @@ inline SharedColor coerceColor( return color; } -inline std::optional coerceLength(const RawValue& value) { +inline std::optional coerceLength(const RawValue &value) +{ if (value.hasType()) { return (Float)value; } diff --git a/packages/react-native/ReactCommon/react/renderer/components/view/ConcreteViewShadowNode.h b/packages/react-native/ReactCommon/react/renderer/components/view/ConcreteViewShadowNode.h index 38ac9ea6d05..de54b71a810 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/view/ConcreteViewShadowNode.h +++ b/packages/react-native/ReactCommon/react/renderer/components/view/ConcreteViewShadowNode.h @@ -26,7 +26,7 @@ namespace facebook::react { * For example: , , but not , . */ template < - const char* concreteComponentName, + const char *concreteComponentName, typename ViewPropsT = ViewProps, typename ViewEventEmitterT = ViewEventEmitter, typename StateDataT = StateData> @@ -37,9 +37,7 @@ class ConcreteViewShadowNode : public ConcreteShadowNode< ViewPropsT, ViewEventEmitterT, StateDataT> { - static_assert( - std::is_base_of::value, - "ViewPropsT must be a descendant of ViewProps"); + static_assert(std::is_base_of::value, "ViewPropsT must be a descendant of ViewProps"); static_assert( std::is_base_of::value, "ViewPropsT must be a descendant of YogaStylableProps"); @@ -48,25 +46,21 @@ class ConcreteViewShadowNode : public ConcreteShadowNode< "ViewPropsT must be a descendant of AccessibilityProps"); public: - using BaseShadowNode = ConcreteShadowNode< - concreteComponentName, - YogaLayoutableShadowNode, - ViewPropsT, - ViewEventEmitterT, - StateDataT>; + using BaseShadowNode = + ConcreteShadowNode; ConcreteViewShadowNode( - const ShadowNodeFragment& fragment, - const ShadowNodeFamily::Shared& family, + const ShadowNodeFragment &fragment, + const ShadowNodeFamily::Shared &family, ShadowNodeTraits traits) - : BaseShadowNode(fragment, family, traits) { + : BaseShadowNode(fragment, family, traits) + { initialize(); } - ConcreteViewShadowNode( - const ShadowNode& sourceShadowNode, - const ShadowNodeFragment& fragment) - : BaseShadowNode(sourceShadowNode, fragment) { + ConcreteViewShadowNode(const ShadowNode &sourceShadowNode, const ShadowNodeFragment &fragment) + : BaseShadowNode(sourceShadowNode, fragment) + { initialize(); } @@ -74,7 +68,8 @@ class ConcreteViewShadowNode : public ConcreteShadowNode< using BaseShadowNode::BaseShadowNode; - static ShadowNodeTraits BaseTraits() { + static ShadowNodeTraits BaseTraits() + { auto traits = BaseShadowNode::BaseTraits(); traits.set(ShadowNodeTraits::Trait::ViewKind); traits.set(ShadowNodeTraits::Trait::FormsStackingContext); @@ -82,28 +77,28 @@ class ConcreteViewShadowNode : public ConcreteShadowNode< return traits; } - Transform getTransform() const override { + Transform getTransform() const override + { auto layoutMetrics = BaseShadowNode::getLayoutMetrics(); return BaseShadowNode::getConcreteProps().resolveTransform(layoutMetrics); } - bool canBeTouchTarget() const override { - auto pointerEvents = - BaseShadowNode::getConcreteProps().ViewProps::pointerEvents; - return pointerEvents == PointerEventsMode::Auto || - pointerEvents == PointerEventsMode::BoxOnly; + bool canBeTouchTarget() const override + { + auto pointerEvents = BaseShadowNode::getConcreteProps().ViewProps::pointerEvents; + return pointerEvents == PointerEventsMode::Auto || pointerEvents == PointerEventsMode::BoxOnly; } - bool canChildrenBeTouchTarget() const override { - auto pointerEvents = - BaseShadowNode::getConcreteProps().ViewProps::pointerEvents; - return pointerEvents == PointerEventsMode::Auto || - pointerEvents == PointerEventsMode::BoxNone; + bool canChildrenBeTouchTarget() const override + { + auto pointerEvents = BaseShadowNode::getConcreteProps().ViewProps::pointerEvents; + return pointerEvents == PointerEventsMode::Auto || pointerEvents == PointerEventsMode::BoxNone; } private: - void initialize() noexcept { - auto& props = BaseShadowNode::getConcreteProps(); + void initialize() noexcept + { + auto &props = BaseShadowNode::getConcreteProps(); if (props.yogaStyle.display() == yoga::Display::None) { BaseShadowNode::traits_.set(ShadowNodeTraits::Trait::Hidden); @@ -118,9 +113,7 @@ class ConcreteViewShadowNode : public ConcreteShadowNode< BaseShadowNode::orderIndex_ = 0; } - bool isKeyboardFocusable = - HostPlatformViewTraitsInitializer::isKeyboardFocusable(props) || - props.accessible; + bool isKeyboardFocusable = HostPlatformViewTraitsInitializer::isKeyboardFocusable(props) || props.accessible; if (isKeyboardFocusable) { BaseShadowNode::traits_.set(ShadowNodeTraits::Trait::KeyboardFocusable); diff --git a/packages/react-native/ReactCommon/react/renderer/components/view/FilterPropsConversions.h b/packages/react-native/ReactCommon/react/renderer/components/view/FilterPropsConversions.h index 8cea91e4fd0..0877a749a2d 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/view/FilterPropsConversions.h +++ b/packages/react-native/ReactCommon/react/renderer/components/view/FilterPropsConversions.h @@ -22,10 +22,9 @@ namespace facebook::react { -inline void parseProcessedFilter( - const PropsParserContext& context, - const RawValue& value, - std::vector& result) { +inline void +parseProcessedFilter(const PropsParserContext &context, const RawValue &value, std::vector &result) +{ react_native_expect(value.hasType>()); if (!value.hasType>()) { result = {}; @@ -34,9 +33,8 @@ inline void parseProcessedFilter( std::vector filter{}; auto rawFilter = static_cast>(value); - for (const auto& rawFilterPrimitive : rawFilter) { - bool isMap = - rawFilterPrimitive.hasType>(); + for (const auto &rawFilterPrimitive : rawFilter) { + bool isMap = rawFilterPrimitive.hasType>(); react_native_expect(isMap); if (!isMap) { // If a filter is malformed then we should not apply any of them which @@ -45,17 +43,12 @@ inline void parseProcessedFilter( return; } - auto rawFilterFunction = - static_cast>( - rawFilterPrimitive); + auto rawFilterFunction = static_cast>(rawFilterPrimitive); FilterFunction filterFunction{}; try { - filterFunction.type = - filterTypeFromString(rawFilterFunction.begin()->first); + filterFunction.type = filterTypeFromString(rawFilterFunction.begin()->first); if (filterFunction.type == FilterType::DropShadow) { - auto rawDropShadow = - static_cast>( - rawFilterFunction.begin()->second); + auto rawDropShadow = static_cast>(rawFilterFunction.begin()->second); DropShadowParams dropShadowParams{}; auto offsetX = rawDropShadow.find("offsetX"); @@ -97,11 +90,7 @@ inline void parseProcessedFilter( auto color = rawDropShadow.find("color"); if (color != rawDropShadow.end()) { - fromRawValue( - context.contextContainer, - context.surfaceId, - color->second, - dropShadowParams.color); + fromRawValue(context.contextContainer, context.surfaceId, color->second, dropShadowParams.color); } filterFunction.parameters = dropShadowParams; @@ -109,7 +98,7 @@ inline void parseProcessedFilter( filterFunction.parameters = (float)rawFilterFunction.begin()->second; } filter.push_back(std::move(filterFunction)); - } catch (const std::exception& e) { + } catch (const std::exception &e) { LOG(ERROR) << "Could not parse FilterFunction: " << e.what(); result = {}; return; @@ -119,10 +108,10 @@ inline void parseProcessedFilter( result = filter; } -inline FilterType filterTypeFromVariant( - const CSSFilterFunctionVariant& filter) { +inline FilterType filterTypeFromVariant(const CSSFilterFunctionVariant &filter) +{ return std::visit( - [](auto&& filter) -> FilterType { + [](auto &&filter) -> FilterType { using FilterT = std::decay_t; if constexpr (std::is_same_v) { @@ -159,10 +148,10 @@ inline FilterType filterTypeFromVariant( filter); } -inline std::optional fromCSSFilter( - const CSSFilterFunctionVariant& cssFilter) { +inline std::optional fromCSSFilter(const CSSFilterFunctionVariant &cssFilter) +{ return std::visit( - [&](auto&& filter) -> std::optional { + [&](auto &&filter) -> std::optional { using FilterT = std::decay_t; if constexpr (std::is_same_v) { @@ -178,8 +167,7 @@ inline std::optional fromCSSFilter( if constexpr (std::is_same_v) { // TODO: support non-px values - if (filter.offsetX.unit != CSSLengthUnit::Px || - filter.offsetY.unit != CSSLengthUnit::Px || + if (filter.offsetX.unit != CSSLengthUnit::Px || filter.offsetY.unit != CSSLengthUnit::Px || filter.standardDeviation.unit != CSSLengthUnit::Px) { return {}; } @@ -195,12 +183,9 @@ inline std::optional fromCSSFilter( } if constexpr ( - std::is_same_v || - std::is_same_v || - std::is_same_v || - std::is_same_v || - std::is_same_v || - std::is_same_v || + std::is_same_v || std::is_same_v || + std::is_same_v || std::is_same_v || + std::is_same_v || std::is_same_v || std::is_same_v) { return FilterFunction{ .type = filterTypeFromVariant(cssFilter), @@ -218,16 +203,15 @@ inline std::optional fromCSSFilter( cssFilter); } -inline void parseUnprocessedFilterString( - std::string&& value, - std::vector& result) { +inline void parseUnprocessedFilterString(std::string &&value, std::vector &result) +{ auto filterList = parseCSSProperty((std::string)value); if (!std::holds_alternative(filterList)) { result = {}; return; } - for (const auto& cssFilter : std::get(filterList)) { + for (const auto &cssFilter : std::get(filterList)) { if (auto filter = fromCSSFilter(cssFilter)) { result.push_back(*filter); } else { @@ -237,12 +221,10 @@ inline void parseUnprocessedFilterString( } } -inline std::optional parseDropShadow( - const PropsParserContext& context, - const RawValue& value) { +inline std::optional parseDropShadow(const PropsParserContext &context, const RawValue &value) +{ if (value.hasType()) { - auto val = parseCSSProperty( - std::string("drop-shadow(") + (std::string)value + ")"); + auto val = parseCSSProperty(std::string("drop-shadow(") + (std::string)value + ")"); if (std::holds_alternative(val)) { return fromCSSFilter(std::get(val)); } @@ -252,8 +234,7 @@ inline std::optional parseDropShadow( if (!value.hasType>()) { return {}; } - auto rawDropShadow = - static_cast>(value); + auto rawDropShadow = static_cast>(value); DropShadowParams dropShadowParams{}; @@ -281,8 +262,7 @@ inline std::optional parseDropShadow( auto standardDeviation = rawDropShadow.find("standardDeviation"); if (standardDeviation != rawDropShadow.end()) { - if (auto parsedStandardDeviation = - coerceLength(standardDeviation->second)) { + if (auto parsedStandardDeviation = coerceLength(standardDeviation->second)) { if (*parsedStandardDeviation < 0.0f) { return {}; } @@ -301,24 +281,21 @@ inline std::optional parseDropShadow( } } - return FilterFunction{ - .type = FilterType::DropShadow, .parameters = dropShadowParams}; + return FilterFunction{.type = FilterType::DropShadow, .parameters = dropShadowParams}; } -inline std::optional parseFilterRawValue( - const PropsParserContext& context, - const RawValue& value) { +inline std::optional parseFilterRawValue(const PropsParserContext &context, const RawValue &value) +{ if (!value.hasType>()) { return {}; } - auto rawFilter = - static_cast>(value); + auto rawFilter = static_cast>(value); if (rawFilter.size() != 1) { return {}; } - const auto& filterKey = rawFilter.begin()->first; + const auto &filterKey = rawFilter.begin()->first; if (filterKey == "drop-shadow") { return parseDropShadow(context, rawFilter.begin()->second); @@ -332,8 +309,7 @@ inline std::optional parseFilterRawValue( return {}; } else if (filterKey == "hue-rotate") { if (auto angle = coerceAngle(rawFilter.begin()->second)) { - return FilterFunction{ - .type = FilterType::HueRotate, .parameters = *angle}; + return FilterFunction{.type = FilterType::HueRotate, .parameters = *angle}; } return {}; } else { @@ -341,18 +317,18 @@ inline std::optional parseFilterRawValue( if (*amount < 0.0f) { return {}; } - return FilterFunction{ - .type = filterTypeFromString(filterKey), .parameters = *amount}; + return FilterFunction{.type = filterTypeFromString(filterKey), .parameters = *amount}; } return {}; } } inline void parseUnprocessedFilterList( - const PropsParserContext& context, - std::vector&& value, - std::vector& result) { - for (const auto& rawValue : value) { + const PropsParserContext &context, + std::vector &&value, + std::vector &result) +{ + for (const auto &rawValue : value) { if (auto Filter = parseFilterRawValue(context, rawValue)) { result.push_back(*Filter); } else { @@ -362,10 +338,9 @@ inline void parseUnprocessedFilterList( } } -inline void parseUnprocessedFilter( - const PropsParserContext& context, - const RawValue& value, - std::vector& result) { +inline void +parseUnprocessedFilter(const PropsParserContext &context, const RawValue &value, std::vector &result) +{ if (value.hasType()) { parseUnprocessedFilterString((std::string)value, result); } else if (value.hasType>()) { @@ -375,10 +350,8 @@ inline void parseUnprocessedFilter( } } -inline void fromRawValue( - const PropsParserContext& context, - const RawValue& value, - std::vector& result) { +inline void fromRawValue(const PropsParserContext &context, const RawValue &value, std::vector &result) +{ if (ReactNativeFeatureFlags::enableNativeCSSParsing()) { parseUnprocessedFilter(context, value, result); } else { diff --git a/packages/react-native/ReactCommon/react/renderer/components/view/LayoutConformanceComponentDescriptor.h b/packages/react-native/ReactCommon/react/renderer/components/view/LayoutConformanceComponentDescriptor.h index fdeae8854e7..39250be8df8 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/view/LayoutConformanceComponentDescriptor.h +++ b/packages/react-native/ReactCommon/react/renderer/components/view/LayoutConformanceComponentDescriptor.h @@ -12,7 +12,6 @@ namespace facebook::react { -using LayoutConformanceComponentDescriptor = - ConcreteComponentDescriptor; +using LayoutConformanceComponentDescriptor = ConcreteComponentDescriptor; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/components/view/LayoutConformanceProps.h b/packages/react-native/ReactCommon/react/renderer/components/view/LayoutConformanceProps.h index 7425ece1123..6e80c3508e6 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/view/LayoutConformanceProps.h +++ b/packages/react-native/ReactCommon/react/renderer/components/view/LayoutConformanceProps.h @@ -21,16 +21,13 @@ struct LayoutConformanceProps final : public YogaStylableProps { LayoutConformanceProps() = default; LayoutConformanceProps( - const PropsParserContext& context, - const LayoutConformanceProps& sourceProps, - const RawProps& rawProps) + const PropsParserContext &context, + const LayoutConformanceProps &sourceProps, + const RawProps &rawProps) : YogaStylableProps(context, sourceProps, rawProps), - mode{convertRawProp( - context, - rawProps, - "mode", - mode, - LayoutConformance::Strict)} {} + mode{convertRawProp(context, rawProps, "mode", mode, LayoutConformance::Strict)} + { + } }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/components/view/LayoutConformanceShadowNode.h b/packages/react-native/ReactCommon/react/renderer/components/view/LayoutConformanceShadowNode.h index 2f1cfdd89eb..9621c6295b1 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/view/LayoutConformanceShadowNode.h +++ b/packages/react-native/ReactCommon/react/renderer/components/view/LayoutConformanceShadowNode.h @@ -14,14 +14,12 @@ namespace facebook::react { // NOLINTNEXTLINE(facebook-hte-CArray,modernize-avoid-c-arrays) -constexpr const char LayoutConformanceShadowNodeComponentName[] = - "LayoutConformance"; +constexpr const char LayoutConformanceShadowNodeComponentName[] = "LayoutConformance"; -class LayoutConformanceShadowNode final - : public ConcreteShadowNode< - LayoutConformanceShadowNodeComponentName, - YogaLayoutableShadowNode, - LayoutConformanceProps> { +class LayoutConformanceShadowNode final : public ConcreteShadowNode< + LayoutConformanceShadowNodeComponentName, + YogaLayoutableShadowNode, + LayoutConformanceProps> { public: using ConcreteShadowNode::ConcreteShadowNode; }; diff --git a/packages/react-native/ReactCommon/react/renderer/components/view/PointerEvent.h b/packages/react-native/ReactCommon/react/renderer/components/view/PointerEvent.h index a594e6b94cd..158d73d2096 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/view/PointerEvent.h +++ b/packages/react-native/ReactCommon/react/renderer/components/view/PointerEvent.h @@ -114,15 +114,15 @@ struct PointerEvent : public EventPayload { /* * EventPayload implementations */ - jsi::Value asJSIValue(jsi::Runtime& runtime) const override; + jsi::Value asJSIValue(jsi::Runtime &runtime) const override; EventPayloadType getType() const override; }; #if RN_DEBUG_STRING_CONVERTIBLE -std::string getDebugName(const PointerEvent& pointerEvent); +std::string getDebugName(const PointerEvent &pointerEvent); std::vector getDebugProps( - const PointerEvent& pointerEvent, + const PointerEvent &pointerEvent, DebugStringConvertibleOptions options); #endif diff --git a/packages/react-native/ReactCommon/react/renderer/components/view/TouchEvent.h b/packages/react-native/ReactCommon/react/renderer/components/view/TouchEvent.h index 6010f0e21d8..3907869831e 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/view/TouchEvent.h +++ b/packages/react-native/ReactCommon/react/renderer/components/view/TouchEvent.h @@ -41,9 +41,9 @@ struct TouchEvent { #if RN_DEBUG_STRING_CONVERTIBLE -std::string getDebugName(const TouchEvent& touchEvent); +std::string getDebugName(const TouchEvent &touchEvent); std::vector getDebugProps( - const TouchEvent& touchEvent, + const TouchEvent &touchEvent, DebugStringConvertibleOptions options); #endif diff --git a/packages/react-native/ReactCommon/react/renderer/components/view/TouchEventEmitter.h b/packages/react-native/ReactCommon/react/renderer/components/view/TouchEventEmitter.h index e7dcfa7d84a..74c20029322 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/view/TouchEventEmitter.h +++ b/packages/react-native/ReactCommon/react/renderer/components/view/TouchEventEmitter.h @@ -42,14 +42,8 @@ class TouchEventEmitter : public EventEmitter { void onLostPointerCapture(PointerEvent event) const; private: - void dispatchTouchEvent( - std::string type, - TouchEvent event, - RawEvent::Category category) const; - void dispatchPointerEvent( - std::string type, - PointerEvent event, - RawEvent::Category category) const; + void dispatchTouchEvent(std::string type, TouchEvent event, RawEvent::Category category) const; + void dispatchPointerEvent(std::string type, PointerEvent event, RawEvent::Category category) const; }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/components/view/ViewComponentDescriptor.h b/packages/react-native/ReactCommon/react/renderer/components/view/ViewComponentDescriptor.h index e2581d31168..e1958134b4c 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/view/ViewComponentDescriptor.h +++ b/packages/react-native/ReactCommon/react/renderer/components/view/ViewComponentDescriptor.h @@ -12,11 +12,12 @@ namespace facebook::react { -class ViewComponentDescriptor - : public ConcreteComponentDescriptor { +class ViewComponentDescriptor : public ConcreteComponentDescriptor { public: - ViewComponentDescriptor(const ComponentDescriptorParameters& parameters) - : ConcreteComponentDescriptor(parameters) {} + ViewComponentDescriptor(const ComponentDescriptorParameters ¶meters) + : ConcreteComponentDescriptor(parameters) + { + } }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/components/view/ViewPropsInterpolation.h b/packages/react-native/ReactCommon/react/renderer/components/view/ViewPropsInterpolation.h index c9ad50ca5b8..55bf085c7d2 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/view/ViewPropsInterpolation.h +++ b/packages/react-native/ReactCommon/react/renderer/components/view/ViewPropsInterpolation.h @@ -23,24 +23,19 @@ namespace facebook::react { */ static inline void interpolateViewProps( Float animationProgress, - const Props::Shared& oldPropsShared, - const Props::Shared& newPropsShared, - Props::Shared& interpolatedPropsShared, - const Size& size) { - const ViewProps* oldViewProps = - static_cast(oldPropsShared.get()); - const ViewProps* newViewProps = - static_cast(newPropsShared.get()); - ViewProps* interpolatedProps = const_cast( - static_cast(interpolatedPropsShared.get())); + const Props::Shared &oldPropsShared, + const Props::Shared &newPropsShared, + Props::Shared &interpolatedPropsShared, + const Size &size) +{ + const ViewProps *oldViewProps = static_cast(oldPropsShared.get()); + const ViewProps *newViewProps = static_cast(newPropsShared.get()); + ViewProps *interpolatedProps = const_cast(static_cast(interpolatedPropsShared.get())); - interpolatedProps->opacity = oldViewProps->opacity + - (newViewProps->opacity - oldViewProps->opacity) * animationProgress; - interpolatedProps->transform = Transform::Interpolate( - animationProgress, - oldViewProps->transform, - newViewProps->transform, - size); + interpolatedProps->opacity = + oldViewProps->opacity + (newViewProps->opacity - oldViewProps->opacity) * animationProgress; + interpolatedProps->transform = + Transform::Interpolate(animationProgress, oldViewProps->transform, newViewProps->transform, size); // Android uses RawProps, not props, to update props on the platform... // Since interpolated props don't interpolate at all using RawProps, we need @@ -53,8 +48,7 @@ static inline void interpolateViewProps( if (!interpolatedProps->rawProps.isNull()) { interpolatedProps->rawProps["opacity"] = interpolatedProps->opacity; - interpolatedProps->rawProps["transform"] = - (folly::dynamic)interpolatedProps->transform; + interpolatedProps->rawProps["transform"] = (folly::dynamic)interpolatedProps->transform; } #endif } diff --git a/packages/react-native/ReactCommon/react/renderer/components/view/ViewShadowNode.cpp b/packages/react-native/ReactCommon/react/renderer/components/view/ViewShadowNode.cpp index d61dc42d486..641f544bee6 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/view/ViewShadowNode.cpp +++ b/packages/react-native/ReactCommon/react/renderer/components/view/ViewShadowNode.cpp @@ -18,7 +18,7 @@ ViewShadowNodeProps::ViewShadowNodeProps( const PropsParserContext& context, const ViewShadowNodeProps& sourceProps, const RawProps& rawProps) - : ViewProps(context, sourceProps, rawProps){}; + : ViewProps(context, sourceProps, rawProps) {}; ViewShadowNode::ViewShadowNode( const ShadowNodeFragment& fragment, diff --git a/packages/react-native/ReactCommon/react/renderer/components/view/ViewShadowNode.h b/packages/react-native/ReactCommon/react/renderer/components/view/ViewShadowNode.h index 87218bbd518..b3195934440 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/view/ViewShadowNode.h +++ b/packages/react-native/ReactCommon/react/renderer/components/view/ViewShadowNode.h @@ -22,27 +22,19 @@ class ViewShadowNodeProps final : public ViewProps { public: ViewShadowNodeProps() = default; ViewShadowNodeProps( - const PropsParserContext& context, - const ViewShadowNodeProps& sourceProps, - const RawProps& rawProps); + const PropsParserContext &context, + const ViewShadowNodeProps &sourceProps, + const RawProps &rawProps); }; /* * `ShadowNode` for component. */ -class ViewShadowNode final : public ConcreteViewShadowNode< - ViewComponentName, - ViewShadowNodeProps, - ViewEventEmitter> { +class ViewShadowNode final : public ConcreteViewShadowNode { public: - ViewShadowNode( - const ShadowNodeFragment& fragment, - const ShadowNodeFamily::Shared& family, - ShadowNodeTraits traits); + ViewShadowNode(const ShadowNodeFragment &fragment, const ShadowNodeFamily::Shared &family, ShadowNodeTraits traits); - ViewShadowNode( - const ShadowNode& sourceShadowNode, - const ShadowNodeFragment& fragment); + ViewShadowNode(const ShadowNode &sourceShadowNode, const ShadowNodeFragment &fragment); private: void initialize() noexcept; diff --git a/packages/react-native/ReactCommon/react/renderer/components/view/YogaLayoutableShadowNode.cpp b/packages/react-native/ReactCommon/react/renderer/components/view/YogaLayoutableShadowNode.cpp index bfe2c82b9a3..bd327efc351 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/view/YogaLayoutableShadowNode.cpp +++ b/packages/react-native/ReactCommon/react/renderer/components/view/YogaLayoutableShadowNode.cpp @@ -97,8 +97,9 @@ YogaLayoutableShadowNode::YogaLayoutableShadowNode( const ShadowNodeFragment& fragment) : LayoutableShadowNode(sourceShadowNode, fragment), yogaConfig_(FabricDefaultYogaLog), - yogaNode_(static_cast(sourceShadowNode) - .yogaNode_) { + yogaNode_( + static_cast(sourceShadowNode) + .yogaNode_) { // Note, cloned `yoga::Node` instance (copied using copy-constructor) inherits // dirty flag, measure function, and other properties being set originally in // the `YogaLayoutableShadowNode` constructor above. diff --git a/packages/react-native/ReactCommon/react/renderer/components/view/YogaLayoutableShadowNode.h b/packages/react-native/ReactCommon/react/renderer/components/view/YogaLayoutableShadowNode.h index 977416bc1c5..25714d5f489 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/view/YogaLayoutableShadowNode.h +++ b/packages/react-native/ReactCommon/react/renderer/components/view/YogaLayoutableShadowNode.h @@ -29,17 +29,13 @@ class YogaLayoutableShadowNode : public LayoutableShadowNode { #pragma mark - Constructors YogaLayoutableShadowNode( - const ShadowNodeFragment& fragment, - const ShadowNodeFamily::Shared& family, + const ShadowNodeFragment &fragment, + const ShadowNodeFamily::Shared &family, ShadowNodeTraits traits); - YogaLayoutableShadowNode( - const ShadowNode& sourceShadowNode, - const ShadowNodeFragment& fragment); + YogaLayoutableShadowNode(const ShadowNode &sourceShadowNode, const ShadowNodeFragment &fragment); - void completeClone( - const ShadowNode& sourceShadowNode, - const ShadowNodeFragment& fragment) override; + void completeClone(const ShadowNode &sourceShadowNode, const ShadowNodeFragment &fragment) override; #pragma mark - Mutating Methods @@ -49,10 +45,10 @@ class YogaLayoutableShadowNode : public LayoutableShadowNode { */ void enableMeasurement(); - void appendChild(const std::shared_ptr& child) override; + void appendChild(const std::shared_ptr &child) override; void replaceChild( - const ShadowNode& oldChild, - const std::shared_ptr& newChild, + const ShadowNode &oldChild, + const std::shared_ptr &newChild, size_t suggestedIndex = SIZE_MAX) override; void updateYogaChildren(); @@ -80,9 +76,7 @@ class YogaLayoutableShadowNode : public LayoutableShadowNode { * Computes layout using Yoga layout engine. * See `LayoutableShadowNode` for more details. */ - void layoutTree( - LayoutContext layoutContext, - LayoutConstraints layoutConstraints) override; + void layoutTree(LayoutContext layoutContext, LayoutConstraints layoutConstraints) override; void layout(LayoutContext layoutContext) override; @@ -93,9 +87,8 @@ class YogaLayoutableShadowNode : public LayoutableShadowNode { * Subclasses which provide MeasurableYogaNode may override to signal that a * new ShadowNode revision does not need to invalidate existing measurements. */ - virtual bool shouldNewRevisionDirtyMeasurement( - const ShadowNode& sourceShadowNode, - const ShadowNodeFragment& fragment) const; + virtual bool shouldNewRevisionDirtyMeasurement(const ShadowNode &sourceShadowNode, const ShadowNodeFragment &fragment) + const; /* * Yoga config associated (only) with this particular node. @@ -124,14 +117,14 @@ class YogaLayoutableShadowNode : public LayoutableShadowNode { * Return true if child's yogaNode's owner is this->yogaNode_. Otherwise * returns false. */ - bool doesOwn(const YogaLayoutableShadowNode& child) const; + bool doesOwn(const YogaLayoutableShadowNode &child) const; /* * Appends a Yoga node to the Yoga node associated with this node. * The method does *not* do anything besides that (no cloning or `owner` field * adjustment). */ - void appendYogaChild(const YogaLayoutableShadowNode::Shared& childNode); + void appendYogaChild(const YogaLayoutableShadowNode::Shared &childNode); /* * Makes the child node with a given `index` (and Yoga node associated with) a @@ -144,10 +137,7 @@ class YogaLayoutableShadowNode : public LayoutableShadowNode { * ShadowTree has been constructed, but before it has been is laid out or * committed. */ - void configureYogaTree( - float pointScaleFactor, - YGErrata defaultErrata, - bool swapLeftAndRight); + void configureYogaTree(float pointScaleFactor, YGErrata defaultErrata, bool swapLeftAndRight); /** * Return an errata based on a `layoutConformance` prop if given, otherwise @@ -158,27 +148,19 @@ class YogaLayoutableShadowNode : public LayoutableShadowNode { /** * Replcaes a child with a mutable clone of itself, returning the clone. */ - YogaLayoutableShadowNode& cloneChildInPlace(size_t layoutableChildIndex); + YogaLayoutableShadowNode &cloneChildInPlace(size_t layoutableChildIndex); - static yoga::Config& initializeYogaConfig( - yoga::Config& config, - YGConfigConstRef previousConfig = nullptr); - static YGNodeRef yogaNodeCloneCallbackConnector( - YGNodeConstRef oldYogaNode, - YGNodeConstRef parentYogaNode, - size_t childIndex); + static yoga::Config &initializeYogaConfig(yoga::Config &config, YGConfigConstRef previousConfig = nullptr); + static YGNodeRef + yogaNodeCloneCallbackConnector(YGNodeConstRef oldYogaNode, YGNodeConstRef parentYogaNode, size_t childIndex); static YGSize yogaNodeMeasureCallbackConnector( YGNodeConstRef yogaNode, float width, YGMeasureMode widthMode, float height, YGMeasureMode heightMode); - static float yogaNodeBaselineCallbackConnector( - YGNodeConstRef yogaNode, - float width, - float height); - static YogaLayoutableShadowNode& shadowNodeFromContext( - YGNodeConstRef yogaNode); + static float yogaNodeBaselineCallbackConnector(YGNodeConstRef yogaNode, float width, float height); + static YogaLayoutableShadowNode &shadowNodeFromContext(YGNodeConstRef yogaNode); #pragma mark - RTL Legacy Autoflip @@ -215,9 +197,7 @@ class YogaLayoutableShadowNode : public LayoutableShadowNode { * Combine a base yoga::Style with aliased properties which should be * flattened into it. E.g. reconciling "marginInlineStart" and "marginStart". */ - static yoga::Style applyAliasedProps( - const yoga::Style& baseStyle, - const YogaStylableProps& props); + static yoga::Style applyAliasedProps(const yoga::Style &baseStyle, const YogaStylableProps &props); #pragma mark - Consistency Ensuring Helpers diff --git a/packages/react-native/ReactCommon/react/renderer/components/view/YogaStylableProps.h b/packages/react-native/ReactCommon/react/renderer/components/view/YogaStylableProps.h index 1f7dfa908a9..6febf08d5ce 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/view/YogaStylableProps.h +++ b/packages/react-native/ReactCommon/react/renderer/components/view/YogaStylableProps.h @@ -19,17 +19,13 @@ class YogaStylableProps : public Props { public: YogaStylableProps() = default; YogaStylableProps( - const PropsParserContext& context, - const YogaStylableProps& sourceProps, - const RawProps& rawProps, - const std::function& filterObjectKeys = - nullptr); + const PropsParserContext &context, + const YogaStylableProps &sourceProps, + const RawProps &rawProps, + const std::function &filterObjectKeys = nullptr); - void setProp( - const PropsParserContext& context, - RawPropsPropNameHash hash, - const char* propName, - const RawValue& value); + void + setProp(const PropsParserContext &context, RawPropsPropNameHash hash, const char *propName, const RawValue &value); #pragma mark - Props yoga::Style yogaStyle{}; @@ -71,9 +67,9 @@ class YogaStylableProps : public Props { private: void convertRawPropAliases( - const PropsParserContext& context, - const YogaStylableProps& sourceProps, - const RawProps& rawProps); + const PropsParserContext &context, + const YogaStylableProps &sourceProps, + const RawProps &rawProps); }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/components/view/accessibilityPropsConversions.h b/packages/react-native/ReactCommon/react/renderer/components/view/accessibilityPropsConversions.h index 306ab60baf0..de6408c4621 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/view/accessibilityPropsConversions.h +++ b/packages/react-native/ReactCommon/react/renderer/components/view/accessibilityPropsConversions.h @@ -20,7 +20,8 @@ namespace facebook::react { -inline void fromString(const std::string& string, AccessibilityTraits& result) { +inline void fromString(const std::string &string, AccessibilityTraits &result) +{ if (string == "none") { result = AccessibilityTraits::None; return; @@ -108,10 +109,8 @@ inline void fromString(const std::string& string, AccessibilityTraits& result) { result = AccessibilityTraits::None; } -inline void fromRawValue( - const PropsParserContext& context, - const RawValue& value, - AccessibilityTraits& result) { +inline void fromRawValue(const PropsParserContext &context, const RawValue &value, AccessibilityTraits &result) +{ if (value.hasType()) { fromString((std::string)value, result); return; @@ -122,7 +121,7 @@ inline void fromRawValue( react_native_expect(value.hasType>()); if (value.hasType>()) { auto items = (std::vector)value; - for (auto& item : items) { + for (auto &item : items) { AccessibilityTraits itemAccessibilityTraits; fromString(item, itemAccessibilityTraits); result = result | itemAccessibilityTraits; @@ -132,10 +131,8 @@ inline void fromRawValue( } } -inline void fromRawValue( - const PropsParserContext& context, - const RawValue& value, - AccessibilityState& result) { +inline void fromRawValue(const PropsParserContext &context, const RawValue &value, AccessibilityState &result) +{ auto map = (std::unordered_map)value; auto selected = map.find("selected"); if (selected != map.end()) { @@ -173,8 +170,8 @@ inline void fromRawValue( } } -inline std::string toString( - const ImportantForAccessibility& importantForAccessibility) { +inline std::string toString(const ImportantForAccessibility &importantForAccessibility) +{ switch (importantForAccessibility) { case ImportantForAccessibility::Auto: return "auto"; @@ -187,10 +184,8 @@ inline std::string toString( } } -inline void fromRawValue( - const PropsParserContext& context, - const RawValue& value, - ImportantForAccessibility& result) { +inline void fromRawValue(const PropsParserContext &context, const RawValue &value, ImportantForAccessibility &result) +{ result = ImportantForAccessibility::Auto; react_native_expect(value.hasType()); if (value.hasType()) { @@ -212,10 +207,8 @@ inline void fromRawValue( } } -inline void fromRawValue( - const PropsParserContext& context, - const RawValue& value, - AccessibilityAction& result) { +inline void fromRawValue(const PropsParserContext &context, const RawValue &value, AccessibilityAction &result) +{ auto map = (std::unordered_map)value; auto name = map.find("name"); @@ -232,10 +225,8 @@ inline void fromRawValue( } } -inline void fromRawValue( - const PropsParserContext& /*unused*/, - const RawValue& value, - AccessibilityValue& result) { +inline void fromRawValue(const PropsParserContext & /*unused*/, const RawValue &value, AccessibilityValue &result) +{ auto map = (std::unordered_map)value; auto min = map.find("min"); @@ -267,10 +258,8 @@ inline void fromRawValue( } } -inline void fromRawValue( - const PropsParserContext& context, - const RawValue& value, - AccessibilityLabelledBy& result) { +inline void fromRawValue(const PropsParserContext &context, const RawValue &value, AccessibilityLabelledBy &result) +{ if (value.hasType()) { result.value.push_back((std::string)value); } else if (value.hasType>()) { @@ -278,10 +267,8 @@ inline void fromRawValue( } } -inline void fromRawValue( - const PropsParserContext& context, - const RawValue& value, - AccessibilityLiveRegion& result) { +inline void fromRawValue(const PropsParserContext &context, const RawValue &value, AccessibilityLiveRegion &result) +{ result = AccessibilityLiveRegion::None; react_native_expect(value.hasType()); if (value.hasType()) { @@ -301,7 +288,8 @@ inline void fromRawValue( } } -inline std::string toString(const AccessibilityRole& accessibilityRole) { +inline std::string toString(const AccessibilityRole &accessibilityRole) +{ switch (accessibilityRole) { case AccessibilityRole::None: return "none"; @@ -391,10 +379,8 @@ inline std::string toString(const AccessibilityRole& accessibilityRole) { return "none"; } -inline void fromRawValue( - const PropsParserContext& context, - const RawValue& value, - AccessibilityRole& result) { +inline void fromRawValue(const PropsParserContext &context, const RawValue &value, AccessibilityRole &result) +{ react_native_expect(value.hasType()); if (value.hasType()) { auto string = (std::string)value; @@ -491,7 +477,8 @@ inline void fromRawValue( result = AccessibilityRole::None; } -inline std::string toString(const Role& role) { +inline std::string toString(const Role &role) +{ switch (role) { case Role::Alert: return "alert"; @@ -631,10 +618,8 @@ inline std::string toString(const Role& role) { return "none"; } -inline void fromRawValue( - const PropsParserContext& context, - const RawValue& value, - Role& result) { +inline void fromRawValue(const PropsParserContext &context, const RawValue &value, Role &result) +{ react_native_expect(value.hasType()); if (value.hasType()) { auto string = (std::string)value; @@ -783,7 +768,8 @@ inline void fromRawValue( result = Role::None; } -inline std::string toString(AccessibilityLiveRegion accessibilityLiveRegion) { +inline std::string toString(AccessibilityLiveRegion accessibilityLiveRegion) +{ switch (accessibilityLiveRegion) { case AccessibilityLiveRegion::None: return "none"; @@ -795,7 +781,8 @@ inline std::string toString(AccessibilityLiveRegion accessibilityLiveRegion) { } #if RN_DEBUG_STRING_CONVERTIBLE -inline std::string toString(AccessibilityState::CheckedState state) { +inline std::string toString(AccessibilityState::CheckedState state) +{ switch (state) { case AccessibilityState::Unchecked: return "Unchecked"; @@ -808,7 +795,8 @@ inline std::string toString(AccessibilityState::CheckedState state) { } } -inline std::string toString(const AccessibilityAction& accessibilityAction) { +inline std::string toString(const AccessibilityAction &accessibilityAction) +{ std::string result = accessibilityAction.name; if (accessibilityAction.label.has_value()) { result += ": '" + accessibilityAction.label.value() + "'"; @@ -816,8 +804,8 @@ inline std::string toString(const AccessibilityAction& accessibilityAction) { return result; } -inline std::string toString( - std::vector accessibilityActions) { +inline std::string toString(std::vector accessibilityActions) +{ std::string result = "["; for (size_t i = 0; i < accessibilityActions.size(); i++) { result += toString(accessibilityActions[i]); @@ -829,11 +817,10 @@ inline std::string toString( return result; } -inline std::string toString(const AccessibilityState& accessibilityState) { - return "{disabled:" + toString(accessibilityState.disabled) + - ",selected:" + toString(accessibilityState.selected) + - ",checked:" + toString(accessibilityState.checked) + - ",busy:" + toString(accessibilityState.busy) + +inline std::string toString(const AccessibilityState &accessibilityState) +{ + return "{disabled:" + toString(accessibilityState.disabled) + ",selected:" + toString(accessibilityState.selected) + + ",checked:" + toString(accessibilityState.checked) + ",busy:" + toString(accessibilityState.busy) + ",expanded:" + toString(accessibilityState.expanded) + "}"; } #endif diff --git a/packages/react-native/ReactCommon/react/renderer/components/view/conversions.h b/packages/react-native/ReactCommon/react/renderer/components/view/conversions.h index 7b21ed155f8..b39e27fe4a8 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/view/conversions.h +++ b/packages/react-native/ReactCommon/react/renderer/components/view/conversions.h @@ -47,10 +47,9 @@ namespace facebook::react { * values have special "no limit" meaning in Yoga, therefore ` YGUndefined` * usually corresponds to `Infinity` value. */ -inline Float floatFromYogaFloat(float value) { - static_assert( - YGUndefined != YGUndefined, - "The code of this function assumes that YGUndefined is NaN."); +inline Float floatFromYogaFloat(float value) +{ + static_assert(YGUndefined != YGUndefined, "The code of this function assumes that YGUndefined is NaN."); if (std::isnan(value) /* means: `value == YGUndefined` */) { return std::numeric_limits::infinity(); } @@ -58,7 +57,8 @@ inline Float floatFromYogaFloat(float value) { return (Float)value; } -inline float yogaFloatFromFloat(Float value) { +inline float yogaFloatFromFloat(Float value) +{ if (!std::isfinite(value)) { return YGUndefined; } @@ -76,7 +76,8 @@ inline float yogaFloatFromFloat(Float value) { * which usually has some special corresponding representation for an empty * value. */ -inline Float floatFromYogaOptionalFloat(yoga::FloatOptional value) { +inline Float floatFromYogaOptionalFloat(yoga::FloatOptional value) +{ if (value.isUndefined()) { return std::numeric_limits::quiet_NaN(); } @@ -84,7 +85,8 @@ inline Float floatFromYogaOptionalFloat(yoga::FloatOptional value) { return floatFromYogaFloat(value.unwrap()); } -inline yoga::FloatOptional yogaOptionalFloatFromFloat(Float value) { +inline yoga::FloatOptional yogaOptionalFloatFromFloat(Float value) +{ if (std::isnan(value)) { return yoga::FloatOptional(); } @@ -93,22 +95,21 @@ inline yoga::FloatOptional yogaOptionalFloatFromFloat(Float value) { } inline std::optional optionalFloatFromYogaValue( - const yoga::Style::Length& length, - std::optional base = {}) { + const yoga::Style::Length &length, + std::optional base = {}) +{ if (length.isPoints()) { return floatFromYogaOptionalFloat(length.value()); } else if (length.isPercent()) { - return base.has_value() - ? std::optional( - base.value() * floatFromYogaOptionalFloat(length.value())) - : std::optional(); + return base.has_value() ? std::optional(base.value() * floatFromYogaOptionalFloat(length.value())) + : std::optional(); } else { return {}; } } -static inline PositionType positionTypeFromYogaPositionType( - yoga::PositionType positionType) { +static inline PositionType positionTypeFromYogaPositionType(yoga::PositionType positionType) +{ switch (positionType) { case yoga::PositionType::Static: return PositionType::Static; @@ -119,7 +120,8 @@ static inline PositionType positionTypeFromYogaPositionType( } } -inline DisplayType displayTypeFromYGDisplay(YGDisplay display) { +inline DisplayType displayTypeFromYGDisplay(YGDisplay display) +{ switch (display) { case YGDisplayNone: return DisplayType::None; @@ -130,7 +132,8 @@ inline DisplayType displayTypeFromYGDisplay(YGDisplay display) { } } -inline LayoutMetrics layoutMetricsFromYogaNode(yoga::Node& yogaNode) { +inline LayoutMetrics layoutMetricsFromYogaNode(yoga::Node &yogaNode) +{ auto layoutMetrics = LayoutMetrics{}; layoutMetrics.frame = Rect{ @@ -149,30 +152,23 @@ inline LayoutMetrics layoutMetricsFromYogaNode(yoga::Node& yogaNode) { floatFromYogaFloat(YGNodeLayoutGetBorder(&yogaNode, YGEdgeBottom))}; layoutMetrics.contentInsets = EdgeInsets{ - layoutMetrics.borderWidth.left + - floatFromYogaFloat(YGNodeLayoutGetPadding(&yogaNode, YGEdgeLeft)), - layoutMetrics.borderWidth.top + - floatFromYogaFloat(YGNodeLayoutGetPadding(&yogaNode, YGEdgeTop)), - layoutMetrics.borderWidth.right + - floatFromYogaFloat(YGNodeLayoutGetPadding(&yogaNode, YGEdgeRight)), - layoutMetrics.borderWidth.bottom + - floatFromYogaFloat(YGNodeLayoutGetPadding(&yogaNode, YGEdgeBottom))}; + layoutMetrics.borderWidth.left + floatFromYogaFloat(YGNodeLayoutGetPadding(&yogaNode, YGEdgeLeft)), + layoutMetrics.borderWidth.top + floatFromYogaFloat(YGNodeLayoutGetPadding(&yogaNode, YGEdgeTop)), + layoutMetrics.borderWidth.right + floatFromYogaFloat(YGNodeLayoutGetPadding(&yogaNode, YGEdgeRight)), + layoutMetrics.borderWidth.bottom + floatFromYogaFloat(YGNodeLayoutGetPadding(&yogaNode, YGEdgeBottom))}; - layoutMetrics.displayType = - displayTypeFromYGDisplay(YGNodeStyleGetDisplay(&yogaNode)); + layoutMetrics.displayType = displayTypeFromYGDisplay(YGNodeStyleGetDisplay(&yogaNode)); - layoutMetrics.positionType = - positionTypeFromYogaPositionType(yogaNode.style().positionType()); + layoutMetrics.positionType = positionTypeFromYogaPositionType(yogaNode.style().positionType()); - layoutMetrics.layoutDirection = - YGNodeLayoutGetDirection(&yogaNode) == YGDirectionRTL - ? LayoutDirection::RightToLeft - : LayoutDirection::LeftToRight; + layoutMetrics.layoutDirection = YGNodeLayoutGetDirection(&yogaNode) == YGDirectionRTL ? LayoutDirection::RightToLeft + : LayoutDirection::LeftToRight; return layoutMetrics; } -inline YGDirection yogaDirectionFromLayoutDirection(LayoutDirection direction) { +inline YGDirection yogaDirectionFromLayoutDirection(LayoutDirection direction) +{ switch (direction) { case LayoutDirection::Undefined: return YGDirectionInherit; @@ -183,10 +179,8 @@ inline YGDirection yogaDirectionFromLayoutDirection(LayoutDirection direction) { } } -inline void fromRawValue( - const PropsParserContext& context, - const RawValue& value, - yoga::Direction& result) { +inline void fromRawValue(const PropsParserContext &context, const RawValue &value, yoga::Direction &result) +{ result = yoga::Direction::Inherit; react_native_expect(value.hasType()); if (!value.hasType()) { @@ -208,10 +202,8 @@ inline void fromRawValue( LOG(ERROR) << "Could not parse yoga::Direction: " << stringValue; } -inline void fromRawValue( - const PropsParserContext& context, - const RawValue& value, - yoga::FlexDirection& result) { +inline void fromRawValue(const PropsParserContext &context, const RawValue &value, yoga::FlexDirection &result) +{ result = yoga::FlexDirection::Column; react_native_expect(value.hasType()); if (!value.hasType()) { @@ -237,10 +229,8 @@ inline void fromRawValue( LOG(ERROR) << "Could not parse yoga::FlexDirection: " << stringValue; } -inline void fromRawValue( - const PropsParserContext& /*context*/, - const RawValue& value, - yoga::BoxSizing& result) { +inline void fromRawValue(const PropsParserContext & /*context*/, const RawValue &value, yoga::BoxSizing &result) +{ result = yoga::BoxSizing::BorderBox; react_native_expect(value.hasType()); if (!value.hasType()) { @@ -259,10 +249,8 @@ inline void fromRawValue( LOG(ERROR) << "Could not parse yoga::BoxSizing: " << stringValue; } -inline void fromRawValue( - const PropsParserContext& context, - const RawValue& value, - yoga::Justify& result) { +inline void fromRawValue(const PropsParserContext &context, const RawValue &value, yoga::Justify &result) +{ result = yoga::Justify::FlexStart; react_native_expect(value.hasType()); if (!value.hasType()) { @@ -296,10 +284,8 @@ inline void fromRawValue( LOG(ERROR) << "Could not parse yoga::Justify: " << stringValue; } -inline void fromRawValue( - const PropsParserContext& context, - const RawValue& value, - yoga::Align& result) { +inline void fromRawValue(const PropsParserContext &context, const RawValue &value, yoga::Align &result) +{ result = yoga::Align::Stretch; react_native_expect(value.hasType()); if (!value.hasType()) { @@ -346,10 +332,8 @@ inline void fromRawValue( react_native_expect(false); } -inline void fromRawValue( - const PropsParserContext& context, - const RawValue& value, - yoga::PositionType& result) { +inline void fromRawValue(const PropsParserContext &context, const RawValue &value, yoga::PositionType &result) +{ result = yoga::PositionType::Relative; react_native_expect(value.hasType()); if (!value.hasType()) { @@ -371,10 +355,8 @@ inline void fromRawValue( LOG(ERROR) << "Could not parse yoga::PositionType: " << stringValue; } -inline void fromRawValue( - const PropsParserContext& context, - const RawValue& value, - yoga::Wrap& result) { +inline void fromRawValue(const PropsParserContext &context, const RawValue &value, yoga::Wrap &result) +{ result = yoga::Wrap::NoWrap; react_native_expect(value.hasType()); if (!value.hasType()) { @@ -396,10 +378,8 @@ inline void fromRawValue( LOG(ERROR) << "Could not parse yoga::Wrap: " << stringValue; } -inline void fromRawValue( - const PropsParserContext& context, - const RawValue& value, - yoga::Overflow& result) { +inline void fromRawValue(const PropsParserContext &context, const RawValue &value, yoga::Overflow &result) +{ result = yoga::Overflow::Visible; react_native_expect(value.hasType()); if (!value.hasType()) { @@ -422,10 +402,8 @@ inline void fromRawValue( react_native_expect(false); } -inline void fromRawValue( - const PropsParserContext& context, - const RawValue& value, - yoga::Display& result) { +inline void fromRawValue(const PropsParserContext &context, const RawValue &value, yoga::Display &result) +{ result = yoga::Display::Flex; react_native_expect(value.hasType()); if (!value.hasType()) { @@ -447,10 +425,8 @@ inline void fromRawValue( LOG(ERROR) << "Could not parse yoga::Display: " << stringValue; } -inline void fromRawValue( - const PropsParserContext& /*context*/, - const RawValue& value, - yoga::Style::SizeLength& result) { +inline void fromRawValue(const PropsParserContext & /*context*/, const RawValue &value, yoga::Style::SizeLength &result) +{ if (value.hasType()) { result = yoga::StyleSizeLength::points((float)value); return; @@ -471,12 +447,10 @@ inline void fromRawValue( } else { auto parsed = parseCSSProperty(stringValue); if (std::holds_alternative(parsed)) { - result = yoga::StyleSizeLength::percent( - std::get(parsed).value); + result = yoga::StyleSizeLength::percent(std::get(parsed).value); return; } else if (std::holds_alternative(parsed)) { - result = - yoga::StyleSizeLength::points(std::get(parsed).value); + result = yoga::StyleSizeLength::points(std::get(parsed).value); return; } } @@ -484,10 +458,8 @@ inline void fromRawValue( result = yoga::StyleSizeLength::undefined(); } -inline void fromRawValue( - const PropsParserContext& context, - const RawValue& value, - yoga::Style::Length& result) { +inline void fromRawValue(const PropsParserContext &context, const RawValue &value, yoga::Style::Length &result) +{ if (value.hasType()) { result = yoga::StyleLength::points((float)value); return; @@ -499,8 +471,7 @@ inline void fromRawValue( } else { auto parsed = parseCSSProperty(stringValue); if (std::holds_alternative(parsed)) { - result = - yoga::StyleLength::percent(std::get(parsed).value); + result = yoga::StyleLength::percent(std::get(parsed).value); return; } else if (std::holds_alternative(parsed)) { result = yoga::StyleLength::points(std::get(parsed).value); @@ -511,24 +482,20 @@ inline void fromRawValue( result = yoga::StyleLength::undefined(); } -inline void fromRawValue( - const PropsParserContext& context, - const RawValue& value, - YGValue& result) { +inline void fromRawValue(const PropsParserContext &context, const RawValue &value, YGValue &result) +{ yoga::Style::Length length{}; fromRawValue(context, value, length); result = (YGValue)length; } -inline void fromRawValue( - const PropsParserContext& context, - const RawValue& value, - yoga::FloatOptional& result) { - result = value.hasType() ? yoga::FloatOptional((float)value) - : yoga::FloatOptional(); +inline void fromRawValue(const PropsParserContext &context, const RawValue &value, yoga::FloatOptional &result) +{ + result = value.hasType() ? yoga::FloatOptional((float)value) : yoga::FloatOptional(); } -inline std::optional toRadians(const RawValue& value) { +inline std::optional toRadians(const RawValue &value) +{ if (value.hasType()) { return (Float)value; } @@ -538,14 +505,14 @@ inline std::optional toRadians(const RawValue& value) { auto angle = parseCSSProperty((std::string)value); if (std::holds_alternative(angle)) { - return static_cast( - std::get(angle).degrees * M_PI / 180.0f); + return static_cast(std::get(angle).degrees * M_PI / 180.0f); } return {}; } -inline ValueUnit toValueUnit(const RawValue& value) { +inline ValueUnit toValueUnit(const RawValue &value) +{ if (value.hasType()) { return ValueUnit((Float)value, UnitType::Point); } @@ -561,17 +528,13 @@ inline ValueUnit toValueUnit(const RawValue& value) { return {}; } -inline void fromRawValue( - const PropsParserContext& /*context*/, - const RawValue& value, - ValueUnit& result) { +inline void fromRawValue(const PropsParserContext & /*context*/, const RawValue &value, ValueUnit &result) +{ result = toValueUnit(value); } -inline void fromRawValue( - const PropsParserContext& /*context*/, - const RawValue& value, - Transform& result) { +inline void fromRawValue(const PropsParserContext & /*context*/, const RawValue &value, Transform &result) +{ auto transformMatrix = Transform{}; react_native_expect(value.hasType>()); if (!value.hasType>()) { @@ -580,14 +543,13 @@ inline void fromRawValue( } auto configurations = static_cast>(value); - for (const auto& configuration : configurations) { + for (const auto &configuration : configurations) { if (!configuration.hasType>()) { result = {}; return; } - auto configurationPair = - static_cast>(configuration); + auto configurationPair = static_cast>(configuration); if (configurationPair.size() != 1) { result = {}; return; @@ -595,7 +557,7 @@ inline void fromRawValue( auto pair = configurationPair.begin(); auto operation = pair->first; - auto& parameters = pair->second; + auto ¶meters = pair->second; auto Zero = ValueUnit(0, UnitType::Point); auto One = ValueUnit(1, UnitType::Point); @@ -649,22 +611,20 @@ inline void fromRawValue( transformMatrix.matrix[14] = 0; transformMatrix.matrix[15] = numbers[8]; } - transformMatrix.operations.push_back(TransformOperation{ - .type = TransformOperationType::Arbitrary, - .x = Zero, - .y = Zero, - .z = Zero}); + transformMatrix.operations.push_back( + TransformOperation{.type = TransformOperationType::Arbitrary, .x = Zero, .y = Zero, .z = Zero}); } else if (operation == "perspective") { if (!parameters.hasType()) { result = {}; return; } - transformMatrix.operations.push_back(TransformOperation{ - .type = TransformOperationType::Perspective, - .x = ValueUnit((Float)parameters, UnitType::Point), - .y = Zero, - .z = Zero}); + transformMatrix.operations.push_back( + TransformOperation{ + .type = TransformOperationType::Perspective, + .x = ValueUnit((Float)parameters, UnitType::Point), + .y = Zero, + .z = Zero}); } else if (operation == "rotateX") { auto radians = toRadians(parameters); if (!radians.has_value()) { @@ -672,11 +632,9 @@ inline void fromRawValue( return; } - transformMatrix.operations.push_back(TransformOperation{ - .type = TransformOperationType::Rotate, - .x = ValueUnit(*radians, UnitType::Point), - .y = Zero, - .z = Zero}); + transformMatrix.operations.push_back( + TransformOperation{ + .type = TransformOperationType::Rotate, .x = ValueUnit(*radians, UnitType::Point), .y = Zero, .z = Zero}); } else if (operation == "rotateY") { auto radians = toRadians(parameters); if (!radians.has_value()) { @@ -684,11 +642,9 @@ inline void fromRawValue( return; } - transformMatrix.operations.push_back(TransformOperation{ - .type = TransformOperationType::Rotate, - .x = Zero, - .y = ValueUnit(*radians, UnitType::Point), - .z = Zero}); + transformMatrix.operations.push_back( + TransformOperation{ + .type = TransformOperationType::Rotate, .x = Zero, .y = ValueUnit(*radians, UnitType::Point), .z = Zero}); } else if (operation == "rotateZ" || operation == "rotate") { auto radians = toRadians(parameters); if (!radians.has_value()) { @@ -696,11 +652,9 @@ inline void fromRawValue( return; } - transformMatrix.operations.push_back(TransformOperation{ - .type = TransformOperationType::Rotate, - .x = Zero, - .y = Zero, - .z = ValueUnit(*radians, UnitType::Point)}); + transformMatrix.operations.push_back( + TransformOperation{ + .type = TransformOperationType::Rotate, .x = Zero, .y = Zero, .z = ValueUnit(*radians, UnitType::Point)}); } else if (operation == "scale") { if (!parameters.hasType()) { result = {}; @@ -708,44 +662,44 @@ inline void fromRawValue( } auto number = ValueUnit((Float)parameters, UnitType::Point); - transformMatrix.operations.push_back(TransformOperation{ - .type = TransformOperationType::Scale, - .x = number, - .y = number, - .z = number}); + transformMatrix.operations.push_back( + TransformOperation{.type = TransformOperationType::Scale, .x = number, .y = number, .z = number}); } else if (operation == "scaleX") { if (!parameters.hasType()) { result = {}; return; } - transformMatrix.operations.push_back(TransformOperation{ - .type = TransformOperationType::Scale, - .x = ValueUnit((Float)parameters, UnitType::Point), - .y = One, - .z = One}); + transformMatrix.operations.push_back( + TransformOperation{ + .type = TransformOperationType::Scale, + .x = ValueUnit((Float)parameters, UnitType::Point), + .y = One, + .z = One}); } else if (operation == "scaleY") { if (!parameters.hasType()) { result = {}; return; } - transformMatrix.operations.push_back(TransformOperation{ - .type = TransformOperationType::Scale, - .x = One, - .y = ValueUnit((Float)parameters, UnitType::Point), - .z = One}); + transformMatrix.operations.push_back( + TransformOperation{ + .type = TransformOperationType::Scale, + .x = One, + .y = ValueUnit((Float)parameters, UnitType::Point), + .z = One}); } else if (operation == "scaleZ") { if (!parameters.hasType()) { result = {}; return; } - transformMatrix.operations.push_back(TransformOperation{ - .type = TransformOperationType::Scale, - .x = One, - .y = One, - .z = ValueUnit((Float)parameters, UnitType::Point)}); + transformMatrix.operations.push_back( + TransformOperation{ + .type = TransformOperationType::Scale, + .x = One, + .y = One, + .z = ValueUnit((Float)parameters, UnitType::Point)}); } else if (operation == "translate") { if (!parameters.hasType>()) { result = {}; @@ -770,11 +724,8 @@ inline void fromRawValue( return; } - transformMatrix.operations.push_back(TransformOperation{ - .type = TransformOperationType::Translate, - .x = valueX, - .y = valueY, - .z = Zero}); + transformMatrix.operations.push_back( + TransformOperation{.type = TransformOperationType::Translate, .x = valueX, .y = valueY, .z = Zero}); } else if (operation == "translateX") { auto valueX = toValueUnit(parameters); if (!valueX) { @@ -782,11 +733,8 @@ inline void fromRawValue( return; } - transformMatrix.operations.push_back(TransformOperation{ - .type = TransformOperationType::Translate, - .x = valueX, - .y = Zero, - .z = Zero}); + transformMatrix.operations.push_back( + TransformOperation{.type = TransformOperationType::Translate, .x = valueX, .y = Zero, .z = Zero}); } else if (operation == "translateY") { auto valueY = toValueUnit(parameters); if (!valueY) { @@ -794,11 +742,8 @@ inline void fromRawValue( return; } - transformMatrix.operations.push_back(TransformOperation{ - .type = TransformOperationType::Translate, - .x = Zero, - .y = valueY, - .z = Zero}); + transformMatrix.operations.push_back( + TransformOperation{.type = TransformOperationType::Translate, .x = Zero, .y = valueY, .z = Zero}); } else if (operation == "skewX") { auto radians = toRadians(parameters); if (!radians.has_value()) { @@ -806,11 +751,9 @@ inline void fromRawValue( return; } - transformMatrix.operations.push_back(TransformOperation{ - .type = TransformOperationType::Skew, - .x = ValueUnit(*radians, UnitType::Point), - .y = Zero, - .z = Zero}); + transformMatrix.operations.push_back( + TransformOperation{ + .type = TransformOperationType::Skew, .x = ValueUnit(*radians, UnitType::Point), .y = Zero, .z = Zero}); } else if (operation == "skewY") { auto radians = toRadians(parameters); if (!radians.has_value()) { @@ -818,21 +761,17 @@ inline void fromRawValue( return; } - transformMatrix.operations.push_back(TransformOperation{ - .type = TransformOperationType::Skew, - .x = Zero, - .y = ValueUnit(*radians, UnitType::Point), - .z = Zero}); + transformMatrix.operations.push_back( + TransformOperation{ + .type = TransformOperationType::Skew, .x = Zero, .y = ValueUnit(*radians, UnitType::Point), .z = Zero}); } } result = transformMatrix; } -inline void fromRawValue( - const PropsParserContext& context, - const RawValue& value, - TransformOrigin& result) { +inline void fromRawValue(const PropsParserContext &context, const RawValue &value, TransformOrigin &result) +{ if (!value.hasType>()) { result = {}; return; @@ -865,10 +804,8 @@ inline void fromRawValue( result = transformOrigin; } -inline void fromRawValue( - const PropsParserContext& context, - const RawValue& value, - PointerEventsMode& result) { +inline void fromRawValue(const PropsParserContext &context, const RawValue &value, PointerEventsMode &result) +{ result = PointerEventsMode::Auto; react_native_expect(value.hasType()); if (!value.hasType()) { @@ -895,7 +832,8 @@ inline void fromRawValue( react_native_expect(false); } -inline std::string toString(PointerEventsMode value) { +inline std::string toString(PointerEventsMode value) +{ switch (value) { case PointerEventsMode::Auto: return "auto"; @@ -908,10 +846,8 @@ inline std::string toString(PointerEventsMode value) { } } -inline void fromRawValue( - const PropsParserContext& context, - const RawValue& value, - BackfaceVisibility& result) { +inline void fromRawValue(const PropsParserContext &context, const RawValue &value, BackfaceVisibility &result) +{ result = BackfaceVisibility::Auto; react_native_expect(value.hasType()); if (!value.hasType()) { @@ -934,10 +870,8 @@ inline void fromRawValue( react_native_expect(false); } -inline void fromRawValue( - const PropsParserContext& context, - const RawValue& value, - BorderCurve& result) { +inline void fromRawValue(const PropsParserContext &context, const RawValue &value, BorderCurve &result) +{ result = BorderCurve::Circular; react_native_expect(value.hasType()); if (!value.hasType()) { @@ -956,10 +890,8 @@ inline void fromRawValue( react_native_expect(false); } -inline void fromRawValue( - const PropsParserContext& context, - const RawValue& value, - BorderStyle& result) { +inline void fromRawValue(const PropsParserContext &context, const RawValue &value, BorderStyle &result) +{ result = BorderStyle::Solid; react_native_expect(value.hasType()); if (!value.hasType()) { @@ -982,10 +914,8 @@ inline void fromRawValue( react_native_expect(false); } -inline void fromRawValue( - const PropsParserContext& context, - const RawValue& value, - OutlineStyle& result) { +inline void fromRawValue(const PropsParserContext &context, const RawValue &value, OutlineStyle &result) +{ result = OutlineStyle::Solid; react_native_expect(value.hasType()); if (!value.hasType()) { @@ -1008,10 +938,8 @@ inline void fromRawValue( react_native_expect(false); } -inline void fromRawValue( - const PropsParserContext& context, - const RawValue& value, - Cursor& result) { +inline void fromRawValue(const PropsParserContext &context, const RawValue &value, Cursor &result) +{ result = Cursor::Auto; react_native_expect(value.hasType()); if (!value.hasType()) { @@ -1166,10 +1094,8 @@ inline void fromRawValue( react_native_expect(false); } -inline void fromRawValue( - const PropsParserContext& /*context*/, - const RawValue& value, - LayoutConformance& result) { +inline void fromRawValue(const PropsParserContext & /*context*/, const RawValue &value, LayoutConformance &result) +{ react_native_expect(value.hasType()); result = LayoutConformance::Strict; if (!value.hasType()) { @@ -1187,10 +1113,8 @@ inline void fromRawValue( } } -inline void fromRawValue( - const PropsParserContext& /*context*/, - const RawValue& value, - BlendMode& result) { +inline void fromRawValue(const PropsParserContext & /*context*/, const RawValue &value, BlendMode &result) +{ react_native_expect(value.hasType()); result = BlendMode::Normal; if (!value.hasType()) { @@ -1208,10 +1132,9 @@ inline void fromRawValue( result = blendMode.value(); } -inline void fromRawValue( - const PropsParserContext& /*context*/, - const RawValue& value, - std::vector& result) { +inline void +fromRawValue(const PropsParserContext & /*context*/, const RawValue &value, std::vector &result) +{ react_native_expect(value.hasType>()); if (!value.hasType>()) { result = {}; @@ -1221,7 +1144,7 @@ inline void fromRawValue( std::vector backgroundSizes{}; auto rawBackgroundSizes = static_cast>(value); - for (const auto& rawBackgroundSizeValue : rawBackgroundSizes) { + for (const auto &rawBackgroundSizeValue : rawBackgroundSizes) { if (rawBackgroundSizeValue.hasType()) { auto sizeStr = (std::string)rawBackgroundSizeValue; if (sizeStr == "cover") { @@ -1229,17 +1152,14 @@ inline void fromRawValue( } else if (sizeStr == "contain") { backgroundSizes.emplace_back(BackgroundSizeKeyword::Contain); } - } else if (rawBackgroundSizeValue - .hasType>()) { - auto sizeMap = static_cast>( - rawBackgroundSizeValue); + } else if (rawBackgroundSizeValue.hasType>()) { + auto sizeMap = static_cast>(rawBackgroundSizeValue); BackgroundSizeLengthPercentage sizeLengthPercentage; auto xIt = sizeMap.find("x"); if (xIt != sizeMap.end()) { - if (xIt->second.hasType() && - (std::string)(xIt->second) == "auto") { + if (xIt->second.hasType() && (std::string)(xIt->second) == "auto") { sizeLengthPercentage.x = std::monostate{}; } else { auto valueUnit = toValueUnit(xIt->second); @@ -1251,8 +1171,7 @@ inline void fromRawValue( auto yIt = sizeMap.find("y"); if (yIt != sizeMap.end()) { - if (yIt->second.hasType() && - (std::string)(yIt->second) == "auto") { + if (yIt->second.hasType() && (std::string)(yIt->second) == "auto") { sizeLengthPercentage.y = std::monostate{}; } else { auto valueUnit = toValueUnit(yIt->second); @@ -1269,10 +1188,9 @@ inline void fromRawValue( result = backgroundSizes; } -inline void fromRawValue( - const PropsParserContext& /*context*/, - const RawValue& value, - std::vector& result) { +inline void +fromRawValue(const PropsParserContext & /*context*/, const RawValue &value, std::vector &result) +{ react_native_expect(value.hasType>()); if (!value.hasType>()) { result = {}; @@ -1282,11 +1200,9 @@ inline void fromRawValue( std::vector backgroundPositions{}; auto rawBackgroundPositions = static_cast>(value); - for (const auto& rawBackgroundPositionValue : rawBackgroundPositions) { - if (rawBackgroundPositionValue - .hasType>()) { - auto positionMap = static_cast>( - rawBackgroundPositionValue); + for (const auto &rawBackgroundPositionValue : rawBackgroundPositions) { + if (rawBackgroundPositionValue.hasType>()) { + auto positionMap = static_cast>(rawBackgroundPositionValue); BackgroundPosition backgroundPosition; @@ -1329,10 +1245,9 @@ inline void fromRawValue( result = backgroundPositions; } -inline void fromRawValue( - const PropsParserContext& /*context*/, - const RawValue& value, - std::vector& result) { +inline void +fromRawValue(const PropsParserContext & /*context*/, const RawValue &value, std::vector &result) +{ react_native_expect(value.hasType>()); if (!value.hasType>()) { result = {}; @@ -1342,11 +1257,9 @@ inline void fromRawValue( std::vector backgroundRepeats{}; auto rawBackgroundRepeats = static_cast>(value); - for (const auto& rawBackgroundRepeatValue : rawBackgroundRepeats) { - if (rawBackgroundRepeatValue - .hasType>()) { - auto repeatMap = static_cast>( - rawBackgroundRepeatValue); + for (const auto &rawBackgroundRepeatValue : rawBackgroundRepeats) { + if (rawBackgroundRepeatValue.hasType>()) { + auto repeatMap = static_cast>(rawBackgroundRepeatValue); BackgroundRepeat backgroundRepeat; @@ -1385,10 +1298,8 @@ inline void fromRawValue( result = backgroundRepeats; } -inline void fromRawValue( - const PropsParserContext& /*context*/, - const RawValue& value, - Isolation& result) { +inline void fromRawValue(const PropsParserContext & /*context*/, const RawValue &value, Isolation &result) +{ react_native_expect(value.hasType()); result = Isolation::Auto; if (!value.hasType()) { @@ -1408,7 +1319,8 @@ inline void fromRawValue( #if RN_DEBUG_STRING_CONVERTIBLE template -inline std::string toString(const std::array vec) { +inline std::string toString(const std::array vec) +{ std::string s; s.append("{"); @@ -1421,39 +1333,48 @@ inline std::string toString(const std::array vec) { return s; } -inline std::string toString(const yoga::Direction& value) { +inline std::string toString(const yoga::Direction &value) +{ return YGDirectionToString(yoga::unscopedEnum(value)); } -inline std::string toString(const yoga::FlexDirection& value) { +inline std::string toString(const yoga::FlexDirection &value) +{ return YGFlexDirectionToString(yoga::unscopedEnum(value)); } -inline std::string toString(const yoga::Justify& value) { +inline std::string toString(const yoga::Justify &value) +{ return YGJustifyToString(yoga::unscopedEnum(value)); } -inline std::string toString(const yoga::Align& value) { +inline std::string toString(const yoga::Align &value) +{ return YGAlignToString(yoga::unscopedEnum(value)); } -inline std::string toString(const yoga::PositionType& value) { +inline std::string toString(const yoga::PositionType &value) +{ return YGPositionTypeToString(yoga::unscopedEnum(value)); } -inline std::string toString(const yoga::Wrap& value) { +inline std::string toString(const yoga::Wrap &value) +{ return YGWrapToString(yoga::unscopedEnum(value)); } -inline std::string toString(const yoga::Overflow& value) { +inline std::string toString(const yoga::Overflow &value) +{ return YGOverflowToString(yoga::unscopedEnum(value)); } -inline std::string toString(const yoga::Display& value) { +inline std::string toString(const yoga::Display &value) +{ return YGDisplayToString(yoga::unscopedEnum(value)); } -inline std::string toString(const yoga::Style::Length& length) { +inline std::string toString(const yoga::Style::Length &length) +{ if (length.isUndefined()) { return "undefined"; } else if (length.isAuto()) { @@ -1467,7 +1388,8 @@ inline std::string toString(const yoga::Style::Length& length) { } } -inline std::string toString(const yoga::Style::SizeLength& length) { +inline std::string toString(const yoga::Style::SizeLength &length) +{ if (length.isUndefined()) { return "undefined"; } else if (length.isAuto()) { @@ -1487,7 +1409,8 @@ inline std::string toString(const yoga::Style::SizeLength& length) { } } -inline std::string toString(const yoga::FloatOptional& value) { +inline std::string toString(const yoga::FloatOptional &value) +{ if (value.isUndefined()) { return "undefined"; } @@ -1495,7 +1418,8 @@ inline std::string toString(const yoga::FloatOptional& value) { return std::to_string(value.unwrap()); } -inline std::string toString(const LayoutConformance& value) { +inline std::string toString(const LayoutConformance &value) +{ switch (value) { case LayoutConformance::Strict: return "strict"; @@ -1504,24 +1428,26 @@ inline std::string toString(const LayoutConformance& value) { } } -inline std::string toString(const std::array& m) { +inline std::string toString(const std::array &m) +{ std::string result; - result += "[ " + std::to_string(m[0]) + " " + std::to_string(m[1]) + " " + - std::to_string(m[2]) + " " + std::to_string(m[3]) + " ]\n"; - result += "[ " + std::to_string(m[4]) + " " + std::to_string(m[5]) + " " + - std::to_string(m[6]) + " " + std::to_string(m[7]) + " ]\n"; - result += "[ " + std::to_string(m[8]) + " " + std::to_string(m[9]) + " " + - std::to_string(m[10]) + " " + std::to_string(m[11]) + " ]\n"; - result += "[ " + std::to_string(m[12]) + " " + std::to_string(m[13]) + " " + - std::to_string(m[14]) + " " + std::to_string(m[15]) + " ]"; + result += "[ " + std::to_string(m[0]) + " " + std::to_string(m[1]) + " " + std::to_string(m[2]) + " " + + std::to_string(m[3]) + " ]\n"; + result += "[ " + std::to_string(m[4]) + " " + std::to_string(m[5]) + " " + std::to_string(m[6]) + " " + + std::to_string(m[7]) + " ]\n"; + result += "[ " + std::to_string(m[8]) + " " + std::to_string(m[9]) + " " + std::to_string(m[10]) + " " + + std::to_string(m[11]) + " ]\n"; + result += "[ " + std::to_string(m[12]) + " " + std::to_string(m[13]) + " " + std::to_string(m[14]) + " " + + std::to_string(m[15]) + " ]"; return result; } -inline std::string toString(const Transform& transform) { +inline std::string toString(const Transform &transform) +{ std::string result = "["; bool first = true; - for (const auto& operation : transform.operations) { + for (const auto &operation : transform.operations) { if (!first) { result += ", "; } @@ -1529,31 +1455,21 @@ inline std::string toString(const Transform& transform) { switch (operation.type) { case TransformOperationType::Perspective: { - result += - "{\"perspective\": " + std::to_string(operation.x.value) + "}"; + result += "{\"perspective\": " + std::to_string(operation.x.value) + "}"; break; } case TransformOperationType::Rotate: { - if (operation.x.value != 0 && operation.y.value == 0 && - operation.z.value == 0) { - result += - R"({"rotateX": ")" + std::to_string(operation.x.value) + "rad\"}"; - } else if ( - operation.x.value == 0 && operation.y.value != 0 && - operation.z.value == 0) { - result += - R"({"rotateY": ")" + std::to_string(operation.y.value) + "rad\"}"; - } else if ( - operation.x.value == 0 && operation.y.value == 0 && - operation.z.value != 0) { - result += - R"({"rotateZ": ")" + std::to_string(operation.z.value) + "rad\"}"; + if (operation.x.value != 0 && operation.y.value == 0 && operation.z.value == 0) { + result += R"({"rotateX": ")" + std::to_string(operation.x.value) + "rad\"}"; + } else if (operation.x.value == 0 && operation.y.value != 0 && operation.z.value == 0) { + result += R"({"rotateY": ")" + std::to_string(operation.y.value) + "rad\"}"; + } else if (operation.x.value == 0 && operation.y.value == 0 && operation.z.value != 0) { + result += R"({"rotateZ": ")" + std::to_string(operation.z.value) + "rad\"}"; } break; } case TransformOperationType::Scale: { - if (operation.x.value == operation.y.value && - operation.x.value == operation.z.value) { + if (operation.x.value == operation.y.value && operation.x.value == operation.z.value) { result += "{\"scale\": " + std::to_string(operation.x.value) + "}"; } else if (operation.y.value == 1 && operation.z.value == 1) { result += "{\"scaleX\": " + std::to_string(operation.x.value) + "}"; @@ -1565,28 +1481,22 @@ inline std::string toString(const Transform& transform) { break; } case TransformOperationType::Translate: { - if (operation.x.value != 0 && operation.y.value != 0 && - operation.z.value == 0) { + if (operation.x.value != 0 && operation.y.value != 0 && operation.z.value == 0) { result += "{\"translate\": ["; - result += std::to_string(operation.x.value) + ", " + - std::to_string(operation.y.value); + result += std::to_string(operation.x.value) + ", " + std::to_string(operation.y.value); result += "]}"; } else if (operation.x.value != 0 && operation.y.value == 0) { - result += - "{\"translateX\": " + std::to_string(operation.x.value) + "}"; + result += "{\"translateX\": " + std::to_string(operation.x.value) + "}"; } else if (operation.x.value == 0 && operation.y.value != 0) { - result += - "{\"translateY\": " + std::to_string(operation.y.value) + "}"; + result += "{\"translateY\": " + std::to_string(operation.y.value) + "}"; } break; } case TransformOperationType::Skew: { if (operation.x.value != 0 && operation.y.value == 0) { - result += - R"({"skewX": ")" + std::to_string(operation.x.value) + "rad\"}"; + result += R"({"skewX": ")" + std::to_string(operation.x.value) + "rad\"}"; } else if (operation.x.value == 0 && operation.y.value != 0) { - result += - R"({"skewY": ")" + std::to_string(operation.y.value) + "rad\"}"; + result += R"({"skewY": ")" + std::to_string(operation.y.value) + "rad\"}"; } break; } diff --git a/packages/react-native/ReactCommon/react/renderer/components/view/platform/android/react/renderer/components/view/HostPlatformViewProps.h b/packages/react-native/ReactCommon/react/renderer/components/view/platform/android/react/renderer/components/view/HostPlatformViewProps.h index c318cb60afa..154be6f017b 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/view/platform/android/react/renderer/components/view/HostPlatformViewProps.h +++ b/packages/react-native/ReactCommon/react/renderer/components/view/platform/android/react/renderer/components/view/HostPlatformViewProps.h @@ -24,17 +24,13 @@ class HostPlatformViewProps : public BaseViewProps { public: HostPlatformViewProps() = default; HostPlatformViewProps( - const PropsParserContext& context, - const HostPlatformViewProps& sourceProps, - const RawProps& rawProps, - const std::function& filterObjectKeys = - nullptr); + const PropsParserContext &context, + const HostPlatformViewProps &sourceProps, + const RawProps &rawProps, + const std::function &filterObjectKeys = nullptr); - void setProp( - const PropsParserContext& context, - RawPropsPropNameHash hash, - const char* propName, - const RawValue& value); + void + setProp(const PropsParserContext &context, RawPropsPropNameHash hash, const char *propName, const RawValue &value); #pragma mark - Props @@ -65,7 +61,7 @@ class HostPlatformViewProps : public BaseViewProps { #ifdef RN_SERIALIZABLE_STATE ComponentName getDiffPropsImplementationTarget() const override; - folly::dynamic getDiffProps(const Props* prevProps) const override; + folly::dynamic getDiffProps(const Props *prevProps) const override; #endif }; diff --git a/packages/react-native/ReactCommon/react/renderer/components/view/platform/android/react/renderer/components/view/HostPlatformViewTraitsInitializer.h b/packages/react-native/ReactCommon/react/renderer/components/view/platform/android/react/renderer/components/view/HostPlatformViewTraitsInitializer.h index 8550d271637..16b32af2b93 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/view/platform/android/react/renderer/components/view/HostPlatformViewTraitsInitializer.h +++ b/packages/react-native/ReactCommon/react/renderer/components/view/platform/android/react/renderer/components/view/HostPlatformViewTraitsInitializer.h @@ -12,20 +12,20 @@ namespace facebook::react::HostPlatformViewTraitsInitializer { -inline bool formsStackingContext(const ViewProps& viewProps) { +inline bool formsStackingContext(const ViewProps &viewProps) +{ return viewProps.elevation != 0; } -inline bool formsView(const ViewProps& viewProps) { - return viewProps.nativeBackground.has_value() || - viewProps.nativeForeground.has_value() || viewProps.focusable || - viewProps.hasTVPreferredFocus || - viewProps.needsOffscreenAlphaCompositing || - viewProps.renderToHardwareTextureAndroid || - viewProps.screenReaderFocusable; +inline bool formsView(const ViewProps &viewProps) +{ + return viewProps.nativeBackground.has_value() || viewProps.nativeForeground.has_value() || viewProps.focusable || + viewProps.hasTVPreferredFocus || viewProps.needsOffscreenAlphaCompositing || + viewProps.renderToHardwareTextureAndroid || viewProps.screenReaderFocusable; } -inline bool isKeyboardFocusable(const ViewProps& viewProps) { +inline bool isKeyboardFocusable(const ViewProps &viewProps) +{ return (viewProps.focusable || viewProps.hasTVPreferredFocus); } diff --git a/packages/react-native/ReactCommon/react/renderer/components/view/platform/android/react/renderer/components/view/NativeDrawable.h b/packages/react-native/ReactCommon/react/renderer/components/view/platform/android/react/renderer/components/view/NativeDrawable.h index c2668f291e1..f02bb82205a 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/view/platform/android/react/renderer/components/view/NativeDrawable.h +++ b/packages/react-native/ReactCommon/react/renderer/components/view/platform/android/react/renderer/components/view/NativeDrawable.h @@ -26,7 +26,8 @@ struct NativeDrawable { std::optional rippleRadius{}; bool borderless{false}; - bool operator==(const Ripple& rhs) const { + bool operator==(const Ripple &rhs) const + { return std::tie(this->color, this->borderless, this->rippleRadius) == std::tie(rhs.color, rhs.borderless, rhs.rippleRadius); } @@ -36,7 +37,8 @@ struct NativeDrawable { Ripple ripple; Kind kind; - bool operator==(const NativeDrawable& rhs) const { + bool operator==(const NativeDrawable &rhs) const + { if (this->kind != rhs.kind) { return false; } @@ -49,29 +51,26 @@ struct NativeDrawable { } } - bool operator!=(const NativeDrawable& rhs) const { + bool operator!=(const NativeDrawable &rhs) const + { return !(*this == rhs); } ~NativeDrawable() = default; }; -static inline void fromRawValue( - const PropsParserContext& /*context*/, - const RawValue& rawValue, - NativeDrawable& result) { +static inline void +fromRawValue(const PropsParserContext & /*context*/, const RawValue &rawValue, NativeDrawable &result) +{ auto map = (std::unordered_map)rawValue; auto typeIterator = map.find("type"); - react_native_expect( - typeIterator != map.end() && typeIterator->second.hasType()); + react_native_expect(typeIterator != map.end() && typeIterator->second.hasType()); std::string type = (std::string)typeIterator->second; if (type == "ThemeAttrAndroid") { auto attrIterator = map.find("attribute"); - react_native_expect( - attrIterator != map.end() && - attrIterator->second.hasType()); + react_native_expect(attrIterator != map.end() && attrIterator->second.hasType()); result = NativeDrawable{ (std::string)attrIterator->second, @@ -86,15 +85,10 @@ static inline void fromRawValue( result = NativeDrawable{ std::string{}, NativeDrawable::Ripple{ - color != map.end() && color->second.hasType() - ? (int32_t)color->second - : std::optional{}, - rippleRadius != map.end() && rippleRadius->second.hasType() - ? (Float)rippleRadius->second - : std::optional{}, - borderless != map.end() && borderless->second.hasType() - ? (bool)borderless->second - : false, + color != map.end() && color->second.hasType() ? (int32_t)color->second : std::optional{}, + rippleRadius != map.end() && rippleRadius->second.hasType() ? (Float)rippleRadius->second + : std::optional{}, + borderless != map.end() && borderless->second.hasType() ? (bool)borderless->second : false, }, NativeDrawable::Kind::Ripple, }; diff --git a/packages/react-native/ReactCommon/react/renderer/components/view/platform/cxx/react/renderer/components/view/HostPlatformViewTraitsInitializer.h b/packages/react-native/ReactCommon/react/renderer/components/view/platform/cxx/react/renderer/components/view/HostPlatformViewTraitsInitializer.h index 88debe19dff..a423f3192a6 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/view/platform/cxx/react/renderer/components/view/HostPlatformViewTraitsInitializer.h +++ b/packages/react-native/ReactCommon/react/renderer/components/view/platform/cxx/react/renderer/components/view/HostPlatformViewTraitsInitializer.h @@ -12,15 +12,18 @@ namespace facebook::react::HostPlatformViewTraitsInitializer { -inline bool formsStackingContext(const ViewProps& props) { +inline bool formsStackingContext(const ViewProps &props) +{ return false; } -inline bool formsView(const ViewProps& props) { +inline bool formsView(const ViewProps &props) +{ return false; } -inline bool isKeyboardFocusable(const ViewProps& /*props*/) { +inline bool isKeyboardFocusable(const ViewProps & /*props*/) +{ return false; } diff --git a/packages/react-native/ReactCommon/react/renderer/components/view/primitives.h b/packages/react-native/ReactCommon/react/renderer/components/view/primitives.h index 96d379b6c4b..a396579c234 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/view/primitives.h +++ b/packages/react-native/ReactCommon/react/renderer/components/view/primitives.h @@ -69,20 +69,24 @@ struct ViewEvents { PointerUpCapture = 37, }; - constexpr bool operator[](const Offset offset) const { + constexpr bool operator[](const Offset offset) const + { return bits[static_cast(offset)]; } - std::bitset<64>::reference operator[](const Offset offset) { + std::bitset<64>::reference operator[](const Offset offset) + { return bits[static_cast(offset)]; } }; -inline static bool operator==(const ViewEvents& lhs, const ViewEvents& rhs) { +inline static bool operator==(const ViewEvents &lhs, const ViewEvents &rhs) +{ return lhs.bits == rhs.bits; } -inline static bool operator!=(const ViewEvents& lhs, const ViewEvents& rhs) { +inline static bool operator!=(const ViewEvents &lhs, const ViewEvents &rhs) +{ return lhs.bits != rhs.bits; } @@ -98,7 +102,7 @@ struct CornerRadii { float vertical{0.0f}; float horizontal{0.0f}; - bool operator==(const CornerRadii& other) const = default; + bool operator==(const CornerRadii &other) const = default; }; enum class Cursor : uint8_t { @@ -160,29 +164,27 @@ struct CascadedRectangleEdges { OptionalT blockStart{}; OptionalT blockEnd{}; - Counterpart resolve(bool isRTL, T defaults) const { + Counterpart resolve(bool isRTL, T defaults) const + { const auto leadingEdge = isRTL ? end : start; const auto trailingEdge = isRTL ? start : end; - const auto horizontalOrAllOrDefault = - horizontal.value_or(all.value_or(defaults)); - const auto verticalOrAllOrDefault = - vertical.value_or(all.value_or(defaults)); + const auto horizontalOrAllOrDefault = horizontal.value_or(all.value_or(defaults)); + const auto verticalOrAllOrDefault = vertical.value_or(all.value_or(defaults)); return { /* .left = */ left.value_or(leadingEdge.value_or(horizontalOrAllOrDefault)), /* .top = */ - blockStart.value_or( - block.value_or(top.value_or(verticalOrAllOrDefault))), + blockStart.value_or(block.value_or(top.value_or(verticalOrAllOrDefault))), /* .right = */ right.value_or(trailingEdge.value_or(horizontalOrAllOrDefault)), /* .bottom = */ - blockEnd.value_or( - block.value_or(bottom.value_or(verticalOrAllOrDefault))), + blockEnd.value_or(block.value_or(bottom.value_or(verticalOrAllOrDefault))), }; } - bool operator==(const CascadedRectangleEdges& rhs) const { + bool operator==(const CascadedRectangleEdges &rhs) const + { return std::tie( this->left, this->top, @@ -211,7 +213,8 @@ struct CascadedRectangleEdges { rhs.blockEnd); } - bool operator!=(const CascadedRectangleEdges& rhs) const { + bool operator!=(const CascadedRectangleEdges &rhs) const + { return !(*this == rhs); } }; @@ -235,7 +238,8 @@ struct CascadedRectangleCorners { OptionalT startEnd{}; OptionalT startStart{}; - Counterpart resolve(bool isRTL, T defaults) const { + Counterpart resolve(bool isRTL, T defaults) const + { const auto logicalTopStart = topStart ? topStart : startStart; const auto logicalTopEnd = topEnd ? topEnd : startEnd; const auto logicalBottomStart = bottomStart ? bottomStart : endStart; @@ -247,8 +251,7 @@ struct CascadedRectangleCorners { const auto bottomTrailing = isRTL ? logicalBottomStart : logicalBottomEnd; return { - /* .topLeft = */ topLeft.value_or( - topLeading.value_or(all.value_or(defaults))), + /* .topLeft = */ topLeft.value_or(topLeading.value_or(all.value_or(defaults))), /* .topRight = */ topRight.value_or(topTrailing.value_or(all.value_or(defaults))), /* .bottomLeft = */ @@ -258,7 +261,8 @@ struct CascadedRectangleCorners { }; } - bool operator==(const CascadedRectangleCorners& rhs) const { + bool operator==(const CascadedRectangleCorners &rhs) const + { return std::tie( this->topLeft, this->topRight, @@ -289,7 +293,8 @@ struct CascadedRectangleCorners { rhs.startStart); } - bool operator!=(const CascadedRectangleCorners& rhs) const { + bool operator!=(const CascadedRectangleCorners &rhs) const + { return !(*this == rhs); } }; @@ -313,22 +318,15 @@ struct BorderMetrics { BorderCurves borderCurves{}; BorderStyles borderStyles{}; - bool operator==(const BorderMetrics& rhs) const { + bool operator==(const BorderMetrics &rhs) const + { return std::tie( - this->borderColors, - this->borderWidths, - this->borderRadii, - this->borderCurves, - this->borderStyles) == - std::tie( - rhs.borderColors, - rhs.borderWidths, - rhs.borderRadii, - rhs.borderCurves, - rhs.borderStyles); + this->borderColors, this->borderWidths, this->borderRadii, this->borderCurves, this->borderStyles) == + std::tie(rhs.borderColors, rhs.borderWidths, rhs.borderRadii, rhs.borderCurves, rhs.borderStyles); } - bool operator!=(const BorderMetrics& rhs) const { + bool operator!=(const BorderMetrics &rhs) const + { return !(*this == rhs); } }; diff --git a/packages/react-native/ReactCommon/react/renderer/components/view/propsConversions.h b/packages/react-native/ReactCommon/react/renderer/components/view/propsConversions.h index 74dcc8f1642..410fde1b56d 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/view/propsConversions.h +++ b/packages/react-native/ReactCommon/react/renderer/components/view/propsConversions.h @@ -16,123 +16,57 @@ namespace facebook::react { // Nearly this entire file can be deleted when iterator-style Prop parsing // ships fully for View -static inline yoga::Style convertRawProp( - const PropsParserContext& context, - const RawProps& rawProps, - const yoga::Style& sourceValue) { +static inline yoga::Style +convertRawProp(const PropsParserContext &context, const RawProps &rawProps, const yoga::Style &sourceValue) +{ yoga::Style yogaStyle{}; - yogaStyle.setDirection(convertRawProp( - context, - rawProps, - "direction", - sourceValue.direction(), - yogaStyle.direction())); + yogaStyle.setDirection( + convertRawProp(context, rawProps, "direction", sourceValue.direction(), yogaStyle.direction())); - yogaStyle.setFlexDirection(convertRawProp( - context, - rawProps, - "flexDirection", - sourceValue.flexDirection(), - yogaStyle.flexDirection())); + yogaStyle.setFlexDirection( + convertRawProp(context, rawProps, "flexDirection", sourceValue.flexDirection(), yogaStyle.flexDirection())); - yogaStyle.setJustifyContent(convertRawProp( - context, - rawProps, - "justifyContent", - sourceValue.justifyContent(), - yogaStyle.justifyContent())); + yogaStyle.setJustifyContent( + convertRawProp(context, rawProps, "justifyContent", sourceValue.justifyContent(), yogaStyle.justifyContent())); - yogaStyle.setAlignContent(convertRawProp( - context, - rawProps, - "alignContent", - sourceValue.alignContent(), - yogaStyle.alignContent())); + yogaStyle.setAlignContent( + convertRawProp(context, rawProps, "alignContent", sourceValue.alignContent(), yogaStyle.alignContent())); - yogaStyle.setAlignItems(convertRawProp( - context, - rawProps, - "alignItems", - sourceValue.alignItems(), - yogaStyle.alignItems())); + yogaStyle.setAlignItems( + convertRawProp(context, rawProps, "alignItems", sourceValue.alignItems(), yogaStyle.alignItems())); - yogaStyle.setAlignSelf(convertRawProp( - context, - rawProps, - "alignSelf", - sourceValue.alignSelf(), - yogaStyle.alignSelf())); + yogaStyle.setAlignSelf( + convertRawProp(context, rawProps, "alignSelf", sourceValue.alignSelf(), yogaStyle.alignSelf())); - yogaStyle.setPositionType(convertRawProp( - context, - rawProps, - "position", - sourceValue.positionType(), - yogaStyle.positionType())); + yogaStyle.setPositionType( + convertRawProp(context, rawProps, "position", sourceValue.positionType(), yogaStyle.positionType())); - yogaStyle.setFlexWrap(convertRawProp( - context, - rawProps, - "flexWrap", - sourceValue.flexWrap(), - yogaStyle.flexWrap())); + yogaStyle.setFlexWrap(convertRawProp(context, rawProps, "flexWrap", sourceValue.flexWrap(), yogaStyle.flexWrap())); - yogaStyle.setOverflow(convertRawProp( - context, - rawProps, - "overflow", - sourceValue.overflow(), - yogaStyle.overflow())); + yogaStyle.setOverflow(convertRawProp(context, rawProps, "overflow", sourceValue.overflow(), yogaStyle.overflow())); - yogaStyle.setDisplay(convertRawProp( - context, - rawProps, - "display", - sourceValue.display(), - yogaStyle.display())); + yogaStyle.setDisplay(convertRawProp(context, rawProps, "display", sourceValue.display(), yogaStyle.display())); - yogaStyle.setFlex(convertRawProp( - context, rawProps, "flex", sourceValue.flex(), yogaStyle.flex())); + yogaStyle.setFlex(convertRawProp(context, rawProps, "flex", sourceValue.flex(), yogaStyle.flex())); - yogaStyle.setFlexGrow(convertRawProp( - context, - rawProps, - "flexGrow", - sourceValue.flexGrow(), - yogaStyle.flexGrow())); + yogaStyle.setFlexGrow(convertRawProp(context, rawProps, "flexGrow", sourceValue.flexGrow(), yogaStyle.flexGrow())); - yogaStyle.setFlexShrink(convertRawProp( - context, - rawProps, - "flexShrink", - sourceValue.flexShrink(), - yogaStyle.flexShrink())); + yogaStyle.setFlexShrink( + convertRawProp(context, rawProps, "flexShrink", sourceValue.flexShrink(), yogaStyle.flexShrink())); - yogaStyle.setFlexBasis(convertRawProp( - context, - rawProps, - "flexBasis", - sourceValue.flexBasis(), - yogaStyle.flexBasis())); + yogaStyle.setFlexBasis( + convertRawProp(context, rawProps, "flexBasis", sourceValue.flexBasis(), yogaStyle.flexBasis())); yogaStyle.setMargin( yoga::Edge::Left, convertRawProp( - context, - rawProps, - "marginLeft", - sourceValue.margin(yoga::Edge::Left), - yogaStyle.margin(yoga::Edge::Left))); + context, rawProps, "marginLeft", sourceValue.margin(yoga::Edge::Left), yogaStyle.margin(yoga::Edge::Left))); yogaStyle.setMargin( yoga::Edge::Top, convertRawProp( - context, - rawProps, - "marginTop", - sourceValue.margin(yoga::Edge::Top), - yogaStyle.margin(yoga::Edge::Top))); + context, rawProps, "marginTop", sourceValue.margin(yoga::Edge::Top), yogaStyle.margin(yoga::Edge::Top))); yogaStyle.setMargin( yoga::Edge::Right, @@ -164,11 +98,7 @@ static inline yoga::Style convertRawProp( yogaStyle.setMargin( yoga::Edge::End, convertRawProp( - context, - rawProps, - "marginEnd", - sourceValue.margin(yoga::Edge::End), - yogaStyle.margin(yoga::Edge::End))); + context, rawProps, "marginEnd", sourceValue.margin(yoga::Edge::End), yogaStyle.margin(yoga::Edge::End))); yogaStyle.setMargin( yoga::Edge::Horizontal, @@ -191,38 +121,22 @@ static inline yoga::Style convertRawProp( yogaStyle.setMargin( yoga::Edge::All, convertRawProp( - context, - rawProps, - "margin", - sourceValue.margin(yoga::Edge::All), - yogaStyle.margin(yoga::Edge::All))); + context, rawProps, "margin", sourceValue.margin(yoga::Edge::All), yogaStyle.margin(yoga::Edge::All))); yogaStyle.setPosition( yoga::Edge::Left, convertRawProp( - context, - rawProps, - "left", - sourceValue.position(yoga::Edge::Left), - yogaStyle.position(yoga::Edge::Left))); + context, rawProps, "left", sourceValue.position(yoga::Edge::Left), yogaStyle.position(yoga::Edge::Left))); yogaStyle.setPosition( yoga::Edge::Top, convertRawProp( - context, - rawProps, - "top", - sourceValue.position(yoga::Edge::Top), - yogaStyle.position(yoga::Edge::Top))); + context, rawProps, "top", sourceValue.position(yoga::Edge::Top), yogaStyle.position(yoga::Edge::Top))); yogaStyle.setPosition( yoga::Edge::Right, convertRawProp( - context, - rawProps, - "right", - sourceValue.position(yoga::Edge::Right), - yogaStyle.position(yoga::Edge::Right))); + context, rawProps, "right", sourceValue.position(yoga::Edge::Right), yogaStyle.position(yoga::Edge::Right))); yogaStyle.setPosition( yoga::Edge::Bottom, @@ -236,20 +150,12 @@ static inline yoga::Style convertRawProp( yogaStyle.setPosition( yoga::Edge::Start, convertRawProp( - context, - rawProps, - "start", - sourceValue.position(yoga::Edge::Start), - yogaStyle.position(yoga::Edge::Start))); + context, rawProps, "start", sourceValue.position(yoga::Edge::Start), yogaStyle.position(yoga::Edge::Start))); yogaStyle.setPosition( yoga::Edge::End, convertRawProp( - context, - rawProps, - "end", - sourceValue.position(yoga::Edge::End), - yogaStyle.position(yoga::Edge::End))); + context, rawProps, "end", sourceValue.position(yoga::Edge::End), yogaStyle.position(yoga::Edge::End))); yogaStyle.setPosition( yoga::Edge::Horizontal, @@ -272,11 +178,7 @@ static inline yoga::Style convertRawProp( yogaStyle.setPosition( yoga::Edge::All, convertRawProp( - context, - rawProps, - "inset", - sourceValue.position(yoga::Edge::All), - yogaStyle.position(yoga::Edge::All))); + context, rawProps, "inset", sourceValue.position(yoga::Edge::All), yogaStyle.position(yoga::Edge::All))); yogaStyle.setPadding( yoga::Edge::Left, @@ -290,11 +192,7 @@ static inline yoga::Style convertRawProp( yogaStyle.setPadding( yoga::Edge::Top, convertRawProp( - context, - rawProps, - "paddingTop", - sourceValue.padding(yoga::Edge::Top), - yogaStyle.padding(yoga::Edge::Top))); + context, rawProps, "paddingTop", sourceValue.padding(yoga::Edge::Top), yogaStyle.padding(yoga::Edge::Top))); yogaStyle.setPadding( yoga::Edge::Right, @@ -326,11 +224,7 @@ static inline yoga::Style convertRawProp( yogaStyle.setPadding( yoga::Edge::End, convertRawProp( - context, - rawProps, - "paddingEnd", - sourceValue.padding(yoga::Edge::End), - yogaStyle.padding(yoga::Edge::End))); + context, rawProps, "paddingEnd", sourceValue.padding(yoga::Edge::End), yogaStyle.padding(yoga::Edge::End))); yogaStyle.setPadding( yoga::Edge::Horizontal, @@ -353,38 +247,21 @@ static inline yoga::Style convertRawProp( yogaStyle.setPadding( yoga::Edge::All, convertRawProp( - context, - rawProps, - "padding", - sourceValue.padding(yoga::Edge::All), - yogaStyle.padding(yoga::Edge::All))); + context, rawProps, "padding", sourceValue.padding(yoga::Edge::All), yogaStyle.padding(yoga::Edge::All))); yogaStyle.setGap( yoga::Gutter::Row, convertRawProp( - context, - rawProps, - "rowGap", - sourceValue.gap(yoga::Gutter::Row), - yogaStyle.gap(yoga::Gutter::Row))); + context, rawProps, "rowGap", sourceValue.gap(yoga::Gutter::Row), yogaStyle.gap(yoga::Gutter::Row))); yogaStyle.setGap( yoga::Gutter::Column, convertRawProp( - context, - rawProps, - "columnGap", - sourceValue.gap(yoga::Gutter::Column), - yogaStyle.gap(yoga::Gutter::Column))); + context, rawProps, "columnGap", sourceValue.gap(yoga::Gutter::Column), yogaStyle.gap(yoga::Gutter::Column))); yogaStyle.setGap( yoga::Gutter::All, - convertRawProp( - context, - rawProps, - "gap", - sourceValue.gap(yoga::Gutter::All), - yogaStyle.gap(yoga::Gutter::All))); + convertRawProp(context, rawProps, "gap", sourceValue.gap(yoga::Gutter::All), yogaStyle.gap(yoga::Gutter::All))); yogaStyle.setBorder( yoga::Edge::Left, @@ -398,11 +275,7 @@ static inline yoga::Style convertRawProp( yogaStyle.setBorder( yoga::Edge::Top, convertRawProp( - context, - rawProps, - "borderTopWidth", - sourceValue.border(yoga::Edge::Top), - yogaStyle.border(yoga::Edge::Top))); + context, rawProps, "borderTopWidth", sourceValue.border(yoga::Edge::Top), yogaStyle.border(yoga::Edge::Top))); yogaStyle.setBorder( yoga::Edge::Right, @@ -434,11 +307,7 @@ static inline yoga::Style convertRawProp( yogaStyle.setBorder( yoga::Edge::End, convertRawProp( - context, - rawProps, - "borderEndWidth", - sourceValue.border(yoga::Edge::End), - yogaStyle.border(yoga::Edge::End))); + context, rawProps, "borderEndWidth", sourceValue.border(yoga::Edge::End), yogaStyle.border(yoga::Edge::End))); yogaStyle.setBorder( yoga::Edge::Horizontal, @@ -461,79 +330,37 @@ static inline yoga::Style convertRawProp( yogaStyle.setBorder( yoga::Edge::All, convertRawProp( - context, - rawProps, - "borderWidth", - sourceValue.border(yoga::Edge::All), - yogaStyle.border(yoga::Edge::All))); + context, rawProps, "borderWidth", sourceValue.border(yoga::Edge::All), yogaStyle.border(yoga::Edge::All))); yogaStyle.setDimension( yoga::Dimension::Width, - convertRawProp( - context, - rawProps, - "width", - sourceValue.dimension(yoga::Dimension::Width), - {})); + convertRawProp(context, rawProps, "width", sourceValue.dimension(yoga::Dimension::Width), {})); yogaStyle.setDimension( yoga::Dimension::Height, - convertRawProp( - context, - rawProps, - "height", - sourceValue.dimension(yoga::Dimension::Height), - {})); + convertRawProp(context, rawProps, "height", sourceValue.dimension(yoga::Dimension::Height), {})); yogaStyle.setMinDimension( yoga::Dimension::Width, - convertRawProp( - context, - rawProps, - "minWidth", - sourceValue.minDimension(yoga::Dimension::Width), - {})); + convertRawProp(context, rawProps, "minWidth", sourceValue.minDimension(yoga::Dimension::Width), {})); yogaStyle.setMinDimension( yoga::Dimension::Height, - convertRawProp( - context, - rawProps, - "minHeight", - sourceValue.minDimension(yoga::Dimension::Height), - {})); + convertRawProp(context, rawProps, "minHeight", sourceValue.minDimension(yoga::Dimension::Height), {})); yogaStyle.setMaxDimension( yoga::Dimension::Width, - convertRawProp( - context, - rawProps, - "maxWidth", - sourceValue.maxDimension(yoga::Dimension::Width), - {})); + convertRawProp(context, rawProps, "maxWidth", sourceValue.maxDimension(yoga::Dimension::Width), {})); yogaStyle.setMaxDimension( yoga::Dimension::Height, - convertRawProp( - context, - rawProps, - "maxHeight", - sourceValue.maxDimension(yoga::Dimension::Height), - {})); + convertRawProp(context, rawProps, "maxHeight", sourceValue.maxDimension(yoga::Dimension::Height), {})); - yogaStyle.setAspectRatio(convertRawProp( - context, - rawProps, - "aspectRatio", - sourceValue.aspectRatio(), - yogaStyle.aspectRatio())); + yogaStyle.setAspectRatio( + convertRawProp(context, rawProps, "aspectRatio", sourceValue.aspectRatio(), yogaStyle.aspectRatio())); - yogaStyle.setBoxSizing(convertRawProp( - context, - rawProps, - "boxSizing", - sourceValue.boxSizing(), - yogaStyle.boxSizing())); + yogaStyle.setBoxSizing( + convertRawProp(context, rawProps, "boxSizing", sourceValue.boxSizing(), yogaStyle.boxSizing())); return yogaStyle; } @@ -541,251 +368,93 @@ static inline yoga::Style convertRawProp( // This can be deleted when non-iterator ViewProp parsing is deleted template static inline CascadedRectangleCorners convertRawProp( - const PropsParserContext& context, - const RawProps& rawProps, - const char* prefix, - const char* suffix, - const CascadedRectangleCorners& sourceValue, - const CascadedRectangleCorners& defaultValue) { + const PropsParserContext &context, + const RawProps &rawProps, + const char *prefix, + const char *suffix, + const CascadedRectangleCorners &sourceValue, + const CascadedRectangleCorners &defaultValue) +{ CascadedRectangleCorners result; - result.topLeft = convertRawProp( - context, - rawProps, - "TopLeft", - sourceValue.topLeft, - defaultValue.topLeft, - prefix, - suffix); - result.topRight = convertRawProp( - context, - rawProps, - "TopRight", - sourceValue.topRight, - defaultValue.topRight, - prefix, - suffix); - result.bottomLeft = convertRawProp( - context, - rawProps, - "BottomLeft", - sourceValue.bottomLeft, - defaultValue.bottomLeft, - prefix, - suffix); + result.topLeft = + convertRawProp(context, rawProps, "TopLeft", sourceValue.topLeft, defaultValue.topLeft, prefix, suffix); + result.topRight = + convertRawProp(context, rawProps, "TopRight", sourceValue.topRight, defaultValue.topRight, prefix, suffix); + result.bottomLeft = + convertRawProp(context, rawProps, "BottomLeft", sourceValue.bottomLeft, defaultValue.bottomLeft, prefix, suffix); result.bottomRight = convertRawProp( - context, - rawProps, - "BottomRight", - sourceValue.bottomRight, - defaultValue.bottomRight, - prefix, - suffix); + context, rawProps, "BottomRight", sourceValue.bottomRight, defaultValue.bottomRight, prefix, suffix); - result.topStart = convertRawProp( - context, - rawProps, - "TopStart", - sourceValue.topStart, - defaultValue.topStart, - prefix, - suffix); - result.topEnd = convertRawProp( - context, - rawProps, - "TopEnd", - sourceValue.topEnd, - defaultValue.topEnd, - prefix, - suffix); + result.topStart = + convertRawProp(context, rawProps, "TopStart", sourceValue.topStart, defaultValue.topStart, prefix, suffix); + result.topEnd = convertRawProp(context, rawProps, "TopEnd", sourceValue.topEnd, defaultValue.topEnd, prefix, suffix); result.bottomStart = convertRawProp( - context, - rawProps, - "BottomStart", - sourceValue.bottomStart, - defaultValue.bottomStart, - prefix, - suffix); - result.bottomEnd = convertRawProp( - context, - rawProps, - "BottomEnd", - sourceValue.bottomEnd, - defaultValue.bottomEnd, - prefix, - suffix); - result.endEnd = convertRawProp( - context, - rawProps, - "EndEnd", - sourceValue.endEnd, - defaultValue.endEnd, - prefix, - suffix); - result.endStart = convertRawProp( - context, - rawProps, - "EndStart", - sourceValue.endStart, - defaultValue.endStart, - prefix, - suffix); - result.startEnd = convertRawProp( - context, - rawProps, - "StartEnd", - sourceValue.startEnd, - defaultValue.startEnd, - prefix, - suffix); - result.startStart = convertRawProp( - context, - rawProps, - "StartStart", - sourceValue.startStart, - defaultValue.startStart, - prefix, - suffix); + context, rawProps, "BottomStart", sourceValue.bottomStart, defaultValue.bottomStart, prefix, suffix); + result.bottomEnd = + convertRawProp(context, rawProps, "BottomEnd", sourceValue.bottomEnd, defaultValue.bottomEnd, prefix, suffix); + result.endEnd = convertRawProp(context, rawProps, "EndEnd", sourceValue.endEnd, defaultValue.endEnd, prefix, suffix); + result.endStart = + convertRawProp(context, rawProps, "EndStart", sourceValue.endStart, defaultValue.endStart, prefix, suffix); + result.startEnd = + convertRawProp(context, rawProps, "StartEnd", sourceValue.startEnd, defaultValue.startEnd, prefix, suffix); + result.startStart = + convertRawProp(context, rawProps, "StartStart", sourceValue.startStart, defaultValue.startStart, prefix, suffix); - result.all = convertRawProp( - context, rawProps, "", sourceValue.all, defaultValue.all, prefix, suffix); + result.all = convertRawProp(context, rawProps, "", sourceValue.all, defaultValue.all, prefix, suffix); return result; } template static inline CascadedRectangleEdges convertRawProp( - const PropsParserContext& context, - const RawProps& rawProps, - const char* prefix, - const char* suffix, - const CascadedRectangleEdges& sourceValue, - const CascadedRectangleEdges& defaultValue) { + const PropsParserContext &context, + const RawProps &rawProps, + const char *prefix, + const char *suffix, + const CascadedRectangleEdges &sourceValue, + const CascadedRectangleEdges &defaultValue) +{ CascadedRectangleEdges result; - result.left = convertRawProp( - context, - rawProps, - "Left", - sourceValue.left, - defaultValue.left, - prefix, - suffix); - result.right = convertRawProp( - context, - rawProps, - "Right", - sourceValue.right, - defaultValue.right, - prefix, - suffix); - result.top = convertRawProp( - context, - rawProps, - "Top", - sourceValue.top, - defaultValue.top, - prefix, - suffix); - result.bottom = convertRawProp( - context, - rawProps, - "Bottom", - sourceValue.bottom, - defaultValue.bottom, - prefix, - suffix); + result.left = convertRawProp(context, rawProps, "Left", sourceValue.left, defaultValue.left, prefix, suffix); + result.right = convertRawProp(context, rawProps, "Right", sourceValue.right, defaultValue.right, prefix, suffix); + result.top = convertRawProp(context, rawProps, "Top", sourceValue.top, defaultValue.top, prefix, suffix); + result.bottom = convertRawProp(context, rawProps, "Bottom", sourceValue.bottom, defaultValue.bottom, prefix, suffix); - result.start = convertRawProp( - context, - rawProps, - "Start", - sourceValue.start, - defaultValue.start, - prefix, - suffix); - result.end = convertRawProp( - context, - rawProps, - "End", - sourceValue.end, - defaultValue.end, - prefix, - suffix); - result.horizontal = convertRawProp( - context, - rawProps, - "Horizontal", - sourceValue.horizontal, - defaultValue.horizontal, - prefix, - suffix); - result.vertical = convertRawProp( - context, - rawProps, - "Vertical", - sourceValue.vertical, - defaultValue.vertical, - prefix, - suffix); - result.block = convertRawProp( - context, - rawProps, - "Block", - sourceValue.block, - defaultValue.block, - prefix, - suffix); - result.blockEnd = convertRawProp( - context, - rawProps, - "BlockEnd", - sourceValue.blockEnd, - defaultValue.blockEnd, - prefix, - suffix); - result.blockStart = convertRawProp( - context, - rawProps, - "BlockStart", - sourceValue.blockStart, - defaultValue.blockStart, - prefix, - suffix); + result.start = convertRawProp(context, rawProps, "Start", sourceValue.start, defaultValue.start, prefix, suffix); + result.end = convertRawProp(context, rawProps, "End", sourceValue.end, defaultValue.end, prefix, suffix); + result.horizontal = + convertRawProp(context, rawProps, "Horizontal", sourceValue.horizontal, defaultValue.horizontal, prefix, suffix); + result.vertical = + convertRawProp(context, rawProps, "Vertical", sourceValue.vertical, defaultValue.vertical, prefix, suffix); + result.block = convertRawProp(context, rawProps, "Block", sourceValue.block, defaultValue.block, prefix, suffix); + result.blockEnd = + convertRawProp(context, rawProps, "BlockEnd", sourceValue.blockEnd, defaultValue.blockEnd, prefix, suffix); + result.blockStart = + convertRawProp(context, rawProps, "BlockStart", sourceValue.blockStart, defaultValue.blockStart, prefix, suffix); - result.all = convertRawProp( - context, rawProps, "", sourceValue.all, defaultValue.all, prefix, suffix); + result.all = convertRawProp(context, rawProps, "", sourceValue.all, defaultValue.all, prefix, suffix); return result; } // This can be deleted when non-iterator ViewProp parsing is deleted static inline ViewEvents convertRawProp( - const PropsParserContext& context, - const RawProps& rawProps, - const ViewEvents& sourceValue, - const ViewEvents& defaultValue) { + const PropsParserContext &context, + const RawProps &rawProps, + const ViewEvents &sourceValue, + const ViewEvents &defaultValue) +{ ViewEvents result{}; using Offset = ViewEvents::Offset; result[Offset::PointerEnter] = convertRawProp( - context, - rawProps, - "onPointerEnter", - sourceValue[Offset::PointerEnter], - defaultValue[Offset::PointerEnter]); + context, rawProps, "onPointerEnter", sourceValue[Offset::PointerEnter], defaultValue[Offset::PointerEnter]); result[Offset::PointerMove] = convertRawProp( - context, - rawProps, - "onPointerMove", - sourceValue[Offset::PointerMove], - defaultValue[Offset::PointerMove]); + context, rawProps, "onPointerMove", sourceValue[Offset::PointerMove], defaultValue[Offset::PointerMove]); result[Offset::PointerLeave] = convertRawProp( - context, - rawProps, - "onPointerLeave", - sourceValue[Offset::PointerLeave], - defaultValue[Offset::PointerLeave]); + context, rawProps, "onPointerLeave", sourceValue[Offset::PointerLeave], defaultValue[Offset::PointerLeave]); // Experimental W3C Pointer callbacks result[Offset::PointerEnterCapture] = convertRawProp( @@ -807,11 +476,7 @@ static inline ViewEvents convertRawProp( sourceValue[Offset::PointerLeaveCapture], defaultValue[Offset::PointerLeaveCapture]); result[Offset::PointerOver] = convertRawProp( - context, - rawProps, - "onPointerOver", - sourceValue[Offset::PointerOver], - defaultValue[Offset::PointerOver]); + context, rawProps, "onPointerOver", sourceValue[Offset::PointerOver], defaultValue[Offset::PointerOver]); result[Offset::PointerOverCapture] = convertRawProp( context, rawProps, @@ -819,47 +484,27 @@ static inline ViewEvents convertRawProp( sourceValue[Offset::PointerOverCapture], defaultValue[Offset::PointerOverCapture]); result[Offset::PointerOut] = convertRawProp( - context, - rawProps, - "onPointerOut", - sourceValue[Offset::PointerOut], - defaultValue[Offset::PointerOut]); + context, rawProps, "onPointerOut", sourceValue[Offset::PointerOut], defaultValue[Offset::PointerOut]); result[Offset::PointerOutCapture] = convertRawProp( context, rawProps, "onPointerOutCapture", sourceValue[Offset::PointerOutCapture], defaultValue[Offset::PointerOutCapture]); - result[Offset::Click] = convertRawProp( - context, - rawProps, - "onClick", - sourceValue[Offset::Click], - defaultValue[Offset::Click]); + result[Offset::Click] = + convertRawProp(context, rawProps, "onClick", sourceValue[Offset::Click], defaultValue[Offset::Click]); result[Offset::ClickCapture] = convertRawProp( - context, - rawProps, - "onClickCapture", - sourceValue[Offset::ClickCapture], - defaultValue[Offset::ClickCapture]); + context, rawProps, "onClickCapture", sourceValue[Offset::ClickCapture], defaultValue[Offset::ClickCapture]); result[Offset::PointerDown] = convertRawProp( - context, - rawProps, - "onPointerDown", - sourceValue[Offset::PointerDown], - defaultValue[Offset::PointerDown]); + context, rawProps, "onPointerDown", sourceValue[Offset::PointerDown], defaultValue[Offset::PointerDown]); result[Offset::PointerDownCapture] = convertRawProp( context, rawProps, "onPointerDownCapture", sourceValue[Offset::PointerDownCapture], defaultValue[Offset::PointerDownCapture]); - result[Offset::PointerUp] = convertRawProp( - context, - rawProps, - "onPointerUp", - sourceValue[Offset::PointerUp], - defaultValue[Offset::PointerUp]); + result[Offset::PointerUp] = + convertRawProp(context, rawProps, "onPointerUp", sourceValue[Offset::PointerUp], defaultValue[Offset::PointerUp]); result[Offset::PointerUpCapture] = convertRawProp( context, rawProps, @@ -894,11 +539,7 @@ static inline ViewEvents convertRawProp( sourceValue[Offset::StartShouldSetResponderCapture], defaultValue[Offset::StartShouldSetResponderCapture]); result[Offset::ResponderGrant] = convertRawProp( - context, - rawProps, - "onResponderGrant", - sourceValue[Offset::ResponderGrant], - defaultValue[Offset::ResponderGrant]); + context, rawProps, "onResponderGrant", sourceValue[Offset::ResponderGrant], defaultValue[Offset::ResponderGrant]); result[Offset::ResponderReject] = convertRawProp( context, rawProps, @@ -906,17 +547,9 @@ static inline ViewEvents convertRawProp( sourceValue[Offset::ResponderReject], defaultValue[Offset::ResponderReject]); result[Offset::ResponderStart] = convertRawProp( - context, - rawProps, - "onResponderStart", - sourceValue[Offset::ResponderStart], - defaultValue[Offset::ResponderStart]); + context, rawProps, "onResponderStart", sourceValue[Offset::ResponderStart], defaultValue[Offset::ResponderStart]); result[Offset::ResponderEnd] = convertRawProp( - context, - rawProps, - "onResponderEnd", - sourceValue[Offset::ResponderEnd], - defaultValue[Offset::ResponderEnd]); + context, rawProps, "onResponderEnd", sourceValue[Offset::ResponderEnd], defaultValue[Offset::ResponderEnd]); result[Offset::ResponderRelease] = convertRawProp( context, rawProps, @@ -924,11 +557,7 @@ static inline ViewEvents convertRawProp( sourceValue[Offset::ResponderRelease], defaultValue[Offset::ResponderRelease]); result[Offset::ResponderMove] = convertRawProp( - context, - rawProps, - "onResponderMove", - sourceValue[Offset::ResponderMove], - defaultValue[Offset::ResponderMove]); + context, rawProps, "onResponderMove", sourceValue[Offset::ResponderMove], defaultValue[Offset::ResponderMove]); result[Offset::ResponderTerminate] = convertRawProp( context, rawProps, @@ -950,29 +579,13 @@ static inline ViewEvents convertRawProp( // Touch events result[Offset::TouchStart] = convertRawProp( - context, - rawProps, - "onTouchStart", - sourceValue[Offset::TouchStart], - defaultValue[Offset::TouchStart]); - result[Offset::TouchMove] = convertRawProp( - context, - rawProps, - "onTouchMove", - sourceValue[Offset::TouchMove], - defaultValue[Offset::TouchMove]); - result[Offset::TouchEnd] = convertRawProp( - context, - rawProps, - "onTouchEnd", - sourceValue[Offset::TouchEnd], - defaultValue[Offset::TouchEnd]); + context, rawProps, "onTouchStart", sourceValue[Offset::TouchStart], defaultValue[Offset::TouchStart]); + result[Offset::TouchMove] = + convertRawProp(context, rawProps, "onTouchMove", sourceValue[Offset::TouchMove], defaultValue[Offset::TouchMove]); + result[Offset::TouchEnd] = + convertRawProp(context, rawProps, "onTouchEnd", sourceValue[Offset::TouchEnd], defaultValue[Offset::TouchEnd]); result[Offset::TouchCancel] = convertRawProp( - context, - rawProps, - "onTouchCancel", - sourceValue[Offset::TouchCancel], - defaultValue[Offset::TouchCancel]); + context, rawProps, "onTouchCancel", sourceValue[Offset::TouchCancel], defaultValue[Offset::TouchCancel]); return result; } diff --git a/packages/react-native/ReactCommon/react/renderer/components/view/tests/ConversionsTest.cpp b/packages/react-native/ReactCommon/react/renderer/components/view/tests/ConversionsTest.cpp index a21bade8c22..b54b60430f7 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/view/tests/ConversionsTest.cpp +++ b/packages/react-native/ReactCommon/react/renderer/components/view/tests/ConversionsTest.cpp @@ -64,8 +64,9 @@ TEST(ConversionsTest, unprocessed_box_shadow_objects) { } TEST(ConversionsTest, unprocessed_box_object_invalid_color) { - RawValue value{folly::dynamic::array(folly::dynamic::object("offsetX", 10)( - "offsetY", 2)("blurRadius", 3)("spreadDistance", 5)("color", "hello"))}; + RawValue value{folly::dynamic::array( + folly::dynamic::object("offsetX", 10)("offsetY", 2)("blurRadius", 3)( + "spreadDistance", 5)("color", "hello"))}; std::vector boxShadows; parseUnprocessedBoxShadow( @@ -75,8 +76,9 @@ TEST(ConversionsTest, unprocessed_box_object_invalid_color) { } TEST(ConversionsTest, unprocessed_box_object_negative_blur) { - RawValue value{folly::dynamic::array(folly::dynamic::object("offsetX", 10)( - "offsetY", 2)("blurRadius", -3)("spreadDistance", 5))}; + RawValue value{folly::dynamic::array( + folly::dynamic::object("offsetX", 10)("offsetY", 2)("blurRadius", -3)( + "spreadDistance", 5))}; std::vector boxShadows; parseUnprocessedBoxShadow( @@ -177,10 +179,11 @@ TEST(ConversionsTest, unprocessed_filter_objects) { } TEST(ConversionsTest, unprocessed_filter_objects_negative_shadow_blur) { - RawValue value{folly::dynamic::array(folly::dynamic::object( - "drop-shadow", - folly::dynamic::object("offsetX", 10)("offsetY", "-2px")( - "standardDeviation", -0.5)))}; + RawValue value{folly::dynamic::array( + folly::dynamic::object( + "drop-shadow", + folly::dynamic::object("offsetX", 10)("offsetY", "-2px")( + "standardDeviation", -0.5)))}; std::vector filters; parseUnprocessedFilter( diff --git a/packages/react-native/ReactCommon/react/renderer/components/virtualview/VirtualViewComponentDescriptor.h b/packages/react-native/ReactCommon/react/renderer/components/virtualview/VirtualViewComponentDescriptor.h index 955cfe6a731..a8b739d0911 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/virtualview/VirtualViewComponentDescriptor.h +++ b/packages/react-native/ReactCommon/react/renderer/components/virtualview/VirtualViewComponentDescriptor.h @@ -15,6 +15,5 @@ namespace facebook::react { /* * Descriptor for component. */ -using VirtualViewComponentDescriptor = - ConcreteComponentDescriptor; +using VirtualViewComponentDescriptor = ConcreteComponentDescriptor; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/components/virtualview/VirtualViewShadowNode.h b/packages/react-native/ReactCommon/react/renderer/components/virtualview/VirtualViewShadowNode.h index 1bb3411501a..7b1d1fc6cc0 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/virtualview/VirtualViewShadowNode.h +++ b/packages/react-native/ReactCommon/react/renderer/components/virtualview/VirtualViewShadowNode.h @@ -18,14 +18,13 @@ constexpr const char VirtualViewComponentName[] = "VirtualView"; /* * `ShadowNode` for component. */ -class VirtualViewShadowNode final : public ConcreteViewShadowNode< - VirtualViewComponentName, - VirtualViewProps, - VirtualViewEventEmitter> { +class VirtualViewShadowNode final + : public ConcreteViewShadowNode { public: using ConcreteViewShadowNode::ConcreteViewShadowNode; - static ShadowNodeTraits BaseTraits() { + static ShadowNodeTraits BaseTraits() + { auto traits = ConcreteViewShadowNode::BaseTraits(); // has a side effect: it listens to scroll events. // It must not be culled, otherwise Fling will not work. diff --git a/packages/react-native/ReactCommon/react/renderer/components/virtualviewexperimental/VirtualViewExperimentalComponentDescriptor.h b/packages/react-native/ReactCommon/react/renderer/components/virtualviewexperimental/VirtualViewExperimentalComponentDescriptor.h index f45a0fdcf4a..35928f9eb3b 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/virtualviewexperimental/VirtualViewExperimentalComponentDescriptor.h +++ b/packages/react-native/ReactCommon/react/renderer/components/virtualviewexperimental/VirtualViewExperimentalComponentDescriptor.h @@ -15,6 +15,5 @@ namespace facebook::react { /* * Descriptor for component. */ -using VirtualViewExperimentalComponentDescriptor = - ConcreteComponentDescriptor; +using VirtualViewExperimentalComponentDescriptor = ConcreteComponentDescriptor; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/components/virtualviewexperimental/VirtualViewExperimentalShadowNode.h b/packages/react-native/ReactCommon/react/renderer/components/virtualviewexperimental/VirtualViewExperimentalShadowNode.h index 3f64ab34fda..38ff24c7b59 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/virtualviewexperimental/VirtualViewExperimentalShadowNode.h +++ b/packages/react-native/ReactCommon/react/renderer/components/virtualviewexperimental/VirtualViewExperimentalShadowNode.h @@ -13,21 +13,20 @@ namespace facebook::react { -constexpr const char VirtualViewExperimentalComponentName[] = - "VirtualViewExperimental"; +constexpr const char VirtualViewExperimentalComponentName[] = "VirtualViewExperimental"; /* * `ShadowNode` for component. */ -class VirtualViewExperimentalShadowNode final - : public ConcreteViewShadowNode< - VirtualViewExperimentalComponentName, - VirtualViewExperimentalProps, - VirtualViewEventEmitter> { +class VirtualViewExperimentalShadowNode final : public ConcreteViewShadowNode< + VirtualViewExperimentalComponentName, + VirtualViewExperimentalProps, + VirtualViewEventEmitter> { public: using ConcreteViewShadowNode::ConcreteViewShadowNode; - static ShadowNodeTraits BaseTraits() { + static ShadowNodeTraits BaseTraits() + { auto traits = ConcreteViewShadowNode::BaseTraits(); // has a side effect: it listens to scroll events. // It must not be culled, otherwise Fling will not work. diff --git a/packages/react-native/ReactCommon/react/renderer/consistency/ScopedShadowTreeRevisionLock.h b/packages/react-native/ReactCommon/react/renderer/consistency/ScopedShadowTreeRevisionLock.h index 2bc68d8a2be..51df90e7f26 100644 --- a/packages/react-native/ReactCommon/react/renderer/consistency/ScopedShadowTreeRevisionLock.h +++ b/packages/react-native/ReactCommon/react/renderer/consistency/ScopedShadowTreeRevisionLock.h @@ -23,32 +23,31 @@ namespace facebook::react { */ class ScopedShadowTreeRevisionLock { public: - explicit ScopedShadowTreeRevisionLock( - ShadowTreeRevisionConsistencyManager* consistencyManager) noexcept - : consistencyManager_(consistencyManager) { + explicit ScopedShadowTreeRevisionLock(ShadowTreeRevisionConsistencyManager *consistencyManager) noexcept + : consistencyManager_(consistencyManager) + { if (consistencyManager_ != nullptr) { consistencyManager_->lockRevisions(); } } // Non-movable - ScopedShadowTreeRevisionLock(const ScopedShadowTreeRevisionLock&) = delete; - ScopedShadowTreeRevisionLock(ScopedShadowTreeRevisionLock&&) = delete; + ScopedShadowTreeRevisionLock(const ScopedShadowTreeRevisionLock &) = delete; + ScopedShadowTreeRevisionLock(ScopedShadowTreeRevisionLock &&) = delete; // Non-copyable - ScopedShadowTreeRevisionLock& operator=(const ScopedShadowTreeRevisionLock&) = - delete; - ScopedShadowTreeRevisionLock& operator=(ScopedShadowTreeRevisionLock&&) = - delete; + ScopedShadowTreeRevisionLock &operator=(const ScopedShadowTreeRevisionLock &) = delete; + ScopedShadowTreeRevisionLock &operator=(ScopedShadowTreeRevisionLock &&) = delete; - ~ScopedShadowTreeRevisionLock() noexcept { + ~ScopedShadowTreeRevisionLock() noexcept + { if (consistencyManager_ != nullptr) { consistencyManager_->unlockRevisions(); } } private: - ShadowTreeRevisionConsistencyManager* consistencyManager_; + ShadowTreeRevisionConsistencyManager *consistencyManager_; }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/core/ComponentDescriptor.h b/packages/react-native/ReactCommon/react/renderer/core/ComponentDescriptor.h index aa12f01db39..371f238ecec 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/ComponentDescriptor.h +++ b/packages/react-native/ReactCommon/react/renderer/core/ComponentDescriptor.h @@ -46,16 +46,14 @@ class ComponentDescriptor { */ using Flavor = std::shared_ptr; - explicit ComponentDescriptor( - const ComponentDescriptorParameters& parameters, - RawPropsParser&& rawPropsParser = {}); + explicit ComponentDescriptor(const ComponentDescriptorParameters ¶meters, RawPropsParser &&rawPropsParser = {}); virtual ~ComponentDescriptor() = default; /* * Returns stored instance of `ContextContainer`. */ - const std::shared_ptr& getContextContainer() const; + const std::shared_ptr &getContextContainer() const; /* * Returns `componentHandle` associated with particular kind of components. @@ -79,22 +77,22 @@ class ComponentDescriptor { * Creates a new `ShadowNode` of a particular component type. */ virtual std::shared_ptr createShadowNode( - const ShadowNodeFragment& fragment, - const ShadowNodeFamily::Shared& family) const = 0; + const ShadowNodeFragment &fragment, + const ShadowNodeFamily::Shared &family) const = 0; /* * Clones a `ShadowNode` with optionally new `props` and/or `children`. */ virtual std::shared_ptr cloneShadowNode( - const ShadowNode& sourceShadowNode, - const ShadowNodeFragment& fragment) const = 0; + const ShadowNode &sourceShadowNode, + const ShadowNodeFragment &fragment) const = 0; /* * Appends (by mutating) a given `childShadowNode` to `parentShadowNode`. */ virtual void appendChild( - const std::shared_ptr& parentShadowNode, - const std::shared_ptr& childShadowNode) const = 0; + const std::shared_ptr &parentShadowNode, + const std::shared_ptr &childShadowNode) const = 0; /* * Creates a new `Props` of a particular type with all values copied from @@ -103,32 +101,26 @@ class ComponentDescriptor { * will be used. * Must return an object which is NOT pointer equal to `props`. */ - virtual Props::Shared cloneProps( - const PropsParserContext& context, - const Props::Shared& props, - RawProps rawProps) const = 0; + virtual Props::Shared cloneProps(const PropsParserContext &context, const Props::Shared &props, RawProps rawProps) + const = 0; /* * Create an initial State object that represents (and contains) an initial * State's data which can be constructed based on initial Props. */ - virtual State::Shared createInitialState( - const Props::Shared& props, - const ShadowNodeFamily::Shared& family) const = 0; + virtual State::Shared createInitialState(const Props::Shared &props, const ShadowNodeFamily::Shared &family) + const = 0; /* * Creates a new State object that represents (and contains) a new version of * State's data. */ - virtual State::Shared createState( - const ShadowNodeFamily& family, - const StateData::Shared& data) const = 0; + virtual State::Shared createState(const ShadowNodeFamily &family, const StateData::Shared &data) const = 0; /* * Creates a shadow node family for particular node. */ - virtual ShadowNodeFamily::Shared createFamily( - const ShadowNodeFamilyFragment& fragment) const = 0; + virtual ShadowNodeFamily::Shared createFamily(const ShadowNodeFamilyFragment &fragment) const = 0; protected: friend ShadowNode; @@ -151,7 +143,7 @@ class ComponentDescriptor { * - Set `ShadowNode`'s size from state in * `ModalHostViewComponentDescriptor`. */ - virtual void adopt(ShadowNode& shadowNode) const = 0; + virtual void adopt(ShadowNode &shadowNode) const = 0; }; /* diff --git a/packages/react-native/ReactCommon/react/renderer/core/ConcreteComponentDescriptor.h b/packages/react-native/ReactCommon/react/renderer/core/ConcreteComponentDescriptor.h index db69fd56cca..811d7d4725d 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/ConcreteComponentDescriptor.h +++ b/packages/react-native/ReactCommon/react/renderer/core/ConcreteComponentDescriptor.h @@ -30,9 +30,7 @@ namespace facebook::react { */ template class ConcreteComponentDescriptor : public ComponentDescriptor { - static_assert( - std::is_base_of::value, - "ShadowNodeT must be a descendant of ShadowNode"); + static_assert(std::is_base_of::value, "ShadowNodeT must be a descendant of ShadowNode"); using SharedShadowNodeT = std::shared_ptr; @@ -41,44 +39,47 @@ class ConcreteComponentDescriptor : public ComponentDescriptor { using ConcreteProps = typename ShadowNodeT::ConcreteProps; using SharedConcreteProps = typename ShadowNodeT::SharedConcreteProps; using ConcreteEventEmitter = typename ShadowNodeT::ConcreteEventEmitter; - using SharedConcreteEventEmitter = - typename ShadowNodeT::SharedConcreteEventEmitter; + using SharedConcreteEventEmitter = typename ShadowNodeT::SharedConcreteEventEmitter; using ConcreteState = typename ShadowNodeT::ConcreteState; using ConcreteStateData = typename ShadowNodeT::ConcreteState::Data; explicit ConcreteComponentDescriptor( - const ComponentDescriptorParameters& parameters, - RawPropsParser&& rawPropsParser = {}) - : ComponentDescriptor(parameters, std::move(rawPropsParser)) { + const ComponentDescriptorParameters ¶meters, + RawPropsParser &&rawPropsParser = {}) + : ComponentDescriptor(parameters, std::move(rawPropsParser)) + { rawPropsParser_.prepare(); } - ComponentHandle getComponentHandle() const override { + ComponentHandle getComponentHandle() const override + { return ShadowNodeT::Handle(); } - ComponentName getComponentName() const override { + ComponentName getComponentName() const override + { return ShadowNodeT::Name(); } - ShadowNodeTraits getTraits() const override { + ShadowNodeTraits getTraits() const override + { return ShadowNodeT::BaseTraits(); } std::shared_ptr createShadowNode( - const ShadowNodeFragment& fragment, - const ShadowNodeFamily::Shared& family) const override { - auto shadowNode = - std::make_shared(fragment, family, getTraits()); + const ShadowNodeFragment &fragment, + const ShadowNodeFamily::Shared &family) const override + { + auto shadowNode = std::make_shared(fragment, family, getTraits()); adopt(*shadowNode); return shadowNode; } - std::shared_ptr cloneShadowNode( - const ShadowNode& sourceShadowNode, - const ShadowNodeFragment& fragment) const override { + std::shared_ptr cloneShadowNode(const ShadowNode &sourceShadowNode, const ShadowNodeFragment &fragment) + const override + { auto shadowNode = std::make_shared(sourceShadowNode, fragment); shadowNode->completeClone(sourceShadowNode, fragment); sourceShadowNode.transferRuntimeShadowNodeReference(shadowNode, fragment); @@ -88,18 +89,16 @@ class ConcreteComponentDescriptor : public ComponentDescriptor { } void appendChild( - const std::shared_ptr& parentShadowNode, - const std::shared_ptr& childShadowNode) const override { - auto& concreteParentShadowNode = - static_cast(*parentShadowNode); - const_cast(concreteParentShadowNode) - .appendChild(childShadowNode); + const std::shared_ptr &parentShadowNode, + const std::shared_ptr &childShadowNode) const override + { + auto &concreteParentShadowNode = static_cast(*parentShadowNode); + const_cast(concreteParentShadowNode).appendChild(childShadowNode); } - virtual Props::Shared cloneProps( - const PropsParserContext& context, - const Props::Shared& props, - RawProps rawProps) const override { + virtual Props::Shared cloneProps(const PropsParserContext &context, const Props::Shared &props, RawProps rawProps) + const override + { // Optimization: // Quite often nodes are constructed with default/empty props: the base // `props` object is `null` (there no base because it's not cloning) and the @@ -121,39 +120,32 @@ class ConcreteComponentDescriptor : public ComponentDescriptor { // the type of ShadowNode; it acts as the single global flag. if (ReactNativeFeatureFlags::enableCppPropsIteratorSetter()) { #ifdef RN_SERIALIZABLE_STATE - const auto& dynamic = shadowNodeProps->rawProps; + const auto &dynamic = shadowNodeProps->rawProps; #else - const auto& dynamic = static_cast(rawProps); + const auto &dynamic = static_cast(rawProps); #endif - for (const auto& pair : dynamic.items()) { - const auto& name = pair.first.getString(); - shadowNodeProps->setProp( - context, - RAW_PROPS_KEY_HASH(name), - name.c_str(), - RawValue(pair.second)); + for (const auto &pair : dynamic.items()) { + const auto &name = pair.first.getString(); + shadowNodeProps->setProp(context, RAW_PROPS_KEY_HASH(name), name.c_str(), RawValue(pair.second)); } } return shadowNodeProps; }; - virtual State::Shared createInitialState( - const Props::Shared& props, - const ShadowNodeFamily::Shared& family) const override { + virtual State::Shared createInitialState(const Props::Shared &props, const ShadowNodeFamily::Shared &family) + const override + { if (std::is_same::value) { // Default case: Returning `null` for nodes that don't use `State`. return nullptr; } return std::make_shared( - std::make_shared( - ConcreteShadowNode::initialStateData(props, family, *this)), - family); + std::make_shared(ConcreteShadowNode::initialStateData(props, family, *this)), family); } - virtual State::Shared createState( - const ShadowNodeFamily& family, - const StateData::Shared& data) const override { + virtual State::Shared createState(const ShadowNodeFamily &family, const StateData::Shared &data) const override + { if (std::is_same::value) { // Default case: Returning `null` for nodes that don't use `State`. return nullptr; @@ -162,37 +154,31 @@ class ConcreteComponentDescriptor : public ComponentDescriptor { react_native_assert(data && "Provided `data` is nullptr."); return std::make_shared( - std::static_pointer_cast(data), - *family.getMostRecentState()); + std::static_pointer_cast(data), *family.getMostRecentState()); } - ShadowNodeFamily::Shared createFamily( - const ShadowNodeFamilyFragment& fragment) const override { + ShadowNodeFamily::Shared createFamily(const ShadowNodeFamilyFragment &fragment) const override + { auto eventEmitter = std::make_shared( - std::make_shared( - fragment.instanceHandle, fragment.surfaceId), - eventDispatcher_); - auto family = std::make_shared( - fragment, eventEmitter, eventDispatcher_, *this); + std::make_shared(fragment.instanceHandle, fragment.surfaceId), eventDispatcher_); + auto family = std::make_shared(fragment, eventEmitter, eventDispatcher_, *this); eventEmitter->setShadowNodeFamily(family); return family; } protected: - virtual void adopt(ShadowNode& shadowNode) const override { + virtual void adopt(ShadowNode &shadowNode) const override + { // Default implementation does nothing. - react_native_assert( - shadowNode.getComponentHandle() == getComponentHandle()); + react_native_assert(shadowNode.getComponentHandle() == getComponentHandle()); } }; template -std::shared_ptr getManagerByName( - std::shared_ptr& contextContainer, - const char name[]) { +std::shared_ptr getManagerByName(std::shared_ptr &contextContainer, const char name[]) +{ if (contextContainer) { - if (auto manager = contextContainer->find>(name); - manager.has_value()) { + if (auto manager = contextContainer->find>(name); manager.has_value()) { return manager.value(); } } diff --git a/packages/react-native/ReactCommon/react/renderer/core/ConcreteShadowNode.h b/packages/react-native/ReactCommon/react/renderer/core/ConcreteShadowNode.h index 4f3174c19a0..9b885a0026f 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/ConcreteShadowNode.h +++ b/packages/react-native/ReactCommon/react/renderer/core/ConcreteShadowNode.h @@ -34,9 +34,7 @@ class ConcreteShadowNode : public BaseShadowNodeT { static_assert( std::is_base_of::value, "BaseShadowNodeT must be a descendant of ShadowNode"); - static_assert( - std::is_base_of::value, - "PropsT must be a descendant of Props"); + static_assert(std::is_base_of::value, "PropsT must be a descendant of Props"); protected: using ShadowNode::props_; @@ -54,11 +52,13 @@ class ConcreteShadowNode : public BaseShadowNodeT { using ConcreteState = ConcreteState; using ConcreteStateData = StateDataT; - static ComponentName Name() { + static ComponentName Name() + { return ComponentName(concreteComponentName); } - static ComponentHandle Handle() { + static ComponentHandle Handle() + { return ComponentHandle(concreteComponentName); } @@ -66,31 +66,29 @@ class ConcreteShadowNode : public BaseShadowNodeT { * A set of traits associated with a particular class. * Reimplement in subclasses to declare class-specific traits. */ - static ShadowNodeTraits BaseTraits() { + static ShadowNodeTraits BaseTraits() + { return BaseShadowNodeT::BaseTraits(); } - static UnsharedConcreteProps Props( - const PropsParserContext& context, - const RawProps& rawProps, - const Props::Shared& baseProps = nullptr) { + static UnsharedConcreteProps + Props(const PropsParserContext &context, const RawProps &rawProps, const Props::Shared &baseProps = nullptr) + { return std::make_shared( - context, - baseProps ? static_cast(*baseProps) - : *defaultSharedProps(), - rawProps); + context, baseProps ? static_cast(*baseProps) : *defaultSharedProps(), rawProps); } - static const SharedConcreteProps& defaultSharedProps() { - static const SharedConcreteProps defaultSharedProps = - std::make_shared(); + static const SharedConcreteProps &defaultSharedProps() + { + static const SharedConcreteProps defaultSharedProps = std::make_shared(); return defaultSharedProps; } static ConcreteStateData initialStateData( - const Props::Shared& /*props*/, - const ShadowNodeFamily::Shared& /*family*/, - const ComponentDescriptor& /*componentDescriptor*/) { + const Props::Shared & /*props*/, + const ShadowNodeFamily::Shared & /*family*/, + const ComponentDescriptor & /*componentDescriptor*/) + { return {}; } @@ -98,19 +96,19 @@ class ConcreteShadowNode : public BaseShadowNodeT { * Returns a concrete props object associated with the node. * Thread-safe after the node is sealed. */ - const ConcreteProps& getConcreteProps() const { - react_native_assert( - BaseShadowNodeT::props_ && "Props must not be `nullptr`."); - return static_cast(*props_); + const ConcreteProps &getConcreteProps() const + { + react_native_assert(BaseShadowNodeT::props_ && "Props must not be `nullptr`."); + return static_cast(*props_); } /* * Returns a concrete props object associated with the node, as a shared_ptr. * Thread-safe after the node is sealed. */ - const std::shared_ptr& getConcreteSharedProps() const { - react_native_assert( - BaseShadowNodeT::props_ && "Props must not be `nullptr`."); + const std::shared_ptr &getConcreteSharedProps() const + { + react_native_assert(BaseShadowNodeT::props_ && "Props must not be `nullptr`."); return std::static_pointer_cast(props_); } @@ -118,28 +116,29 @@ class ConcreteShadowNode : public BaseShadowNodeT { * Returns a concrete event emitter object associated with the node. * Thread-safe after the node is sealed. */ - const ConcreteEventEmitter& getConcreteEventEmitter() const { - return static_cast( - *BaseShadowNodeT::getEventEmitter()); + const ConcreteEventEmitter &getConcreteEventEmitter() const + { + return static_cast(*BaseShadowNodeT::getEventEmitter()); } /* * Returns a concrete state data associated with the node. * Thread-safe after the node is sealed. */ - const ConcreteStateData& getStateData() const { + const ConcreteStateData &getStateData() const + { react_native_assert(state_ && "State must not be `nullptr`."); - return static_cast(state_.get())->getData(); + return static_cast(state_.get())->getData(); } /* * Creates and assigns a new state object containing given state data. * Can be called only before the node is sealed (usually during construction). */ - void setStateData(ConcreteStateData&& data) { + void setStateData(ConcreteStateData &&data) + { Sealable::ensureUnsealed(); - state_ = std::make_shared( - std::make_shared(std::move(data)), *state_); + state_ = std::make_shared(std::make_shared(std::move(data)), *state_); } }; diff --git a/packages/react-native/ReactCommon/react/renderer/core/ConcreteState.h b/packages/react-native/ReactCommon/react/renderer/core/ConcreteState.h index c5bbfdf3f32..46ecb31aaf2 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/ConcreteState.h +++ b/packages/react-native/ReactCommon/react/renderer/core/ConcreteState.h @@ -49,23 +49,22 @@ class ConcreteState : public State { /* * Creates an updated `State` object with given previous one and `data`. */ - explicit ConcreteState(SharedData data, const State& previousState) - : State(std::move(data), previousState) {} + explicit ConcreteState(SharedData data, const State &previousState) : State(std::move(data), previousState) {} /* * Creates a first-of-its-family `State` object with given `family` and * `data`. */ - explicit ConcreteState(SharedData data, ShadowNodeFamily::Weak family) - : State(std::move(data), std::move(family)) {} + explicit ConcreteState(SharedData data, ShadowNodeFamily::Weak family) : State(std::move(data), std::move(family)) {} ~ConcreteState() override = default; /* * Returns stored data. */ - const Data& getData() const { - return *static_cast(data_.get()); + const Data &getData() const + { + return *static_cast(data_.get()); } /* @@ -74,12 +73,10 @@ class ConcreteState : public State { * function for cases where a new value of data does not depend on an old * value. */ - void updateState( - Data&& newData, - EventQueue::UpdateMode updateMode = - EventQueue::UpdateMode::Asynchronous) const { + void updateState(Data &&newData, EventQueue::UpdateMode updateMode = EventQueue::UpdateMode::Asynchronous) const + { updateState( - [data{std::move(newData)}](const Data& /*oldData*/) -> SharedData { + [data{std::move(newData)}](const Data & /*oldData*/) -> SharedData { return std::make_shared(data); }, updateMode); @@ -94,9 +91,9 @@ class ConcreteState : public State { * return `nullptr`. */ void updateState( - std::function callback, - EventQueue::UpdateMode updateMode = - EventQueue::UpdateMode::Asynchronous) const { + std::function callback, + EventQueue::UpdateMode updateMode = EventQueue::UpdateMode::Asynchronous) const + { auto family = family_.lock(); if (!family) { @@ -105,25 +102,27 @@ class ConcreteState : public State { return; } - auto stateUpdate = StateUpdate{ - family, [=](const StateData::Shared& oldData) -> StateData::Shared { - react_native_assert(oldData); - return callback(*static_cast(oldData.get())); - }}; + auto stateUpdate = StateUpdate{family, [=](const StateData::Shared &oldData) -> StateData::Shared { + react_native_assert(oldData); + return callback(*static_cast(oldData.get())); + }}; family->dispatchRawState(std::move(stateUpdate), updateMode); } #if defined(RN_SERIALIZABLE_STATE) - folly::dynamic getDynamic() const override { + folly::dynamic getDynamic() const override + { return getData().getDynamic(); } - void updateState(folly::dynamic&& data) const override { + void updateState(folly::dynamic &&data) const override + { updateState(Data(getData(), std::move(data))); } - MapBuffer getMapBuffer() const override { + MapBuffer getMapBuffer() const override + { if constexpr (StateDataWithMapBuffer) { return getData().getMapBuffer(); } else { @@ -131,7 +130,8 @@ class ConcreteState : public State { } } - jni::local_ref getJNIReference() const override { + jni::local_ref getJNIReference() const override + { if constexpr (StateDataWithJNIReference) { return getData().getJNIReference(); } else { diff --git a/packages/react-native/ReactCommon/react/renderer/core/DynamicEventPayload.h b/packages/react-native/ReactCommon/react/renderer/core/DynamicEventPayload.h index 26f55299fa9..22f26e6d65b 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/DynamicEventPayload.h +++ b/packages/react-native/ReactCommon/react/renderer/core/DynamicEventPayload.h @@ -13,15 +13,14 @@ namespace facebook::react { struct DynamicEventPayload : public EventPayload { - explicit DynamicEventPayload(folly::dynamic&& payload); + explicit DynamicEventPayload(folly::dynamic &&payload); /* * EventPayload implementations */ - jsi::Value asJSIValue(jsi::Runtime& runtime) const override; + jsi::Value asJSIValue(jsi::Runtime &runtime) const override; EventPayloadType getType() const override; - std::optional extractValue( - const std::vector& path) const override; + std::optional extractValue(const std::vector &path) const override; private: folly::dynamic payload_; diff --git a/packages/react-native/ReactCommon/react/renderer/core/DynamicPropsUtilities.h b/packages/react-native/ReactCommon/react/renderer/core/DynamicPropsUtilities.h index c318b77309c..a49d43b4f0a 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/DynamicPropsUtilities.h +++ b/packages/react-native/ReactCommon/react/renderer/core/DynamicPropsUtilities.h @@ -43,13 +43,9 @@ enum class NullValueStrategy { * represent a dictionary. It updates `source` with key/value pairs from * `patch`. */ -folly::dynamic mergeDynamicProps( - const folly::dynamic& source, - const folly::dynamic& patch, - NullValueStrategy nullValueStrategy); +folly::dynamic +mergeDynamicProps(const folly::dynamic &source, const folly::dynamic &patch, NullValueStrategy nullValueStrategy); -folly::dynamic diffDynamicProps( - const folly::dynamic& oldProps, - const folly::dynamic& newProps); +folly::dynamic diffDynamicProps(const folly::dynamic &oldProps, const folly::dynamic &newProps); } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/core/EventBeat.h b/packages/react-native/ReactCommon/react/renderer/core/EventBeat.h index de5cabccbe0..3740b457e78 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/EventBeat.h +++ b/packages/react-native/ReactCommon/react/renderer/core/EventBeat.h @@ -55,20 +55,17 @@ class EventBeat { std::weak_ptr owner; }; - using Factory = std::function( - std::shared_ptr ownerBox)>; + using Factory = std::function(std::shared_ptr ownerBox)>; - using BeatCallback = std::function; + using BeatCallback = std::function; - explicit EventBeat( - std::shared_ptr ownerBox, - RuntimeScheduler& runtimeScheduler); + explicit EventBeat(std::shared_ptr ownerBox, RuntimeScheduler &runtimeScheduler); virtual ~EventBeat() = default; // not copyable - EventBeat(const EventBeat& other) = delete; - EventBeat& operator=(const EventBeat& other) = delete; + EventBeat(const EventBeat &other) = delete; + EventBeat &operator=(const EventBeat &other) = delete; /* * Communicates to the Beat that a consumer (for example EventQueue) is @@ -147,7 +144,7 @@ class EventBeat { mutable std::atomic isEventBeatRequested_{false}; private: - RuntimeScheduler& runtimeScheduler_; + RuntimeScheduler &runtimeScheduler_; mutable std::atomic isBeatCallbackScheduled_{false}; mutable std::atomic isSynchronousRequested_{false}; }; diff --git a/packages/react-native/ReactCommon/react/renderer/core/EventDispatcher.h b/packages/react-native/ReactCommon/react/renderer/core/EventDispatcher.h index f68cf5bd4d9..88a9a953e42 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/EventDispatcher.h +++ b/packages/react-native/ReactCommon/react/renderer/core/EventDispatcher.h @@ -31,7 +31,7 @@ class EventDispatcher { using Weak = std::weak_ptr; EventDispatcher( - const EventQueueProcessor& eventProcessor, + const EventQueueProcessor &eventProcessor, std::unique_ptr eventBeat, StatePipe statePipe, std::weak_ptr eventLogger); @@ -39,7 +39,7 @@ class EventDispatcher { /* * Dispatches a raw event with given priority using event-delivery pipe. */ - void dispatchEvent(RawEvent&& rawEvent) const; + void dispatchEvent(RawEvent &&rawEvent) const; /* * Experimental API exposed to support EventEmitter::experimental_flushSync. @@ -51,14 +51,12 @@ class EventDispatcher { * dispatch we make sure that no other RawEvent of same type and same target * is on the queue. */ - void dispatchUniqueEvent(RawEvent&& rawEvent) const; + void dispatchUniqueEvent(RawEvent &&rawEvent) const; /* * Dispatches a state update with given priority. */ - void dispatchStateUpdate( - StateUpdate&& stateUpdate, - EventQueue::UpdateMode updateMode) const; + void dispatchStateUpdate(StateUpdate &&stateUpdate, EventQueue::UpdateMode updateMode) const; #pragma mark - Event listeners /* @@ -69,8 +67,7 @@ class EventDispatcher { /* * Removes provided event listener to the event dispatcher. */ - void removeListener( - const std::shared_ptr& listener) const; + void removeListener(const std::shared_ptr &listener) const; private: EventQueue eventQueue_; diff --git a/packages/react-native/ReactCommon/react/renderer/core/EventEmitter.h b/packages/react-native/ReactCommon/react/renderer/core/EventEmitter.h index 42e5ffabcd5..84a64112a8e 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/EventEmitter.h +++ b/packages/react-native/ReactCommon/react/renderer/core/EventEmitter.h @@ -35,13 +35,11 @@ class EventEmitter { static std::string normalizeEventType(std::string type); - static std::mutex& DispatchMutex(); + static std::mutex &DispatchMutex(); static ValueFactory defaultPayloadFactory(); - EventEmitter( - SharedEventTarget eventTarget, - EventDispatcher::Weak eventDispatcher); + EventEmitter(SharedEventTarget eventTarget, EventDispatcher::Weak eventDispatcher); virtual ~EventEmitter() = default; @@ -60,16 +58,16 @@ class EventEmitter { /* * Sets a weak reference to the cooresponding ShadowNodeFamily */ - void setShadowNodeFamily( - std::weak_ptr shadowNodeFamily) const; + void setShadowNodeFamily(std::weak_ptr shadowNodeFamily) const; - const SharedEventTarget& getEventTarget() const; + const SharedEventTarget &getEventTarget() const; /* * Experimental API that will change in the future. */ template - void experimental_flushSync(Lambda syncFunc) const { + void experimental_flushSync(Lambda syncFunc) const + { auto eventDispatcher = eventDispatcher_.lock(); if (!eventDispatcher) { return; @@ -85,13 +83,12 @@ class EventEmitter { */ void dispatchEvent( std::string type, - const ValueFactory& payloadFactory = - EventEmitter::defaultPayloadFactory(), + const ValueFactory &payloadFactory = EventEmitter::defaultPayloadFactory(), RawEvent::Category category = RawEvent::Category::Unspecified) const; void dispatchEvent( std::string type, - folly::dynamic&& payload, + folly::dynamic &&payload, RawEvent::Category category = RawEvent::Category::Unspecified) const; void dispatchEvent( @@ -99,12 +96,10 @@ class EventEmitter { SharedEventPayload payload, RawEvent::Category category = RawEvent::Category::Unspecified) const; - void dispatchUniqueEvent(std::string type, folly::dynamic&& payload) const; + void dispatchUniqueEvent(std::string type, folly::dynamic &&payload) const; - void dispatchUniqueEvent( - std::string type, - const ValueFactory& payloadFactory = - EventEmitter::defaultPayloadFactory()) const; + void dispatchUniqueEvent(std::string type, const ValueFactory &payloadFactory = EventEmitter::defaultPayloadFactory()) + const; void dispatchUniqueEvent(std::string type, SharedEventPayload payload) const; diff --git a/packages/react-native/ReactCommon/react/renderer/core/EventListener.h b/packages/react-native/ReactCommon/react/renderer/core/EventListener.h index 1d5e72168dd..4535e4fb8bb 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/EventListener.h +++ b/packages/react-native/ReactCommon/react/renderer/core/EventListener.h @@ -19,7 +19,7 @@ namespace facebook::react { * Return `true` to interrupt default dispatch to JS event emitter, `false` to * pass through to default handlers. */ -using EventListener = std::function; +using EventListener = std::function; class EventListenerContainer { public: @@ -28,10 +28,10 @@ class EventListenerContainer { * Returns true if event was handled by the listener, false to continue * default dispatch. */ - bool willDispatchEvent(const RawEvent& event); + bool willDispatchEvent(const RawEvent &event); void addListener(std::shared_ptr listener); - void removeListener(const std::shared_ptr& listener); + void removeListener(const std::shared_ptr &listener); private: std::shared_mutex mutex_; diff --git a/packages/react-native/ReactCommon/react/renderer/core/EventPayload.h b/packages/react-native/ReactCommon/react/renderer/core/EventPayload.h index f0a00ac9196..30e2d73fae5 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/EventPayload.h +++ b/packages/react-native/ReactCommon/react/renderer/core/EventPayload.h @@ -22,12 +22,12 @@ struct EventPayload { virtual ~EventPayload() = default; EventPayload() = default; - EventPayload(const EventPayload&) = default; - EventPayload& operator=(const EventPayload&) = default; - EventPayload(EventPayload&&) = default; - EventPayload& operator=(EventPayload&&) = default; + EventPayload(const EventPayload &) = default; + EventPayload &operator=(const EventPayload &) = default; + EventPayload(EventPayload &&) = default; + EventPayload &operator=(EventPayload &&) = default; - virtual jsi::Value asJSIValue(jsi::Runtime& runtime) const = 0; + virtual jsi::Value asJSIValue(jsi::Runtime &runtime) const = 0; /** * Reports the type of the event payload for efficient downcasting. @@ -42,8 +42,8 @@ struct EventPayload { * be used in conjunction with listeners on EventEmitters to do * things like drive native animations. */ - virtual std::optional extractValue( - const std::vector& /* path */) const { + virtual std::optional extractValue(const std::vector & /* path */) const + { return std::nullopt; } }; diff --git a/packages/react-native/ReactCommon/react/renderer/core/EventPipe.h b/packages/react-native/ReactCommon/react/renderer/core/EventPipe.h index 0c94b2f202b..28dec4068dc 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/EventPipe.h +++ b/packages/react-native/ReactCommon/react/renderer/core/EventPipe.h @@ -19,12 +19,12 @@ namespace facebook::react { using EventPipe = std::function; + const EventPayload &payload)>; -using EventPipeConclusion = std::function; +using EventPipeConclusion = std::function; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/core/EventQueue.h b/packages/react-native/ReactCommon/react/renderer/core/EventQueue.h index 3d4bb7cdbed..f525767478a 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/EventQueue.h +++ b/packages/react-native/ReactCommon/react/renderer/core/EventQueue.h @@ -37,30 +37,26 @@ class EventQueue { unstable_Immediate, }; - EventQueue( - EventQueueProcessor eventProcessor, - std::unique_ptr eventBeat); + EventQueue(EventQueueProcessor eventProcessor, std::unique_ptr eventBeat); /* * Enqueues and (probably later) dispatch a given event. * Can be called on any thread. */ - void enqueueEvent(RawEvent&& rawEvent) const; + void enqueueEvent(RawEvent &&rawEvent) const; /* * Enqueues and (probably later) dispatches a given event. * Deletes last RawEvent from the queue if it has the same type and target. * Can be called on any thread. */ - void enqueueUniqueEvent(RawEvent&& rawEvent) const; + void enqueueUniqueEvent(RawEvent &&rawEvent) const; /* * Enqueues and (probably later) dispatch a given state update. * Can be called on any thread. */ - void enqueueStateUpdate( - StateUpdate&& stateUpdate, - UpdateMode updateMode = UpdateMode::Asynchronous) const; + void enqueueStateUpdate(StateUpdate &&stateUpdate, UpdateMode updateMode = UpdateMode::Asynchronous) const; /* * Experimental API exposed to support EventEmitter::experimental_flushSync. @@ -74,9 +70,9 @@ class EventQueue { * Default implementation does nothing. */ void onEnqueue() const; - void onBeat(jsi::Runtime& runtime) const; + void onBeat(jsi::Runtime &runtime) const; - void flushEvents(jsi::Runtime& runtime) const; + void flushEvents(jsi::Runtime &runtime) const; void flushStateUpdates() const; EventQueueProcessor eventProcessor_; diff --git a/packages/react-native/ReactCommon/react/renderer/core/EventQueueProcessor.h b/packages/react-native/ReactCommon/react/renderer/core/EventQueueProcessor.h index 5c1c9f2b0d1..d1abcd99bff 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/EventQueueProcessor.h +++ b/packages/react-native/ReactCommon/react/renderer/core/EventQueueProcessor.h @@ -25,8 +25,8 @@ class EventQueueProcessor { StatePipe statePipe, std::weak_ptr eventLogger); - void flushEvents(jsi::Runtime& runtime, std::vector&& events) const; - void flushStateUpdates(std::vector&& states) const; + void flushEvents(jsi::Runtime &runtime, std::vector &&events) const; + void flushStateUpdates(std::vector &&states) const; private: const EventPipe eventPipe_; diff --git a/packages/react-native/ReactCommon/react/renderer/core/EventTarget.h b/packages/react-native/ReactCommon/react/renderer/core/EventTarget.h index e08ddcab047..fa8c6796628 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/EventTarget.h +++ b/packages/react-native/ReactCommon/react/renderer/core/EventTarget.h @@ -34,9 +34,7 @@ class EventTarget { /* * Constructs an EventTarget from a weak instance handler and a tag. */ - explicit EventTarget( - InstanceHandle::Shared instanceHandle, - SurfaceId surfaceId); + explicit EventTarget(InstanceHandle::Shared instanceHandle, SurfaceId surfaceId); /* * Sets the `enabled` flag that allows creating a strong instance handle from @@ -48,18 +46,18 @@ class EventTarget { * Retains an instance handler by creating a strong reference to it. * If the EventTarget is disabled, does nothing. */ - void retain(jsi::Runtime& runtime) const; + void retain(jsi::Runtime &runtime) const; /* * Releases the instance handler by nulling a strong reference to it. */ - void release(jsi::Runtime& runtime) const; + void release(jsi::Runtime &runtime) const; /* * Creates and returns the `instanceHandle`. * Returns `null` if the `instanceHandle` is not retained at this moment. */ - jsi::Value getInstanceHandle(jsi::Runtime& runtime) const; + jsi::Value getInstanceHandle(jsi::Runtime &runtime) const; SurfaceId getSurfaceId() const; diff --git a/packages/react-native/ReactCommon/react/renderer/core/InstanceHandle.h b/packages/react-native/ReactCommon/react/renderer/core/InstanceHandle.h index 17f5a3d2763..e916bb24b89 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/InstanceHandle.h +++ b/packages/react-native/ReactCommon/react/renderer/core/InstanceHandle.h @@ -17,16 +17,13 @@ class InstanceHandle { public: using Shared = std::shared_ptr; - InstanceHandle( - jsi::Runtime& runtime, - const jsi::Value& instanceHandle, - Tag tag); + InstanceHandle(jsi::Runtime &runtime, const jsi::Value &instanceHandle, Tag tag); /* * Creates and returns the `instanceHandle`. * Returns `null` if the `instanceHandle` is not retained at this moment. */ - jsi::Value getInstanceHandle(jsi::Runtime& runtime) const; + jsi::Value getInstanceHandle(jsi::Runtime &runtime) const; /* * Deprecated. Do not use. diff --git a/packages/react-native/ReactCommon/react/renderer/core/LayoutConstraints.h b/packages/react-native/ReactCommon/react/renderer/core/LayoutConstraints.h index 20bfebca74b..9649c953eb0 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/LayoutConstraints.h +++ b/packages/react-native/ReactCommon/react/renderer/core/LayoutConstraints.h @@ -20,28 +20,24 @@ namespace facebook::react { */ struct LayoutConstraints { Size minimumSize{.width = 0, .height = 0}; - Size maximumSize{ - .width = std::numeric_limits::infinity(), - .height = std::numeric_limits::infinity()}; + Size maximumSize{.width = std::numeric_limits::infinity(), .height = std::numeric_limits::infinity()}; LayoutDirection layoutDirection{LayoutDirection::Undefined}; /* * Clamps the provided `Size` between the `minimumSize` and `maximumSize` * bounds of this `LayoutConstraints`. */ - Size clamp(const Size& size) const; + Size clamp(const Size &size) const; }; -inline bool operator==( - const LayoutConstraints& lhs, - const LayoutConstraints& rhs) { +inline bool operator==(const LayoutConstraints &lhs, const LayoutConstraints &rhs) +{ return std::tie(lhs.minimumSize, lhs.maximumSize, lhs.layoutDirection) == std::tie(rhs.minimumSize, rhs.maximumSize, rhs.layoutDirection); } -inline bool operator!=( - const LayoutConstraints& lhs, - const LayoutConstraints& rhs) { +inline bool operator!=(const LayoutConstraints &lhs, const LayoutConstraints &rhs) +{ return !(lhs == rhs); } @@ -50,12 +46,9 @@ inline bool operator!=( namespace std { template <> struct hash { - size_t operator()( - const facebook::react::LayoutConstraints& constraints) const { - return facebook::react::hash_combine( - constraints.minimumSize, - constraints.maximumSize, - constraints.layoutDirection); + size_t operator()(const facebook::react::LayoutConstraints &constraints) const + { + return facebook::react::hash_combine(constraints.minimumSize, constraints.maximumSize, constraints.layoutDirection); } }; } // namespace std diff --git a/packages/react-native/ReactCommon/react/renderer/core/LayoutContext.h b/packages/react-native/ReactCommon/react/renderer/core/LayoutContext.h index fb2afbeb52e..c71d447be37 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/LayoutContext.h +++ b/packages/react-native/ReactCommon/react/renderer/core/LayoutContext.h @@ -33,7 +33,7 @@ struct LayoutContext { * list. The order is not specified. Nothing in this collection is owing (on * purpose), make sure the memory is managed responsibly. */ - std::vector* affectedNodes{}; + std::vector *affectedNodes{}; /* * Flag indicating whether in reassignment of direction @@ -61,7 +61,8 @@ struct LayoutContext { Point viewportOffset{}; }; -inline bool operator==(const LayoutContext& lhs, const LayoutContext& rhs) { +inline bool operator==(const LayoutContext &lhs, const LayoutContext &rhs) +{ return std::tie( lhs.pointScaleFactor, lhs.affectedNodes, @@ -76,7 +77,8 @@ inline bool operator==(const LayoutContext& lhs, const LayoutContext& rhs) { rhs.viewportOffset); } -inline bool operator!=(const LayoutContext& lhs, const LayoutContext& rhs) { +inline bool operator!=(const LayoutContext &lhs, const LayoutContext &rhs) +{ return !(lhs == rhs); } diff --git a/packages/react-native/ReactCommon/react/renderer/core/LayoutMetrics.h b/packages/react-native/ReactCommon/react/renderer/core/LayoutMetrics.h index 74515cbaf3c..8be251aabf5 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/LayoutMetrics.h +++ b/packages/react-native/ReactCommon/react/renderer/core/LayoutMetrics.h @@ -48,47 +48,46 @@ struct LayoutMetrics { // Origin: the outer border of the node. // Size: includes content only. - Rect getContentFrame() const { + Rect getContentFrame() const + { return Rect{ .origin = Point{.x = contentInsets.left, .y = contentInsets.top}, .size = Size{ - .width = - frame.size.width - contentInsets.left - contentInsets.right, - .height = - frame.size.height - contentInsets.top - contentInsets.bottom}}; + .width = frame.size.width - contentInsets.left - contentInsets.right, + .height = frame.size.height - contentInsets.top - contentInsets.bottom}}; } // Calculates the frame of the node including overflow insets. // If the frame was drawn on screen, it would include all the children of the // node (and their children, recursively). - Rect getOverflowInsetFrame() const { + Rect getOverflowInsetFrame() const + { return Rect{ .origin = Point{ .x = frame.origin.x + std::min(Float{0}, overflowInset.left), .y = frame.origin.y + std::min(Float{0}, overflowInset.top)}, .size = Size{ - .width = frame.size.width - std::min(Float{0}, overflowInset.left) + - -std::min(Float{0}, overflowInset.right), - .height = frame.size.height - - std::min(Float{0}, overflowInset.top) + - -std::min(Float{0}, overflowInset.bottom)}}; + .width = + frame.size.width - std::min(Float{0}, overflowInset.left) + -std::min(Float{0}, overflowInset.right), + .height = + frame.size.height - std::min(Float{0}, overflowInset.top) + -std::min(Float{0}, overflowInset.bottom)}}; } // Origin: the outer border of the node. // Size: includes content and padding (but no borders). - Rect getPaddingFrame() const { + Rect getPaddingFrame() const + { return Rect{ .origin = Point{.x = borderWidth.left, .y = borderWidth.top}, .size = Size{ .width = frame.size.width - borderWidth.left - borderWidth.right, - .height = - frame.size.height - borderWidth.top - borderWidth.bottom}}; + .height = frame.size.height - borderWidth.top - borderWidth.bottom}}; } - bool operator==(const LayoutMetrics& rhs) const = default; + bool operator==(const LayoutMetrics &rhs) const = default; - bool operator!=(const LayoutMetrics& rhs) const = default; + bool operator!=(const LayoutMetrics &rhs) const = default; }; /* @@ -97,15 +96,13 @@ struct LayoutMetrics { * The value is comparable by equality with any other `LayoutMetrics` value. */ static const LayoutMetrics EmptyLayoutMetrics = { - /* .frame = */ .frame = { - .origin = {.x = 0, .y = 0}, - .size = {.width = -1.0, .height = -1.0}}}; + /* .frame = */ .frame = {.origin = {.x = 0, .y = 0}, .size = {.width = -1.0, .height = -1.0}}}; #if RN_DEBUG_STRING_CONVERTIBLE -std::string getDebugName(const LayoutMetrics& object); +std::string getDebugName(const LayoutMetrics &object); std::vector getDebugProps( - const LayoutMetrics& object, + const LayoutMetrics &object, DebugStringConvertibleOptions options); #endif @@ -116,7 +113,8 @@ namespace std { template <> struct hash { - size_t operator()(const facebook::react::LayoutMetrics& layoutMetrics) const { + size_t operator()(const facebook::react::LayoutMetrics &layoutMetrics) const + { return facebook::react::hash_combine( layoutMetrics.frame, layoutMetrics.contentInsets, diff --git a/packages/react-native/ReactCommon/react/renderer/core/LayoutableShadowNode.cpp b/packages/react-native/ReactCommon/react/renderer/core/LayoutableShadowNode.cpp index c604120be4f..515ee47a39f 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/LayoutableShadowNode.cpp +++ b/packages/react-native/ReactCommon/react/renderer/core/LayoutableShadowNode.cpp @@ -29,8 +29,9 @@ LayoutableShadowNode::LayoutableShadowNode( const ShadowNode& sourceShadowNode, const ShadowNodeFragment& fragment) : ShadowNode(sourceShadowNode, fragment), - layoutMetrics_(static_cast(sourceShadowNode) - .layoutMetrics_) {} + layoutMetrics_( + static_cast(sourceShadowNode) + .layoutMetrics_) {} LayoutMetrics LayoutableShadowNode::computeLayoutMetricsFromRoot( const ShadowNodeFamily& descendantNodeFamily, @@ -356,17 +357,20 @@ SharedDebugStringConvertibleList LayoutableShadowNode::getDebugProps() const { auto layoutMetrics = getLayoutMetrics(); auto defaultLayoutMetrics = LayoutMetrics(); - layoutInfo.push_back(std::make_shared( - "frame", toString(layoutMetrics.frame))); + layoutInfo.push_back( + std::make_shared( + "frame", toString(layoutMetrics.frame))); if (layoutMetrics.borderWidth != defaultLayoutMetrics.borderWidth) { - layoutInfo.push_back(std::make_shared( - "borderWidth", toString(layoutMetrics.borderWidth))); + layoutInfo.push_back( + std::make_shared( + "borderWidth", toString(layoutMetrics.borderWidth))); } if (layoutMetrics.contentInsets != defaultLayoutMetrics.contentInsets) { - layoutInfo.push_back(std::make_shared( - "contentInsets", toString(layoutMetrics.contentInsets))); + layoutInfo.push_back( + std::make_shared( + "contentInsets", toString(layoutMetrics.contentInsets))); } if (layoutMetrics.displayType == DisplayType::None) { diff --git a/packages/react-native/ReactCommon/react/renderer/core/LayoutableShadowNode.h b/packages/react-native/ReactCommon/react/renderer/core/LayoutableShadowNode.h index 7ec834c6a3d..e983dce2ad3 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/LayoutableShadowNode.h +++ b/packages/react-native/ReactCommon/react/renderer/core/LayoutableShadowNode.h @@ -31,13 +31,11 @@ struct LayoutContext; class LayoutableShadowNode : public ShadowNode { public: LayoutableShadowNode( - const ShadowNodeFragment& fragment, - const ShadowNodeFamily::Shared& family, + const ShadowNodeFragment &fragment, + const ShadowNodeFamily::Shared &family, ShadowNodeTraits traits); - LayoutableShadowNode( - const ShadowNode& sourceShadowNode, - const ShadowNodeFragment& fragment); + LayoutableShadowNode(const ShadowNode &sourceShadowNode, const ShadowNodeFragment &fragment); struct LayoutInspectingPolicy { bool includeTransform{true}; @@ -45,7 +43,7 @@ class LayoutableShadowNode : public ShadowNode { bool enableOverflowClipping{false}; }; - using UnsharedList = std::vector; + using UnsharedList = std::vector; /* * Returns layout metrics of a node represented as `descendantNodeFamily` @@ -53,8 +51,8 @@ class LayoutableShadowNode : public ShadowNode { * transform for node if used as root. */ static LayoutMetrics computeLayoutMetricsFromRoot( - const ShadowNodeFamily& descendantNodeFamily, - const LayoutableShadowNode& rootNode, + const ShadowNodeFamily &descendantNodeFamily, + const LayoutableShadowNode &rootNode, LayoutInspectingPolicy policy); /* @@ -64,43 +62,35 @@ class LayoutableShadowNode : public ShadowNode { * tree. */ static LayoutMetrics computeRelativeLayoutMetrics( - const ShadowNodeFamily& descendantNodeFamily, - const LayoutableShadowNode& ancestorNode, + const ShadowNodeFamily &descendantNodeFamily, + const LayoutableShadowNode &ancestorNode, LayoutInspectingPolicy policy); /* * Computes the layout metrics of a node relative to its specified ancestors. */ - static LayoutMetrics computeRelativeLayoutMetrics( - const AncestorList& ancestors, - LayoutInspectingPolicy policy); + static LayoutMetrics computeRelativeLayoutMetrics(const AncestorList &ancestors, LayoutInspectingPolicy policy); /* * Performs layout of the tree starting from this node. Usually is being * called on the root node. * Default implementation does nothing. */ - virtual void layoutTree( - LayoutContext layoutContext, - LayoutConstraints layoutConstraints) = 0; + virtual void layoutTree(LayoutContext layoutContext, LayoutConstraints layoutConstraints) = 0; /* * Measures the node (and node content, probably recursively) with * given constrains and relying on possible layout. * Default implementation returns zero size. */ - virtual Size measureContent( - const LayoutContext& layoutContext, - const LayoutConstraints& layoutConstraints) const; + virtual Size measureContent(const LayoutContext &layoutContext, const LayoutConstraints &layoutConstraints) const; /* * Measures the node with given `layoutContext` and `layoutConstraints`. * The size of nested content and the padding should be included, the margin * should *not* be included. Default implementation returns zero size. */ - virtual Size measure( - const LayoutContext& layoutContext, - const LayoutConstraints& layoutConstraints) const; + virtual Size measure(const LayoutContext &layoutContext, const LayoutConstraints &layoutConstraints) const; /* * Computes layout recursively. @@ -147,9 +137,7 @@ class LayoutableShadowNode : public ShadowNode { * Returns the ShadowNode that is rendered at the Point received as a * parameter. */ - static std::shared_ptr findNodeAtPoint( - const std::shared_ptr& node, - Point point); + static std::shared_ptr findNodeAtPoint(const std::shared_ptr &node, Point point); /* * Clean or Dirty layout state: @@ -162,7 +150,7 @@ class LayoutableShadowNode : public ShadowNode { /* * Unifed methods to access text layout metrics. */ - virtual Float baseline(const LayoutContext& layoutContext, Size size) const; + virtual Float baseline(const LayoutContext &layoutContext, Size size) const; virtual bool canBeTouchTarget() const; virtual bool canChildrenBeTouchTarget() const; diff --git a/packages/react-native/ReactCommon/react/renderer/core/Props.h b/packages/react-native/ReactCommon/react/renderer/core/Props.h index 3ddb6041833..eda64a4e176 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/Props.h +++ b/packages/react-native/ReactCommon/react/renderer/core/Props.h @@ -30,11 +30,10 @@ class Props : public virtual Sealable, public virtual DebugStringConvertible { Props() = default; Props( - const PropsParserContext& context, - const Props& sourceProps, - const RawProps& rawProps, - const std::function& filterObjectKeys = - nullptr); + const PropsParserContext &context, + const Props &sourceProps, + const RawProps &rawProps, + const std::function &filterObjectKeys = nullptr); #if RN_DEBUG_STRING_CONVERTIBLE virtual ~Props() override = default; @@ -42,8 +41,8 @@ class Props : public virtual Sealable, public virtual DebugStringConvertible { virtual ~Props() = default; #endif - Props(const Props& other) = delete; - Props& operator=(const Props& other) = delete; + Props(const Props &other) = delete; + Props &operator=(const Props &other) = delete; /** * Set a prop value via iteration (see enableIterator above). @@ -55,22 +54,21 @@ class Props : public virtual Sealable, public virtual DebugStringConvertible { * multiple times for different values in the hierarchy. For example, if * ViewProps uses "propX", Props may also use "propX". */ - void setProp( - const PropsParserContext& context, - RawPropsPropNameHash hash, - const char* propName, - const RawValue& value); + void + setProp(const PropsParserContext &context, RawPropsPropNameHash hash, const char *propName, const RawValue &value); std::string nativeId; #ifdef RN_SERIALIZABLE_STATE folly::dynamic rawProps = folly::dynamic::object(); - virtual ComponentName getDiffPropsImplementationTarget() const { + virtual ComponentName getDiffPropsImplementationTarget() const + { return ""; } - virtual folly::dynamic getDiffProps(const Props* prevProps) const { + virtual folly::dynamic getDiffProps(const Props *prevProps) const + { return folly::dynamic::object(); } #endif @@ -86,15 +84,14 @@ class Props : public virtual Sealable, public virtual DebugStringConvertible { protected: /** Initialize member variables of Props instance */ void initialize( - const PropsParserContext& context, - const Props& sourceProps, - const RawProps& rawProps, + const PropsParserContext &context, + const Props &sourceProps, + const RawProps &rawProps, /** * Filter object keys to be excluded when converting the RawProps to * folly::dynamic (android only) */ - const std::function& filterObjectKeys = - nullptr); + const std::function &filterObjectKeys = nullptr); }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/core/PropsMacros.h b/packages/react-native/ReactCommon/react/renderer/core/PropsMacros.h index 55fe5224dd0..b6cc947972f 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/PropsMacros.h +++ b/packages/react-native/ReactCommon/react/renderer/core/PropsMacros.h @@ -40,89 +40,60 @@ // Convenience for building setProps switch statements where the field name is // the same as the string identifier -#define RAW_SET_PROP_SWITCH_CASE_BASIC(field) \ - RAW_SET_PROP_SWITCH_CASE(field, #field) +#define RAW_SET_PROP_SWITCH_CASE_BASIC(field) RAW_SET_PROP_SWITCH_CASE(field, #field) -#define CASE_STATEMENT_SET_FIELD_VALUE_INDEXED( \ - struct, field, fieldNameString, value) \ - case CONSTEXPR_RAW_PROPS_KEY_HASH(fieldNameString): { \ - if (!value.hasValue()) { \ - decltype(struct) defaultValues{}; \ - struct.field = defaultValues.field; \ - return; \ - } \ - fromRawValue(context, value, struct.field); \ - return; \ +#define CASE_STATEMENT_SET_FIELD_VALUE_INDEXED(struct, field, fieldNameString, value) \ + case CONSTEXPR_RAW_PROPS_KEY_HASH(fieldNameString): { \ + if (!value.hasValue()) { \ + decltype(struct) defaultValues{}; \ + struct.field = defaultValues.field; \ + return; \ + } \ + fromRawValue(context, value, struct.field); \ + return; \ } -#define SET_CASCADED_RECTANGLE_CORNERS(struct, prefix, suffix, rawValue) \ - CASE_STATEMENT_SET_FIELD_VALUE_INDEXED( \ - struct, topLeft, prefix "TopLeft" suffix, rawValue) \ - CASE_STATEMENT_SET_FIELD_VALUE_INDEXED( \ - struct, topRight, prefix "TopRight" suffix, rawValue) \ - CASE_STATEMENT_SET_FIELD_VALUE_INDEXED( \ - struct, bottomLeft, prefix "BottomLeft" suffix, rawValue) \ - CASE_STATEMENT_SET_FIELD_VALUE_INDEXED( \ - struct, bottomRight, prefix "BottomRight" suffix, rawValue) \ - CASE_STATEMENT_SET_FIELD_VALUE_INDEXED( \ - struct, topStart, prefix "TopStart" suffix, rawValue) \ - CASE_STATEMENT_SET_FIELD_VALUE_INDEXED( \ - struct, topEnd, prefix "TopEnd" suffix, rawValue) \ - CASE_STATEMENT_SET_FIELD_VALUE_INDEXED( \ - struct, bottomStart, prefix "BottomStart" suffix, rawValue) \ - CASE_STATEMENT_SET_FIELD_VALUE_INDEXED( \ - struct, bottomEnd, prefix "BottomEnd" suffix, rawValue) \ - CASE_STATEMENT_SET_FIELD_VALUE_INDEXED( \ - struct, all, prefix "" suffix, rawValue) \ - CASE_STATEMENT_SET_FIELD_VALUE_INDEXED( \ - struct, endEnd, prefix "EndEnd" suffix, rawValue) \ - CASE_STATEMENT_SET_FIELD_VALUE_INDEXED( \ - struct, endStart, prefix "EndStart" suffix, rawValue) \ - CASE_STATEMENT_SET_FIELD_VALUE_INDEXED( \ - struct, startEnd, prefix "StartEnd" suffix, rawValue) \ - CASE_STATEMENT_SET_FIELD_VALUE_INDEXED( \ - struct, startStart, prefix "StartStart" suffix, rawValue) +#define SET_CASCADED_RECTANGLE_CORNERS(struct, prefix, suffix, rawValue) \ + CASE_STATEMENT_SET_FIELD_VALUE_INDEXED(struct, topLeft, prefix "TopLeft" suffix, rawValue) \ + CASE_STATEMENT_SET_FIELD_VALUE_INDEXED(struct, topRight, prefix "TopRight" suffix, rawValue) \ + CASE_STATEMENT_SET_FIELD_VALUE_INDEXED(struct, bottomLeft, prefix "BottomLeft" suffix, rawValue) \ + CASE_STATEMENT_SET_FIELD_VALUE_INDEXED(struct, bottomRight, prefix "BottomRight" suffix, rawValue) \ + CASE_STATEMENT_SET_FIELD_VALUE_INDEXED(struct, topStart, prefix "TopStart" suffix, rawValue) \ + CASE_STATEMENT_SET_FIELD_VALUE_INDEXED(struct, topEnd, prefix "TopEnd" suffix, rawValue) \ + CASE_STATEMENT_SET_FIELD_VALUE_INDEXED(struct, bottomStart, prefix "BottomStart" suffix, rawValue) \ + CASE_STATEMENT_SET_FIELD_VALUE_INDEXED(struct, bottomEnd, prefix "BottomEnd" suffix, rawValue) \ + CASE_STATEMENT_SET_FIELD_VALUE_INDEXED(struct, all, prefix "" suffix, rawValue) \ + CASE_STATEMENT_SET_FIELD_VALUE_INDEXED(struct, endEnd, prefix "EndEnd" suffix, rawValue) \ + CASE_STATEMENT_SET_FIELD_VALUE_INDEXED(struct, endStart, prefix "EndStart" suffix, rawValue) \ + CASE_STATEMENT_SET_FIELD_VALUE_INDEXED(struct, startEnd, prefix "StartEnd" suffix, rawValue) \ + CASE_STATEMENT_SET_FIELD_VALUE_INDEXED(struct, startStart, prefix "StartStart" suffix, rawValue) -#define SET_CASCADED_RECTANGLE_EDGES(struct, prefix, suffix, rawValue) \ - CASE_STATEMENT_SET_FIELD_VALUE_INDEXED( \ - struct, left, prefix "Left" suffix, rawValue) \ - CASE_STATEMENT_SET_FIELD_VALUE_INDEXED( \ - struct, right, prefix "Right" suffix, rawValue) \ - CASE_STATEMENT_SET_FIELD_VALUE_INDEXED( \ - struct, top, prefix "Top" suffix, rawValue) \ - CASE_STATEMENT_SET_FIELD_VALUE_INDEXED( \ - struct, bottom, prefix "Bottom" suffix, rawValue) \ - CASE_STATEMENT_SET_FIELD_VALUE_INDEXED( \ - struct, start, prefix "Start" suffix, rawValue) \ - CASE_STATEMENT_SET_FIELD_VALUE_INDEXED( \ - struct, end, prefix "End" suffix, rawValue) \ - CASE_STATEMENT_SET_FIELD_VALUE_INDEXED( \ - struct, horizontal, prefix "Horizontal" suffix, rawValue) \ - CASE_STATEMENT_SET_FIELD_VALUE_INDEXED( \ - struct, vertical, prefix "Vertical" suffix, rawValue) \ - CASE_STATEMENT_SET_FIELD_VALUE_INDEXED( \ - struct, all, prefix "" suffix, rawValue) \ - CASE_STATEMENT_SET_FIELD_VALUE_INDEXED( \ - struct, block, prefix "Block" suffix, rawValue) \ - CASE_STATEMENT_SET_FIELD_VALUE_INDEXED( \ - struct, blockEnd, prefix "BlockEnd" suffix, rawValue) \ - CASE_STATEMENT_SET_FIELD_VALUE_INDEXED( \ - struct, blockStart, prefix "BlockStart" suffix, rawValue) +#define SET_CASCADED_RECTANGLE_EDGES(struct, prefix, suffix, rawValue) \ + CASE_STATEMENT_SET_FIELD_VALUE_INDEXED(struct, left, prefix "Left" suffix, rawValue) \ + CASE_STATEMENT_SET_FIELD_VALUE_INDEXED(struct, right, prefix "Right" suffix, rawValue) \ + CASE_STATEMENT_SET_FIELD_VALUE_INDEXED(struct, top, prefix "Top" suffix, rawValue) \ + CASE_STATEMENT_SET_FIELD_VALUE_INDEXED(struct, bottom, prefix "Bottom" suffix, rawValue) \ + CASE_STATEMENT_SET_FIELD_VALUE_INDEXED(struct, start, prefix "Start" suffix, rawValue) \ + CASE_STATEMENT_SET_FIELD_VALUE_INDEXED(struct, end, prefix "End" suffix, rawValue) \ + CASE_STATEMENT_SET_FIELD_VALUE_INDEXED(struct, horizontal, prefix "Horizontal" suffix, rawValue) \ + CASE_STATEMENT_SET_FIELD_VALUE_INDEXED(struct, vertical, prefix "Vertical" suffix, rawValue) \ + CASE_STATEMENT_SET_FIELD_VALUE_INDEXED(struct, all, prefix "" suffix, rawValue) \ + CASE_STATEMENT_SET_FIELD_VALUE_INDEXED(struct, block, prefix "Block" suffix, rawValue) \ + CASE_STATEMENT_SET_FIELD_VALUE_INDEXED(struct, blockEnd, prefix "BlockEnd" suffix, rawValue) \ + CASE_STATEMENT_SET_FIELD_VALUE_INDEXED(struct, blockStart, prefix "BlockStart" suffix, rawValue) // Rebuild a type that contains multiple fields from a single field value -#define REBUILD_FIELD_SWITCH_CASE( \ - defaults, rawValue, property, field, fieldName) \ - case CONSTEXPR_RAW_PROPS_KEY_HASH(fieldName): { \ - if ((rawValue).hasValue()) [[likely]] { \ - try { \ - fromRawValue(context, rawValue, (property).field); \ - } catch (const std::exception& e) { \ - LOG(ERROR) << "Error while converting prop '" << fieldName \ - << "': " << e.what(); \ - (property).field = (defaults).field; \ - } \ - } else { \ - (property).field = (defaults).field; \ - } \ - return; \ +#define REBUILD_FIELD_SWITCH_CASE(defaults, rawValue, property, field, fieldName) \ + case CONSTEXPR_RAW_PROPS_KEY_HASH(fieldName): { \ + if ((rawValue).hasValue()) [[likely]] { \ + try { \ + fromRawValue(context, rawValue, (property).field); \ + } catch (const std::exception &e) { \ + LOG(ERROR) << "Error while converting prop '" << fieldName << "': " << e.what(); \ + (property).field = (defaults).field; \ + } \ + } else { \ + (property).field = (defaults).field; \ + } \ + return; \ } diff --git a/packages/react-native/ReactCommon/react/renderer/core/PropsParserContext.h b/packages/react-native/ReactCommon/react/renderer/core/PropsParserContext.h index dee30506aa3..b5abcfc3096 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/PropsParserContext.h +++ b/packages/react-native/ReactCommon/react/renderer/core/PropsParserContext.h @@ -18,17 +18,17 @@ namespace facebook::react { // It should be used as infrequently as possible - most props can and should // be parsed without any context. struct PropsParserContext { - PropsParserContext( - const SurfaceId surfaceId, - const ContextContainer& contextContainer) - : surfaceId(surfaceId), contextContainer(contextContainer) {} + PropsParserContext(const SurfaceId surfaceId, const ContextContainer &contextContainer) + : surfaceId(surfaceId), contextContainer(contextContainer) + { + } // Non-copyable - PropsParserContext(const PropsParserContext&) = delete; - PropsParserContext& operator=(const PropsParserContext&) = delete; + PropsParserContext(const PropsParserContext &) = delete; + PropsParserContext &operator=(const PropsParserContext &) = delete; const SurfaceId surfaceId; - const ContextContainer& contextContainer; + const ContextContainer &contextContainer; }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/core/RawProps.h b/packages/react-native/ReactCommon/react/renderer/core/RawProps.h index 75e8852ab6f..631ef315c98 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/RawProps.h +++ b/packages/react-native/ReactCommon/react/renderer/core/RawProps.h @@ -48,13 +48,13 @@ class RawProps final { /* * Creates an object with given `runtime` and `value`. */ - RawProps(jsi::Runtime& runtime, const jsi::Value& value) noexcept; + RawProps(jsi::Runtime &runtime, const jsi::Value &value) noexcept; - explicit RawProps(const RawProps& other) noexcept; - RawProps(RawProps&& other) noexcept = default; + explicit RawProps(const RawProps &other) noexcept; + RawProps(RawProps &&other) noexcept = default; - RawProps& operator=(const RawProps& other) noexcept = delete; - RawProps& operator=(RawProps&& other) noexcept = delete; + RawProps &operator=(const RawProps &other) noexcept = delete; + RawProps &operator=(RawProps &&other) noexcept = delete; /* * Creates an object with given `folly::dynamic` object. @@ -64,7 +64,7 @@ class RawProps final { */ explicit RawProps(folly::dynamic dynamic) noexcept; - void parse(const RawPropsParser& parser) noexcept; + void parse(const RawPropsParser &parser) noexcept; /* * Deprecated. Do not use. @@ -78,9 +78,7 @@ class RawProps final { * The support for explicit conversion to `folly::dynamic` is deprecated and * will be removed as soon Android implementation does not need it. */ - folly::dynamic toDynamic( - const std::function& filterObjectKeys = - nullptr) const; + folly::dynamic toDynamic(const std::function &filterObjectKeys = nullptr) const; /* * Returns `true` if the object is empty. @@ -92,13 +90,12 @@ class RawProps final { * Returns a const unowning pointer to `RawValue` of a prop with a given name. * Returns `nullptr` if a prop with the given name does not exist. */ - const RawValue* at(const char* name, const char* prefix, const char* suffix) - const noexcept; + const RawValue *at(const char *name, const char *prefix, const char *suffix) const noexcept; private: friend class RawPropsParser; - mutable const RawPropsParser* parser_{nullptr}; + mutable const RawPropsParser *parser_{nullptr}; /* * Source artefacts: @@ -108,7 +105,7 @@ class RawProps final { Mode mode_; // Case 1: Source data is represented as `jsi::Object`. - jsi::Runtime* runtime_{}; + jsi::Runtime *runtime_{}; jsi::Value value_; // Case 2: Source data is represented as `folly::dynamic`. @@ -136,7 +133,7 @@ class RawProps final { * Java. */ template -concept RawPropsFilterable = requires(RawProps& rawProps) { +concept RawPropsFilterable = requires(RawProps &rawProps) { { T::filterRawProps(rawProps) } -> std::same_as; }; diff --git a/packages/react-native/ReactCommon/react/renderer/core/RawPropsKey.h b/packages/react-native/ReactCommon/react/renderer/core/RawPropsKey.h index d85de9792e3..de03c22035e 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/RawPropsKey.h +++ b/packages/react-native/ReactCommon/react/renderer/core/RawPropsKey.h @@ -18,9 +18,9 @@ namespace facebook::react { */ class RawPropsKey final { public: - const char* prefix{}; - const char* name{}; - const char* suffix{}; + const char *prefix{}; + const char *name{}; + const char *suffix{}; /* * Converts to `std::string`. @@ -31,10 +31,10 @@ class RawPropsKey final { * Renders compound prop name to given buffer and put the resulting length * into `length`. */ - void render(char* buffer, RawPropsPropNameLength* length) const noexcept; + void render(char *buffer, RawPropsPropNameLength *length) const noexcept; }; -bool operator==(const RawPropsKey& lhs, const RawPropsKey& rhs) noexcept; -bool operator!=(const RawPropsKey& lhs, const RawPropsKey& rhs) noexcept; +bool operator==(const RawPropsKey &lhs, const RawPropsKey &rhs) noexcept; +bool operator!=(const RawPropsKey &lhs, const RawPropsKey &rhs) noexcept; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/core/RawPropsKeyMap.h b/packages/react-native/ReactCommon/react/renderer/core/RawPropsKeyMap.h index be83532d54e..ee14ea4ccbb 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/RawPropsKeyMap.h +++ b/packages/react-native/ReactCommon/react/renderer/core/RawPropsKeyMap.h @@ -25,7 +25,7 @@ class RawPropsKeyMap final { /* * Stores `value` with by given `key`. */ - void insert(const RawPropsKey& key, RawPropsValueIndex value) noexcept; + void insert(const RawPropsKey &key, RawPropsValueIndex value) noexcept; /* * Reindexes the stored data. @@ -37,9 +37,7 @@ class RawPropsKeyMap final { * Finds and returns the `value` (some index) by given `key`. * Returns `kRawPropsValueIndexEmpty` if the value wan't found. */ - RawPropsValueIndex at( - const char* name, - RawPropsPropNameLength length) noexcept; + RawPropsValueIndex at(const char *name, RawPropsPropNameLength length) noexcept; private: struct Item { @@ -48,10 +46,8 @@ class RawPropsKeyMap final { char name[kPropNameLengthHardCap]; }; - static bool shouldFirstOneBeBeforeSecondOne( - const Item& lhs, - const Item& rhs) noexcept; - static bool hasSameName(const Item& lhs, const Item& rhs) noexcept; + static bool shouldFirstOneBeBeforeSecondOne(const Item &lhs, const Item &rhs) noexcept; + static bool hasSameName(const Item &lhs, const Item &rhs) noexcept; std::vector items_{}; std::vector buckets_{}; diff --git a/packages/react-native/ReactCommon/react/renderer/core/RawPropsParser.h b/packages/react-native/ReactCommon/react/renderer/core/RawPropsParser.h index b0c520f3edd..c5ff52c7260 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/RawPropsParser.h +++ b/packages/react-native/ReactCommon/react/renderer/core/RawPropsParser.h @@ -30,18 +30,16 @@ class RawPropsParser final { * If `useRawPropsJsiValue` is `true`, the parser will use `jsi::Value` * directly for RawValues instead of converting them to `folly::dynamic`. */ - RawPropsParser( - bool useRawPropsJsiValue = ReactNativeFeatureFlags::useRawPropsJsiValue()) - : useRawPropsJsiValue_(useRawPropsJsiValue){}; + RawPropsParser(bool useRawPropsJsiValue = ReactNativeFeatureFlags::useRawPropsJsiValue()) + : useRawPropsJsiValue_(useRawPropsJsiValue) {}; /* * To be used by `ConcreteComponentDescriptor` only. */ template - void prepare() noexcept { - static_assert( - std::is_base_of::value, - "PropsT must be a descendant of Props"); + void prepare() noexcept + { + static_assert(std::is_base_of::value, "PropsT must be a descendant of Props"); RawProps emptyRawProps{}; // Create a stub parser context. @@ -66,7 +64,7 @@ class RawPropsParser final { /* * To be used by `RawProps` only. */ - void preparse(const RawProps& rawProps) const noexcept; + void preparse(const RawProps &rawProps) const noexcept; /* * Non-generic part of `prepare`. @@ -76,8 +74,7 @@ class RawPropsParser final { /* * To be used by `RawProps` only. */ - const RawValue* at(const RawProps& rawProps, const RawPropsKey& key) - const noexcept; + const RawValue *at(const RawProps &rawProps, const RawPropsKey &key) const noexcept; mutable std::vector keys_{}; mutable RawPropsKeyMap nameToIndex_{}; diff --git a/packages/react-native/ReactCommon/react/renderer/core/RawPropsPrimitives.h b/packages/react-native/ReactCommon/react/renderer/core/RawPropsPrimitives.h index e2a9f6714cb..c63b2aad7e4 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/RawPropsPrimitives.h +++ b/packages/react-native/ReactCommon/react/renderer/core/RawPropsPrimitives.h @@ -16,17 +16,14 @@ namespace facebook::react { * Type used to represent an index of some stored values in small arrays. */ using RawPropsValueIndex = uint16_t; -static_assert( - sizeof(RawPropsValueIndex) == 2, - "RawPropsValueIndex must be two byte size."); +static_assert(sizeof(RawPropsValueIndex) == 2, "RawPropsValueIndex must be two byte size."); using RawPropsPropNameLength = uint16_t; using RawPropsPropNameHash = uint32_t; /* * Special value of `RawPropsValueIndex` which is used to represent `no value`. */ -constexpr static RawPropsValueIndex kRawPropsValueIndexEmpty = - std::numeric_limits::max(); +constexpr static RawPropsValueIndex kRawPropsValueIndexEmpty = std::numeric_limits::max(); /* * The maximum length of the prop name. diff --git a/packages/react-native/ReactCommon/react/renderer/core/RawValue.h b/packages/react-native/ReactCommon/react/renderer/core/RawValue.h index 31a49a457ab..fd67679acd2 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/RawValue.h +++ b/packages/react-native/ReactCommon/react/renderer/core/RawValue.h @@ -57,48 +57,54 @@ class RawValue { */ RawValue() noexcept : value_(folly::dynamic(nullptr)) {} - RawValue(RawValue&& other) noexcept : value_(std::move(other.value_)) {} + RawValue(RawValue &&other) noexcept : value_(std::move(other.value_)) {} - RawValue& operator=(RawValue&& other) noexcept { + RawValue &operator=(RawValue &&other) noexcept + { if (this != &other) { value_ = std::move(other.value_); } return *this; } - explicit RawValue(jsi::Runtime& runtime, const jsi::Value& value) noexcept - : value_(std::make_pair(&runtime, jsi::Value(runtime, value))) {} + explicit RawValue(jsi::Runtime &runtime, const jsi::Value &value) noexcept + : value_(std::make_pair(&runtime, jsi::Value(runtime, value))) + { + } - explicit RawValue(jsi::Runtime& runtime, jsi::Value&& value) noexcept - : value_(std::make_pair(&runtime, std::move(value))) {} + explicit RawValue(jsi::Runtime &runtime, jsi::Value &&value) noexcept + : value_(std::make_pair(&runtime, std::move(value))) + { + } - explicit RawValue(const folly::dynamic& dynamic) noexcept : value_(dynamic) {} + explicit RawValue(const folly::dynamic &dynamic) noexcept : value_(dynamic) {} - explicit RawValue(folly::dynamic&& dynamic) noexcept - : value_(std::move(dynamic)) {} + explicit RawValue(folly::dynamic &&dynamic) noexcept : value_(std::move(dynamic)) {} private: friend class RawProps; friend class RawPropsParser; friend class UIManagerBinding; - RawValue(const RawValue& other) { + RawValue(const RawValue &other) + { if (std::holds_alternative(other.value_)) { - auto& dynamic = std::get(other.value_); + auto &dynamic = std::get(other.value_); value_ = dynamic; } else { - const auto& [runtime, value] = std::get(other.value_); + const auto &[runtime, value] = std::get(other.value_); value_ = std::make_pair(runtime, jsi::Value(*runtime, value)); } } - RawValue& operator=(const RawValue& other) { + RawValue &operator=(const RawValue &other) + { if (this != &other) { if (std::holds_alternative(other.value_)) { - auto& dynamic = std::get(other.value_); + auto &dynamic = std::get(other.value_); value_ = dynamic; } else { - const auto& [runtime, value] = std::get(other.value_); + const auto &[runtime, value] = std::get(other.value_); value_ = std::make_pair(runtime, jsi::Value(*runtime, value)); } } @@ -110,21 +116,23 @@ class RawValue { * Casts the value to a specified type. */ template - explicit operator T() const { + explicit operator T() const + { if (std::holds_alternative(value_)) { - auto& dynamic = std::get(value_); - return castValue(dynamic, (T*)nullptr); + auto &dynamic = std::get(value_); + return castValue(dynamic, (T *)nullptr); } else { - const auto& [runtime, value] = std::get(value_); - return castValue(runtime, value, (T*)nullptr); + const auto &[runtime, value] = std::get(value_); + return castValue(runtime, value, (T *)nullptr); } } - inline explicit operator folly::dynamic() const { + inline explicit operator folly::dynamic() const + { if (std::holds_alternative(value_)) { return std::get(value_); } else { - const auto& [runtime, value] = std::get(value_); + const auto &[runtime, value] = std::get(value_); return jsi::dynamicFromValue(*runtime, value); } } @@ -133,158 +141,133 @@ class RawValue { * Checks if the stored value has specified type. */ template - bool hasType() const { + bool hasType() const + { if (std::holds_alternative(value_)) { - auto& dynamic = std::get(value_); - return checkValueType(dynamic, (T*)nullptr); + auto &dynamic = std::get(value_); + return checkValueType(dynamic, (T *)nullptr); } else { - const auto& [runtime, value] = std::get(value_); - return checkValueType(runtime, value, (T*)nullptr); + const auto &[runtime, value] = std::get(value_); + return checkValueType(runtime, value, (T *)nullptr); } } /* * Checks if the stored value is *not* `null`. */ - bool hasValue() const { + bool hasValue() const + { if (std::holds_alternative(value_)) { - auto& dynamic = std::get(value_); + auto &dynamic = std::get(value_); return !dynamic.isNull(); } else { - const auto& [runtime, value] = std::get(value_); + const auto &[runtime, value] = std::get(value_); return !value.isNull() && !value.isUndefined(); } } private: - using JsiValuePair = std::pair; + using JsiValuePair = std::pair; std::variant value_; - static bool checkValueType( - const folly::dynamic& /*dynamic*/, - RawValue* /*type*/) noexcept { + static bool checkValueType(const folly::dynamic & /*dynamic*/, RawValue * /*type*/) noexcept + { return true; } - static bool checkValueType( - jsi::Runtime* /*runtime*/, - const jsi::Value& /*value*/, - RawValue* /*type*/) noexcept { + static bool checkValueType(jsi::Runtime * /*runtime*/, const jsi::Value & /*value*/, RawValue * /*type*/) noexcept + { return true; } - static bool checkValueType( - const folly::dynamic& dynamic, - bool* /*type*/) noexcept { + static bool checkValueType(const folly::dynamic &dynamic, bool * /*type*/) noexcept + { return dynamic.isBool(); } - static bool checkValueType( - jsi::Runtime* /*runtime*/, - const jsi::Value& value, - bool* /*type*/) noexcept { + static bool checkValueType(jsi::Runtime * /*runtime*/, const jsi::Value &value, bool * /*type*/) noexcept + { return value.isBool(); } - static bool checkValueType( - const folly::dynamic& dynamic, - int* /*type*/) noexcept { + static bool checkValueType(const folly::dynamic &dynamic, int * /*type*/) noexcept + { return dynamic.isNumber(); } - static bool checkValueType( - jsi::Runtime* /*runtime*/, - const jsi::Value& value, - int* /*type*/) noexcept { + static bool checkValueType(jsi::Runtime * /*runtime*/, const jsi::Value &value, int * /*type*/) noexcept + { return value.isNumber(); } - static bool checkValueType( - const folly::dynamic& dynamic, - int64_t* /*type*/) noexcept { + static bool checkValueType(const folly::dynamic &dynamic, int64_t * /*type*/) noexcept + { return dynamic.isNumber(); } - static bool checkValueType( - jsi::Runtime* /*runtime*/, - const jsi::Value& value, - int64_t* /*type*/) noexcept { + static bool checkValueType(jsi::Runtime * /*runtime*/, const jsi::Value &value, int64_t * /*type*/) noexcept + { return value.isNumber(); } - static bool checkValueType( - const folly::dynamic& dynamic, - float* /*type*/) noexcept { + static bool checkValueType(const folly::dynamic &dynamic, float * /*type*/) noexcept + { return dynamic.isNumber(); } - static bool checkValueType( - jsi::Runtime* /*runtime*/, - const jsi::Value& value, - float* /*type*/) noexcept { + static bool checkValueType(jsi::Runtime * /*runtime*/, const jsi::Value &value, float * /*type*/) noexcept + { return value.isNumber(); } - static bool checkValueType( - const folly::dynamic& dynamic, - double* /*type*/) noexcept { + static bool checkValueType(const folly::dynamic &dynamic, double * /*type*/) noexcept + { return dynamic.isNumber(); } - static bool checkValueType( - jsi::Runtime* /*runtime*/, - const jsi::Value& value, - double* /*type*/) noexcept { + static bool checkValueType(jsi::Runtime * /*runtime*/, const jsi::Value &value, double * /*type*/) noexcept + { return value.isNumber(); } - static bool checkValueType( - const folly::dynamic& dynamic, - std::string* /*type*/) noexcept { + static bool checkValueType(const folly::dynamic &dynamic, std::string * /*type*/) noexcept + { return dynamic.isString(); } - static bool checkValueType( - jsi::Runtime* /*runtime*/, - const jsi::Value& value, - std::string* /*type*/) noexcept { + static bool checkValueType(jsi::Runtime * /*runtime*/, const jsi::Value &value, std::string * /*type*/) noexcept + { return value.isString(); } - static bool checkValueType( - const folly::dynamic& /*dynamic*/, - JsiValuePair* /*type*/) noexcept { + static bool checkValueType(const folly::dynamic & /*dynamic*/, JsiValuePair * /*type*/) noexcept + { return false; } - static bool checkValueType( - jsi::Runtime* /*runtime*/, - const jsi::Value& /*value*/, - JsiValuePair* /*type*/) noexcept { + static bool checkValueType(jsi::Runtime * /*runtime*/, const jsi::Value & /*value*/, JsiValuePair * /*type*/) noexcept + { return true; } template - static bool checkValueType( - const folly::dynamic& dynamic, - std::vector* /*type*/) noexcept { + static bool checkValueType(const folly::dynamic &dynamic, std::vector * /*type*/) noexcept + { if (!dynamic.isArray()) { return false; } - for (const auto& item : dynamic) { + for (const auto &item : dynamic) { // Note: We test only one element. - return checkValueType(item, (T*)nullptr); + return checkValueType(item, (T *)nullptr); } return true; } template - static bool checkValueType( - jsi::Runtime* runtime, - const jsi::Value& value, - std::vector* /*type*/) noexcept { + static bool checkValueType(jsi::Runtime *runtime, const jsi::Value &value, std::vector * /*type*/) noexcept + { if (!value.isObject()) { return false; } @@ -299,34 +282,32 @@ class RawValue { for (size_t i = 0; i < size; i++) { jsi::Value itemValue = array.getValueAtIndex(*runtime, i); // Note: We test only one element. - return checkValueType(runtime, itemValue, (T*)nullptr); + return checkValueType(runtime, itemValue, (T *)nullptr); } return true; } template - static bool checkValueType( - const folly::dynamic& dynamic, - std::unordered_map* /*type*/) noexcept { + static bool checkValueType(const folly::dynamic &dynamic, std::unordered_map * /*type*/) noexcept + { if (!dynamic.isObject()) { return false; } - for (const auto& item : dynamic.items()) { + for (const auto &item : dynamic.items()) { react_native_assert(item.first.isString()); // Note: We test only one element. - return checkValueType(item.second, (T*)nullptr); + return checkValueType(item.second, (T *)nullptr); } return true; } template - static bool checkValueType( - jsi::Runtime* runtime, - const jsi::Value& value, - std::unordered_map* /*type*/) { + static bool + checkValueType(jsi::Runtime *runtime, const jsi::Value &value, std::unordered_map * /*type*/) + { if (!value.isObject()) { return false; } @@ -336,134 +317,118 @@ class RawValue { auto propertyNames = asObject.getPropertyNames(*runtime); size_t size = propertyNames.size(*runtime); for (size_t i = 0; i < size; i++) { - jsi::String propertyName = - propertyNames.getValueAtIndex(*runtime, i).getString(*runtime); + jsi::String propertyName = propertyNames.getValueAtIndex(*runtime, i).getString(*runtime); jsi::Value propertyValue = asObject.getProperty(*runtime, propertyName); // Note: We test only one element. - return checkValueType(runtime, propertyValue, (T*)nullptr); + return checkValueType(runtime, propertyValue, (T *)nullptr); } return true; } // Casts - static RawValue castValue( - const folly::dynamic& dynamic, - RawValue* /*type*/) noexcept { + static RawValue castValue(const folly::dynamic &dynamic, RawValue * /*type*/) noexcept + { return RawValue(dynamic); } - static RawValue castValue( - jsi::Runtime* runtime, - const jsi::Value& value, - RawValue* /*type*/) noexcept { + static RawValue castValue(jsi::Runtime *runtime, const jsi::Value &value, RawValue * /*type*/) noexcept + { return RawValue(*runtime, value); } - static bool castValue(const folly::dynamic& dynamic, bool* /*type*/) { + static bool castValue(const folly::dynamic &dynamic, bool * /*type*/) + { return dynamic.getBool(); } - static bool castValue( - jsi::Runtime* /*runtime*/, - const jsi::Value& value, - bool* /*type*/) { + static bool castValue(jsi::Runtime * /*runtime*/, const jsi::Value &value, bool * /*type*/) + { return value.asBool(); } - static int castValue(const folly::dynamic& dynamic, int* /*type*/) { + static int castValue(const folly::dynamic &dynamic, int * /*type*/) + { return static_cast(dynamic.asInt()); } - static int - castValue(jsi::Runtime* /*runtime*/, const jsi::Value& value, int* /*type*/) { + static int castValue(jsi::Runtime * /*runtime*/, const jsi::Value &value, int * /*type*/) + { // Casting directly from double to int loses precision, go via int64 auto number = static_cast(value.asNumber()); return static_cast(number); } - static int64_t castValue(const folly::dynamic& dynamic, int64_t* /*type*/) { + static int64_t castValue(const folly::dynamic &dynamic, int64_t * /*type*/) + { return dynamic.asInt(); } - static int64_t castValue( - jsi::Runtime* /*runtime*/, - const jsi::Value& value, - int64_t* /*type*/) { + static int64_t castValue(jsi::Runtime * /*runtime*/, const jsi::Value &value, int64_t * /*type*/) + { double number = value.asNumber(); return static_cast(number); } - static float castValue(const folly::dynamic& dynamic, float* /*type*/) { + static float castValue(const folly::dynamic &dynamic, float * /*type*/) + { return static_cast(dynamic.asDouble()); } - static float castValue( - jsi::Runtime* /*runtime*/, - const jsi::Value& value, - float* /*type*/) { + static float castValue(jsi::Runtime * /*runtime*/, const jsi::Value &value, float * /*type*/) + { double number = value.asNumber(); return static_cast(number); } - static double castValue(const folly::dynamic& dynamic, double* /*type*/) { + static double castValue(const folly::dynamic &dynamic, double * /*type*/) + { return dynamic.asDouble(); } - static double castValue( - jsi::Runtime* /*runtime*/, - const jsi::Value& value, - double* /*type*/) { + static double castValue(jsi::Runtime * /*runtime*/, const jsi::Value &value, double * /*type*/) + { return value.asNumber(); } - static std::string castValue( - const folly::dynamic& dynamic, - std::string* /*type*/) { + static std::string castValue(const folly::dynamic &dynamic, std::string * /*type*/) + { return dynamic.getString(); } - static std::string castValue( - jsi::Runtime* runtime, - const jsi::Value& value, - std::string* /*type*/) { + static std::string castValue(jsi::Runtime *runtime, const jsi::Value &value, std::string * /*type*/) + { jsi::String stringValue = value.asString(*runtime); return stringValue.utf8(*runtime); } - static JsiValuePair castValue( - const folly::dynamic& /*dynamic*/, - JsiValuePair* /*type*/) { + static JsiValuePair castValue(const folly::dynamic & /*dynamic*/, JsiValuePair * /*type*/) + { react_native_assert(false); throw std::runtime_error( "Cannot cast dynamic to a jsi::Value type. Please use the 'useRawPropsJsiValue' feature flag to enable jsi::Value support for RawValues."); } - static JsiValuePair castValue( - jsi::Runtime* runtime, - const jsi::Value& value, - JsiValuePair* /*type*/) { + static JsiValuePair castValue(jsi::Runtime *runtime, const jsi::Value &value, JsiValuePair * /*type*/) + { return {runtime, jsi::Value(*runtime, value)}; } template - static std::vector castValue( - const folly::dynamic& dynamic, - std::vector* /*type*/) { + static std::vector castValue(const folly::dynamic &dynamic, std::vector * /*type*/) + { react_native_assert(dynamic.isArray()); auto result = std::vector{}; result.reserve(dynamic.size()); - for (const auto& item : dynamic) { - result.push_back(castValue(item, (T*)nullptr)); + for (const auto &item : dynamic) { + result.push_back(castValue(item, (T *)nullptr)); } return result; } template - static std::vector castValue( - jsi::Runtime* runtime, - const jsi::Value& value, - std::vector* /*type*/) { + static std::vector castValue(jsi::Runtime *runtime, const jsi::Value &value, std::vector * /*type*/) + { react_native_assert(value.isObject()); jsi::Object object = value.getObject(*runtime); react_native_assert(object.isArray(*runtime)); @@ -473,30 +438,28 @@ class RawValue { result.reserve(size); for (size_t i = 0; i < size; i++) { jsi::Value itemValue = array.getValueAtIndex(*runtime, i); - T item = castValue(runtime, itemValue, (T*)nullptr); + T item = castValue(runtime, itemValue, (T *)nullptr); result.push_back(std::move(item)); } return result; } template - static std::vector> castValue( - const folly::dynamic& dynamic, - std::vector>* /*type*/) { + static std::vector> castValue(const folly::dynamic &dynamic, std::vector> * /*type*/) + { react_native_assert(dynamic.isArray()); auto result = std::vector>{}; result.reserve(dynamic.size()); - for (const auto& item : dynamic) { - result.push_back(castValue(item, (std::vector*)nullptr)); + for (const auto &item : dynamic) { + result.push_back(castValue(item, (std::vector *)nullptr)); } return result; } template - static std::vector> castValue( - jsi::Runtime* runtime, - const jsi::Value& value, - std::vector>* /*type*/) { + static std::vector> + castValue(jsi::Runtime *runtime, const jsi::Value &value, std::vector> * /*type*/) + { react_native_assert(value.isObject()); jsi::Object object = value.getObject(*runtime); react_native_assert(object.isArray(*runtime)); @@ -506,8 +469,7 @@ class RawValue { result.reserve(size); for (size_t i = 0; i < size; i++) { jsi::Value itemValue = array.getValueAtIndex(*runtime, i); - std::vector item = - castValue(runtime, itemValue, (std::vector*)nullptr); + std::vector item = castValue(runtime, itemValue, (std::vector *)nullptr); result.push_back(std::move(item)); } return result; @@ -515,22 +477,22 @@ class RawValue { template static std::unordered_map castValue( - const folly::dynamic& dynamic, - std::unordered_map* /*type*/) { + const folly::dynamic &dynamic, + std::unordered_map * /*type*/) + { react_native_assert(dynamic.isObject()); auto result = std::unordered_map{}; - for (const auto& item : dynamic.items()) { + for (const auto &item : dynamic.items()) { react_native_assert(item.first.isString()); - result[item.first.getString()] = castValue(item.second, (T*)nullptr); + result[item.first.getString()] = castValue(item.second, (T *)nullptr); } return result; } template - static std::unordered_map castValue( - jsi::Runtime* runtime, - const jsi::Value& value, - std::unordered_map* /*type*/) { + static std::unordered_map + castValue(jsi::Runtime *runtime, const jsi::Value &value, std::unordered_map * /*type*/) + { react_native_assert(value.isObject()); jsi::Object object = value.getObject(*runtime); jsi::Array propertyNames = object.getPropertyNames(*runtime); @@ -547,7 +509,7 @@ class RawValue { } std::string propertyNameString = propertyName.utf8(*runtime); - T property = castValue(runtime, propertyValue, (T*)nullptr); + T property = castValue(runtime, propertyValue, (T *)nullptr); result.emplace(propertyNameString, std::move(property)); } return result; diff --git a/packages/react-native/ReactCommon/react/renderer/core/ReactEventPriority.h b/packages/react-native/ReactCommon/react/renderer/core/ReactEventPriority.h index f85a9a01b7b..99a96bef25b 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/ReactEventPriority.h +++ b/packages/react-native/ReactCommon/react/renderer/core/ReactEventPriority.h @@ -37,10 +37,9 @@ enum class ReactEventPriority { Idle, }; -static constexpr std::underlying_type::type serialize( - ReactEventPriority reactEventPriority) { - return static_cast::type>( - reactEventPriority); +static constexpr std::underlying_type::type serialize(ReactEventPriority reactEventPriority) +{ + return static_cast::type>(reactEventPriority); } } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/core/ReactPrimitives.h b/packages/react-native/ReactCommon/react/renderer/core/ReactPrimitives.h index de546adf143..84bdffabbf2 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/ReactPrimitives.h +++ b/packages/react-native/ReactCommon/react/renderer/core/ReactPrimitives.h @@ -33,7 +33,7 @@ using ComponentHandle = int64_t; * String identifier for components used for addressing them from * JavaScript side. */ -using ComponentName = const char*; +using ComponentName = const char *; /* * Defines how visual side effects (views, images, text, and so on) are diff --git a/packages/react-native/ReactCommon/react/renderer/core/Sealable.cpp b/packages/react-native/ReactCommon/react/renderer/core/Sealable.cpp index 6edb6f77213..fe256c39201 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/Sealable.cpp +++ b/packages/react-native/ReactCommon/react/renderer/core/Sealable.cpp @@ -28,7 +28,7 @@ namespace facebook::react { Sealable::Sealable() : sealed_(false) {} -Sealable::Sealable(const Sealable& /*other*/) : sealed_(false){}; +Sealable::Sealable(const Sealable& /*other*/) : sealed_(false) {}; Sealable::Sealable(Sealable&& other) noexcept : sealed_(false) { other.ensureUnsealed(); diff --git a/packages/react-native/ReactCommon/react/renderer/core/Sealable.h b/packages/react-native/ReactCommon/react/renderer/core/Sealable.h index 72603b510f0..55930d46008 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/Sealable.h +++ b/packages/react-native/ReactCommon/react/renderer/core/Sealable.h @@ -49,7 +49,8 @@ namespace facebook::react { class Sealable { public: inline void seal() const {} - inline bool getSealed() const { + inline bool getSealed() const + { return true; } inline void ensureUnsealed() const {} @@ -61,11 +62,11 @@ class Sealable { class Sealable { public: Sealable(); - Sealable(const Sealable& other); - Sealable(Sealable&& other) noexcept; + Sealable(const Sealable &other); + Sealable(Sealable &&other) noexcept; ~Sealable() noexcept; - Sealable& operator=(const Sealable& other); - Sealable& operator=(Sealable&& other) noexcept; + Sealable &operator=(const Sealable &other); + Sealable &operator=(Sealable &&other) noexcept; /* * Seals the object. This operation is irreversible; diff --git a/packages/react-native/ReactCommon/react/renderer/core/ShadowNode.h b/packages/react-native/ReactCommon/react/renderer/core/ShadowNode.h index 3b79fd344dc..44303d534d9 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/ShadowNode.h +++ b/packages/react-native/ReactCommon/react/renderer/core/ShadowNode.h @@ -28,37 +28,26 @@ class ComponentDescriptor; struct ShadowNodeFragment; struct ShadowNodeWrapper; -class ShadowNode : public Sealable, - public DebugStringConvertible, - public jsi::NativeState { +class ShadowNode : public Sealable, public DebugStringConvertible, public jsi::NativeState { public: // TODO(T223558094): delete this in the next version. - using Shared [[deprecated("Use std::shared_ptr instead")]] = - std::shared_ptr; + using Shared [[deprecated("Use std::shared_ptr instead")]] = std::shared_ptr; // TODO(T223558094): delete this in the next version. - using Weak [[deprecated("Use std::weak_ptr instead")]] = - std::weak_ptr; + using Weak [[deprecated("Use std::weak_ptr instead")]] = std::weak_ptr; // TODO(T223558094): delete this in the next version. - using Unshared [[deprecated("Use std::shared_ptr instead")]] = - std::shared_ptr; + using Unshared [[deprecated("Use std::shared_ptr instead")]] = std::shared_ptr; // TODO(T223558094): delete this in the next version. - using ListOfShared [[deprecated( - "Use std::vector> instead")]] = + using ListOfShared [[deprecated("Use std::vector> instead")]] = std::vector>; // TODO(T223558094): delete this in the next version. - using ListOfWeak [[deprecated( - "Use std::vector> instead")]] = + using ListOfWeak [[deprecated("Use std::vector> instead")]] = std::vector>; - using SharedListOfShared = - std::shared_ptr>>; - using UnsharedListOfShared = - std::shared_ptr>>; - using UnsharedListOfWeak = - std::shared_ptr>>; + using SharedListOfShared = std::shared_ptr>>; + using UnsharedListOfShared = std::shared_ptr>>; + using UnsharedListOfWeak = std::shared_ptr>>; - using AncestorList = std::vector /* parentNode */, - int /* childIndex */>>; + using AncestorList = + std::vector /* parentNode */, int /* childIndex */>>; static SharedListOfShared emptySharedShadowNodeSharedList(); @@ -66,13 +55,14 @@ class ShadowNode : public Sealable, * Returns `true` if nodes belong to the same family (they were cloned one * from each other or from the same source node). */ - static bool sameFamily(const ShadowNode& first, const ShadowNode& second); + static bool sameFamily(const ShadowNode &first, const ShadowNode &second); /* * A set of traits associated with a particular class. * Reimplement in subclasses to declare class-specific traits. */ - static ShadowNodeTraits BaseTraits() { + static ShadowNodeTraits BaseTraits() + { return ShadowNodeTraits{}; } @@ -83,32 +73,27 @@ class ShadowNode : public Sealable, /* * Creates a Shadow Node based on fields specified in a `fragment`. */ - ShadowNode( - const ShadowNodeFragment& fragment, - ShadowNodeFamily::Shared family, - ShadowNodeTraits traits); + ShadowNode(const ShadowNodeFragment &fragment, ShadowNodeFamily::Shared family, ShadowNodeTraits traits); /* * Creates a Shadow Node via cloning given `sourceShadowNode` and * applying fields from given `fragment`. * Note: `tag`, `surfaceId`, and `eventEmitter` cannot be changed. */ - ShadowNode( - const ShadowNode& sourceShadowNode, - const ShadowNodeFragment& fragment); + ShadowNode(const ShadowNode &sourceShadowNode, const ShadowNodeFragment &fragment); /* * Not copyable. */ - ShadowNode(const ShadowNode& shadowNode) noexcept = delete; - ShadowNode& operator=(const ShadowNode& other) noexcept = delete; + ShadowNode(const ShadowNode &shadowNode) noexcept = delete; + ShadowNode &operator=(const ShadowNode &other) noexcept = delete; virtual ~ShadowNode() override = default; /* * Clones the shadow node using the ShadowNode's ComponentDescriptor. */ - std::shared_ptr clone(const ShadowNodeFragment& fragment) const; + std::shared_ptr clone(const ShadowNodeFragment &fragment) const; /* * Clones the node (and partially the tree starting from the node) by @@ -118,9 +103,8 @@ class ShadowNode : public Sealable, * Returns `nullptr` if the operation cannot be performed successfully. */ std::shared_ptr cloneTree( - const ShadowNodeFamily& shadowNodeFamily, - const std::function( - const ShadowNode& oldShadowNode)>& callback) const; + const ShadowNodeFamily &shadowNodeFamily, + const std::function(const ShadowNode &oldShadowNode)> &callback) const; /* * Clones the nodes (and the subtree containing all the nodes) by @@ -130,18 +114,16 @@ class ShadowNode : public Sealable, * Returns `nullptr` if the operation cannot be performed successfully. */ std::shared_ptr cloneMultiple( - const std::unordered_set& familiesToUpdate, - const std::function( - const ShadowNode& oldShadowNode, - const ShadowNodeFragment& fragment)>& callback) const; + const std::unordered_set &familiesToUpdate, + const std::function< + std::shared_ptr(const ShadowNode &oldShadowNode, const ShadowNodeFragment &fragment)> &callback) + const; /** * Called, once a fully derived ShadowNode clone has been created via * ComponentDescriptor::cloneShadowNode. */ - virtual void completeClone( - const ShadowNode& sourceShadowNode, - const ShadowNodeFragment& fragment) {} + virtual void completeClone(const ShadowNode &sourceShadowNode, const ShadowNodeFragment &fragment) {} #pragma mark - Getters @@ -153,17 +135,17 @@ class ShadowNode : public Sealable, */ ShadowNodeTraits getTraits() const; - const Props::Shared& getProps() const; - const std::vector>& getChildren() const; - const SharedEventEmitter& getEventEmitter() const; - jsi::Value getInstanceHandle(jsi::Runtime& runtime) const; + const Props::Shared &getProps() const; + const std::vector> &getChildren() const; + const SharedEventEmitter &getEventEmitter() const; + jsi::Value getInstanceHandle(jsi::Runtime &runtime) const; Tag getTag() const; SurfaceId getSurfaceId() const; /* * Returns a concrete `ComponentDescriptor` that manages nodes of this type. */ - const ComponentDescriptor& getComponentDescriptor() const; + const ComponentDescriptor &getComponentDescriptor() const; /* * Returns the `ContextContainer` used by this ShadowNode. @@ -173,7 +155,7 @@ class ShadowNode : public Sealable, /* * Returns a state associated with the particular node. */ - const State::Shared& getState() const; + const State::Shared &getState() const; /* * Returns a momentary value of the most recently created or committed state @@ -193,16 +175,16 @@ class ShadowNode : public Sealable, void sealRecursive() const; - const ShadowNodeFamily& getFamily() const; + const ShadowNodeFamily &getFamily() const; ShadowNodeFamily::Shared getFamilyShared() const; #pragma mark - Mutating Methods - virtual void appendChild(const std::shared_ptr& child); + virtual void appendChild(const std::shared_ptr &child); virtual void replaceChild( - const ShadowNode& oldChild, - const std::shared_ptr& newChild, + const ShadowNode &oldChild, + const std::shared_ptr &newChild, size_t suggestedIndex = std::numeric_limits::max()); /* @@ -222,21 +204,19 @@ class ShadowNode : public Sealable, * Bind the runtime reference to this `ShadowNode` with a weak pointer, * allowing to update the reference to this `ShadowNode` when cloned. */ - void setRuntimeShadowNodeReference(const std::shared_ptr& - runtimeShadowNodeReference) const; + void setRuntimeShadowNodeReference(const std::shared_ptr &runtimeShadowNodeReference) const; /* * Update the runtime reference to point to the provided shadow node. */ - void updateRuntimeShadowNodeReference( - const std::shared_ptr& destinationShadowNode) const; + void updateRuntimeShadowNodeReference(const std::shared_ptr &destinationShadowNode) const; /* * Transfer the runtime reference based on the fragment instructions. */ void transferRuntimeShadowNodeReference( - const std::shared_ptr& destinationShadowNode, - const ShadowNodeFragment& fragment) const; + const std::shared_ptr &destinationShadowNode, + const ShadowNodeFragment &fragment) const; #pragma mark - DebugStringConvertible @@ -282,8 +262,7 @@ class ShadowNode : public Sealable, * Transfer the runtime reference to this `ShadowNode` to a new instance, * updating the reference to point to the new `ShadowNode` referencing it. */ - void transferRuntimeShadowNodeReference( - const std::shared_ptr& destinationShadowNode) const; + void transferRuntimeShadowNodeReference(const std::shared_ptr &destinationShadowNode) const; /* * Pointer to a family object that this shadow node belongs to. @@ -301,9 +280,7 @@ class ShadowNode : public Sealable, */ mutable bool hasBeenPromoted_{false}; - static Props::Shared propsForClonedShadowNode( - const ShadowNode& sourceShadowNode, - const Props::Shared& props); + static Props::Shared propsForClonedShadowNode(const ShadowNode &sourceShadowNode, const Props::Shared &props); protected: /* @@ -318,13 +295,10 @@ class ShadowNode : public Sealable, mutable std::weak_ptr runtimeShadowNodeReference_{}; }; -static_assert( - std::has_virtual_destructor::value, - "ShadowNode must have a virtual destructor"); +static_assert(std::has_virtual_destructor::value, "ShadowNode must have a virtual destructor"); struct ShadowNodeWrapper : public jsi::NativeState { - explicit ShadowNodeWrapper(std::shared_ptr shadowNode) - : shadowNode(std::move(shadowNode)) {} + explicit ShadowNodeWrapper(std::shared_ptr shadowNode) : shadowNode(std::move(shadowNode)) {} // The below method needs to be implemented out-of-line in order for the class // to have at least one "key function" (see diff --git a/packages/react-native/ReactCommon/react/renderer/core/ShadowNodeFamily.h b/packages/react-native/ReactCommon/react/renderer/core/ShadowNodeFamily.h index 2699cad51ba..f27b59014dc 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/ShadowNodeFamily.h +++ b/packages/react-native/ReactCommon/react/renderer/core/ShadowNodeFamily.h @@ -44,22 +44,21 @@ class ShadowNodeFamily final : public jsi::NativeState { using Shared = std::shared_ptr; using Weak = std::weak_ptr; - using AncestorList = std::vector /* parentNode */, - int /* childIndex */>>; + using AncestorList = + std::vector /* parentNode */, int /* childIndex */>>; ShadowNodeFamily( - const ShadowNodeFamilyFragment& fragment, + const ShadowNodeFamilyFragment &fragment, SharedEventEmitter eventEmitter, EventDispatcher::Weak eventDispatcher, - const ComponentDescriptor& componentDescriptor); + const ComponentDescriptor &componentDescriptor); /* * Sets the parent. * This is not technically thread-safe, but practically it mutates the object * only once (and the model enforces that this first call is not concurrent). */ - void setParent(const ShadowNodeFamily::Shared& parent) const; + void setParent(const ShadowNodeFamily::Shared &parent) const; /* * Returns a handle (or name) associated with the component. @@ -70,7 +69,7 @@ class ShadowNodeFamily final : public jsi::NativeState { /* * Returns a concrete `ComponentDescriptor` that manages nodes of this type. */ - const ComponentDescriptor& getComponentDescriptor() const; + const ComponentDescriptor &getComponentDescriptor() const; /* * Returns a list of all ancestors of the node relative to the given ancestor. @@ -81,7 +80,7 @@ class ShadowNodeFamily final : public jsi::NativeState { * Can be called from any thread. * The theoretical complexity of the algorithm is `O(ln(n))`. Use it wisely. */ - AncestorList getAncestors(const ShadowNode& ancestorShadowNode) const; + AncestorList getAncestors(const ShadowNode &ancestorShadowNode) const; SurfaceId getSurfaceId() const; @@ -91,14 +90,13 @@ class ShadowNodeFamily final : public jsi::NativeState { * @param callback will be executed when an unmounted instance of * ShadowNodeFamily is destroyed. */ - void onUnmountedFamilyDestroyed( - std::function callback) const; + void onUnmountedFamilyDestroyed(std::function callback) const; /* * Sets and gets the most recent state. */ std::shared_ptr getMostRecentState() const; - void setMostRecentState(const std::shared_ptr& state) const; + void setMostRecentState(const std::shared_ptr &state) const; /** * Mark this ShadowNodeFamily as mounted. @@ -108,9 +106,7 @@ class ShadowNodeFamily final : public jsi::NativeState { /* * Dispatches a state update with given priority. */ - void dispatchRawState( - StateUpdate&& stateUpdate, - EventQueue::UpdateMode updateMode) const; + void dispatchRawState(StateUpdate &&stateUpdate, EventQueue::UpdateMode updateMode) const; /* * Holds currently applied native props. `nullptr` if setNativeProps API is @@ -124,9 +120,9 @@ class ShadowNodeFamily final : public jsi::NativeState { */ Tag getTag() const; - jsi::Value getInstanceHandle(jsi::Runtime& runtime) const; + jsi::Value getInstanceHandle(jsi::Runtime &runtime) const; InstanceHandle::Shared getInstanceHandle() const; - void setInstanceHandle(InstanceHandle::Shared& instanceHandle) const; + void setInstanceHandle(InstanceHandle::Shared &instanceHandle) const; /** * Override destructor to call onUnmountedFamilyDestroyedCallback() for @@ -143,15 +139,13 @@ class ShadowNodeFamily final : public jsi::NativeState { * otherwise returns `nullptr`. * To be used by `State` only. */ - std::shared_ptr getMostRecentStateIfObsolete( - const State& state) const; + std::shared_ptr getMostRecentStateIfObsolete(const State &state) const; EventDispatcher::Weak eventDispatcher_; mutable std::shared_ptr mostRecentState_; mutable std::shared_mutex mutex_; - mutable std::function - onUnmountedFamilyDestroyedCallback_ = nullptr; + mutable std::function onUnmountedFamilyDestroyedCallback_ = nullptr; /* * Deprecated. @@ -177,7 +171,7 @@ class ShadowNodeFamily final : public jsi::NativeState { * Reference to a concrete `ComponentDescriptor` that manages nodes of this * type. */ - const ComponentDescriptor& componentDescriptor_; + const ComponentDescriptor &componentDescriptor_; /* * ComponentHandle and ComponentName must be stored (cached) inside the object diff --git a/packages/react-native/ReactCommon/react/renderer/core/ShadowNodeFragment.h b/packages/react-native/ReactCommon/react/renderer/core/ShadowNodeFragment.h index 4651dce387f..1742c1979ec 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/ShadowNodeFragment.h +++ b/packages/react-native/ReactCommon/react/renderer/core/ShadowNodeFragment.h @@ -23,9 +23,9 @@ namespace facebook::react { * retain ownership of them. */ struct ShadowNodeFragment { - const Props::Shared& props = propsPlaceholder(); - const ShadowNode::SharedListOfShared& children = childrenPlaceholder(); - const State::Shared& state = statePlaceholder(); + const Props::Shared &props = propsPlaceholder(); + const ShadowNode::SharedListOfShared &children = childrenPlaceholder(); + const State::Shared &state = statePlaceholder(); const bool runtimeShadowNodeReference = true; /* @@ -33,9 +33,9 @@ struct ShadowNodeFragment { * Use as default arguments as an indication that the field does not need to * be changed. */ - static const Props::Shared& propsPlaceholder(); - static const ShadowNode::SharedListOfShared& childrenPlaceholder(); - static const State::Shared& statePlaceholder(); + static const Props::Shared &propsPlaceholder(); + static const ShadowNode::SharedListOfShared &childrenPlaceholder(); + static const State::Shared &statePlaceholder(); }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/core/ShadowNodeTraits.h b/packages/react-native/ReactCommon/react/renderer/core/ShadowNodeTraits.h index a6896b84678..cb401a161ce 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/ShadowNodeTraits.h +++ b/packages/react-native/ReactCommon/react/renderer/core/ShadowNodeTraits.h @@ -96,19 +96,23 @@ class ShadowNodeTraits { /* * Sets, unsets, and checks individual traits. */ - inline void set(Trait trait) { + inline void set(Trait trait) + { traits_ = ShadowNodeTraits::Trait(traits_ | trait); } - inline void unset(Trait trait) { + inline void unset(Trait trait) + { traits_ = ShadowNodeTraits::Trait(traits_ & ~trait); } - inline bool check(Trait traits) const { + inline bool check(Trait traits) const + { return ShadowNodeTraits::Trait(traits_ & traits) == traits; } - inline Trait get() const { + inline Trait get() const + { return traits_; } diff --git a/packages/react-native/ReactCommon/react/renderer/core/State.cpp b/packages/react-native/ReactCommon/react/renderer/core/State.cpp index fd5a9d7e436..76665eaac85 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/State.cpp +++ b/packages/react-native/ReactCommon/react/renderer/core/State.cpp @@ -19,7 +19,7 @@ namespace facebook::react { State::State(StateData::Shared data, const State& previousState) : family_(previousState.family_), data_(std::move(data)), - revision_(previousState.revision_ + 1){}; + revision_(previousState.revision_ + 1) {}; State::State(StateData::Shared data, ShadowNodeFamily::Weak family) : family_(std::move(family)), diff --git a/packages/react-native/ReactCommon/react/renderer/core/State.h b/packages/react-native/ReactCommon/react/renderer/core/State.h index 21980378075..fab24360dea 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/State.h +++ b/packages/react-native/ReactCommon/react/renderer/core/State.h @@ -33,7 +33,7 @@ class State { * Constructors are protected to make calling them directly with * type-erasured arguments impossible. */ - explicit State(StateData::Shared data, const State& previousState); + explicit State(StateData::Shared data, const State &previousState); explicit State(StateData::Shared data, ShadowNodeFamily::Weak family); public: @@ -66,7 +66,7 @@ class State { virtual folly::dynamic getDynamic() const = 0; virtual MapBuffer getMapBuffer() const = 0; virtual jni::local_ref getJNIReference() const = 0; - virtual void updateState(folly::dynamic&& data) const = 0; + virtual void updateState(folly::dynamic &&data) const = 0; #endif protected: @@ -77,7 +77,8 @@ class State { * Returns a shared pointer to data. * To be used by `UIManager` only. */ - const StateData::Shared& getDataPointer() const { + const StateData::Shared &getDataPointer() const + { return data_; } diff --git a/packages/react-native/ReactCommon/react/renderer/core/StateData.h b/packages/react-native/ReactCommon/react/renderer/core/StateData.h index cfefa0e9ac6..a796ef180c1 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/StateData.h +++ b/packages/react-native/ReactCommon/react/renderer/core/StateData.h @@ -26,7 +26,7 @@ struct StateData final { #ifdef RN_SERIALIZABLE_STATE StateData() = default; - StateData(const StateData& previousState, folly::dynamic data) {} + StateData(const StateData &previousState, folly::dynamic data) {} folly::dynamic getDynamic() const; MapBuffer getMapBuffer() const; #endif diff --git a/packages/react-native/ReactCommon/react/renderer/core/StatePipe.h b/packages/react-native/ReactCommon/react/renderer/core/StatePipe.h index 0b2b65c4672..a32a00b8111 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/StatePipe.h +++ b/packages/react-native/ReactCommon/react/renderer/core/StatePipe.h @@ -13,6 +13,6 @@ namespace facebook::react { -using StatePipe = std::function; +using StatePipe = std::function; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/core/StateUpdate.h b/packages/react-native/ReactCommon/react/renderer/core/StateUpdate.h index d1a8e381f6c..c4b75217e05 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/StateUpdate.h +++ b/packages/react-native/ReactCommon/react/renderer/core/StateUpdate.h @@ -18,8 +18,7 @@ using SharedShadowNodeFamily = std::shared_ptr; class StateUpdate { public: - using Callback = - std::function; + using Callback = std::function; using FailureCallback = std::function; SharedShadowNodeFamily family; diff --git a/packages/react-native/ReactCommon/react/renderer/core/ValueFactory.h b/packages/react-native/ReactCommon/react/renderer/core/ValueFactory.h index ba554335f54..ddf262293e3 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/ValueFactory.h +++ b/packages/react-native/ReactCommon/react/renderer/core/ValueFactory.h @@ -13,6 +13,6 @@ namespace facebook::react { -using ValueFactory = std::function; +using ValueFactory = std::function; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/core/ValueFactoryEventPayload.h b/packages/react-native/ReactCommon/react/renderer/core/ValueFactoryEventPayload.h index b0e1398ffac..205929a8e02 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/ValueFactoryEventPayload.h +++ b/packages/react-native/ReactCommon/react/renderer/core/ValueFactoryEventPayload.h @@ -15,7 +15,7 @@ namespace facebook::react { class ValueFactoryEventPayload : public EventPayload { public: explicit ValueFactoryEventPayload(ValueFactory factory); - jsi::Value asJSIValue(jsi::Runtime& runtime) const override; + jsi::Value asJSIValue(jsi::Runtime &runtime) const override; EventPayloadType getType() const override; private: diff --git a/packages/react-native/ReactCommon/react/renderer/core/conversions.h b/packages/react-native/ReactCommon/react/renderer/core/conversions.h index f778974811c..74796174353 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/conversions.h +++ b/packages/react-native/ReactCommon/react/renderer/core/conversions.h @@ -11,7 +11,8 @@ namespace facebook::react { -inline std::string toString(const LayoutDirection& layoutDirection) { +inline std::string toString(const LayoutDirection &layoutDirection) +{ switch (layoutDirection) { case LayoutDirection::Undefined: return "undefined"; @@ -22,7 +23,8 @@ inline std::string toString(const LayoutDirection& layoutDirection) { } } -inline int toInt(const LayoutDirection& layoutDirection) { +inline int toInt(const LayoutDirection &layoutDirection) +{ switch (layoutDirection) { case LayoutDirection::Undefined: return 0; @@ -33,7 +35,8 @@ inline int toInt(const LayoutDirection& layoutDirection) { } } -inline int toInt(const DisplayType& displayType) { +inline int toInt(const DisplayType &displayType) +{ switch (displayType) { case DisplayType::None: return 0; @@ -44,7 +47,8 @@ inline int toInt(const DisplayType& displayType) { } } -inline std::string toString(const DisplayType& displayType) { +inline std::string toString(const DisplayType &displayType) +{ switch (displayType) { case DisplayType::None: return "none"; @@ -55,16 +59,15 @@ inline std::string toString(const DisplayType& displayType) { } } -inline Size yogaMeassureToSize(int64_t value) { - static_assert( - sizeof(value) == 8, - "Expected measureResult to be 8 bytes, or two 32 bit ints"); +inline Size yogaMeassureToSize(int64_t value) +{ + static_assert(sizeof(value) == 8, "Expected measureResult to be 8 bytes, or two 32 bit ints"); int32_t wBits = 0xFFFFFFFF & (value >> 32); int32_t hBits = 0xFFFFFFFF & value; - float* measuredWidth = reinterpret_cast(&wBits); - float* measuredHeight = reinterpret_cast(&hBits); + float *measuredWidth = reinterpret_cast(&wBits); + float *measuredHeight = reinterpret_cast(&hBits); return {*measuredWidth, *measuredHeight}; } diff --git a/packages/react-native/ReactCommon/react/renderer/core/graphicsConversions.h b/packages/react-native/ReactCommon/react/renderer/core/graphicsConversions.h index 5f3327407d2..ccc6510b140 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/graphicsConversions.h +++ b/packages/react-native/ReactCommon/react/renderer/core/graphicsConversions.h @@ -32,27 +32,28 @@ namespace facebook::react { #pragma mark - Color -inline void fromRawValue( - const PropsParserContext& context, - const RawValue& value, - SharedColor& result) { +inline void fromRawValue(const PropsParserContext &context, const RawValue &value, SharedColor &result) +{ fromRawValue(context.contextContainer, context.surfaceId, value, result); } #ifdef ANDROID -inline int toAndroidRepr(const SharedColor& color) { +inline int toAndroidRepr(const SharedColor &color) +{ return *color; } #endif -inline std::string toString(const SharedColor& value) { +inline std::string toString(const SharedColor &value) +{ return value.toString(); } #pragma mark - Geometry #ifdef RN_SERIALIZABLE_STATE -inline folly::dynamic toDynamic(const YGValue& dimension) { +inline folly::dynamic toDynamic(const YGValue &dimension) +{ switch (dimension.unit) { case YGUnitUndefined: return "undefined"; @@ -73,7 +74,8 @@ inline folly::dynamic toDynamic(const YGValue& dimension) { return nullptr; } -inline folly::dynamic toDynamic(const Point& point) { +inline folly::dynamic toDynamic(const Point &point) +{ folly::dynamic pointResult = folly::dynamic::object(); pointResult["x"] = point.x; pointResult["y"] = point.y; @@ -81,13 +83,11 @@ inline folly::dynamic toDynamic(const Point& point) { } #endif -inline void fromRawValue( - const PropsParserContext& context, - const RawValue& value, - Point& result) { +inline void fromRawValue(const PropsParserContext &context, const RawValue &value, Point &result) +{ if (value.hasType>()) { auto map = (std::unordered_map)value; - for (const auto& pair : map) { + for (const auto &pair : map) { if (pair.first == "x") { result.x = pair.second; } else if (pair.first == "y") { @@ -112,13 +112,11 @@ inline void fromRawValue( } } -inline void fromRawValue( - const PropsParserContext& context, - const RawValue& value, - Size& result) { +inline void fromRawValue(const PropsParserContext &context, const RawValue &value, Size &result) +{ if (value.hasType>()) { auto map = (std::unordered_map)value; - for (const auto& pair : map) { + for (const auto &pair : map) { if (pair.first == "width") { result.width = pair.second; } else if (pair.first == "height") { @@ -146,10 +144,8 @@ inline void fromRawValue( } } -inline void fromRawValue( - const PropsParserContext& context, - const RawValue& value, - EdgeInsets& result) { +inline void fromRawValue(const PropsParserContext &context, const RawValue &value, EdgeInsets &result) +{ if (value.hasType()) { auto number = (Float)value; result = {.left = number, .top = number, .right = number, .bottom = number}; @@ -158,7 +154,7 @@ inline void fromRawValue( if (value.hasType>()) { auto map = (std::unordered_map)value; - for (const auto& pair : map) { + for (const auto &pair : map) { if (pair.first == "top") { result.top = pair.second; } else if (pair.first == "left") { @@ -180,11 +176,7 @@ inline void fromRawValue( auto array = (std::vector)value; react_native_expect(array.size() == 4); if (array.size() >= 4) { - result = { - .left = array.at(0), - .top = array.at(1), - .right = array.at(2), - .bottom = array.at(3)}; + result = {.left = array.at(0), .top = array.at(1), .right = array.at(2), .bottom = array.at(3)}; } else { result = {.left = 0, .top = 0, .right = 0, .bottom = 0}; LOG(ERROR) << "Unsupported EdgeInsets vector size: " << array.size(); @@ -195,7 +187,8 @@ inline void fromRawValue( } #ifdef RN_SERIALIZABLE_STATE -inline folly::dynamic toDynamic(const EdgeInsets& edgeInsets) { +inline folly::dynamic toDynamic(const EdgeInsets &edgeInsets) +{ folly::dynamic edgeInsetsResult = folly::dynamic::object(); edgeInsetsResult["left"] = edgeInsets.left; edgeInsetsResult["top"] = edgeInsets.top; @@ -205,23 +198,17 @@ inline folly::dynamic toDynamic(const EdgeInsets& edgeInsets) { } #endif -inline void fromRawValue( - const PropsParserContext& context, - const RawValue& value, - CornerInsets& result) { +inline void fromRawValue(const PropsParserContext &context, const RawValue &value, CornerInsets &result) +{ if (value.hasType()) { auto number = (Float)value; - result = { - .topLeft = number, - .topRight = number, - .bottomLeft = number, - .bottomRight = number}; + result = {.topLeft = number, .topRight = number, .bottomLeft = number, .bottomRight = number}; return; } if (value.hasType>()) { auto map = (std::unordered_map)value; - for (const auto& pair : map) { + for (const auto &pair : map) { if (pair.first == "topLeft") { result.topLeft = pair.second; } else if (pair.first == "topRight") { @@ -243,11 +230,7 @@ inline void fromRawValue( auto array = (std::vector)value; react_native_expect(array.size() == 4); if (array.size() >= 4) { - result = { - .topLeft = array.at(0), - .topRight = array.at(1), - .bottomLeft = array.at(2), - .bottomRight = array.at(3)}; + result = {.topLeft = array.at(0), .topRight = array.at(1), .bottomLeft = array.at(2), .bottomRight = array.at(3)}; } else { LOG(ERROR) << "Unsupported CornerInsets vector size: " << array.size(); } @@ -261,29 +244,31 @@ inline void fromRawValue( #if RN_DEBUG_STRING_CONVERTIBLE -inline std::string toString(const Point& point) { +inline std::string toString(const Point &point) +{ return "{" + toString(point.x) + ", " + toString(point.y) + "}"; } -inline std::string toString(const Size& size) { +inline std::string toString(const Size &size) +{ return "{" + toString(size.width) + ", " + toString(size.height) + "}"; } -inline std::string toString(const Rect& rect) { +inline std::string toString(const Rect &rect) +{ return "{" + toString(rect.origin) + ", " + toString(rect.size) + "}"; } -inline std::string toString(const EdgeInsets& edgeInsets) { - return "{" + toString(edgeInsets.left) + ", " + toString(edgeInsets.top) + - ", " + toString(edgeInsets.right) + ", " + toString(edgeInsets.bottom) + - "}"; +inline std::string toString(const EdgeInsets &edgeInsets) +{ + return "{" + toString(edgeInsets.left) + ", " + toString(edgeInsets.top) + ", " + toString(edgeInsets.right) + ", " + + toString(edgeInsets.bottom) + "}"; } -inline std::string toString(const CornerInsets& cornerInsets) { - return "{" + toString(cornerInsets.topLeft) + ", " + - toString(cornerInsets.topRight) + ", " + - toString(cornerInsets.bottomLeft) + ", " + - toString(cornerInsets.bottomRight) + "}"; +inline std::string toString(const CornerInsets &cornerInsets) +{ + return "{" + toString(cornerInsets.topLeft) + ", " + toString(cornerInsets.topRight) + ", " + + toString(cornerInsets.bottomLeft) + ", " + toString(cornerInsets.bottomRight) + "}"; } #endif diff --git a/packages/react-native/ReactCommon/react/renderer/core/propsConversions.h b/packages/react-native/ReactCommon/react/renderer/core/propsConversions.h index f0400693c7a..6148f7f71d6 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/propsConversions.h +++ b/packages/react-native/ReactCommon/react/renderer/core/propsConversions.h @@ -18,7 +18,8 @@ namespace facebook::react { #ifdef RN_SERIALIZABLE_STATE -inline folly::dynamic toDynamic(const std::vector& arrayValue) { +inline folly::dynamic toDynamic(const std::vector &arrayValue) +{ folly::dynamic resultArray = folly::dynamic::array(); for (auto value : arrayValue) { resultArray.push_back(value); @@ -26,15 +27,17 @@ inline folly::dynamic toDynamic(const std::vector& arrayValue) { return resultArray; } -inline folly::dynamic toDynamic(const std::vector& arrayValue) { +inline folly::dynamic toDynamic(const std::vector &arrayValue) +{ folly::dynamic resultArray = folly::dynamic::array(); - for (auto& value : arrayValue) { + for (auto &value : arrayValue) { resultArray.push_back(value); } return resultArray; } -inline folly::dynamic toDynamic(const std::vector& arrayValue) { +inline folly::dynamic toDynamic(const std::vector &arrayValue) +{ folly::dynamic resultArray = folly::dynamic::array(); for (auto value : arrayValue) { resultArray.push_back(value); @@ -42,7 +45,8 @@ inline folly::dynamic toDynamic(const std::vector& arrayValue) { return resultArray; } -inline folly::dynamic toDynamic(const std::vector& arrayValue) { +inline folly::dynamic toDynamic(const std::vector &arrayValue) +{ folly::dynamic resultArray = folly::dynamic::array(); for (auto value : arrayValue) { resultArray.push_back(value); @@ -50,7 +54,8 @@ inline folly::dynamic toDynamic(const std::vector& arrayValue) { return resultArray; } -inline folly::dynamic toDynamic(const std::vector& arrayValue) { +inline folly::dynamic toDynamic(const std::vector &arrayValue) +{ folly::dynamic resultArray = folly::dynamic::array(); for (auto value : arrayValue) { resultArray.push_back(value); @@ -58,18 +63,20 @@ inline folly::dynamic toDynamic(const std::vector& arrayValue) { return resultArray; } -inline folly::dynamic toDynamic(const std::vector& arrayValue) { +inline folly::dynamic toDynamic(const std::vector &arrayValue) +{ folly::dynamic resultArray = folly::dynamic::array(); - for (auto& value : arrayValue) { + for (auto &value : arrayValue) { resultArray.push_back(value); } return resultArray; } template -folly::dynamic toDynamic(const std::vector& arrayValue) { +folly::dynamic toDynamic(const std::vector &arrayValue) +{ folly::dynamic resultArray = folly::dynamic::array(); - for (const auto& value : arrayValue) { + for (const auto &value : arrayValue) { resultArray.push_back(toDynamic(value)); } return resultArray; @@ -83,11 +90,8 @@ folly::dynamic toDynamic(const std::vector& arrayValue) { * nullptr. */ template -void fromRawValue( - const PropsParserContext& context, - const RawValue& rawValue, - T& result, - T defaultValue) { +void fromRawValue(const PropsParserContext &context, const RawValue &rawValue, T &result, T defaultValue) +{ if (!rawValue.hasValue()) { result = std::move(defaultValue); return; @@ -97,34 +101,28 @@ void fromRawValue( } template -void fromRawValue( - const PropsParserContext& context, - const RawValue& rawValue, - T& result) { +void fromRawValue(const PropsParserContext &context, const RawValue &rawValue, T &result) +{ result = (T)rawValue; } template -void fromRawValue( - const PropsParserContext& context, - const RawValue& rawValue, - std::optional& result) { +void fromRawValue(const PropsParserContext &context, const RawValue &rawValue, std::optional &result) +{ T resultValue; fromRawValue(context, rawValue, resultValue); result = std::optional{std::move(resultValue)}; } template -void fromRawValue( - const PropsParserContext& context, - const RawValue& rawValue, - std::vector& result) { +void fromRawValue(const PropsParserContext &context, const RawValue &rawValue, std::vector &result) +{ if (rawValue.hasType>()) { auto items = (std::vector)rawValue; auto length = items.size(); result.clear(); result.reserve(length); - for (auto& item : items) { + for (auto &item : items) { T itemResult; fromRawValue(context, item, itemResult); result.push_back(itemResult); @@ -141,16 +139,14 @@ void fromRawValue( } template -void fromRawValue( - const PropsParserContext& context, - const RawValue& rawValue, - std::vector>& result) { +void fromRawValue(const PropsParserContext &context, const RawValue &rawValue, std::vector> &result) +{ if (rawValue.hasType>>()) { auto items = (std::vector>)rawValue; auto length = items.size(); result.clear(); result.reserve(length); - for (auto& item : items) { + for (auto &item : items) { T itemResult; fromRawValue(context, item, itemResult); result.push_back(itemResult); @@ -168,14 +164,15 @@ void fromRawValue( template T convertRawProp( - const PropsParserContext& context, - const RawProps& rawProps, - const char* name, - const T& sourceValue, - const U& defaultValue, - const char* namePrefix = nullptr, - const char* nameSuffix = nullptr) { - const auto* rawValue = rawProps.at(name, namePrefix, nameSuffix); + const PropsParserContext &context, + const RawProps &rawProps, + const char *name, + const T &sourceValue, + const U &defaultValue, + const char *namePrefix = nullptr, + const char *nameSuffix = nullptr) +{ + const auto *rawValue = rawProps.at(name, namePrefix, nameSuffix); if (rawValue == nullptr) [[likely]] { return sourceValue; } @@ -190,12 +187,11 @@ T convertRawProp( T result; fromRawValue(context, *rawValue, result); return result; - } catch (const std::exception& e) { + } catch (const std::exception &e) { // In case of errors, log the error and fall back to the default RawPropsKey key{.prefix = namePrefix, .name = name, .suffix = nameSuffix}; // TODO: report this using ErrorUtils so it's more visible to the user - LOG(ERROR) << "Error while converting prop '" - << static_cast(key) << "': " << e.what(); + LOG(ERROR) << "Error while converting prop '" << static_cast(key) << "': " << e.what(); return defaultValue; } } diff --git a/packages/react-native/ReactCommon/react/renderer/core/tests/ComponentDescriptorTest.cpp b/packages/react-native/ReactCommon/react/renderer/core/tests/ComponentDescriptorTest.cpp index 988ab9b54a6..4b3538da347 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/tests/ComponentDescriptorTest.cpp +++ b/packages/react-native/ReactCommon/react/renderer/core/tests/ComponentDescriptorTest.cpp @@ -32,11 +32,12 @@ TEST(ComponentDescriptorTest, createShadowNode) { Props::Shared props = descriptor->cloneProps(parserContext, nullptr, std::move(rawProps)); - auto family = descriptor->createFamily(ShadowNodeFamilyFragment{ - /* .tag = */ .tag = 9, - /* .surfaceId = */ .surfaceId = 1, - /* .instanceHandle = */ .instanceHandle = nullptr, - }); + auto family = descriptor->createFamily( + ShadowNodeFamilyFragment{ + /* .tag = */ .tag = 9, + /* .surfaceId = */ .surfaceId = 1, + /* .instanceHandle = */ .instanceHandle = nullptr, + }); std::shared_ptr node = descriptor->createShadowNode( ShadowNodeFragment{ @@ -66,11 +67,12 @@ TEST(ComponentDescriptorTest, cloneShadowNode) { auto rawProps = RawProps(folly::dynamic::object("nativeID", "abc")); Props::Shared props = descriptor->cloneProps(parserContext, nullptr, std::move(rawProps)); - auto family = descriptor->createFamily(ShadowNodeFamilyFragment{ - /* .tag = */ .tag = 9, - /* .surfaceId = */ .surfaceId = 1, - /* .instanceHandle = */ .instanceHandle = nullptr, - }); + auto family = descriptor->createFamily( + ShadowNodeFamilyFragment{ + /* .tag = */ .tag = 9, + /* .surfaceId = */ .surfaceId = 1, + /* .instanceHandle = */ .instanceHandle = nullptr, + }); std::shared_ptr node = descriptor->createShadowNode( ShadowNodeFragment{ /* .props = */ .props = props, @@ -103,31 +105,34 @@ TEST(ComponentDescriptorTest, appendChild) { auto rawProps = RawProps(folly::dynamic::object("nativeID", "abc")); Props::Shared props = descriptor->cloneProps(parserContext, nullptr, std::move(rawProps)); - auto family1 = descriptor->createFamily(ShadowNodeFamilyFragment{ - /* .tag = */ .tag = 1, - /* .surfaceId = */ .surfaceId = 1, - /* .instanceHandle = */ .instanceHandle = nullptr, - }); + auto family1 = descriptor->createFamily( + ShadowNodeFamilyFragment{ + /* .tag = */ .tag = 1, + /* .surfaceId = */ .surfaceId = 1, + /* .instanceHandle = */ .instanceHandle = nullptr, + }); std::shared_ptr node1 = descriptor->createShadowNode( ShadowNodeFragment{ /* .props = */ .props = props, }, family1); - auto family2 = descriptor->createFamily(ShadowNodeFamilyFragment{ - /* .tag = */ .tag = 2, - /* .surfaceId = */ .surfaceId = 1, - /* .instanceHandle = */ .instanceHandle = nullptr, - }); + auto family2 = descriptor->createFamily( + ShadowNodeFamilyFragment{ + /* .tag = */ .tag = 2, + /* .surfaceId = */ .surfaceId = 1, + /* .instanceHandle = */ .instanceHandle = nullptr, + }); std::shared_ptr node2 = descriptor->createShadowNode( ShadowNodeFragment{ /* .props = */ .props = props, }, family2); - auto family3 = descriptor->createFamily(ShadowNodeFamilyFragment{ - /* .tag = */ .tag = 3, - /* .surfaceId = */ .surfaceId = 1, - /* .instanceHandle = */ .instanceHandle = nullptr, - }); + auto family3 = descriptor->createFamily( + ShadowNodeFamilyFragment{ + /* .tag = */ .tag = 3, + /* .surfaceId = */ .surfaceId = 1, + /* .instanceHandle = */ .instanceHandle = nullptr, + }); std::shared_ptr node3 = descriptor->createShadowNode( ShadowNodeFragment{ /* .props = */ .props = props, diff --git a/packages/react-native/ReactCommon/react/renderer/core/tests/RawPropsTest.cpp b/packages/react-native/ReactCommon/react/renderer/core/tests/RawPropsTest.cpp index 072b72f125f..c905cd1e84e 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/tests/RawPropsTest.cpp +++ b/packages/react-native/ReactCommon/react/renderer/core/tests/RawPropsTest.cpp @@ -240,9 +240,10 @@ TEST(RawPropsTest, handleRawPropsPrimitiveTypes) { ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - auto raw = RawProps(folly::dynamic::object("intValue", (int)42)( - "doubleValue", (double)17.42)("floatValue", (float)66.67)( - "stringValue", "helloworld")("boolValue", true)); + auto raw = RawProps( + folly::dynamic::object("intValue", (int)42)("doubleValue", (double)17.42)( + "floatValue", (float)66.67)("stringValue", "helloworld")( + "boolValue", true)); auto parser = RawPropsParser(); parser.prepare(); @@ -261,9 +262,10 @@ TEST(RawPropsTest, handleRawPropsPrimitiveTypesGetTwice) { ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - auto raw = RawProps(folly::dynamic::object("intValue", (int)42)( - "doubleValue", (double)17.42)("floatValue", (float)66.67)( - "stringValue", "helloworld")("boolValue", true)); + auto raw = RawProps( + folly::dynamic::object("intValue", (int)42)("doubleValue", (double)17.42)( + "floatValue", (float)66.67)("stringValue", "helloworld")( + "boolValue", true)); auto parser = RawPropsParser(); parser.prepare(); @@ -290,9 +292,10 @@ TEST(RawPropsTest, handleRawPropsPrimitiveTypesGetOutOfOrder) { ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - auto raw = RawProps(folly::dynamic::object("intValue", (int)42)( - "doubleValue", (double)17.42)("floatValue", (float)66.67)( - "stringValue", "helloworld")("boolValue", true)); + auto raw = RawProps( + folly::dynamic::object("intValue", (int)42)("doubleValue", (double)17.42)( + "floatValue", (float)66.67)("stringValue", "helloworld")( + "boolValue", true)); auto parser = RawPropsParser(); parser.prepare(); diff --git a/packages/react-native/ReactCommon/react/renderer/core/tests/ShadowNodeTest.cpp b/packages/react-native/ReactCommon/react/renderer/core/tests/ShadowNodeTest.cpp index 4392b67b752..a6ea8da1d62 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/tests/ShadowNodeTest.cpp +++ b/packages/react-native/ReactCommon/react/renderer/core/tests/ShadowNodeTest.cpp @@ -40,11 +40,12 @@ class ShadowNodeTest : public testing::Test { auto traits = TestShadowNode::BaseTraits(); - auto familyAA = componentDescriptor_.createFamily(ShadowNodeFamilyFragment{ - /* .tag = */ .tag = 11, - /* .surfaceId = */ .surfaceId = surfaceId_, - /* .instanceHandle = */ .instanceHandle = nullptr, - }); + auto familyAA = componentDescriptor_.createFamily( + ShadowNodeFamilyFragment{ + /* .tag = */ .tag = 11, + /* .surfaceId = */ .surfaceId = surfaceId_, + /* .instanceHandle = */ .instanceHandle = nullptr, + }); nodeAA_ = std::make_shared( ShadowNodeFragment{ /* .props = */ .props = props, @@ -54,11 +55,12 @@ class ShadowNodeTest : public testing::Test { familyAA, traits); - auto familyABA = componentDescriptor_.createFamily(ShadowNodeFamilyFragment{ - /* .tag = */ .tag = 12, - /* .surfaceId = */ .surfaceId = surfaceId_, - /* .instanceHandle = */ .instanceHandle = nullptr, - }); + auto familyABA = componentDescriptor_.createFamily( + ShadowNodeFamilyFragment{ + /* .tag = */ .tag = 12, + /* .surfaceId = */ .surfaceId = surfaceId_, + /* .instanceHandle = */ .instanceHandle = nullptr, + }); nodeABA_ = std::make_shared( ShadowNodeFragment{ /* .props = */ .props = props, @@ -68,11 +70,12 @@ class ShadowNodeTest : public testing::Test { familyABA, traits); - auto familyABB = componentDescriptor_.createFamily(ShadowNodeFamilyFragment{ - /* .tag = */ .tag = 13, - /* .surfaceId = */ .surfaceId = surfaceId_, - /* .instanceHandle = */ .instanceHandle = nullptr, - }); + auto familyABB = componentDescriptor_.createFamily( + ShadowNodeFamilyFragment{ + /* .tag = */ .tag = 13, + /* .surfaceId = */ .surfaceId = surfaceId_, + /* .instanceHandle = */ .instanceHandle = nullptr, + }); nodeABB_ = std::make_shared( ShadowNodeFragment{ /* .props = */ .props = props, @@ -86,11 +89,12 @@ class ShadowNodeTest : public testing::Test { std::make_shared>>( std::vector>{nodeABA_, nodeABB_}); - auto familyAB = componentDescriptor_.createFamily(ShadowNodeFamilyFragment{ - /* .tag = */ .tag = 15, - /* .surfaceId = */ .surfaceId = surfaceId_, - /* .instanceHandle = */ .instanceHandle = nullptr, - }); + auto familyAB = componentDescriptor_.createFamily( + ShadowNodeFamilyFragment{ + /* .tag = */ .tag = 15, + /* .surfaceId = */ .surfaceId = surfaceId_, + /* .instanceHandle = */ .instanceHandle = nullptr, + }); nodeAB_ = std::make_shared( ShadowNodeFragment{ /* .props = */ .props = props, @@ -99,11 +103,12 @@ class ShadowNodeTest : public testing::Test { familyAB, traits); - auto familyAC = componentDescriptor_.createFamily(ShadowNodeFamilyFragment{ - /* .tag = */ .tag = 16, - /* .surfaceId = */ .surfaceId = surfaceId_, - /* .instanceHandle = */ .instanceHandle = nullptr, - }); + auto familyAC = componentDescriptor_.createFamily( + ShadowNodeFamilyFragment{ + /* .tag = */ .tag = 16, + /* .surfaceId = */ .surfaceId = surfaceId_, + /* .instanceHandle = */ .instanceHandle = nullptr, + }); nodeAC_ = std::make_shared( ShadowNodeFragment{ /* .props = */ .props = props, @@ -118,11 +123,12 @@ class ShadowNodeTest : public testing::Test { std::vector>{ nodeAA_, nodeAB_, nodeAC_}); - auto familyA = componentDescriptor_.createFamily(ShadowNodeFamilyFragment{ - /* .tag = */ .tag = 17, - /* .surfaceId = */ .surfaceId = surfaceId_, - /* .instanceHandle = */ .instanceHandle = nullptr, - }); + auto familyA = componentDescriptor_.createFamily( + ShadowNodeFamilyFragment{ + /* .tag = */ .tag = 17, + /* .surfaceId = */ .surfaceId = surfaceId_, + /* .instanceHandle = */ .instanceHandle = nullptr, + }); nodeA_ = std::make_shared( ShadowNodeFragment{ /* .props = */ .props = props, @@ -131,11 +137,12 @@ class ShadowNodeTest : public testing::Test { familyA, traits); - auto familyZ = componentDescriptor_.createFamily(ShadowNodeFamilyFragment{ - /* .tag = */ .tag = 18, - /* .surfaceId = */ .surfaceId = surfaceId_, - /* .instanceHandle = */ .instanceHandle = nullptr, - }); + auto familyZ = componentDescriptor_.createFamily( + ShadowNodeFamilyFragment{ + /* .tag = */ .tag = 18, + /* .surfaceId = */ .surfaceId = surfaceId_, + /* .instanceHandle = */ .instanceHandle = nullptr, + }); nodeZ_ = std::make_shared( ShadowNodeFragment{ /* .props = */ .props = props, @@ -234,11 +241,12 @@ TEST_F(ShadowNodeTest, handleCloneFunction) { } TEST_F(ShadowNodeTest, handleState) { - auto family = componentDescriptor_.createFamily(ShadowNodeFamilyFragment{ - /* .tag = */ .tag = 9, - /* .surfaceId = */ .surfaceId = surfaceId_, - /* .instanceHandle = */ .instanceHandle = nullptr, - }); + auto family = componentDescriptor_.createFamily( + ShadowNodeFamilyFragment{ + /* .tag = */ .tag = 9, + /* .surfaceId = */ .surfaceId = surfaceId_, + /* .instanceHandle = */ .instanceHandle = nullptr, + }); auto traits = TestShadowNode::BaseTraits(); @@ -248,27 +256,24 @@ TEST_F(ShadowNodeTest, handleState) { componentDescriptor_.createInitialState(props, family); auto firstNode = std::make_shared( - ShadowNodeFragment{ - /* .props = */ .props = props, - /* .children = */ .children = - ShadowNode::emptySharedShadowNodeSharedList(), - /* .state = */ .state = initialState}, + ShadowNodeFragment{/* .props = */ .props = props, + /* .children = */ .children = + ShadowNode::emptySharedShadowNodeSharedList(), + /* .state = */ .state = initialState}, family, traits); auto secondNode = std::make_shared( - ShadowNodeFragment{ - /* .props = */ .props = props, - /* .children = */ .children = - ShadowNode::emptySharedShadowNodeSharedList(), - /* .state = */ .state = initialState}, + ShadowNodeFragment{/* .props = */ .props = props, + /* .children = */ .children = + ShadowNode::emptySharedShadowNodeSharedList(), + /* .state = */ .state = initialState}, family, traits); auto thirdNode = std::make_shared( - ShadowNodeFragment{ - /* .props = */ .props = props, - /* .children = */ .children = - ShadowNode::emptySharedShadowNodeSharedList(), - /* .state = */ .state = initialState}, + ShadowNodeFragment{/* .props = */ .props = props, + /* .children = */ .children = + ShadowNode::emptySharedShadowNodeSharedList(), + /* .state = */ .state = initialState}, family, traits); diff --git a/packages/react-native/ReactCommon/react/renderer/core/tests/TestComponent.h b/packages/react-native/ReactCommon/react/renderer/core/tests/TestComponent.h index 4ba4ee25344..3a0ac5f5cda 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/tests/TestComponent.h +++ b/packages/react-native/ReactCommon/react/renderer/core/tests/TestComponent.h @@ -29,9 +29,10 @@ struct TestState { TestState() = default; #ifdef ANDROID - TestState(const TestState& previousState, folly::dynamic&& data){}; + TestState(const TestState &previousState, folly::dynamic &&data) {}; - folly::dynamic getDynamic() const { + folly::dynamic getDynamic() const + { return {}; } #endif @@ -44,11 +45,10 @@ class TestProps : public ViewProps { public: TestProps() = default; - TestProps( - const PropsParserContext& context, - const TestProps& sourceProps, - const RawProps& rawProps) - : ViewProps(context, sourceProps, rawProps) {} + TestProps(const PropsParserContext &context, const TestProps &sourceProps, const RawProps &rawProps) + : ViewProps(context, sourceProps, rawProps) + { + } }; using SharedTestProps = std::shared_ptr; @@ -57,30 +57,26 @@ class TestShadowNode; using SharedTestShadowNode = std::shared_ptr; -class TestShadowNode final : public ConcreteViewShadowNode< - TestComponentName, - TestProps, - ViewEventEmitter, - TestState> { +class TestShadowNode final : public ConcreteViewShadowNode { public: using ConcreteViewShadowNode::ConcreteViewShadowNode; Transform _transform{Transform::Identity()}; - Transform getTransform() const override { + Transform getTransform() const override + { return _transform; } facebook::react::Point _contentOriginOffset{}; - facebook::react::Point getContentOriginOffset( - bool /*includeTransform*/) const override { + facebook::react::Point getContentOriginOffset(bool /*includeTransform*/) const override + { return _contentOriginOffset; } }; -class TestComponentDescriptor - : public ConcreteComponentDescriptor { +class TestComponentDescriptor : public ConcreteComponentDescriptor { public: using ConcreteComponentDescriptor::ConcreteComponentDescriptor; }; diff --git a/packages/react-native/ReactCommon/react/renderer/css/CSSAngle.h b/packages/react-native/ReactCommon/react/renderer/css/CSSAngle.h index 7f89682335e..bf7bcb1a790 100644 --- a/packages/react-native/ReactCommon/react/renderer/css/CSSAngle.h +++ b/packages/react-native/ReactCommon/react/renderer/css/CSSAngle.h @@ -21,13 +21,13 @@ namespace facebook::react { struct CSSAngle { float degrees{}; - constexpr bool operator==(const CSSAngle& rhs) const = default; + constexpr bool operator==(const CSSAngle &rhs) const = default; }; template <> struct CSSDataTypeParser { - static constexpr auto consumePreservedToken(const CSSPreservedToken& token) - -> std::optional { + static constexpr auto consumePreservedToken(const CSSPreservedToken &token) -> std::optional + { if (token.type() == CSSTokenType::Dimension) { if (auto unit = parseCSSAngleUnit(token.unit())) { return CSSAngle{canonicalize(token.numericValue(), *unit)}; diff --git a/packages/react-native/ReactCommon/react/renderer/css/CSSAngleUnit.h b/packages/react-native/ReactCommon/react/renderer/css/CSSAngleUnit.h index 4e2255f180c..08dfe44648a 100644 --- a/packages/react-native/ReactCommon/react/renderer/css/CSSAngleUnit.h +++ b/packages/react-native/ReactCommon/react/renderer/css/CSSAngleUnit.h @@ -30,7 +30,8 @@ enum class CSSAngleUnit : uint8_t { /** * Parses a unit from a dimension token into a CSS angle unit. */ -constexpr std::optional parseCSSAngleUnit(std::string_view unit) { +constexpr std::optional parseCSSAngleUnit(std::string_view unit) +{ switch (fnv1aLowercase(unit)) { case fnv1a("deg"): return CSSAngleUnit::Deg; @@ -48,7 +49,8 @@ constexpr std::optional parseCSSAngleUnit(std::string_view unit) { /** * Converts a specified CSS angle to its cannonical unit (degrees) */ -constexpr float canonicalize(float value, CSSAngleUnit unit) { +constexpr float canonicalize(float value, CSSAngleUnit unit) +{ switch (unit) { case CSSAngleUnit::Deg: return value; diff --git a/packages/react-native/ReactCommon/react/renderer/css/CSSBackgroundImage.h b/packages/react-native/ReactCommon/react/renderer/css/CSSBackgroundImage.h index 250308773b5..5f11cfaf83f 100644 --- a/packages/react-native/ReactCommon/react/renderer/css/CSSBackgroundImage.h +++ b/packages/react-native/ReactCommon/react/renderer/css/CSSBackgroundImage.h @@ -36,28 +36,26 @@ struct CSSLinearGradientDirection { // angle or keyword like "to bottom" std::variant value; - bool operator==(const CSSLinearGradientDirection& rhs) const = default; + bool operator==(const CSSLinearGradientDirection &rhs) const = default; }; template <> struct CSSDataTypeParser { - static constexpr auto consume(CSSSyntaxParser& parser) - -> std::optional { + static constexpr auto consume(CSSSyntaxParser &parser) -> std::optional + { return parseLinearGradientDirection(parser); } private: - static constexpr std::optional - parseLinearGradientDirection(CSSSyntaxParser& parser) { + static constexpr std::optional parseLinearGradientDirection(CSSSyntaxParser &parser) + { auto angle = parseNextCSSValue(parser); if (std::holds_alternative(angle)) { return CSSLinearGradientDirection{std::get(angle)}; } - auto toResult = parser.consumeComponentValue( - [](const CSSPreservedToken& token) -> bool { - return token.type() == CSSTokenType::Ident && - fnv1aLowercase(token.stringValue()) == fnv1a("to"); - }); + auto toResult = parser.consumeComponentValue([](const CSSPreservedToken &token) -> bool { + return token.type() == CSSTokenType::Ident && fnv1aLowercase(token.stringValue()) == fnv1a("to"); + }); if (!toResult) { // no direction found, default to 180 degrees (to bottom) @@ -67,23 +65,22 @@ struct CSSDataTypeParser { parser.consumeWhitespace(); std::optional primaryDir; - auto primaryResult = - parser.consumeComponentValue>( - [](const CSSPreservedToken& token) -> std::optional { - if (token.type() == CSSTokenType::Ident) { - switch (fnv1aLowercase(token.stringValue())) { - case fnv1a("top"): - return CSSKeyword::Top; - case fnv1a("bottom"): - return CSSKeyword::Bottom; - case fnv1a("left"): - return CSSKeyword::Left; - case fnv1a("right"): - return CSSKeyword::Right; - } - } - return {}; - }); + auto primaryResult = parser.consumeComponentValue>( + [](const CSSPreservedToken &token) -> std::optional { + if (token.type() == CSSTokenType::Ident) { + switch (fnv1aLowercase(token.stringValue())) { + case fnv1a("top"): + return CSSKeyword::Top; + case fnv1a("bottom"): + return CSSKeyword::Bottom; + case fnv1a("left"): + return CSSKeyword::Left; + case fnv1a("right"): + return CSSKeyword::Right; + } + } + return {}; + }); if (!primaryResult) { return {}; @@ -93,33 +90,30 @@ struct CSSDataTypeParser { parser.consumeWhitespace(); std::optional secondaryDir; - auto secondaryResult = - parser.consumeComponentValue>( - [&](const CSSPreservedToken& token) -> std::optional { - if (token.type() == CSSTokenType::Ident) { - auto hash = fnv1aLowercase(token.stringValue()); - // validate compatible combinations - if (primaryDir == CSSKeyword::Top || - primaryDir == CSSKeyword::Bottom) { - if (hash == fnv1a("left")) { - return CSSKeyword::Left; - } - if (hash == fnv1a("right")) { - return CSSKeyword::Right; - } - } - if (primaryDir == CSSKeyword::Left || - primaryDir == CSSKeyword::Right) { - if (hash == fnv1a("top")) { - return CSSKeyword::Top; - } - if (hash == fnv1a("bottom")) { - return CSSKeyword::Bottom; - } - } + auto secondaryResult = parser.consumeComponentValue>( + [&](const CSSPreservedToken &token) -> std::optional { + if (token.type() == CSSTokenType::Ident) { + auto hash = fnv1aLowercase(token.stringValue()); + // validate compatible combinations + if (primaryDir == CSSKeyword::Top || primaryDir == CSSKeyword::Bottom) { + if (hash == fnv1a("left")) { + return CSSKeyword::Left; } - return {}; - }); + if (hash == fnv1a("right")) { + return CSSKeyword::Right; + } + } + if (primaryDir == CSSKeyword::Left || primaryDir == CSSKeyword::Right) { + if (hash == fnv1a("top")) { + return CSSKeyword::Top; + } + if (hash == fnv1a("bottom")) { + return CSSKeyword::Bottom; + } + } + } + return {}; + }); if (secondaryResult) { secondaryDir = secondaryResult; @@ -127,44 +121,36 @@ struct CSSDataTypeParser { if (primaryDir == CSSKeyword::Top) { if (secondaryDir == CSSKeyword::Left) { - return CSSLinearGradientDirection{ - CSSLinearGradientDirectionKeyword::ToTopLeft}; + return CSSLinearGradientDirection{CSSLinearGradientDirectionKeyword::ToTopLeft}; } else if (secondaryDir == CSSKeyword::Right) { - return CSSLinearGradientDirection{ - CSSLinearGradientDirectionKeyword::ToTopRight}; + return CSSLinearGradientDirection{CSSLinearGradientDirectionKeyword::ToTopRight}; } else { // "to top" = 0 degrees return CSSLinearGradientDirection{CSSAngle{0.0f}}; } } else if (primaryDir == CSSKeyword::Bottom) { if (secondaryDir == CSSKeyword::Left) { - return CSSLinearGradientDirection{ - CSSLinearGradientDirectionKeyword::ToBottomLeft}; + return CSSLinearGradientDirection{CSSLinearGradientDirectionKeyword::ToBottomLeft}; } else if (secondaryDir == CSSKeyword::Right) { - return CSSLinearGradientDirection{ - CSSLinearGradientDirectionKeyword::ToBottomRight}; + return CSSLinearGradientDirection{CSSLinearGradientDirectionKeyword::ToBottomRight}; } else { // "to bottom" = 180 degrees return CSSLinearGradientDirection{CSSAngle{180.0f}}; } } else if (primaryDir == CSSKeyword::Left) { if (secondaryDir == CSSKeyword::Top) { - return CSSLinearGradientDirection{ - CSSLinearGradientDirectionKeyword::ToTopLeft}; + return CSSLinearGradientDirection{CSSLinearGradientDirectionKeyword::ToTopLeft}; } else if (secondaryDir == CSSKeyword::Bottom) { - return CSSLinearGradientDirection{ - CSSLinearGradientDirectionKeyword::ToBottomLeft}; + return CSSLinearGradientDirection{CSSLinearGradientDirectionKeyword::ToBottomLeft}; } else { // "to left" = 270 degrees return CSSLinearGradientDirection{CSSAngle{270.0f}}; } } else if (primaryDir == CSSKeyword::Right) { if (secondaryDir == CSSKeyword::Top) { - return CSSLinearGradientDirection{ - CSSLinearGradientDirectionKeyword::ToTopRight}; + return CSSLinearGradientDirection{CSSLinearGradientDirectionKeyword::ToTopRight}; } else if (secondaryDir == CSSKeyword::Bottom) { - return CSSLinearGradientDirection{ - CSSLinearGradientDirectionKeyword::ToBottomRight}; + return CSSLinearGradientDirection{CSSLinearGradientDirectionKeyword::ToBottomRight}; } else { // "to right" = 90 degrees return CSSLinearGradientDirection{CSSAngle{90.0f}}; @@ -181,23 +167,24 @@ static_assert(CSSDataType); * Representation of a color hint (interpolation hint) */ struct CSSColorHint { - std::variant - position{}; // Support both lengths and percentages + std::variant position{}; // Support both lengths and percentages - bool operator==(const CSSColorHint& rhs) const { + bool operator==(const CSSColorHint &rhs) const + { return position == rhs.position; } }; template <> struct CSSDataTypeParser { - static auto consume(CSSSyntaxParser& parser) -> std::optional { + static auto consume(CSSSyntaxParser &parser) -> std::optional + { return parseCSSColorHint(parser); } private: - static std::optional parseCSSColorHint( - CSSSyntaxParser& parser) { + static std::optional parseCSSColorHint(CSSSyntaxParser &parser) + { auto position = parseNextCSSValue(parser); if (std::holds_alternative(position)) { return CSSColorHint{std::get(position)}; @@ -215,7 +202,8 @@ struct CSSColorStop { std::optional> startPosition{}; std::optional> endPosition{}; - bool operator==(const CSSColorStop& rhs) const { + bool operator==(const CSSColorStop &rhs) const + { if (color != rhs.color) { return false; } @@ -250,14 +238,14 @@ struct CSSColorStop { template <> struct CSSDataTypeParser { - static constexpr auto consume(CSSSyntaxParser& parser) - -> std::optional { + static constexpr auto consume(CSSSyntaxParser &parser) -> std::optional + { return parseCSSColorStop(parser); } private: - static constexpr std::optional parseCSSColorStop( - CSSSyntaxParser& parser) { + static constexpr std::optional parseCSSColorStop(CSSSyntaxParser &parser) + { auto color = parseNextCSSValue(parser); if (!std::holds_alternative(color)) { return {}; @@ -266,8 +254,7 @@ struct CSSDataTypeParser { CSSColorStop colorStop; colorStop.color = std::get(color); - auto startPosition = parseNextCSSValue( - parser, CSSDelimiter::Whitespace); + auto startPosition = parseNextCSSValue(parser, CSSDelimiter::Whitespace); if (std::holds_alternative(startPosition)) { colorStop.startPosition = std::get(startPosition); } else if (std::holds_alternative(startPosition)) { @@ -277,8 +264,7 @@ struct CSSDataTypeParser { if (colorStop.startPosition) { // Try to parse second optional position (supports both lengths and // percentages) - auto endPosition = parseNextCSSValue( - parser, CSSDelimiter::Whitespace); + auto endPosition = parseNextCSSValue(parser, CSSDelimiter::Whitespace); if (std::holds_alternative(endPosition)) { colorStop.endPosition = std::get(endPosition); } else if (std::holds_alternative(endPosition)) { @@ -293,13 +279,13 @@ static_assert(CSSDataType); struct CSSLinearGradientFunction { std::optional direction{}; - std::vector> - items{}; // Color stops and color hints + std::vector> items{}; // Color stops and color hints - bool operator==(const CSSLinearGradientFunction& rhs) const = default; + bool operator==(const CSSLinearGradientFunction &rhs) const = default; - static std::pair>, int> - parseGradientColorStopsAndHints(CSSSyntaxParser& parser) { + static std::pair>, int> parseGradientColorStopsAndHints( + CSSSyntaxParser &parser) + { std::vector> items; int colorStopCount = 0; @@ -318,8 +304,7 @@ struct CSSLinearGradientFunction { if (!prevColorStop) { return {}; } - auto nextColorStop = - peekNextCSSValue(parser, CSSDelimiter::Comma); + auto nextColorStop = peekNextCSSValue(parser, CSSDelimiter::Comma); if (!std::holds_alternative(nextColorStop)) { return {}; } @@ -341,8 +326,8 @@ enum class CSSRadialGradientShape : uint8_t { template <> struct CSSDataTypeParser { - static constexpr auto consumePreservedToken(const CSSPreservedToken& token) - -> std::optional { + static constexpr auto consumePreservedToken(const CSSPreservedToken &token) -> std::optional + { if (token.type() == CSSTokenType::Ident) { auto lowercase = fnv1aLowercase(token.stringValue()); if (lowercase == fnv1a("circle")) { @@ -366,8 +351,9 @@ enum class CSSRadialGradientSizeKeyword : uint8_t { template <> struct CSSDataTypeParser { - static constexpr auto consumePreservedToken(const CSSPreservedToken& token) - -> std::optional { + static constexpr auto consumePreservedToken(const CSSPreservedToken &token) + -> std::optional + { if (token.type() == CSSTokenType::Ident) { auto lowercase = fnv1aLowercase(token.stringValue()); if (lowercase == fnv1a("closest-side")) { @@ -390,13 +376,13 @@ struct CSSRadialGradientExplicitSize { std::variant sizeX{}; std::variant sizeY{}; - bool operator==(const CSSRadialGradientExplicitSize& rhs) const = default; + bool operator==(const CSSRadialGradientExplicitSize &rhs) const = default; }; template <> struct CSSDataTypeParser { - static auto consume(CSSSyntaxParser& syntaxParser) - -> std::optional { + static auto consume(CSSSyntaxParser &syntaxParser) -> std::optional + { auto sizeX = parseNextCSSValue(syntaxParser); if (std::holds_alternative(sizeX)) { return {}; @@ -413,8 +399,7 @@ struct CSSDataTypeParser { result.sizeX = std::get(sizeX); } - if (std::holds_alternative(sizeY) || - std::holds_alternative(sizeY)) { + if (std::holds_alternative(sizeY) || std::holds_alternative(sizeY)) { if (std::holds_alternative(sizeY)) { result.sizeY = std::get(sizeY); } else { @@ -430,8 +415,7 @@ struct CSSDataTypeParser { static_assert(CSSDataType); -using CSSRadialGradientSize = - std::variant; +using CSSRadialGradientSize = std::variant; struct CSSRadialGradientPosition { std::optional> top{}; @@ -439,9 +423,9 @@ struct CSSRadialGradientPosition { std::optional> left{}; std::optional> right{}; - bool operator==(const CSSRadialGradientPosition& rhs) const { - return top == rhs.top && bottom == rhs.bottom && left == rhs.left && - right == rhs.right; + bool operator==(const CSSRadialGradientPosition &rhs) const + { + return top == rhs.top && bottom == rhs.bottom && left == rhs.left && right == rhs.right; } }; @@ -449,17 +433,16 @@ struct CSSRadialGradientFunction { std::optional shape{}; std::optional size{}; std::optional position{}; - std::vector> - items{}; // Color stops and color hints + std::vector> items{}; // Color stops and color hints - bool operator==(const CSSRadialGradientFunction& rhs) const = default; + bool operator==(const CSSRadialGradientFunction &rhs) const = default; }; template <> struct CSSDataTypeParser { - static auto consumeFunctionBlock( - const CSSFunctionBlock& func, - CSSSyntaxParser& parser) -> std::optional { + static auto consumeFunctionBlock(const CSSFunctionBlock &func, CSSSyntaxParser &parser) + -> std::optional + { if (!iequals(func.name, "radial-gradient")) { return {}; } @@ -475,40 +458,34 @@ struct CSSDataTypeParser { std::optional sizeResult; - auto sizeKeywordResult = - parseNextCSSValue(parser); + auto sizeKeywordResult = parseNextCSSValue(parser); - if (std::holds_alternative( - sizeKeywordResult)) { - sizeResult = CSSRadialGradientSize{ - std::get(sizeKeywordResult)}; + if (std::holds_alternative(sizeKeywordResult)) { + sizeResult = CSSRadialGradientSize{std::get(sizeKeywordResult)}; parser.consumeWhitespace(); } else { - auto explicitSizeResult = - parseNextCSSValue(parser); - if (std::holds_alternative( - explicitSizeResult)) { - auto explicitSize = - std::get(explicitSizeResult); + auto explicitSizeResult = parseNextCSSValue(parser); + if (std::holds_alternative(explicitSizeResult)) { + auto explicitSize = std::get(explicitSizeResult); // negative value validation if (std::holds_alternative(explicitSize.sizeX)) { - const auto& lengthX = std::get(explicitSize.sizeX); + const auto &lengthX = std::get(explicitSize.sizeX); if (lengthX.value < 0) { return {}; } } else if (std::holds_alternative(explicitSize.sizeX)) { - const auto& percentageX = std::get(explicitSize.sizeX); + const auto &percentageX = std::get(explicitSize.sizeX); if (percentageX.value < 0) { return {}; } } if (std::holds_alternative(explicitSize.sizeY)) { - const auto& lengthY = std::get(explicitSize.sizeY); + const auto &lengthY = std::get(explicitSize.sizeY); if (lengthY.value < 0) { return {}; } } else if (std::holds_alternative(explicitSize.sizeY)) { - const auto& percentageY = std::get(explicitSize.sizeY); + const auto &percentageY = std::get(explicitSize.sizeY); if (percentageY.value < 0) { return {}; } @@ -537,62 +514,55 @@ struct CSSDataTypeParser { gradient.size = *sizeResult; } else { // default to farthest corner - gradient.size = - CSSRadialGradientSize{CSSRadialGradientSizeKeyword::FarthestCorner}; + gradient.size = CSSRadialGradientSize{CSSRadialGradientSizeKeyword::FarthestCorner}; } if (!hasExplicitShape && hasExplicitSingleSize) { gradient.shape = CSSRadialGradientShape::Circle; } - if (hasExplicitSingleSize && hasExplicitShape && - gradient.shape.value() == CSSRadialGradientShape::Ellipse) { + if (hasExplicitSingleSize && hasExplicitShape && gradient.shape.value() == CSSRadialGradientShape::Ellipse) { // if a single size is explicitly set and the shape is an ellipse do not // apply any gradient. Same as web. return {}; } - auto atResult = parser.consumeComponentValue( - [](const CSSPreservedToken& token) -> bool { - return token.type() == CSSTokenType::Ident && - fnv1aLowercase(token.stringValue()) == fnv1a("at"); - }); + auto atResult = parser.consumeComponentValue([](const CSSPreservedToken &token) -> bool { + return token.type() == CSSTokenType::Ident && fnv1aLowercase(token.stringValue()) == fnv1a("at"); + }); CSSRadialGradientPosition position; if (atResult) { parser.consumeWhitespace(); - std::vector> - positionKeywordValues; + std::vector> positionKeywordValues; for (int i = 0; i < 2; i++) { auto keywordFound = false; auto valueFound = false; - auto positionKeyword = - parser.consumeComponentValue>( - [](const CSSPreservedToken& token) - -> std::optional { - if (token.type() == CSSTokenType::Ident) { - auto keyword = std::string(token.stringValue()); - auto hash = fnv1aLowercase(keyword); - if (hash == fnv1a("top")) { - return CSSKeyword::Top; - } else if (hash == fnv1a("bottom")) { - return CSSKeyword::Bottom; - } else if (hash == fnv1a("left")) { - return CSSKeyword::Left; - } else if (hash == fnv1a("right")) { - return CSSKeyword::Right; - } else if (hash == fnv1a("center")) { - return CSSKeyword::Center; - } - } - return {}; - }); + auto positionKeyword = parser.consumeComponentValue>( + [](const CSSPreservedToken &token) -> std::optional { + if (token.type() == CSSTokenType::Ident) { + auto keyword = std::string(token.stringValue()); + auto hash = fnv1aLowercase(keyword); + if (hash == fnv1a("top")) { + return CSSKeyword::Top; + } else if (hash == fnv1a("bottom")) { + return CSSKeyword::Bottom; + } else if (hash == fnv1a("left")) { + return CSSKeyword::Left; + } else if (hash == fnv1a("right")) { + return CSSKeyword::Right; + } else if (hash == fnv1a("center")) { + return CSSKeyword::Center; + } + } + return {}; + }); if (positionKeyword) { // invalid position declaration of same keyword "at top 10% top 20%" - for (const auto& existingValue : positionKeywordValues) { + for (const auto &existingValue : positionKeywordValues) { if (std::holds_alternative(existingValue)) { if (std::get(existingValue) == positionKeyword) { return {}; @@ -605,14 +575,12 @@ struct CSSDataTypeParser { parser.consumeWhitespace(); - auto lengthPercentageValue = - parseNextCSSValue(parser); + auto lengthPercentageValue = parseNextCSSValue(parser); std::optional value; if (std::holds_alternative(lengthPercentageValue)) { value = std::get(lengthPercentageValue); - } else if (std::holds_alternative( - lengthPercentageValue)) { + } else if (std::holds_alternative(lengthPercentageValue)) { value = std::get(lengthPercentageValue); } if (value.has_value()) { @@ -654,8 +622,7 @@ struct CSSDataTypeParser { } else { return {}; } - } else if ((std::holds_alternative(value) || - std::holds_alternative(value))) { + } else if ((std::holds_alternative(value) || std::holds_alternative(value))) { if (std::holds_alternative(value)) { position.left = std::get(value); } else { @@ -671,17 +638,14 @@ struct CSSDataTypeParser { auto value1 = positionKeywordValues[0]; auto value2 = positionKeywordValues[1]; // 2. [ left | center | right ] && [ top | center | bottom ] - if (std::holds_alternative(value1) && - std::holds_alternative(value2)) { + if (std::holds_alternative(value1) && std::holds_alternative(value2)) { auto keyword1 = std::get(value1); auto keyword2 = std::get(value2); auto isHorizontal = [](CSSKeyword kw) { - return kw == CSSKeyword::Left || kw == CSSKeyword::Center || - kw == CSSKeyword::Right; + return kw == CSSKeyword::Left || kw == CSSKeyword::Center || kw == CSSKeyword::Right; }; auto isVertical = [](CSSKeyword kw) { - return kw == CSSKeyword::Top || kw == CSSKeyword::Center || - kw == CSSKeyword::Bottom; + return kw == CSSKeyword::Top || kw == CSSKeyword::Center || kw == CSSKeyword::Bottom; }; if (isHorizontal(keyword1) && isVertical(keyword2)) { // First horizontal, second vertical @@ -735,8 +699,7 @@ struct CSSDataTypeParser { } else { return {}; } - } else if ((std::holds_alternative(value1) || - std::holds_alternative(value1))) { + } else if ((std::holds_alternative(value1) || std::holds_alternative(value1))) { if (std::holds_alternative(value1)) { position.left = std::get(value1); } else { @@ -757,8 +720,7 @@ struct CSSDataTypeParser { } else { return {}; } - } else if ((std::holds_alternative(value2) || - std::holds_alternative(value2))) { + } else if ((std::holds_alternative(value2) || std::holds_alternative(value2))) { if (std::holds_alternative(value2)) { position.top = std::get(value2); } else { @@ -784,25 +746,19 @@ struct CSSDataTypeParser { if (!std::holds_alternative(value3)) { return {}; } - if ((!std::holds_alternative(value2) && - !std::holds_alternative(value2))) { + if ((!std::holds_alternative(value2) && !std::holds_alternative(value2))) { return {}; } - if ((!std::holds_alternative(value4) && - !std::holds_alternative(value4))) { + if ((!std::holds_alternative(value4) && !std::holds_alternative(value4))) { return {}; } auto parsedValue2 = std::holds_alternative(value2) - ? std::variant{std::get( - value2)} - : std::variant{ - std::get(value2)}; + ? std::variant{std::get(value2)} + : std::variant{std::get(value2)}; auto parsedValue4 = std::holds_alternative(value4) - ? std::variant{std::get( - value4)} - : std::variant{ - std::get(value4)}; + ? std::variant{std::get(value4)} + : std::variant{std::get(value4)}; auto keyword1 = std::get(value1); auto keyword3 = std::get(value3); @@ -842,8 +798,7 @@ struct CSSDataTypeParser { } parser.consumeDelimiter(CSSDelimiter::Comma); - auto [items, colorStopCount] = - CSSLinearGradientFunction::parseGradientColorStopsAndHints(parser); + auto [items, colorStopCount] = CSSLinearGradientFunction::parseGradientColorStopsAndHints(parser); if (items.empty() || colorStopCount < 2) { return {}; @@ -858,17 +813,16 @@ static_assert(CSSDataType); template <> struct CSSDataTypeParser { - static auto consumeFunctionBlock( - const CSSFunctionBlock& func, - CSSSyntaxParser& parser) -> std::optional { + static auto consumeFunctionBlock(const CSSFunctionBlock &func, CSSSyntaxParser &parser) + -> std::optional + { if (!iequals(func.name, "linear-gradient")) { return {}; } CSSLinearGradientFunction gradient; - auto parsedDirection = - parseNextCSSValue(parser); + auto parsedDirection = parseNextCSSValue(parser); if (!std::holds_alternative(parsedDirection)) { return {}; } @@ -877,8 +831,7 @@ struct CSSDataTypeParser { gradient.direction = std::get(parsedDirection); - auto [items, colorStopCount] = - CSSLinearGradientFunction::parseGradientColorStopsAndHints(parser); + auto [items, colorStopCount] = CSSLinearGradientFunction::parseGradientColorStopsAndHints(parser); if (items.empty() || colorStopCount < 2) { return {}; @@ -896,8 +849,7 @@ static_assert(CSSDataType); * Representation of * https://www.w3.org/TR/css-backgrounds-3/#background-image */ -using CSSBackgroundImage = - CSSCompoundDataType; +using CSSBackgroundImage = CSSCompoundDataType; /** * Variant of possible CSS background image types diff --git a/packages/react-native/ReactCommon/react/renderer/css/CSSColor.h b/packages/react-native/ReactCommon/react/renderer/css/CSSColor.h index 06f76bf84ac..d373ee2f785 100644 --- a/packages/react-native/ReactCommon/react/renderer/css/CSSColor.h +++ b/packages/react-native/ReactCommon/react/renderer/css/CSSColor.h @@ -26,17 +26,18 @@ struct CSSColor { uint8_t b{}; uint8_t a{}; - constexpr bool operator==(const CSSColor& rhs) const = default; + constexpr bool operator==(const CSSColor &rhs) const = default; - static constexpr CSSColor black() { + static constexpr CSSColor black() + { return {.r = 0, .g = 0, .b = 0, .a = 255}; } }; template <> struct CSSDataTypeParser { - static constexpr auto consumePreservedToken(const CSSPreservedToken& token) - -> std::optional { + static constexpr auto consumePreservedToken(const CSSPreservedToken &token) -> std::optional + { switch (token.type()) { case CSSTokenType::Ident: return parseCSSNamedColor(token.stringValue()); @@ -47,9 +48,9 @@ struct CSSDataTypeParser { } } - static constexpr auto consumeFunctionBlock( - const CSSFunctionBlock& func, - CSSSyntaxParser& parser) -> std::optional { + static constexpr auto consumeFunctionBlock(const CSSFunctionBlock &func, CSSSyntaxParser &parser) + -> std::optional + { return parseCSSColorFunction(func.name, parser); } }; diff --git a/packages/react-native/ReactCommon/react/renderer/css/CSSColorFunction.h b/packages/react-native/ReactCommon/react/renderer/css/CSSColorFunction.h index 29f7ef66969..0c82af922f9 100644 --- a/packages/react-native/ReactCommon/react/renderer/css/CSSColorFunction.h +++ b/packages/react-native/ReactCommon/react/renderer/css/CSSColorFunction.h @@ -26,7 +26,8 @@ namespace facebook::react { namespace detail { -constexpr uint8_t clamp255Component(float f) { +constexpr uint8_t clamp255Component(float f) +{ // Implementations should honor the precision of the channel as authored or // calculated wherever possible. If this is not possible, the channel should // be rounded towards +∞. @@ -36,8 +37,8 @@ constexpr uint8_t clamp255Component(float f) { return static_cast(std::clamp(ceiled, 0, 255)); } -constexpr std::optional normalizeNumberComponent( - const std::variant& component) { +constexpr std::optional normalizeNumberComponent(const std::variant &component) +{ if (std::holds_alternative(component)) { return std::get(component).value; } @@ -45,18 +46,19 @@ constexpr std::optional normalizeNumberComponent( return {}; } -constexpr uint8_t clampAlpha(std::optional alpha) { - return alpha.has_value() ? clamp255Component(*alpha * 255.0f) - : static_cast(255u); +constexpr uint8_t clampAlpha(std::optional alpha) +{ + return alpha.has_value() ? clamp255Component(*alpha * 255.0f) : static_cast(255u); } -inline float normalizeHue(float hue) { +inline float normalizeHue(float hue) +{ auto rem = std::remainder(hue, 360.0f); return (rem < 0 ? rem + 360 : rem) / 360.0f; } -inline std::optional normalizeHueComponent( - const std::variant& component) { +inline std::optional normalizeHueComponent(const std::variant &component) +{ if (std::holds_alternative(component)) { return normalizeHue(std::get(component).value); } else if (std::holds_alternative(component)) { @@ -66,7 +68,8 @@ inline std::optional normalizeHueComponent( return {}; } -constexpr float hueToRgb(float p, float q, float t) { +constexpr float hueToRgb(float p, float q, float t) +{ if (t < 0.0f) { t += 1.0f; } @@ -85,8 +88,8 @@ constexpr float hueToRgb(float p, float q, float t) { return p; } -inline std::tuple -hslToRgb(float h, float s, float l) { +inline std::tuple hslToRgb(float h, float s, float l) +{ s = std::clamp(s / 100.0f, 0.0f, 1.0f); l = std::clamp(l / 100.0f, 0.0f, 1.0f); @@ -104,8 +107,8 @@ hslToRgb(float h, float s, float l) { }; } -inline std::tuple -hwbToRgb(float h, float w, float b) { +inline std::tuple hwbToRgb(float h, float w, float b) +{ w = std::clamp(w / 100.0f, 0.0f, 1.0f); b = std::clamp(b / 100.0f, 0.0f, 1.0f); @@ -130,13 +133,11 @@ hwbToRgb(float h, float w, float b) { } template - requires( - (std::is_same_v || - std::is_same_v) && - ...) + requires((std::is_same_v || std::is_same_v) && ...) constexpr std::optional normalizeComponent( - const std::variant& component, - float baseValue) { + const std::variant &component, + float baseValue) +{ if constexpr (traits::containsType()) { if (std::holds_alternative(component)) { return std::get(component).value / 100.0f * baseValue; @@ -153,7 +154,8 @@ constexpr std::optional normalizeComponent( } template -constexpr bool isLegacyColorFunction(CSSSyntaxParser& parser) { +constexpr bool isLegacyColorFunction(CSSSyntaxParser &parser) +{ auto lookahead = parser; auto next = parseNextCSSValue(lookahead); if (std::holds_alternative(next)) { @@ -161,9 +163,7 @@ constexpr bool isLegacyColorFunction(CSSSyntaxParser& parser) { } return lookahead.consumeComponentValue( - CSSDelimiter::OptionalWhitespace, [](CSSPreservedToken token) { - return token.type() == CSSTokenType::Comma; - }); + CSSDelimiter::OptionalWhitespace, [](CSSPreservedToken token) { return token.type() == CSSTokenType::Comma; }); } /** @@ -172,8 +172,8 @@ constexpr bool isLegacyColorFunction(CSSSyntaxParser& parser) { * https://www.w3.org/TR/css-color-4/#typedef-legacy-rgb-syntax */ template -constexpr std::optional parseLegacyRgbFunction( - CSSSyntaxParser& parser) { +constexpr std::optional parseLegacyRgbFunction(CSSSyntaxParser &parser) +{ auto rawRed = parseNextCSSValue(parser); bool usesNumber = std::holds_alternative(rawRed); @@ -182,29 +182,19 @@ constexpr std::optional parseLegacyRgbFunction( return {}; } - auto green = usesNumber - ? normalizeNumberComponent( - parseNextCSSValue(parser, CSSDelimiter::Comma)) - : normalizeComponent( - parseNextCSSValue(parser, CSSDelimiter::Comma), - 255.0f); + auto green = usesNumber ? normalizeNumberComponent(parseNextCSSValue(parser, CSSDelimiter::Comma)) + : normalizeComponent(parseNextCSSValue(parser, CSSDelimiter::Comma), 255.0f); if (!green.has_value()) { return {}; } - auto blue = usesNumber - ? normalizeNumberComponent( - parseNextCSSValue(parser, CSSDelimiter::Comma)) - : normalizeComponent( - parseNextCSSValue(parser, CSSDelimiter::Comma), - 255.0f); + auto blue = usesNumber ? normalizeNumberComponent(parseNextCSSValue(parser, CSSDelimiter::Comma)) + : normalizeComponent(parseNextCSSValue(parser, CSSDelimiter::Comma), 255.0f); if (!blue.has_value()) { return {}; } - auto alpha = normalizeComponent( - parseNextCSSValue(parser, CSSDelimiter::Comma), - 1.0f); + auto alpha = normalizeComponent(parseNextCSSValue(parser, CSSDelimiter::Comma), 1.0f); return CSSColor{ .r = clamp255Component(*red), @@ -220,34 +210,26 @@ constexpr std::optional parseLegacyRgbFunction( * https://www.w3.org/TR/css-color-4/#typedef-modern-rgb-syntax */ template -constexpr std::optional parseModernRgbFunction( - CSSSyntaxParser& parser) { - auto red = normalizeComponent( - parseNextCSSValue(parser), 255.0f); +constexpr std::optional parseModernRgbFunction(CSSSyntaxParser &parser) +{ + auto red = normalizeComponent(parseNextCSSValue(parser), 255.0f); if (!red.has_value()) { return {}; } - auto green = normalizeComponent( - parseNextCSSValue( - parser, CSSDelimiter::Whitespace), - 255.0f); + auto green = + normalizeComponent(parseNextCSSValue(parser, CSSDelimiter::Whitespace), 255.0f); if (!green.has_value()) { return {}; } - auto blue = normalizeComponent( - parseNextCSSValue( - parser, CSSDelimiter::Whitespace), - 255.0f); + auto blue = normalizeComponent(parseNextCSSValue(parser, CSSDelimiter::Whitespace), 255.0f); if (!blue.has_value()) { return {}; } - auto alpha = normalizeComponent( - parseNextCSSValue( - parser, CSSDelimiter::SolidusOrWhitespace), - 1.0f); + auto alpha = + normalizeComponent(parseNextCSSValue(parser, CSSDelimiter::SolidusOrWhitespace), 1.0f); return CSSColor{ .r = clamp255Component(*red), @@ -262,7 +244,8 @@ constexpr std::optional parseModernRgbFunction( * https://www.w3.org/TR/css-color-4/#funcdef-rgb */ template -constexpr std::optional parseRgbFunction(CSSSyntaxParser& parser) { +constexpr std::optional parseRgbFunction(CSSSyntaxParser &parser) +{ if (isLegacyColorFunction(parser)) { return parseLegacyRgbFunction(parser); } else { @@ -276,28 +259,24 @@ constexpr std::optional parseRgbFunction(CSSSyntaxParser& parser) { * https://www.w3.org/TR/css-color-4/#typedef-legacy-hsl-syntax */ template -inline std::optional parseLegacyHslFunction(CSSSyntaxParser& parser) { - auto h = - normalizeHueComponent(parseNextCSSValue(parser)); +inline std::optional parseLegacyHslFunction(CSSSyntaxParser &parser) +{ + auto h = normalizeHueComponent(parseNextCSSValue(parser)); if (!h.has_value()) { return {}; } - auto s = normalizeComponent( - parseNextCSSValue(parser, CSSDelimiter::Comma), 100.0f); + auto s = normalizeComponent(parseNextCSSValue(parser, CSSDelimiter::Comma), 100.0f); if (!s.has_value()) { return {}; } - auto l = normalizeComponent( - parseNextCSSValue(parser, CSSDelimiter::Comma), 100.0f); + auto l = normalizeComponent(parseNextCSSValue(parser, CSSDelimiter::Comma), 100.0f); if (!l.has_value()) { return {}; } - auto a = normalizeComponent( - parseNextCSSValue(parser, CSSDelimiter::Comma), - 1.0f); + auto a = normalizeComponent(parseNextCSSValue(parser, CSSDelimiter::Comma), 1.0f); auto [r, g, b] = hslToRgb(*h, *s, *l); @@ -314,33 +293,25 @@ inline std::optional parseLegacyHslFunction(CSSSyntaxParser& parser) { * it is valid. https://www.w3.org/TR/css-color-4/#typedef-modern-hsl-syntax */ template -inline std::optional parseModernHslFunction(CSSSyntaxParser& parser) { - auto h = - normalizeHueComponent(parseNextCSSValue(parser)); +inline std::optional parseModernHslFunction(CSSSyntaxParser &parser) +{ + auto h = normalizeHueComponent(parseNextCSSValue(parser)); if (!h.has_value()) { return {}; } - auto s = normalizeComponent( - parseNextCSSValue( - parser, CSSDelimiter::Whitespace), - 100.0f); + auto s = normalizeComponent(parseNextCSSValue(parser, CSSDelimiter::Whitespace), 100.0f); if (!s.has_value()) { return {}; } - auto l = normalizeComponent( - parseNextCSSValue( - parser, CSSDelimiter::Whitespace), - 100.0f); + auto l = normalizeComponent(parseNextCSSValue(parser, CSSDelimiter::Whitespace), 100.0f); if (!l.has_value()) { return {}; } - auto a = normalizeComponent( - parseNextCSSValue( - parser, CSSDelimiter::SolidusOrWhitespace), - 1.0f); + auto a = + normalizeComponent(parseNextCSSValue(parser, CSSDelimiter::SolidusOrWhitespace), 1.0f); auto [r, g, b] = hslToRgb(*h, *s, *l); @@ -357,7 +328,8 @@ inline std::optional parseModernHslFunction(CSSSyntaxParser& parser) { * https://www.w3.org/TR/css-color-4/#funcdef-hsl */ template -inline std::optional parseHslFunction(CSSSyntaxParser& parser) { +inline std::optional parseHslFunction(CSSSyntaxParser &parser) +{ if (isLegacyColorFunction(parser)) { return parseLegacyHslFunction(parser); } else { @@ -370,33 +342,25 @@ inline std::optional parseHslFunction(CSSSyntaxParser& parser) { * https://www.w3.org/TR/css-color-4/#funcdef-hwb */ template -inline std::optional parseHwbFunction(CSSSyntaxParser& parser) { - auto h = - normalizeHueComponent(parseNextCSSValue(parser)); +inline std::optional parseHwbFunction(CSSSyntaxParser &parser) +{ + auto h = normalizeHueComponent(parseNextCSSValue(parser)); if (!h.has_value()) { return {}; } - auto w = normalizeComponent( - parseNextCSSValue( - parser, CSSDelimiter::Whitespace), - 100.0f); + auto w = normalizeComponent(parseNextCSSValue(parser, CSSDelimiter::Whitespace), 100.0f); if (!w.has_value()) { return {}; } - auto b = normalizeComponent( - parseNextCSSValue( - parser, CSSDelimiter::Whitespace), - 100.0f); + auto b = normalizeComponent(parseNextCSSValue(parser, CSSDelimiter::Whitespace), 100.0f); if (!b.has_value()) { return {}; } - auto a = normalizeComponent( - parseNextCSSValue( - parser, CSSDelimiter::SolidusOrWhitespace), - 1.0f); + auto a = + normalizeComponent(parseNextCSSValue(parser, CSSDelimiter::SolidusOrWhitespace), 1.0f); auto [red, green, blue] = hwbToRgb(*h, *w, *b); @@ -416,9 +380,8 @@ inline std::optional parseHwbFunction(CSSSyntaxParser& parser) { * https://www.w3.org/TR/css-color-4/#typedef-color-function */ template -constexpr std::optional parseCSSColorFunction( - std::string_view colorFunction, - CSSSyntaxParser& parser) { +constexpr std::optional parseCSSColorFunction(std::string_view colorFunction, CSSSyntaxParser &parser) +{ switch (fnv1aLowercase(colorFunction)) { // CSS Color Module Level 4 treats the alpha variants of functions as the // same as non-alpha variants (alpha is optional for both). diff --git a/packages/react-native/ReactCommon/react/renderer/css/CSSCompoundDataType.h b/packages/react-native/ReactCommon/react/renderer/css/CSSCompoundDataType.h index 51c2e09b501..a97296e02a0 100644 --- a/packages/react-native/ReactCommon/react/renderer/css/CSSCompoundDataType.h +++ b/packages/react-native/ReactCommon/react/renderer/css/CSSCompoundDataType.h @@ -22,16 +22,14 @@ template struct CSSCompoundDataType : public detail::CSSCompoundDataTypeMarker {}; template -concept CSSValidCompoundDataType = - std::is_base_of_v; +concept CSSValidCompoundDataType = std::is_base_of_v; /** * A concrete data type, or a compound data type which represents multiple other * data types. */ template -concept CSSMaybeCompoundDataType = - CSSDataType || CSSValidCompoundDataType; +concept CSSMaybeCompoundDataType = CSSDataType || CSSValidCompoundDataType; namespace detail { @@ -39,53 +37,24 @@ namespace detail { template struct merge_data_types; -template < - CSSDataType... AlllowedTypes1T, - CSSDataType... AlllowedTypes2T, - CSSMaybeCompoundDataType... RestT> -struct merge_data_types< - CSSCompoundDataType, - CSSCompoundDataType, - RestT...> { - using type = typename merge_data_types< - CSSCompoundDataType, - RestT...>::type; +template +struct merge_data_types, CSSCompoundDataType, RestT...> { + using type = typename merge_data_types, RestT...>::type; }; -template < - CSSDataType AlllowedType1T, - CSSDataType... AlllowedTypes2T, - CSSMaybeCompoundDataType... RestT> -struct merge_data_types< - AlllowedType1T, - CSSCompoundDataType, - RestT...> { - using type = typename merge_data_types< - CSSCompoundDataType, - RestT...>::type; +template +struct merge_data_types, RestT...> { + using type = typename merge_data_types, RestT...>::type; }; -template < - CSSDataType AlllowedType2T, - CSSDataType... AlllowedTypes1T, - CSSMaybeCompoundDataType... RestT> -struct merge_data_types< - CSSCompoundDataType, - AlllowedType2T, - RestT...> { - using type = typename merge_data_types< - CSSCompoundDataType, - RestT...>::type; +template +struct merge_data_types, AlllowedType2T, RestT...> { + using type = typename merge_data_types, RestT...>::type; }; -template < - CSSDataType AlllowedType1T, - CSSDataType AlllowedType2T, - CSSMaybeCompoundDataType... RestT> +template struct merge_data_types { - using type = typename merge_data_types< - CSSCompoundDataType, - RestT...>::type; + using type = typename merge_data_types, RestT...>::type; }; template @@ -115,7 +84,6 @@ template using CSSMergedDataTypes = typename detail::merge_data_types::type; template -using CSSVariantWithTypes = - typename detail::merge_variant::type; +using CSSVariantWithTypes = typename detail::merge_variant::type; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/css/CSSDataType.h b/packages/react-native/ReactCommon/react/renderer/css/CSSDataType.h index ac533422ee1..840fdffa7ba 100644 --- a/packages/react-native/ReactCommon/react/renderer/css/CSSDataType.h +++ b/packages/react-native/ReactCommon/react/renderer/css/CSSDataType.h @@ -28,27 +28,25 @@ struct CSSDataTypeParser {}; * concrete representation. */ template -concept CSSFunctionBlockSink = - requires(const CSSFunctionBlock& func, CSSSyntaxParser& parser) { - { T::consumeFunctionBlock(func, parser) } -> std::convertible_to; - }; +concept CSSFunctionBlockSink = requires(const CSSFunctionBlock &func, CSSSyntaxParser &parser) { + { T::consumeFunctionBlock(func, parser) } -> std::convertible_to; +}; /** * Accepts a CSS simple block and may parse it (and future syntax) into a * concrete representation. */ template -concept CSSSimpleBlockSink = - requires(const CSSSimpleBlock& block, CSSSyntaxParser& parser) { - { T::consumeSimpleBlock(block, parser) } -> std::convertible_to; - }; +concept CSSSimpleBlockSink = requires(const CSSSimpleBlock &block, CSSSyntaxParser &parser) { + { T::consumeSimpleBlock(block, parser) } -> std::convertible_to; +}; /** * Accepts a CSS preserved token and may parse it (and future syntax) into a * concrete representation. */ template -concept CSSPreservedTokenSink = requires(const CSSPreservedToken& token) { +concept CSSPreservedTokenSink = requires(const CSSPreservedToken &token) { { T::consumePreservedToken(token) } -> std::convertible_to; }; @@ -56,7 +54,7 @@ concept CSSPreservedTokenSink = requires(const CSSPreservedToken& token) { * Accepts a raw syntax parser, to be able to parse compounded values */ template -concept CSSParserSink = requires(CSSSyntaxParser& parser) { +concept CSSParserSink = requires(CSSSyntaxParser &parser) { { T::consume(parser) } -> std::convertible_to; }; @@ -65,8 +63,7 @@ concept CSSParserSink = requires(CSSSyntaxParser& parser) { */ template concept CSSValidDataTypeParser = - ((CSSFunctionBlockSink || CSSSimpleBlockSink || - CSSPreservedTokenSink) && + ((CSSFunctionBlockSink || CSSSimpleBlockSink || CSSPreservedTokenSink) && !CSSParserSink) || CSSParserSink; @@ -74,8 +71,6 @@ concept CSSValidDataTypeParser = * Concrete representation for a CSS data type */ template -concept CSSDataType = - CSSValidDataTypeParser, std::optional> && - std::equality_comparable; +concept CSSDataType = CSSValidDataTypeParser, std::optional> && std::equality_comparable; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/css/CSSFilter.h b/packages/react-native/ReactCommon/react/renderer/css/CSSFilter.h index bf9236c0b29..f1ff35eda5d 100644 --- a/packages/react-native/ReactCommon/react/renderer/css/CSSFilter.h +++ b/packages/react-native/ReactCommon/react/renderer/css/CSSFilter.h @@ -28,9 +28,9 @@ namespace detail { template requires(std::is_same_v) struct CSSFilterSimpleAmountParser { - static constexpr auto consumeFunctionBlock( - const CSSFunctionBlock& func, - CSSSyntaxParser& parser) -> std::optional { + static constexpr auto consumeFunctionBlock(const CSSFunctionBlock &func, CSSSyntaxParser &parser) + -> std::optional + { if (!iequals(func.name, Name)) { return {}; } @@ -60,22 +60,20 @@ struct CSSFilterSimpleAmountParser { struct CSSBlurFilter { CSSLength amount{}; - constexpr bool operator==(const CSSBlurFilter& rhs) const = default; + constexpr bool operator==(const CSSBlurFilter &rhs) const = default; }; template <> struct CSSDataTypeParser { - static constexpr auto consumeFunctionBlock( - const CSSFunctionBlock& func, - CSSSyntaxParser& parser) -> std::optional { + static constexpr auto consumeFunctionBlock(const CSSFunctionBlock &func, CSSSyntaxParser &parser) + -> std::optional + { if (!iequals(func.name, "blur")) { return {}; } auto len = parseNextCSSValue(parser); - return CSSBlurFilter{ - std::holds_alternative(len) ? std::get(len) - : CSSLength{}}; + return CSSBlurFilter{std::holds_alternative(len) ? std::get(len) : CSSLength{}}; } }; @@ -87,13 +85,12 @@ static_assert(CSSDataType); struct CSSBrightnessFilter { float amount{1.0f}; - constexpr bool operator==(const CSSBrightnessFilter& rhs) const = default; + constexpr bool operator==(const CSSBrightnessFilter &rhs) const = default; }; template <> struct CSSDataTypeParser - : public detail:: - CSSFilterSimpleAmountParser {}; + : public detail::CSSFilterSimpleAmountParser {}; static_assert(CSSDataType); @@ -103,13 +100,12 @@ static_assert(CSSDataType); struct CSSContrastFilter { float amount{1.0f}; - constexpr bool operator==(const CSSContrastFilter& rhs) const = default; + constexpr bool operator==(const CSSContrastFilter &rhs) const = default; }; template <> struct CSSDataTypeParser - : public detail:: - CSSFilterSimpleAmountParser {}; + : public detail::CSSFilterSimpleAmountParser {}; static_assert(CSSDataType); @@ -122,14 +118,14 @@ struct CSSDropShadowFilter { CSSLength standardDeviation{}; CSSColor color{}; - constexpr bool operator==(const CSSDropShadowFilter& rhs) const = default; + constexpr bool operator==(const CSSDropShadowFilter &rhs) const = default; }; template <> struct CSSDataTypeParser { - static constexpr auto consumeFunctionBlock( - const CSSFunctionBlock& func, - CSSSyntaxParser& parser) -> std::optional { + static constexpr auto consumeFunctionBlock(const CSSFunctionBlock &func, CSSSyntaxParser &parser) + -> std::optional + { if (!iequals(func.name, "drop-shadow")) { return {}; } @@ -151,8 +147,7 @@ struct CSSDataTypeParser { } } - auto secondVal = parseNextCSSValue( - parser, CSSDelimiter::Whitespace); + auto secondVal = parseNextCSSValue(parser, CSSDelimiter::Whitespace); if (std::holds_alternative(secondVal)) { if (color.has_value()) { return {}; @@ -178,28 +173,22 @@ struct CSSDataTypeParser { } private: - static constexpr std::optional> parseLengths( - CSSLength offsetX, - CSSSyntaxParser& parser) { - auto offsetY = - parseNextCSSValue(parser, CSSDelimiter::Whitespace); + static constexpr std::optional> parseLengths(CSSLength offsetX, CSSSyntaxParser &parser) + { + auto offsetY = parseNextCSSValue(parser, CSSDelimiter::Whitespace); if (!std::holds_alternative(offsetY)) { return {}; } - auto standardDeviation = - parseNextCSSValue(parser, CSSDelimiter::Whitespace); - if (std::holds_alternative(standardDeviation) && - std::get(standardDeviation).value < 0.0f) { + auto standardDeviation = parseNextCSSValue(parser, CSSDelimiter::Whitespace); + if (std::holds_alternative(standardDeviation) && std::get(standardDeviation).value < 0.0f) { return {}; } return std::array{ offsetX, std::get(offsetY), - std::holds_alternative(standardDeviation) - ? std::get(standardDeviation) - : CSSLength{}}; + std::holds_alternative(standardDeviation) ? std::get(standardDeviation) : CSSLength{}}; } }; @@ -211,13 +200,12 @@ static_assert(CSSDataType); struct CSSGrayscaleFilter { float amount{1.0f}; - constexpr bool operator==(const CSSGrayscaleFilter& rhs) const = default; + constexpr bool operator==(const CSSGrayscaleFilter &rhs) const = default; }; template <> struct CSSDataTypeParser - : public detail:: - CSSFilterSimpleAmountParser {}; + : public detail::CSSFilterSimpleAmountParser {}; static_assert(CSSDataType); @@ -227,23 +215,20 @@ static_assert(CSSDataType); struct CSSHueRotateFilter { float degrees{}; - constexpr bool operator==(const CSSHueRotateFilter& rhs) const = default; + constexpr bool operator==(const CSSHueRotateFilter &rhs) const = default; }; template <> struct CSSDataTypeParser { - static constexpr auto consumeFunctionBlock( - const CSSFunctionBlock& func, - CSSSyntaxParser& parser) -> std::optional { + static constexpr auto consumeFunctionBlock(const CSSFunctionBlock &func, CSSSyntaxParser &parser) + -> std::optional + { if (!iequals(func.name, "hue-rotate")) { return {}; } auto angle = parseNextCSSValue(parser); - return CSSHueRotateFilter{ - std::holds_alternative(angle) - ? std::get(angle).degrees - : 0.0f}; + return CSSHueRotateFilter{std::holds_alternative(angle) ? std::get(angle).degrees : 0.0f}; } }; @@ -255,12 +240,11 @@ static_assert(CSSDataType); struct CSSInvertFilter { float amount{1.0f}; - constexpr bool operator==(const CSSInvertFilter& rhs) const = default; + constexpr bool operator==(const CSSInvertFilter &rhs) const = default; }; template <> -struct CSSDataTypeParser - : public detail::CSSFilterSimpleAmountParser {}; +struct CSSDataTypeParser : public detail::CSSFilterSimpleAmountParser {}; static_assert(CSSDataType); @@ -270,13 +254,11 @@ static_assert(CSSDataType); struct CSSOpacityFilter { float amount{1.0f}; - constexpr bool operator==(const CSSOpacityFilter& rhs) const = default; + constexpr bool operator==(const CSSOpacityFilter &rhs) const = default; }; template <> -struct CSSDataTypeParser - : public detail::CSSFilterSimpleAmountParser { -}; +struct CSSDataTypeParser : public detail::CSSFilterSimpleAmountParser {}; static_assert(CSSDataType); @@ -286,13 +268,12 @@ static_assert(CSSDataType); struct CSSSaturateFilter { float amount{1.0f}; - constexpr bool operator==(const CSSSaturateFilter& rhs) const = default; + constexpr bool operator==(const CSSSaturateFilter &rhs) const = default; }; template <> struct CSSDataTypeParser - : public detail:: - CSSFilterSimpleAmountParser {}; + : public detail::CSSFilterSimpleAmountParser {}; static_assert(CSSDataType); @@ -302,12 +283,11 @@ static_assert(CSSDataType); struct CSSSepiaFilter { float amount{1.0f}; - constexpr bool operator==(const CSSSepiaFilter& rhs) const = default; + constexpr bool operator==(const CSSSepiaFilter &rhs) const = default; }; template <> -struct CSSDataTypeParser - : public detail::CSSFilterSimpleAmountParser {}; +struct CSSDataTypeParser : public detail::CSSFilterSimpleAmountParser {}; static_assert(CSSDataType); diff --git a/packages/react-native/ReactCommon/react/renderer/css/CSSFontVariant.h b/packages/react-native/ReactCommon/react/renderer/css/CSSFontVariant.h index 9303ebfc2ba..b4749170fe4 100644 --- a/packages/react-native/ReactCommon/react/renderer/css/CSSFontVariant.h +++ b/packages/react-native/ReactCommon/react/renderer/css/CSSFontVariant.h @@ -26,8 +26,7 @@ enum class CSSFontVariant : std::underlying_type_t { CommonLigatures = to_underlying(CSSKeyword::CommonLigatures), NoCommonLigatures = to_underlying(CSSKeyword::NoCommonLigatures), DiscretionaryLigatures = to_underlying(CSSKeyword::DiscretionaryLigatures), - NoDiscretionaryLigatures = - to_underlying(CSSKeyword::NoDiscretionaryLigatures), + NoDiscretionaryLigatures = to_underlying(CSSKeyword::NoDiscretionaryLigatures), HistoricalLigatures = to_underlying(CSSKeyword::HistoricalLigatures), NoHistoricalLigatures = to_underlying(CSSKeyword::NoHistoricalLigatures), Contextual = to_underlying(CSSKeyword::Contextual), diff --git a/packages/react-native/ReactCommon/react/renderer/css/CSSHexColor.h b/packages/react-native/ReactCommon/react/renderer/css/CSSHexColor.h index 8caf1ec13a0..89d126a4e43 100644 --- a/packages/react-native/ReactCommon/react/renderer/css/CSSHexColor.h +++ b/packages/react-native/ReactCommon/react/renderer/css/CSSHexColor.h @@ -20,7 +20,8 @@ enum class HexColorType { Short, }; -constexpr uint8_t hexToNumeric(std::string_view hex, HexColorType hexType) { +constexpr uint8_t hexToNumeric(std::string_view hex, HexColorType hexType) +{ int result = 0; for (char c : hex) { int value = 0; @@ -40,15 +41,16 @@ constexpr uint8_t hexToNumeric(std::string_view hex, HexColorType hexType) { } } -constexpr bool isHexDigit(char c) { +constexpr bool isHexDigit(char c) +{ return (c >= '0' && c <= '9') || (toLower(c) >= 'a' && toLower(c) <= 'f'); } -constexpr bool isValidHexColor(std::string_view hex) { +constexpr bool isValidHexColor(std::string_view hex) +{ // The syntax of a is a token whose value consists // of 3, 4, 6, or 8 hexadecimal digits. - if (hex.size() != 3 && hex.size() != 4 && hex.size() != 6 && - hex.size() != 8) { + if (hex.size() != 3 && hex.size() != 4 && hex.size() != 6 && hex.size() != 8) { return false; } @@ -68,8 +70,8 @@ constexpr bool isValidHexColor(std::string_view hex) { * https://www.w3.org/TR/css-color-4/#hex-color */ template -constexpr std::optional parseCSSHexColor( - std::string_view hexColorValue) { +constexpr std::optional parseCSSHexColor(std::string_view hexColorValue) +{ if (detail::isValidHexColor(hexColorValue)) { if (hexColorValue.length() == 3) { return CSSColor{ @@ -82,8 +84,7 @@ constexpr std::optional parseCSSHexColor( hexToNumeric(hexColorValue.substr(0, 1), detail::HexColorType::Short), hexToNumeric(hexColorValue.substr(1, 1), detail::HexColorType::Short), hexToNumeric(hexColorValue.substr(2, 1), detail::HexColorType::Short), - hexToNumeric( - hexColorValue.substr(3, 1), detail::HexColorType::Short)}; + hexToNumeric(hexColorValue.substr(3, 1), detail::HexColorType::Short)}; } else if (hexColorValue.length() == 6) { return CSSColor{ hexToNumeric(hexColorValue.substr(0, 2), detail::HexColorType::Long), diff --git a/packages/react-native/ReactCommon/react/renderer/css/CSSKeyword.h b/packages/react-native/ReactCommon/react/renderer/css/CSSKeyword.h index f39c10f307d..babacc1948c 100644 --- a/packages/react-native/ReactCommon/react/renderer/css/CSSKeyword.h +++ b/packages/react-native/ReactCommon/react/renderer/css/CSSKeyword.h @@ -121,9 +121,8 @@ enum class CSSKeyword : uint8_t { * Represents a constrained set of CSS keywords. */ template -concept CSSKeywordSet = std::is_enum_v && - std::is_same_v, - std::underlying_type_t>; +concept CSSKeywordSet = + std::is_enum_v && std::is_same_v, std::underlying_type_t>; /** * CSS-wide keywords. @@ -251,7 +250,8 @@ CSS_DEFINE_KEYWORD(WrapReverse, "wrap-reverse") * in the keyword-set, or CSS-wide keywords. */ template -constexpr std::optional parseCSSKeyword(std::string_view ident) { +constexpr std::optional parseCSSKeyword(std::string_view ident) +{ switch (fnv1aLowercase(ident)) { CSS_HANDLE_KEYWORD(Absolute) CSS_HANDLE_KEYWORD(Auto) @@ -353,8 +353,8 @@ constexpr std::optional parseCSSKeyword(std::string_view ident) { template struct CSSDataTypeParser { - static constexpr auto consumePreservedToken(const CSSPreservedToken& token) - -> std::optional { + static constexpr auto consumePreservedToken(const CSSPreservedToken &token) -> std::optional + { if (token.type() == CSSTokenType::Ident) { return parseCSSKeyword(token.stringValue()); } diff --git a/packages/react-native/ReactCommon/react/renderer/css/CSSLength.h b/packages/react-native/ReactCommon/react/renderer/css/CSSLength.h index 130d84f1ab5..900b9d93972 100644 --- a/packages/react-native/ReactCommon/react/renderer/css/CSSLength.h +++ b/packages/react-native/ReactCommon/react/renderer/css/CSSLength.h @@ -22,13 +22,13 @@ struct CSSLength { float value{}; CSSLengthUnit unit{CSSLengthUnit::Px}; - constexpr bool operator==(const CSSLength& rhs) const = default; + constexpr bool operator==(const CSSLength &rhs) const = default; }; template <> struct CSSDataTypeParser { - static constexpr auto consumePreservedToken(const CSSPreservedToken& token) - -> std::optional { + static constexpr auto consumePreservedToken(const CSSPreservedToken &token) -> std::optional + { switch (token.type()) { case CSSTokenType::Dimension: if (auto unit = parseCSSLengthUnit(token.unit())) { @@ -42,8 +42,7 @@ struct CSSDataTypeParser { // property (such as line-height), it must parse as a . // https://www.w3.org/TR/css-values-4/#lengths if (token.numericValue() == 0) { - return CSSLength{ - .value = token.numericValue(), .unit = CSSLengthUnit::Px}; + return CSSLength{.value = token.numericValue(), .unit = CSSLengthUnit::Px}; } break; default: diff --git a/packages/react-native/ReactCommon/react/renderer/css/CSSLengthUnit.h b/packages/react-native/ReactCommon/react/renderer/css/CSSLengthUnit.h index b09199832a8..1fc1a62cb63 100644 --- a/packages/react-native/ReactCommon/react/renderer/css/CSSLengthUnit.h +++ b/packages/react-native/ReactCommon/react/renderer/css/CSSLengthUnit.h @@ -68,8 +68,8 @@ enum class CSSLengthUnit : uint8_t { /** * Parses a unit from a dimension token into a CSS length unit. */ -constexpr std::optional parseCSSLengthUnit( - std::string_view unit) { +constexpr std::optional parseCSSLengthUnit(std::string_view unit) +{ switch (fnv1aLowercase(unit)) { case fnv1a("cap"): return CSSLengthUnit::Cap; diff --git a/packages/react-native/ReactCommon/react/renderer/css/CSSList.h b/packages/react-native/ReactCommon/react/renderer/css/CSSList.h index 99c5cb9d860..1bccd52d7aa 100644 --- a/packages/react-native/ReactCommon/react/renderer/css/CSSList.h +++ b/packages/react-native/ReactCommon/react/renderer/css/CSSList.h @@ -24,25 +24,21 @@ template struct CSSList : public std::vector {}; template -struct CSSList - : public std::vector> {}; +struct CSSList : public std::vector> {}; template struct CSSDataTypeParser> { - static inline auto consume(CSSSyntaxParser& parser) - -> std::optional> { + static inline auto consume(CSSSyntaxParser &parser) -> std::optional> + { CSSList result; - for (auto nextValue = parseNextCSSValue(parser); - !std::holds_alternative(nextValue); + for (auto nextValue = parseNextCSSValue(parser); !std::holds_alternative(nextValue); nextValue = parseNextCSSValue(parser, Delim)) { // Copy from the variant of possible values to the element (either the // concrete type, or a variant of compound types which exlcudes the // possibility of std::monostate for parse error) std::visit( - [&](auto&& v) { - if constexpr (!std::is_same_v< - std::remove_cvref_t, - std::monostate>) { + [&](auto &&v) { + if constexpr (!std::is_same_v, std::monostate>) { result.push_back(std::forward(v)); } }, @@ -71,7 +67,6 @@ using CSSCommaSeparatedList = CSSList; * https://www.w3.org/TR/css-values-4/#component-combinators */ template -using CSSWhitespaceSeparatedList = - CSSList; +using CSSWhitespaceSeparatedList = CSSList; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/css/CSSNamedColor.h b/packages/react-native/ReactCommon/react/renderer/css/CSSNamedColor.h index 4ed3065c96b..f77b7d33863 100644 --- a/packages/react-native/ReactCommon/react/renderer/css/CSSNamedColor.h +++ b/packages/react-native/ReactCommon/react/renderer/css/CSSNamedColor.h @@ -20,7 +20,8 @@ namespace facebook::react { * https://www.w3.org/TR/css-color-4/#named-colors */ template -constexpr std::optional parseCSSNamedColor(std::string_view name) { +constexpr std::optional parseCSSNamedColor(std::string_view name) +{ switch (fnv1aLowercase(name)) { case fnv1a("aliceblue"): return CSSColor{240, 248, 255, 255}; diff --git a/packages/react-native/ReactCommon/react/renderer/css/CSSNumber.h b/packages/react-native/ReactCommon/react/renderer/css/CSSNumber.h index 366c94ece6a..d66eb56b3a1 100644 --- a/packages/react-native/ReactCommon/react/renderer/css/CSSNumber.h +++ b/packages/react-native/ReactCommon/react/renderer/css/CSSNumber.h @@ -20,13 +20,13 @@ namespace facebook::react { struct CSSNumber { float value{}; - constexpr bool operator==(const CSSNumber& rhs) const = default; + constexpr bool operator==(const CSSNumber &rhs) const = default; }; template <> struct CSSDataTypeParser { - static constexpr auto consumePreservedToken(const CSSPreservedToken& token) - -> std::optional { + static constexpr auto consumePreservedToken(const CSSPreservedToken &token) -> std::optional + { if (token.type() == CSSTokenType::Number) { return CSSNumber{token.numericValue()}; } diff --git a/packages/react-native/ReactCommon/react/renderer/css/CSSPercentage.h b/packages/react-native/ReactCommon/react/renderer/css/CSSPercentage.h index 42ed92aaf87..39c4c2cb640 100644 --- a/packages/react-native/ReactCommon/react/renderer/css/CSSPercentage.h +++ b/packages/react-native/ReactCommon/react/renderer/css/CSSPercentage.h @@ -20,13 +20,13 @@ namespace facebook::react { struct CSSPercentage { float value{}; - constexpr bool operator==(const CSSPercentage& rhs) const = default; + constexpr bool operator==(const CSSPercentage &rhs) const = default; }; template <> struct CSSDataTypeParser { - static constexpr auto consumePreservedToken(const CSSPreservedToken& token) - -> std::optional { + static constexpr auto consumePreservedToken(const CSSPreservedToken &token) -> std::optional + { if (token.type() == CSSTokenType::Percentage) { return CSSPercentage{token.numericValue()}; } diff --git a/packages/react-native/ReactCommon/react/renderer/css/CSSRatio.h b/packages/react-native/ReactCommon/react/renderer/css/CSSRatio.h index 2459031a53f..821a9dba8d7 100644 --- a/packages/react-native/ReactCommon/react/renderer/css/CSSRatio.h +++ b/packages/react-native/ReactCommon/react/renderer/css/CSSRatio.h @@ -24,23 +24,22 @@ struct CSSRatio { float numerator{}; float denominator{}; - constexpr bool operator==(const CSSRatio& rhs) const = default; + constexpr bool operator==(const CSSRatio &rhs) const = default; - constexpr bool isDegenerate() const { + constexpr bool isDegenerate() const + { // If either number in the is 0 or infinite, it represents a // degenerate ratio (and, generally, won’t do anything). // https://www.w3.org/TR/css-values-4/#ratios - return numerator == 0.0f || - numerator == std::numeric_limits::infinity() || - denominator == 0.0f || + return numerator == 0.0f || numerator == std::numeric_limits::infinity() || denominator == 0.0f || denominator == std::numeric_limits::infinity(); } }; template <> struct CSSDataTypeParser { - static constexpr auto consume(CSSSyntaxParser& parser) - -> std::optional { + static constexpr auto consume(CSSSyntaxParser &parser) -> std::optional + { // = [ / ]? // https://www.w3.org/TR/css-values-4/#ratio auto numerator = parseNextCSSValue(parser); @@ -50,14 +49,10 @@ struct CSSDataTypeParser { auto numeratorValue = std::get(numerator).value; if (numeratorValue >= 0) { - auto denominator = - peekNextCSSValue(parser, CSSDelimiter::Solidus); - if (std::holds_alternative(denominator) && - std::get(denominator).value >= 0) { + auto denominator = peekNextCSSValue(parser, CSSDelimiter::Solidus); + if (std::holds_alternative(denominator) && std::get(denominator).value >= 0) { parseNextCSSValue(parser, CSSDelimiter::Solidus); - return CSSRatio{ - .numerator = numeratorValue, - .denominator = std::get(denominator).value}; + return CSSRatio{.numerator = numeratorValue, .denominator = std::get(denominator).value}; } return CSSRatio{.numerator = numeratorValue, .denominator = 1.0f}; diff --git a/packages/react-native/ReactCommon/react/renderer/css/CSSShadow.h b/packages/react-native/ReactCommon/react/renderer/css/CSSShadow.h index 6adb85bb799..30f15bcdea9 100644 --- a/packages/react-native/ReactCommon/react/renderer/css/CSSShadow.h +++ b/packages/react-native/ReactCommon/react/renderer/css/CSSShadow.h @@ -32,7 +32,7 @@ struct CSSShadow { CSSColor color{CSSColor::black()}; bool inset{false}; - constexpr bool operator==(const CSSShadow& rhs) const = default; + constexpr bool operator==(const CSSShadow &rhs) const = default; }; /** @@ -46,20 +46,15 @@ static_assert(CSSDataType); template <> struct CSSDataTypeParser { - static constexpr auto consume(CSSSyntaxParser& parser) - -> std::optional { + static constexpr auto consume(CSSSyntaxParser &parser) -> std::optional + { std::optional color{}; bool inset{false}; - std::optional> - lengths{}; + std::optional> lengths{}; - for (auto nextValue = - parseNextCSSValue( - parser); + for (auto nextValue = parseNextCSSValue(parser); !std::holds_alternative(nextValue); - nextValue = - parseNextCSSValue( - parser, CSSDelimiter::Whitespace)) { + nextValue = parseNextCSSValue(parser, CSSDelimiter::Whitespace)) { if (std::holds_alternative(nextValue)) { if (lengths.has_value()) { return {}; @@ -103,41 +98,29 @@ struct CSSDataTypeParser { } private: - static constexpr auto parseRestLengths( - CSSLength offsetX, - CSSSyntaxParser& parser) - -> std::optional> { - auto offsetY = - parseNextCSSValue(parser, CSSDelimiter::Whitespace); + static constexpr auto parseRestLengths(CSSLength offsetX, CSSSyntaxParser &parser) + -> std::optional> + { + auto offsetY = parseNextCSSValue(parser, CSSDelimiter::Whitespace); if (std::holds_alternative(offsetY)) { return {}; } - auto blurRadius = - parseNextCSSValue(parser, CSSDelimiter::Whitespace); + auto blurRadius = parseNextCSSValue(parser, CSSDelimiter::Whitespace); if (std::holds_alternative(blurRadius)) { - return std::make_tuple( - offsetX, std::get(offsetY), CSSLength{}, CSSLength{}); + return std::make_tuple(offsetX, std::get(offsetY), CSSLength{}, CSSLength{}); } if (std::get(blurRadius).value < 0) { return {}; } - auto spreadDistance = - parseNextCSSValue(parser, CSSDelimiter::Whitespace); + auto spreadDistance = parseNextCSSValue(parser, CSSDelimiter::Whitespace); if (std::holds_alternative(spreadDistance)) { - return std::make_tuple( - offsetX, - std::get(offsetY), - std::get(blurRadius), - CSSLength{}); + return std::make_tuple(offsetX, std::get(offsetY), std::get(blurRadius), CSSLength{}); } return std::make_tuple( - offsetX, - std::get(offsetY), - std::get(blurRadius), - std::get(spreadDistance)); + offsetX, std::get(offsetY), std::get(blurRadius), std::get(spreadDistance)); } }; diff --git a/packages/react-native/ReactCommon/react/renderer/css/CSSSyntaxParser.h b/packages/react-native/ReactCommon/react/renderer/css/CSSSyntaxParser.h index 722953fbf0b..811518aeb75 100644 --- a/packages/react-native/ReactCommon/react/renderer/css/CSSSyntaxParser.h +++ b/packages/react-native/ReactCommon/react/renderer/css/CSSSyntaxParser.h @@ -39,8 +39,7 @@ struct CSSSimpleBlock { * Describes a valid return type for a CSSSyntaxParser visitor */ template -concept CSSSyntaxVisitorReturn = - std::is_default_constructible_v && std::equality_comparable; +concept CSSSyntaxVisitorReturn = std::is_default_constructible_v && std::equality_comparable; /** * A CSSFunctionVisitor is called to start parsing a function component value. @@ -49,8 +48,8 @@ concept CSSSyntaxVisitorReturn = * of the function block. */ template -concept CSSFunctionVisitor = CSSSyntaxVisitorReturn && - requires(T visitor, CSSFunctionBlock func, CSSSyntaxParser& blockParser) { +concept CSSFunctionVisitor = + CSSSyntaxVisitorReturn && requires(T visitor, CSSFunctionBlock func, CSSSyntaxParser &blockParser) { { visitor(func, blockParser) } -> std::convertible_to; }; @@ -59,10 +58,9 @@ concept CSSFunctionVisitor = CSSSyntaxVisitorReturn && * component value. */ template -concept CSSPreservedTokenVisitor = CSSSyntaxVisitorReturn && - requires(T visitor, CSSPreservedToken token) { - { visitor(token) } -> std::convertible_to; - }; +concept CSSPreservedTokenVisitor = CSSSyntaxVisitorReturn && requires(T visitor, CSSPreservedToken token) { + { visitor(token) } -> std::convertible_to; +}; /** * A CSSSimpleBlockVisitor is called after parsing a simple block component @@ -70,8 +68,8 @@ concept CSSPreservedTokenVisitor = CSSSyntaxVisitorReturn && * of the block. */ template -concept CSSSimpleBlockVisitor = CSSSyntaxVisitorReturn && - requires(T visitor, CSSSimpleBlock block, CSSSyntaxParser& blockParser) { +concept CSSSimpleBlockVisitor = + CSSSyntaxVisitorReturn && requires(T visitor, CSSSimpleBlock block, CSSSyntaxParser &blockParser) { { visitor(block, blockParser) } -> std::convertible_to; }; @@ -80,16 +78,15 @@ concept CSSSimpleBlockVisitor = CSSSyntaxVisitorReturn && */ template concept CSSComponentValueVisitor = CSSSyntaxVisitorReturn && - (CSSFunctionVisitor || CSSPreservedTokenVisitor || - CSSSimpleBlockVisitor); + (CSSFunctionVisitor || CSSPreservedTokenVisitor || CSSSimpleBlockVisitor); /** * Represents a variadic set of CSSComponentValueVisitor with no more than one * of a specific type of visitor. */ template -concept CSSUniqueComponentValueVisitors = CSSSyntaxVisitorReturn && - (CSSComponentValueVisitor && ...) && +concept CSSUniqueComponentValueVisitors = + CSSSyntaxVisitorReturn && (CSSComponentValueVisitor && ...) && ((CSSFunctionVisitor ? 1 : 0) + ... + 0) <= 1 && ((CSSPreservedTokenVisitor ? 1 : 0) + ... + 0) <= 1 && ((CSSSimpleBlockVisitor ? 1 : 0) + ... + 0) <= 1; @@ -114,9 +111,7 @@ enum class CSSDelimiter { * https://www.w3.org/TR/css-syntax-3/#component-value */ class CSSSyntaxParser { - template < - CSSSyntaxVisitorReturn ReturnT, - CSSComponentValueVisitor... VisitorsT> + template ... VisitorsT> friend struct CSSComponentValueVisitorDispatcher; public: @@ -124,14 +119,13 @@ class CSSSyntaxParser { * Construct the parser over the given string_view, which must stay alive for * the duration of the CSSSyntaxParser. */ - explicit constexpr CSSSyntaxParser(std::string_view css) - : tokenizer_{css}, currentToken_(tokenizer_.next()) {} + explicit constexpr CSSSyntaxParser(std::string_view css) : tokenizer_{css}, currentToken_(tokenizer_.next()) {} - constexpr CSSSyntaxParser(const CSSSyntaxParser&) = default; - constexpr CSSSyntaxParser(CSSSyntaxParser&&) = default; + constexpr CSSSyntaxParser(const CSSSyntaxParser &) = default; + constexpr CSSSyntaxParser(CSSSyntaxParser &&) = default; - constexpr CSSSyntaxParser& operator=(const CSSSyntaxParser&) = default; - constexpr CSSSyntaxParser& operator=(CSSSyntaxParser&&) = default; + constexpr CSSSyntaxParser &operator=(const CSSSyntaxParser &) = default; + constexpr CSSSyntaxParser &operator=(CSSSyntaxParser &&) = default; /** * Directly consume the next component value. The component value is provided @@ -160,25 +154,26 @@ class CSSSyntaxParser { template constexpr ReturnT consumeComponentValue( CSSDelimiter delimiter, - const CSSComponentValueVisitor auto&... visitors) + const CSSComponentValueVisitor auto &...visitors) requires(CSSUniqueComponentValueVisitors); template - constexpr ReturnT consumeComponentValue( - const CSSComponentValueVisitor auto&... visitors) + constexpr ReturnT consumeComponentValue(const CSSComponentValueVisitor auto &...visitors) requires(CSSUniqueComponentValueVisitors); /** * The parser is considered finished when there are no more remaining tokens * to be processed */ - constexpr bool isFinished() const { + constexpr bool isFinished() const + { return currentToken_.type() == CSSTokenType::EndOfFile; } /** * Consume any whitespace tokens. */ - constexpr void consumeWhitespace() { + constexpr void consumeWhitespace() + { if (currentToken_.type() == CSSTokenType::WhiteSpace) { currentToken_ = tokenizer_.next(); } @@ -187,7 +182,8 @@ class CSSSyntaxParser { /** * Consume a delimiter, returning false if a required delimiter is not found. */ - constexpr bool consumeDelimiter(CSSDelimiter delimiter) { + constexpr bool consumeDelimiter(CSSDelimiter delimiter) + { if (delimiter == CSSDelimiter::None) { return true; } @@ -215,16 +211,14 @@ class CSSSyntaxParser { } return hasWhiteSpace; case CSSDelimiter::Solidus: - if (peek().type() == CSSTokenType::Delim && - peek().stringValue() == "/") { + if (peek().type() == CSSTokenType::Delim && peek().stringValue() == "/") { consumeToken(); consumeWhitespace(); return true; } return false; case CSSDelimiter::SolidusOrWhitespace: - if (peek().type() == CSSTokenType::Delim && - peek().stringValue() == "/") { + if (peek().type() == CSSTokenType::Delim && peek().stringValue() == "/") { consumeToken(); consumeWhitespace(); return true; @@ -238,22 +232,25 @@ class CSSSyntaxParser { } private: - constexpr CSSSyntaxParser(CSSSyntaxParser& parser, CSSTokenType terminator) - : tokenizer_{parser.tokenizer_}, - currentToken_{parser.currentToken_}, - terminator_{terminator} {} + constexpr CSSSyntaxParser(CSSSyntaxParser &parser, CSSTokenType terminator) + : tokenizer_{parser.tokenizer_}, currentToken_{parser.currentToken_}, terminator_{terminator} + { + } - constexpr const CSSToken& peek() const { + constexpr const CSSToken &peek() const + { return currentToken_; } - constexpr CSSToken consumeToken() { + constexpr CSSToken consumeToken() + { auto prevToken = currentToken_; currentToken_ = tokenizer_.next(); return prevToken; } - constexpr void advanceToBlockParser(CSSSyntaxParser& blockParser) { + constexpr void advanceToBlockParser(CSSSyntaxParser &blockParser) + { currentToken_ = blockParser.currentToken_; tokenizer_ = blockParser.tokenizer_; } @@ -263,15 +260,12 @@ class CSSSyntaxParser { CSSTokenType terminator_{CSSTokenType::EndOfFile}; }; -template < - CSSSyntaxVisitorReturn ReturnT, - CSSComponentValueVisitor... VisitorsT> +template ... VisitorsT> struct CSSComponentValueVisitorDispatcher { - CSSSyntaxParser& parser; + CSSSyntaxParser &parser; - constexpr ReturnT consumeComponentValue( - CSSDelimiter delimiter, - const VisitorsT&... visitors) { + constexpr ReturnT consumeComponentValue(CSSDelimiter delimiter, const VisitorsT &...visitors) + { auto originalParser = parser; if (!parser.consumeDelimiter(delimiter)) { parser = originalParser; @@ -290,20 +284,17 @@ struct CSSComponentValueVisitorDispatcher { } break; case CSSTokenType::OpenParen: - if (auto ret = - visitSimpleBlock(CSSTokenType::CloseParen, visitors...)) { + if (auto ret = visitSimpleBlock(CSSTokenType::CloseParen, visitors...)) { return *ret; } break; case CSSTokenType::OpenSquare: - if (auto ret = - visitSimpleBlock(CSSTokenType::CloseSquare, visitors...)) { + if (auto ret = visitSimpleBlock(CSSTokenType::CloseSquare, visitors...)) { return *ret; } break; case CSSTokenType::OpenCurly: - if (auto ret = - visitSimpleBlock(CSSTokenType::CloseCurly, visitors...)) { + if (auto ret = visitSimpleBlock(CSSTokenType::CloseCurly, visitors...)) { return *ret; } break; @@ -319,8 +310,9 @@ struct CSSComponentValueVisitorDispatcher { } constexpr std::optional visitFunction( - const CSSComponentValueVisitor auto& visitor, - const CSSComponentValueVisitor auto&... rest) { + const CSSComponentValueVisitor auto &visitor, + const CSSComponentValueVisitor auto &...rest) + { if constexpr (CSSFunctionVisitor) { auto name = parser.consumeToken().stringValue(); @@ -330,13 +322,11 @@ struct CSSComponentValueVisitorDispatcher { // whitespace. https://www.w3.org/TR/css-values-3/#functional-notations parser.consumeWhitespace(); - auto blockParser = - CSSSyntaxParser{parser, CSSTokenType::CloseParen /*terminator*/}; + auto blockParser = CSSSyntaxParser{parser, CSSTokenType::CloseParen /*terminator*/}; auto functionValue = visitor({name}, blockParser); parser.advanceToBlockParser(blockParser); parser.consumeWhitespace(); - if (parser.peek().type() == CSSTokenType::CloseParen && - functionValue != ReturnT{}) { + if (parser.peek().type() == CSSTokenType::CloseParen && functionValue != ReturnT{}) { parser.consumeToken(); return functionValue; } @@ -347,14 +337,16 @@ struct CSSComponentValueVisitorDispatcher { return visitFunction(rest...); } - constexpr std::optional visitFunction() { + constexpr std::optional visitFunction() + { return {}; } constexpr std::optional visitSimpleBlock( CSSTokenType endToken, - const CSSComponentValueVisitor auto& visitor, - const CSSComponentValueVisitor auto&... rest) { + const CSSComponentValueVisitor auto &visitor, + const CSSComponentValueVisitor auto &...rest) + { if constexpr (CSSSimpleBlockVisitor) { auto openBracketType = parser.consumeToken().type(); parser.consumeWhitespace(); @@ -372,13 +364,15 @@ struct CSSComponentValueVisitorDispatcher { return visitSimpleBlock(endToken, rest...); } - constexpr std::optional visitSimpleBlock(CSSTokenType endToken) { + constexpr std::optional visitSimpleBlock(CSSTokenType endToken) + { return {}; } constexpr std::optional visitPreservedToken( - const CSSComponentValueVisitor auto& visitor, - const CSSComponentValueVisitor auto&... rest) { + const CSSComponentValueVisitor auto &visitor, + const CSSComponentValueVisitor auto &...rest) + { if constexpr (CSSPreservedTokenVisitor) { auto ret = visitor(parser.consumeToken()); if (ret != ReturnT{}) { @@ -388,7 +382,8 @@ struct CSSComponentValueVisitorDispatcher { return visitPreservedToken(rest...); } - constexpr std::optional visitPreservedToken() { + constexpr std::optional visitPreservedToken() + { return {}; } }; @@ -396,17 +391,15 @@ struct CSSComponentValueVisitorDispatcher { template constexpr ReturnT CSSSyntaxParser::consumeComponentValue( CSSDelimiter delimiter, - const CSSComponentValueVisitor auto&... visitors) + const CSSComponentValueVisitor auto &...visitors) requires(CSSUniqueComponentValueVisitors) { - return CSSComponentValueVisitorDispatcher{ - *this} - .consumeComponentValue(delimiter, visitors...); + return CSSComponentValueVisitorDispatcher{*this}.consumeComponentValue( + delimiter, visitors...); } template -constexpr ReturnT CSSSyntaxParser::consumeComponentValue( - const CSSComponentValueVisitor auto&... visitors) +constexpr ReturnT CSSSyntaxParser::consumeComponentValue(const CSSComponentValueVisitor auto &...visitors) requires(CSSUniqueComponentValueVisitors) { return consumeComponentValue(CSSDelimiter::None, visitors...); diff --git a/packages/react-native/ReactCommon/react/renderer/css/CSSToken.h b/packages/react-native/ReactCommon/react/renderer/css/CSSToken.h index e7e363365dd..4194ea17992 100644 --- a/packages/react-native/ReactCommon/react/renderer/css/CSSToken.h +++ b/packages/react-native/ReactCommon/react/renderer/css/CSSToken.h @@ -44,35 +44,39 @@ enum class CSSTokenType { class CSSToken { public: explicit constexpr CSSToken(CSSTokenType type) : type_(type) {} - constexpr CSSToken(CSSTokenType type, std::string_view value) - : type_{type}, stringValue_{value} {} - constexpr CSSToken(CSSTokenType type, float value) - : type_{type}, numericValue_{value} {} + constexpr CSSToken(CSSTokenType type, std::string_view value) : type_{type}, stringValue_{value} {} + constexpr CSSToken(CSSTokenType type, float value) : type_{type}, numericValue_{value} {} constexpr CSSToken(CSSTokenType type, float value, std::string_view unit) - : type_{type}, numericValue_{value}, unit_{unit} {} + : type_{type}, numericValue_{value}, unit_{unit} + { + } - constexpr CSSToken(const CSSToken& other) = default; - constexpr CSSToken(CSSToken&& other) = default; - constexpr CSSToken& operator=(const CSSToken& other) = default; - constexpr CSSToken& operator=(CSSToken&& other) = default; + constexpr CSSToken(const CSSToken &other) = default; + constexpr CSSToken(CSSToken &&other) = default; + constexpr CSSToken &operator=(const CSSToken &other) = default; + constexpr CSSToken &operator=(CSSToken &&other) = default; - constexpr CSSTokenType type() const { + constexpr CSSTokenType type() const + { return type_; } - constexpr std::string_view stringValue() const { + constexpr std::string_view stringValue() const + { return stringValue_; } - constexpr float numericValue() const { + constexpr float numericValue() const + { return numericValue_; } - constexpr std::string_view unit() const { + constexpr std::string_view unit() const + { return unit_; } - constexpr bool operator==(const CSSToken& other) const = default; + constexpr bool operator==(const CSSToken &other) const = default; private: CSSTokenType type_; diff --git a/packages/react-native/ReactCommon/react/renderer/css/CSSTokenizer.h b/packages/react-native/ReactCommon/react/renderer/css/CSSTokenizer.h index b6b5e581d95..6ce70a7b54f 100644 --- a/packages/react-native/ReactCommon/react/renderer/css/CSSTokenizer.h +++ b/packages/react-native/ReactCommon/react/renderer/css/CSSTokenizer.h @@ -24,14 +24,14 @@ namespace facebook::react { */ class CSSTokenizer { public: - explicit constexpr CSSTokenizer(std::string_view characters) - : remainingCharacters_{characters} {} + explicit constexpr CSSTokenizer(std::string_view characters) : remainingCharacters_{characters} {} /** * Returns the next token according to the algorithm described in * https://www.w3.org/TR/css-syntax-3/#consume-token */ - constexpr CSSToken next() { + constexpr CSSToken next() + { char nextChar = peek(); if (isWhitespace(nextChar)) { @@ -85,28 +85,32 @@ class CSSTokenizer { } private: - constexpr char peek(size_t i = 0) const { + constexpr char peek(size_t i = 0) const + { auto index = position_ + i; - return index >= remainingCharacters_.size() ? '\0' - : remainingCharacters_[index]; + return index >= remainingCharacters_.size() ? '\0' : remainingCharacters_[index]; } - constexpr void advance() { + constexpr void advance() + { position_ += 1; } - constexpr CSSToken consumeDelim() { + constexpr CSSToken consumeDelim() + { advance(); return {CSSTokenType::Delim, consumeRunningValue()}; } - constexpr CSSToken consumeCharacter(CSSTokenType tokenType) { + constexpr CSSToken consumeCharacter(CSSTokenType tokenType) + { advance(); consumeRunningValue(); return CSSToken{tokenType}; } - constexpr CSSToken consumeWhitespace() { + constexpr CSSToken consumeWhitespace() + { while (isWhitespace(peek())) { advance(); } @@ -115,7 +119,8 @@ class CSSTokenizer { return CSSToken{CSSTokenType::WhiteSpace}; } - constexpr bool wouldStartNumber() const { + constexpr bool wouldStartNumber() const + { // https://www.w3.org/TR/css-syntax-3/#starts-with-a-number if (peek() == '+' || peek() == '-') { if (isDigit(peek(1))) { @@ -133,17 +138,16 @@ class CSSTokenizer { return false; } - constexpr CSSToken consumeNumber() { + constexpr CSSToken consumeNumber() + { // https://www.w3.org/TR/css-syntax-3/#consume-number // https://www.w3.org/TR/css-syntax-3/#convert-a-string-to-a-number - auto* b = remainingCharacters_.data(); - auto* e = b + remainingCharacters_.size(); + auto *b = remainingCharacters_.data(); + auto *e = b + remainingCharacters_.size(); float value; - fast_float::parse_options options{ - fast_float::chars_format::general | - fast_float::chars_format::allow_leading_plus}; + fast_float::parse_options options{fast_float::chars_format::general | fast_float::chars_format::allow_leading_plus}; auto [ptr, ec] = fast_float::from_chars_advanced(b, e, value, options); // Do we need to handle any other errors? @@ -155,16 +159,14 @@ class CSSTokenizer { return {CSSTokenType::Number, value}; } - constexpr CSSToken consumeNumeric() { + constexpr CSSToken consumeNumeric() + { // https://www.w3.org/TR/css-syntax-3/#consume-numeric-token auto numberToken = consumeNumber(); if (isIdent(peek())) { auto ident = consumeIdentSequence(); - return { - CSSTokenType::Dimension, - numberToken.numericValue(), - ident.stringValue()}; + return {CSSTokenType::Dimension, numberToken.numericValue(), ident.stringValue()}; } else if (peek() == '%') { advance(); consumeRunningValue(); @@ -174,7 +176,8 @@ class CSSTokenizer { } } - constexpr CSSToken consumeIdentlikeToken() { + constexpr CSSToken consumeIdentlikeToken() + { // https://www.w3.org/TR/css-syntax-3/#consume-ident-like-token auto ident = consumeIdentSequence(); if (peek() == '(') { @@ -186,7 +189,8 @@ class CSSTokenizer { return ident; } - constexpr CSSToken consumeIdentSequence() { + constexpr CSSToken consumeIdentSequence() + { // https://www.w3.org/TR/css-syntax-3/#consume-an-ident-sequence while (isIdent(peek())) { advance(); @@ -195,7 +199,8 @@ class CSSTokenizer { return {CSSTokenType::Ident, consumeRunningValue()}; } - constexpr CSSToken consumeHash() { + constexpr CSSToken consumeHash() + { // https://www.w3.org/TR/css-syntax-3/#consume-token (U+0023 NUMBER SIGN) advance(); consumeRunningValue(); @@ -203,32 +208,36 @@ class CSSTokenizer { return {CSSTokenType::Hash, consumeIdentSequence().stringValue()}; } - constexpr std::string_view consumeRunningValue() { + constexpr std::string_view consumeRunningValue() + { auto next = remainingCharacters_.substr(0, position_); remainingCharacters_ = remainingCharacters_.substr(next.size()); position_ = 0; return next; } - static constexpr bool isDigit(char c) { + static constexpr bool isDigit(char c) + { // https://www.w3.org/TR/css-syntax-3/#digit return c >= '0' && c <= '9'; } - static constexpr bool isIdentStart(char c) { + static constexpr bool isIdentStart(char c) + { // https://www.w3.org/TR/css-syntax-3/#ident-start-code-point - return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || - static_cast(c) > 0x80; + return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || static_cast(c) > 0x80; } - static constexpr bool isIdent(char c) { + static constexpr bool isIdent(char c) + { { // https://www.w3.org/TR/css-syntax-3/#ident-code-point return isIdentStart(c) || isDigit(c) || c == '-'; } } - static constexpr bool isWhitespace(char c) { + static constexpr bool isWhitespace(char c) + { // https://www.w3.org/TR/css-syntax-3/#whitespace return c == ' ' || c == '\t' || c == '\r' || c == '\n'; } diff --git a/packages/react-native/ReactCommon/react/renderer/css/CSSTransform.h b/packages/react-native/ReactCommon/react/renderer/css/CSSTransform.h index b9829084ae3..2f66f891410 100644 --- a/packages/react-native/ReactCommon/react/renderer/css/CSSTransform.h +++ b/packages/react-native/ReactCommon/react/renderer/css/CSSTransform.h @@ -26,17 +26,12 @@ namespace facebook::react { namespace detail { -template < - typename DataT, - TemplateStringLiteral Name, - CSSDataType... AllowedComponentsT> - requires(std::is_same_v< - decltype(DataT::value), - std::variant>) +template + requires(std::is_same_v>) struct CSSVariantComponentTransformParser { - static constexpr auto consumeFunctionBlock( - const CSSFunctionBlock& func, - CSSSyntaxParser& parser) -> std::optional { + static constexpr auto consumeFunctionBlock(const CSSFunctionBlock &func, CSSSyntaxParser &parser) + -> std::optional + { if (!iequals(func.name, Name)) { return {}; } @@ -44,10 +39,8 @@ struct CSSVariantComponentTransformParser { auto val = parseNextCSSValue(parser); return std::visit( - [&](auto&& v) -> std::optional { - if constexpr (std::is_same_v< - std::remove_cvref_t, - std::monostate>) { + [&](auto &&v) -> std::optional { + if constexpr (std::is_same_v, std::monostate>) { return {}; } else { return DataT{.value = std::forward(v)}; @@ -60,9 +53,9 @@ struct CSSVariantComponentTransformParser { template requires(std::is_same_v) struct CSSNumberPercentTransformParser { - static constexpr auto consumeFunctionBlock( - const CSSFunctionBlock& func, - CSSSyntaxParser& parser) -> std::optional { + static constexpr auto consumeFunctionBlock(const CSSFunctionBlock &func, CSSSyntaxParser &parser) + -> std::optional + { if (!iequals(func.name, Name)) { return {}; } @@ -73,18 +66,17 @@ struct CSSNumberPercentTransformParser { } return DataT{ - .value = std::holds_alternative(val) - ? std::get(val).value - : std::get(val).value / 100.0f}; + .value = std::holds_alternative(val) ? std::get(val).value + : std::get(val).value / 100.0f}; } }; template requires(std::is_same_v) struct CSSAngleTransformParser { - static constexpr auto consumeFunctionBlock( - const CSSFunctionBlock& func, - CSSSyntaxParser& parser) -> std::optional { + static constexpr auto consumeFunctionBlock(const CSSFunctionBlock &func, CSSSyntaxParser &parser) + -> std::optional + { if (!iequals(func.name, Name)) { return {}; } @@ -95,9 +87,7 @@ struct CSSAngleTransformParser { } return DataT{ - .degrees = std::holds_alternative(value) - ? std::get(value).degrees - : 0.0f, + .degrees = std::holds_alternative(value) ? std::get(value).degrees : 0.0f, }; } }; @@ -110,22 +100,21 @@ struct CSSAngleTransformParser { struct CSSMatrix { std::array values{}; - constexpr bool operator==(const CSSMatrix& rhs) const = default; + constexpr bool operator==(const CSSMatrix &rhs) const = default; }; template <> struct CSSDataTypeParser { - static constexpr auto consumeFunctionBlock( - const CSSFunctionBlock& func, - CSSSyntaxParser& parser) -> std::optional { + static constexpr auto consumeFunctionBlock(const CSSFunctionBlock &func, CSSSyntaxParser &parser) + -> std::optional + { if (!iequals(func.name, "matrix")) { return {}; } CSSMatrix matrix{}; for (int i = 0; i < 6; i++) { - auto value = parseNextCSSValue( - parser, i == 0 ? CSSDelimiter::None : CSSDelimiter::Comma); + auto value = parseNextCSSValue(parser, i == 0 ? CSSDelimiter::None : CSSDelimiter::Comma); if (std::holds_alternative(value)) { return {}; } @@ -145,14 +134,14 @@ struct CSSTranslate { std::variant x{}; std::variant y{}; - constexpr bool operator==(const CSSTranslate& rhs) const = default; + constexpr bool operator==(const CSSTranslate &rhs) const = default; }; template <> struct CSSDataTypeParser { - static constexpr auto consumeFunctionBlock( - const CSSFunctionBlock& func, - CSSSyntaxParser& parser) -> std::optional { + static constexpr auto consumeFunctionBlock(const CSSFunctionBlock &func, CSSSyntaxParser &parser) + -> std::optional + { if (!iequals(func.name, "translate")) { return {}; } @@ -162,8 +151,7 @@ struct CSSDataTypeParser { return {}; } - auto y = - parseNextCSSValue(parser, CSSDelimiter::Comma); + auto y = parseNextCSSValue(parser, CSSDelimiter::Comma); CSSTranslate translate{}; translate.x = std::holds_alternative(x) @@ -190,14 +178,14 @@ struct CSSTranslate3D { std::variant y{}; CSSLength z{}; - constexpr bool operator==(const CSSTranslate3D& rhs) const = default; + constexpr bool operator==(const CSSTranslate3D &rhs) const = default; }; template <> struct CSSDataTypeParser { - static constexpr auto consumeFunctionBlock( - const CSSFunctionBlock& func, - CSSSyntaxParser& parser) -> std::optional { + static constexpr auto consumeFunctionBlock(const CSSFunctionBlock &func, CSSSyntaxParser &parser) + -> std::optional + { if (!iequals(func.name, "translate3d")) { return {}; } @@ -207,8 +195,7 @@ struct CSSDataTypeParser { return {}; } - auto y = - parseNextCSSValue(parser, CSSDelimiter::Comma); + auto y = parseNextCSSValue(parser, CSSDelimiter::Comma); if (std::holds_alternative(y)) { return {}; } @@ -219,14 +206,10 @@ struct CSSDataTypeParser { } return CSSTranslate3D{ - .x = std::holds_alternative(x) - ? std::variant{std::get(x)} - : std::variant{std::get( - x)}, - .y = std::holds_alternative(y) - ? std::variant{std::get(y)} - : std::variant{std::get( - y)}, + .x = std::holds_alternative(x) ? std::variant{std::get(x)} + : std::variant{std::get(x)}, + .y = std::holds_alternative(y) ? std::variant{std::get(y)} + : std::variant{std::get(y)}, .z = std::get(z), }; } @@ -240,16 +223,12 @@ static_assert(CSSDataType); struct CSSTranslateX { std::variant value{}; - constexpr bool operator==(const CSSTranslateX& rhs) const = default; + constexpr bool operator==(const CSSTranslateX &rhs) const = default; }; template <> struct CSSDataTypeParser - : public detail::CSSVariantComponentTransformParser< - CSSTranslateX, - "translateX", - CSSLength, - CSSPercentage> {}; + : public detail::CSSVariantComponentTransformParser {}; static_assert(CSSDataType); @@ -259,16 +238,12 @@ static_assert(CSSDataType); struct CSSTranslateY { std::variant value{}; - constexpr bool operator==(const CSSTranslateY& rhs) const = default; + constexpr bool operator==(const CSSTranslateY &rhs) const = default; }; template <> struct CSSDataTypeParser - : public detail::CSSVariantComponentTransformParser< - CSSTranslateY, - "translateY", - CSSLength, - CSSPercentage> {}; + : public detail::CSSVariantComponentTransformParser {}; static_assert(CSSDataType); @@ -279,14 +254,14 @@ struct CSSScale { float x{}; float y{}; - constexpr bool operator==(const CSSScale& rhs) const = default; + constexpr bool operator==(const CSSScale &rhs) const = default; }; template <> struct CSSDataTypeParser { - static constexpr auto consumeFunctionBlock( - const CSSFunctionBlock& func, - CSSSyntaxParser& parser) -> std::optional { + static constexpr auto consumeFunctionBlock(const CSSFunctionBlock &func, CSSSyntaxParser &parser) + -> std::optional + { if (!iequals(func.name, "scale")) { return {}; } @@ -298,17 +273,14 @@ struct CSSDataTypeParser { return {}; } - auto y = parseNextCSSValue( - parser, CSSDelimiter::Comma); + auto y = parseNextCSSValue(parser, CSSDelimiter::Comma); - auto normX = std::holds_alternative(x) - ? std::get(x).value - : std::get(x).value / 100.0f; + auto normX = + std::holds_alternative(x) ? std::get(x).value : std::get(x).value / 100.0f; auto normY = std::holds_alternative(y) ? normX - : std::holds_alternative(y) - ? std::get(y).value - : std::get(y).value / 100.0f; + : std::holds_alternative(y) ? std::get(y).value + : std::get(y).value / 100.0f; return CSSScale{.x = normX, .y = normY}; } @@ -322,12 +294,11 @@ static_assert(CSSDataType); struct CSSScaleX { float value{}; - constexpr bool operator==(const CSSScaleX& rhs) const = default; + constexpr bool operator==(const CSSScaleX &rhs) const = default; }; template <> -struct CSSDataTypeParser - : public detail::CSSNumberPercentTransformParser {}; +struct CSSDataTypeParser : public detail::CSSNumberPercentTransformParser {}; static_assert(CSSDataType); @@ -337,12 +308,11 @@ static_assert(CSSDataType); struct CSSScaleY { float value{}; - constexpr bool operator==(const CSSScaleY& rhs) const = default; + constexpr bool operator==(const CSSScaleY &rhs) const = default; }; template <> -struct CSSDataTypeParser - : public detail::CSSNumberPercentTransformParser {}; +struct CSSDataTypeParser : public detail::CSSNumberPercentTransformParser {}; static_assert(CSSDataType); @@ -352,12 +322,11 @@ static_assert(CSSDataType); struct CSSRotate { float degrees{}; - constexpr bool operator==(const CSSRotate& rhs) const = default; + constexpr bool operator==(const CSSRotate &rhs) const = default; }; template <> -struct CSSDataTypeParser - : public detail::CSSAngleTransformParser {}; +struct CSSDataTypeParser : public detail::CSSAngleTransformParser {}; static_assert(CSSDataType); @@ -367,12 +336,11 @@ static_assert(CSSDataType); struct CSSRotateX { float degrees{}; - constexpr bool operator==(const CSSRotateX& rhs) const = default; + constexpr bool operator==(const CSSRotateX &rhs) const = default; }; template <> -struct CSSDataTypeParser - : public detail::CSSAngleTransformParser {}; +struct CSSDataTypeParser : public detail::CSSAngleTransformParser {}; static_assert(CSSDataType); @@ -382,12 +350,11 @@ static_assert(CSSDataType); struct CSSRotateY { float degrees{}; - constexpr bool operator==(const CSSRotateY& rhs) const = default; + constexpr bool operator==(const CSSRotateY &rhs) const = default; }; template <> -struct CSSDataTypeParser - : public detail::CSSAngleTransformParser {}; +struct CSSDataTypeParser : public detail::CSSAngleTransformParser {}; static_assert(CSSDataType); @@ -397,12 +364,11 @@ static_assert(CSSDataType); struct CSSRotateZ { float degrees{}; - constexpr bool operator==(const CSSRotateZ& rhs) const = default; + constexpr bool operator==(const CSSRotateZ &rhs) const = default; }; template <> -struct CSSDataTypeParser - : public detail::CSSAngleTransformParser {}; +struct CSSDataTypeParser : public detail::CSSAngleTransformParser {}; static_assert(CSSDataType); @@ -412,12 +378,11 @@ static_assert(CSSDataType); struct CSSSkewX { float degrees{}; - constexpr bool operator==(const CSSSkewX& rhs) const = default; + constexpr bool operator==(const CSSSkewX &rhs) const = default; }; template <> -struct CSSDataTypeParser - : public detail::CSSAngleTransformParser {}; +struct CSSDataTypeParser : public detail::CSSAngleTransformParser {}; static_assert(CSSDataType); @@ -427,12 +392,11 @@ static_assert(CSSDataType); struct CSSSkewY { float degrees{}; - constexpr bool operator==(const CSSSkewY& rhs) const = default; + constexpr bool operator==(const CSSSkewY &rhs) const = default; }; template <> -struct CSSDataTypeParser - : public detail::CSSAngleTransformParser {}; +struct CSSDataTypeParser : public detail::CSSAngleTransformParser {}; static_assert(CSSDataType); @@ -442,21 +406,20 @@ static_assert(CSSDataType); struct CSSPerspective { CSSLength length{}; - constexpr bool operator==(const CSSPerspective& rhs) const = default; + constexpr bool operator==(const CSSPerspective &rhs) const = default; }; template <> struct CSSDataTypeParser { - static constexpr auto consumeFunctionBlock( - const CSSFunctionBlock& func, - CSSSyntaxParser& parser) -> std::optional { + static constexpr auto consumeFunctionBlock(const CSSFunctionBlock &func, CSSSyntaxParser &parser) + -> std::optional + { if (!iequals(func.name, "perspective")) { return {}; } auto value = parseNextCSSValue(parser); - if (std::holds_alternative(value) || - std::get(value).value < 0) { + if (std::holds_alternative(value) || std::get(value).value < 0) { return {}; } diff --git a/packages/react-native/ReactCommon/react/renderer/css/CSSTransformOrigin.h b/packages/react-native/ReactCommon/react/renderer/css/CSSTransformOrigin.h index a60c89a4081..ee5d06792dc 100644 --- a/packages/react-native/ReactCommon/react/renderer/css/CSSTransformOrigin.h +++ b/packages/react-native/ReactCommon/react/renderer/css/CSSTransformOrigin.h @@ -40,13 +40,13 @@ struct CSSTransformOrigin { std::variant y{}; CSSLength z{}; - constexpr bool operator==(const CSSTransformOrigin& rhs) const = default; + constexpr bool operator==(const CSSTransformOrigin &rhs) const = default; }; template <> struct CSSDataTypeParser { - static constexpr auto consume(CSSSyntaxParser& parser) - -> std::optional { + static constexpr auto consume(CSSSyntaxParser &parser) -> std::optional + { // [ left | center | right | top | bottom | ] // | // [ left | center | right | ] @@ -54,28 +54,22 @@ struct CSSDataTypeParser { // | // [ [ center | left | right ] && [ center | top | bottom ] ] ? - auto firstValue = - parseNextCSSValue( - parser); + auto firstValue = parseNextCSSValue(parser); if (std::holds_alternative(firstValue)) { return {}; } auto secondValue = - parseNextCSSValue( - parser, CSSDelimiter::Whitespace); + parseNextCSSValue(parser, CSSDelimiter::Whitespace); if (std::holds_alternative(secondValue)) { return singleValue(firstValue); } - auto thirdValue = - parseNextCSSValue(parser, CSSDelimiter::Whitespace); + auto thirdValue = parseNextCSSValue(parser, CSSDelimiter::Whitespace); - if (std::holds_alternative(firstValue) || - std::holds_alternative(firstValue) || - std::holds_alternative(secondValue) || - std::holds_alternative(secondValue)) { + if (std::holds_alternative(firstValue) || std::holds_alternative(firstValue) || + std::holds_alternative(secondValue) || std::holds_alternative(secondValue)) { return xyLengthPercentageValue(firstValue, secondValue, thirdValue); } @@ -92,11 +86,8 @@ struct CSSDataTypeParser { private: static constexpr CSSTransformOrigin singleValue( - const std::variant< - std::monostate, - CSSLength, - CSSPercentage, - CSSTransformOriginKeyword>& value) { + const std::variant &value) + { CSSTransformOrigin result{}; if (std::holds_alternative(value)) { @@ -107,13 +98,11 @@ struct CSSDataTypeParser { result.y = keywordPercentage(CSSTransformOriginKeyword::Center); } else if (std::holds_alternative(value)) { if (isHorizontalKeyword(std::get(value))) { - result.x = - keywordPercentage(std::get(value)); + result.x = keywordPercentage(std::get(value)); result.y = keywordPercentage(CSSTransformOriginKeyword::Center); } else { result.x = keywordPercentage(CSSTransformOriginKeyword::Center); - result.y = - keywordPercentage(std::get(value)); + result.y = keywordPercentage(std::get(value)); } } @@ -121,17 +110,10 @@ struct CSSDataTypeParser { } static constexpr std::optional xyLengthPercentageValue( - const std::variant< - std::monostate, - CSSLength, - CSSPercentage, - CSSTransformOriginKeyword>& val1, - const std::variant< - std::monostate, - CSSLength, - CSSPercentage, - CSSTransformOriginKeyword>& val2, - const std::variant& val3) { + const std::variant &val1, + const std::variant &val2, + const std::variant &val3) + { CSSTransformOrigin result{}; if (std::holds_alternative(val1)) { @@ -168,42 +150,39 @@ struct CSSDataTypeParser { static constexpr std::optional xyKeywordValue( CSSTransformOriginKeyword val1, CSSTransformOriginKeyword val2, - const std::variant& val3) { + const std::variant &val3) + { if (isHorizontalKeyword(val1) && isVerticalKeyword(val2)) { return CSSTransformOrigin{ .x = keywordPercentage(val1), .y = keywordPercentage(val2), - .z = std::holds_alternative(val3) - ? std::get(val3) - : CSSLength{}}; + .z = std::holds_alternative(val3) ? std::get(val3) : CSSLength{}}; } if (isVerticalKeyword(val1) && isHorizontalKeyword(val2)) { return CSSTransformOrigin{ .x = keywordPercentage(val2), .y = keywordPercentage(val1), - .z = std::holds_alternative(val3) - ? std::get(val3) - : CSSLength{}}; + .z = std::holds_alternative(val3) ? std::get(val3) : CSSLength{}}; } return {}; } - static constexpr bool isHorizontalKeyword(CSSTransformOriginKeyword keyword) { - return keyword == CSSTransformOriginKeyword::Left || - keyword == CSSTransformOriginKeyword::Center || + static constexpr bool isHorizontalKeyword(CSSTransformOriginKeyword keyword) + { + return keyword == CSSTransformOriginKeyword::Left || keyword == CSSTransformOriginKeyword::Center || keyword == CSSTransformOriginKeyword::Right; } - static constexpr bool isVerticalKeyword(CSSTransformOriginKeyword keyword) { - return keyword == CSSTransformOriginKeyword::Top || - keyword == CSSTransformOriginKeyword::Center || + static constexpr bool isVerticalKeyword(CSSTransformOriginKeyword keyword) + { + return keyword == CSSTransformOriginKeyword::Top || keyword == CSSTransformOriginKeyword::Center || keyword == CSSTransformOriginKeyword::Bottom; } - static constexpr CSSPercentage keywordPercentage( - CSSTransformOriginKeyword keyword) { + static constexpr CSSPercentage keywordPercentage(CSSTransformOriginKeyword keyword) + { switch (keyword) { case CSSTransformOriginKeyword::Left: return CSSPercentage{0.0f}; diff --git a/packages/react-native/ReactCommon/react/renderer/css/CSSValueParser.h b/packages/react-native/ReactCommon/react/renderer/css/CSSValueParser.h index 213b433a8f6..144c04821d7 100644 --- a/packages/react-native/ReactCommon/react/renderer/css/CSSValueParser.h +++ b/packages/react-native/ReactCommon/react/renderer/css/CSSValueParser.h @@ -22,8 +22,7 @@ namespace detail { class CSSValueParser { public: - explicit constexpr CSSValueParser(CSSSyntaxParser& parser) - : parser_{parser} {} + explicit constexpr CSSValueParser(CSSSyntaxParser &parser) : parser_{parser} {} /* * Attempts to parse the characters starting at the current component value @@ -34,12 +33,11 @@ class CSSValueParser { template constexpr std::variant consumeValue( CSSDelimiter delimeter, - CSSCompoundDataType /*unused*/) { + CSSCompoundDataType /*unused*/) + { using ReturnT = std::variant; - auto consumedValue = - tryConsumeParser...>( - delimeter); + auto consumedValue = tryConsumeParser...>(delimeter); if (!std::holds_alternative(consumedValue)) { return consumedValue; @@ -47,43 +45,37 @@ class CSSValueParser { return parser_.consumeComponentValue( delimeter, - [&](const CSSPreservedToken& token) { - return tryConsumePreservedToken< - ReturnT, - CSSDataTypeParser...>(token); + [&](const CSSPreservedToken &token) { + return tryConsumePreservedToken...>(token); }, - [&](const CSSSimpleBlock& block, CSSSyntaxParser& blockParser) { - return tryConsumeSimpleBlock< - ReturnT, - CSSDataTypeParser...>(block, blockParser); + [&](const CSSSimpleBlock &block, CSSSyntaxParser &blockParser) { + return tryConsumeSimpleBlock...>(block, blockParser); }, - [&](const CSSFunctionBlock& func, CSSSyntaxParser& blockParser) { - return tryConsumeFunctionBlock< - ReturnT, - CSSDataTypeParser...>(func, blockParser); + [&](const CSSFunctionBlock &func, CSSSyntaxParser &blockParser) { + return tryConsumeFunctionBlock...>(func, blockParser); }); } - constexpr bool isFinished() const { + constexpr bool isFinished() const + { return parser_.isFinished(); } - constexpr void consumeWhitespace() { + constexpr void consumeWhitespace() + { parser_.consumeWhitespace(); } private: template - constexpr ReturnT tryConsumePreservedToken( - const CSSPreservedToken& /*token*/) { + constexpr ReturnT tryConsumePreservedToken(const CSSPreservedToken & /*token*/) + { return {}; } - template < - typename ReturnT, - CSSValidDataTypeParser ParserT, - CSSValidDataTypeParser... RestParserT> - constexpr ReturnT tryConsumePreservedToken(const CSSPreservedToken& token) { + template + constexpr ReturnT tryConsumePreservedToken(const CSSPreservedToken &token) + { if constexpr (CSSPreservedTokenSink) { if (auto ret = ParserT::consumePreservedToken(token)) { return *ret; @@ -94,19 +86,14 @@ class CSSValueParser { } template - constexpr ReturnT tryConsumeSimpleBlock( - const CSSSimpleBlock& /*token*/, - CSSSyntaxParser& /*blockParser*/) { + constexpr ReturnT tryConsumeSimpleBlock(const CSSSimpleBlock & /*token*/, CSSSyntaxParser & /*blockParser*/) + { return {}; } - template < - typename ReturnT, - CSSValidDataTypeParser ParserT, - CSSValidDataTypeParser... RestParserT> - constexpr ReturnT tryConsumeSimpleBlock( - const CSSSimpleBlock& block, - CSSSyntaxParser& blockParser) { + template + constexpr ReturnT tryConsumeSimpleBlock(const CSSSimpleBlock &block, CSSSyntaxParser &blockParser) + { if constexpr (CSSSimpleBlockSink) { auto currentParser = blockParser; if (auto ret = ParserT::consumeSimpleBlock(block, blockParser)) { @@ -119,19 +106,14 @@ class CSSValueParser { } template - constexpr ReturnT tryConsumeFunctionBlock( - const CSSFunctionBlock& /*func*/, - CSSSyntaxParser& /*blockParser*/) { + constexpr ReturnT tryConsumeFunctionBlock(const CSSFunctionBlock & /*func*/, CSSSyntaxParser & /*blockParser*/) + { return {}; } - template < - typename ReturnT, - CSSValidDataTypeParser ParserT, - CSSValidDataTypeParser... RestParserT> - constexpr ReturnT tryConsumeFunctionBlock( - const CSSFunctionBlock& func, - CSSSyntaxParser& blockParser) { + template + constexpr ReturnT tryConsumeFunctionBlock(const CSSFunctionBlock &func, CSSSyntaxParser &blockParser) + { if constexpr (CSSFunctionBlockSink) { auto currentParser = blockParser; if (auto ret = ParserT::consumeFunctionBlock(func, blockParser)) { @@ -144,15 +126,14 @@ class CSSValueParser { } template - constexpr ReturnT tryConsumeParser(CSSDelimiter /*delimeter*/) { + constexpr ReturnT tryConsumeParser(CSSDelimiter /*delimeter*/) + { return {}; } - template < - typename ReturnT, - CSSValidDataTypeParser ParserT, - CSSValidDataTypeParser... RestParserT> - constexpr ReturnT tryConsumeParser(CSSDelimiter delimeter) { + template + constexpr ReturnT tryConsumeParser(CSSDelimiter delimeter) + { if constexpr (CSSParserSink) { auto originalParser = parser_; if (parser_.consumeDelimiter(delimeter)) { @@ -166,7 +147,7 @@ class CSSValueParser { return tryConsumeParser(delimeter); } - CSSSyntaxParser& parser_; + CSSSyntaxParser &parser_; }; } // namespace detail @@ -177,16 +158,13 @@ class CSSValueParser { */ template constexpr auto parseCSSProperty(std::string_view css) - -> CSSVariantWithTypes< - CSSMergedDataTypes, - std::monostate> { + -> CSSVariantWithTypes, std::monostate> +{ CSSSyntaxParser syntaxParser(css); detail::CSSValueParser parser(syntaxParser); parser.consumeWhitespace(); - auto value = parser.consumeValue( - CSSDelimiter::None, - CSSMergedDataTypes{}); + auto value = parser.consumeValue(CSSDelimiter::None, CSSMergedDataTypes{}); parser.consumeWhitespace(); if (parser.isFinished()) { @@ -201,15 +179,11 @@ constexpr auto parseCSSProperty(std::string_view css) * current location of the syntax parser, advancing the syntax parser */ template -constexpr auto parseNextCSSValue( - CSSSyntaxParser& syntaxParser, - CSSDelimiter delimeter = CSSDelimiter::None) - -> CSSVariantWithTypes< - CSSMergedDataTypes, - std::monostate> { +constexpr auto parseNextCSSValue(CSSSyntaxParser &syntaxParser, CSSDelimiter delimeter = CSSDelimiter::None) + -> CSSVariantWithTypes, std::monostate> +{ detail::CSSValueParser valueParser(syntaxParser); - return valueParser.consumeValue( - delimeter, CSSMergedDataTypes{}); + return valueParser.consumeValue(delimeter, CSSMergedDataTypes{}); } /** @@ -217,16 +191,12 @@ constexpr auto parseNextCSSValue( * current location of the syntax parser, without advancing the syntax parser */ template -constexpr auto peekNextCSSValue( - CSSSyntaxParser& syntaxParser, - CSSDelimiter delimeter = CSSDelimiter::None) - -> CSSVariantWithTypes< - CSSMergedDataTypes, - std::monostate> { +constexpr auto peekNextCSSValue(CSSSyntaxParser &syntaxParser, CSSDelimiter delimeter = CSSDelimiter::None) + -> CSSVariantWithTypes, std::monostate> +{ auto savedParser = syntaxParser; detail::CSSValueParser valueParser(syntaxParser); - auto ret = valueParser.consumeValue( - delimeter, CSSMergedDataTypes{}); + auto ret = valueParser.consumeValue(delimeter, CSSMergedDataTypes{}); syntaxParser = savedParser; return ret; } diff --git a/packages/react-native/ReactCommon/react/renderer/css/CSSZero.h b/packages/react-native/ReactCommon/react/renderer/css/CSSZero.h index 5f0865f4dd2..8f24fcc04c8 100644 --- a/packages/react-native/ReactCommon/react/renderer/css/CSSZero.h +++ b/packages/react-native/ReactCommon/react/renderer/css/CSSZero.h @@ -21,13 +21,13 @@ namespace facebook::react { * https://www.w3.org/TR/css-values-4/#zero-value */ struct CSSZero { - constexpr bool operator==(const CSSZero& rhs) const = default; + constexpr bool operator==(const CSSZero &rhs) const = default; }; template <> struct CSSDataTypeParser { - static constexpr auto consumePreservedToken(const CSSPreservedToken& token) - -> std::optional { + static constexpr auto consumePreservedToken(const CSSPreservedToken &token) -> std::optional + { if (token.type() == CSSTokenType::Number && token.numericValue() == 0) { return CSSZero{}; } diff --git a/packages/react-native/ReactCommon/react/renderer/css/tests/CSSColorTest.cpp b/packages/react-native/ReactCommon/react/renderer/css/tests/CSSColorTest.cpp index b579f4af274..c5d30aec120 100644 --- a/packages/react-native/ReactCommon/react/renderer/css/tests/CSSColorTest.cpp +++ b/packages/react-native/ReactCommon/react/renderer/css/tests/CSSColorTest.cpp @@ -191,8 +191,9 @@ TEST(CSSColor, rgb_rgba_values) { auto rgbLegacySyntaxWithSolidusAlphaValue = parseCSSProperty("rgb(1, 4, 5 /0.5)"); - EXPECT_TRUE(std::holds_alternative( - rgbLegacySyntaxWithSolidusAlphaValue)); + EXPECT_TRUE( + std::holds_alternative( + rgbLegacySyntaxWithSolidusAlphaValue)); auto rgbaWithSolidusAlphaValue = parseCSSProperty("rgba(255 255 255 / 0.5)"); @@ -317,8 +318,9 @@ TEST(CSSColor, hsl_hsla_values) { auto rgbLegacySyntaxWithSolidusAlphaValue = parseCSSProperty("hsl(1, 4, 5 / 0.5)"); - EXPECT_TRUE(std::holds_alternative( - rgbLegacySyntaxWithSolidusAlphaValue)); + EXPECT_TRUE( + std::holds_alternative( + rgbLegacySyntaxWithSolidusAlphaValue)); auto hslaWithoutAlphaValue = parseCSSProperty("hsla(70 190% 75%)"); EXPECT_TRUE(std::holds_alternative(hslaWithoutAlphaValue)); diff --git a/packages/react-native/ReactCommon/react/renderer/css/tests/CSSFontVariantTest.cpp b/packages/react-native/ReactCommon/react/renderer/css/tests/CSSFontVariantTest.cpp index 332390df72d..de9a41c58e2 100644 --- a/packages/react-native/ReactCommon/react/renderer/css/tests/CSSFontVariantTest.cpp +++ b/packages/react-native/ReactCommon/react/renderer/css/tests/CSSFontVariantTest.cpp @@ -38,8 +38,9 @@ TEST(CSSFontVariant, multiple_variants) { auto commonLigaturesAndHistoricalForms = parseCSSProperty("common-ligatures no-contextual"); - EXPECT_TRUE(std::holds_alternative( - commonLigaturesAndHistoricalForms)); + EXPECT_TRUE( + std::holds_alternative( + commonLigaturesAndHistoricalForms)); EXPECT_EQ( std::get(commonLigaturesAndHistoricalForms).size(), 2); diff --git a/packages/react-native/ReactCommon/react/renderer/css/tests/CSSListTest.cpp b/packages/react-native/ReactCommon/react/renderer/css/tests/CSSListTest.cpp index b622dcd2821..535655371fd 100644 --- a/packages/react-native/ReactCommon/react/renderer/css/tests/CSSListTest.cpp +++ b/packages/react-native/ReactCommon/react/renderer/css/tests/CSSListTest.cpp @@ -35,8 +35,9 @@ TEST(CSSList, single_value) { auto whitespaceValue = parseCSSProperty>(" 20 "); - EXPECT_TRUE(std::holds_alternative>( - whitespaceValue)); + EXPECT_TRUE( + std::holds_alternative>( + whitespaceValue)); EXPECT_EQ( std::get>(whitespaceValue).size(), 1); EXPECT_EQ( @@ -63,8 +64,9 @@ TEST(CSSList, multiple_comma_values) { auto whitespaceValue = parseCSSProperty>(" 20 , 30 , 40 "); - EXPECT_TRUE(std::holds_alternative>( - whitespaceValue)); + EXPECT_TRUE( + std::holds_alternative>( + whitespaceValue)); EXPECT_EQ( std::get>(whitespaceValue).size(), 3); EXPECT_EQ( @@ -78,8 +80,9 @@ TEST(CSSList, multiple_comma_values) { TEST(CSSList, multiple_space_values) { auto simpleValue = parseCSSProperty>("20 30 40"); - EXPECT_TRUE(std::holds_alternative>( - simpleValue)); + EXPECT_TRUE( + std::holds_alternative>( + simpleValue)); EXPECT_EQ( std::get>(simpleValue).size(), 3); EXPECT_EQ( @@ -94,8 +97,9 @@ TEST(CSSList, multiple_space_values) { auto whitespaceValue = parseCSSProperty>(" 20 \n 30 40 "); - EXPECT_TRUE(std::holds_alternative>( - whitespaceValue)); + EXPECT_TRUE( + std::holds_alternative>( + whitespaceValue)); EXPECT_EQ( std::get>(whitespaceValue).size(), 3); diff --git a/packages/react-native/ReactCommon/react/renderer/css/tests/CSSSyntaxParserTest.cpp b/packages/react-native/ReactCommon/react/renderer/css/tests/CSSSyntaxParserTest.cpp index 3f2e7ac5687..09c8b23e0b8 100644 --- a/packages/react-native/ReactCommon/react/renderer/css/tests/CSSSyntaxParserTest.cpp +++ b/packages/react-native/ReactCommon/react/renderer/css/tests/CSSSyntaxParserTest.cpp @@ -250,15 +250,17 @@ TEST(CSSSyntaxParser, complex) { } TEST(CSSSyntaxParser, unterminated_functions) { - EXPECT_FALSE(CSSSyntaxParser{"foo("}.consumeComponentValue( - [](const CSSFunctionBlock&, CSSSyntaxParser& /*blockParser*/) { - return true; - })); + EXPECT_FALSE( + CSSSyntaxParser{"foo("}.consumeComponentValue( + [](const CSSFunctionBlock&, CSSSyntaxParser& /*blockParser*/) { + return true; + })); - EXPECT_FALSE(CSSSyntaxParser{"foo(a bar()baz()"}.consumeComponentValue( - [](const CSSFunctionBlock&, CSSSyntaxParser& /*blockParser*/) { - return true; - })); + EXPECT_FALSE( + CSSSyntaxParser{"foo(a bar()baz()"}.consumeComponentValue( + [](const CSSFunctionBlock&, CSSSyntaxParser& /*blockParser*/) { + return true; + })); } TEST(CSSSyntaxParser, simple_blocks) { diff --git a/packages/react-native/ReactCommon/react/renderer/debug/DebugStringConvertible.h b/packages/react-native/ReactCommon/react/renderer/debug/DebugStringConvertible.h index 1220027322d..166d9a51110 100644 --- a/packages/react-native/ReactCommon/react/renderer/debug/DebugStringConvertible.h +++ b/packages/react-native/ReactCommon/react/renderer/debug/DebugStringConvertible.h @@ -22,10 +22,8 @@ namespace facebook::react { class DebugStringConvertible; -using SharedDebugStringConvertible = - std::shared_ptr; -using SharedDebugStringConvertibleList = - std::vector; +using SharedDebugStringConvertible = std::shared_ptr; +using SharedDebugStringConvertibleList = std::vector; struct DebugStringConvertibleOptions { bool format{true}; @@ -68,15 +66,12 @@ class DebugStringConvertible { // Returns a string which represents the object in a human-readable way. // Default implementation returns a description of the subtree // rooted at this node, represented in XML-like format. - virtual std::string getDebugDescription( - DebugStringConvertibleOptions options = {}) const; + virtual std::string getDebugDescription(DebugStringConvertibleOptions options = {}) const; // Do same as `getDebugDescription` but return only *children* and // *properties* parts (which are used in `getDebugDescription`). - virtual std::string getDebugPropsDescription( - DebugStringConvertibleOptions options = {}) const; - virtual std::string getDebugChildrenDescription( - DebugStringConvertibleOptions options = {}) const; + virtual std::string getDebugPropsDescription(DebugStringConvertibleOptions options = {}) const; + virtual std::string getDebugChildrenDescription(DebugStringConvertibleOptions options = {}) const; }; #else @@ -92,27 +87,33 @@ class DebugStringConvertible {}; * Set of particular-format-opinionated functions that convert base types to * `std::string` */ -std::string toString(const double& value); -std::string toString(const void* value); +std::string toString(const double &value); +std::string toString(const void *value); -inline std::string toString(const std::string& value) { +inline std::string toString(const std::string &value) +{ return value; } -inline std::string toString(const int& value) { +inline std::string toString(const int &value) +{ return std::to_string(value); } -inline std::string toString(const unsigned int& value) { +inline std::string toString(const unsigned int &value) +{ return std::to_string(value); } -inline std::string toString(const bool& value) { +inline std::string toString(const bool &value) +{ return value ? "true" : "false"; } -inline std::string toString(const float& value) { +inline std::string toString(const float &value) +{ return toString(static_cast(value)); } template -std::string toString(const std::optional& value) { +std::string toString(const std::optional &value) +{ if (!value) { return "null"; } @@ -120,7 +121,8 @@ std::string toString(const std::optional& value) { } template -std::string toString(const std::vector& value) { +std::string toString(const std::vector &value) +{ std::string result = "["; for (size_t i = 0; i < value.size(); i++) { result += toString(value[i]); @@ -165,33 +167,32 @@ std::string toString(const std::vector& value) { * types. */ template -std::string getDebugName(const T& /*object*/) { +std::string getDebugName(const T & /*object*/) +{ return "Node"; } template -std::string getDebugValue(const T& /*object*/) { +std::string getDebugValue(const T & /*object*/) +{ return ""; } template -std::vector getDebugChildren( - const T& /*object*/, - DebugStringConvertibleOptions /*options*/) { +std::vector getDebugChildren(const T & /*object*/, DebugStringConvertibleOptions /*options*/) +{ return {}; } template -std::vector getDebugProps( - const T& /*object*/, - DebugStringConvertibleOptions /*options*/) { +std::vector getDebugProps(const T & /*object*/, DebugStringConvertibleOptions /*options*/) +{ return {}; } template -std::string getDebugPropsDescription( - const T& object, - DebugStringConvertibleOptions options) { +std::string getDebugPropsDescription(const T &object, DebugStringConvertibleOptions options) +{ if (options.depth >= options.maximumDepth) { return ""; } @@ -204,10 +205,8 @@ std::string getDebugPropsDescription( auto name = getDebugName(prop); auto value = getDebugValue(prop); auto children = getDebugPropsDescription(prop, options); - auto valueAndChildren = - value + (children.empty() ? "" : "(" + children + ")"); - propsString += - " " + name + (valueAndChildren.empty() ? "" : "=" + valueAndChildren); + auto valueAndChildren = value + (children.empty() ? "" : "(" + children + ")"); + propsString += " " + name + (valueAndChildren.empty() ? "" : "=" + valueAndChildren); } if (!propsString.empty()) { @@ -219,9 +218,8 @@ std::string getDebugPropsDescription( } template -std::string getDebugChildrenDescription( - const T& object, - DebugStringConvertibleOptions options) { +std::string getDebugChildrenDescription(const T &object, DebugStringConvertibleOptions options) +{ if (options.depth >= options.maximumDepth) { return ""; } @@ -243,9 +241,8 @@ std::string getDebugChildrenDescription( } template -std::string getDebugDescription( - const T& object, - DebugStringConvertibleOptions options) { +std::string getDebugDescription(const T &object, DebugStringConvertibleOptions options) +{ auto nameString = getDebugName(object); auto valueString = getDebugValue(object); @@ -264,88 +261,78 @@ std::string getDebugDescription( auto childrenString = getDebugChildrenDescription(object, options); auto propsString = getDebugPropsDescription(object, options); - auto prefix = - options.format ? std::string(options.depth * 2, ' ') : std::string{""}; + auto prefix = options.format ? std::string(options.depth * 2, ' ') : std::string{""}; auto separator = options.format ? std::string{"\n"} : std::string{""}; - return prefix + "<" + nameString + - (valueString.empty() ? "" : "=" + valueString) + + return prefix + "<" + nameString + (valueString.empty() ? "" : "=" + valueString) + (propsString.empty() ? "" : " " + propsString) + - (childrenString.empty() ? "/>" - : ">" + separator + childrenString + separator + - prefix + ""); + (childrenString.empty() ? "/>" : ">" + separator + childrenString + separator + prefix + ""); } /* * Functions of `getDebugDescription`-family for primitive types. */ // `int` -inline std::string getDebugDescription( - int number, - DebugStringConvertibleOptions /*options*/) { +inline std::string getDebugDescription(int number, DebugStringConvertibleOptions /*options*/) +{ return toString(number); } // `float` -inline std::string getDebugDescription( - float number, - DebugStringConvertibleOptions /*options*/) { +inline std::string getDebugDescription(float number, DebugStringConvertibleOptions /*options*/) +{ return toString(number); } // `double` -inline std::string getDebugDescription( - double number, - DebugStringConvertibleOptions /*options*/) { +inline std::string getDebugDescription(double number, DebugStringConvertibleOptions /*options*/) +{ return toString(number); } // `bool` -inline std::string getDebugDescription( - bool boolean, - DebugStringConvertibleOptions /*options*/) { +inline std::string getDebugDescription(bool boolean, DebugStringConvertibleOptions /*options*/) +{ return toString(boolean); } // `void *` -inline std::string getDebugDescription( - void* pointer, - DebugStringConvertibleOptions /*options*/) { +inline std::string getDebugDescription(void *pointer, DebugStringConvertibleOptions /*options*/) +{ return toString(pointer); } // `std::string` -inline std::string getDebugDescription( - const std::string& string, - DebugStringConvertibleOptions /*options*/) { +inline std::string getDebugDescription(const std::string &string, DebugStringConvertibleOptions /*options*/) +{ return string; } // `std::vector` template -std::string getDebugName(const std::vector& /*vector*/) { +std::string getDebugName(const std::vector & /*vector*/) +{ return "List"; } template -std::vector getDebugChildren( - const std::vector& vector, - DebugStringConvertibleOptions /*options*/) { +std::vector getDebugChildren(const std::vector &vector, DebugStringConvertibleOptions /*options*/) +{ return vector; } // `std::array` template -std::string getDebugName(const std::array& /*array*/) { +std::string getDebugName(const std::array & /*array*/) +{ return "List"; } template -std::vector getDebugChildren( - const std::array& array, - DebugStringConvertibleOptions /*options*/) { +std::vector getDebugChildren(const std::array &array, DebugStringConvertibleOptions /*options*/) +{ auto vector = std::vector{}; - for (const auto& value : array) { + for (const auto &value : array) { vector.push_back(value); } return vector; @@ -353,14 +340,14 @@ std::vector getDebugChildren( // `std::unordered_set` template -std::string getDebugName(const std::unordered_set& /*set*/) { +std::string getDebugName(const std::unordered_set & /*set*/) +{ return "Set"; } template -std::vector getDebugChildren( - const std::unordered_set& set, - DebugStringConvertibleOptions /*options*/) { +std::vector getDebugChildren(const std::unordered_set &set, DebugStringConvertibleOptions /*options*/) +{ auto vector = std::vector{}; vector.insert(vector.end(), set.begin(), set.end()); return vector; @@ -368,26 +355,23 @@ std::vector getDebugChildren( // `std::shared_ptr` template -inline std::string getDebugDescription( - const std::shared_ptr& pointer, - DebugStringConvertibleOptions options) { - return getDebugDescription((void*)pointer.get(), options) + "(shared)"; +inline std::string getDebugDescription(const std::shared_ptr &pointer, DebugStringConvertibleOptions options) +{ + return getDebugDescription((void *)pointer.get(), options) + "(shared)"; } // `std::weak_ptr` template -inline std::string getDebugDescription( - const std::weak_ptr& pointer, - DebugStringConvertibleOptions options) { - return getDebugDescription((void*)pointer.lock().get(), options) + "(weak)"; +inline std::string getDebugDescription(const std::weak_ptr &pointer, DebugStringConvertibleOptions options) +{ + return getDebugDescription((void *)pointer.lock().get(), options) + "(weak)"; } // `std::unique_ptr` template -inline std::string getDebugDescription( - const std::unique_ptr& pointer, - DebugStringConvertibleOptions options) { - return getDebugDescription((void*)pointer.get(), options) + "(unique)"; +inline std::string getDebugDescription(const std::unique_ptr &pointer, DebugStringConvertibleOptions options) +{ + return getDebugDescription((void *)pointer.get(), options) + "(unique)"; } /* @@ -399,11 +383,13 @@ struct DebugStringConvertibleObject { std::string value; }; -inline std::string getDebugName(const DebugStringConvertibleObject& object) { +inline std::string getDebugName(const DebugStringConvertibleObject &object) +{ return object.name; } -inline std::string getDebugValue(const DebugStringConvertibleObject& object) { +inline std::string getDebugValue(const DebugStringConvertibleObject &object) +{ return object.value; } diff --git a/packages/react-native/ReactCommon/react/renderer/debug/DebugStringConvertibleItem.h b/packages/react-native/ReactCommon/react/renderer/debug/DebugStringConvertibleItem.h index bd200e2041b..dd9e7903959 100644 --- a/packages/react-native/ReactCommon/react/renderer/debug/DebugStringConvertibleItem.h +++ b/packages/react-native/ReactCommon/react/renderer/debug/DebugStringConvertibleItem.h @@ -20,7 +20,7 @@ namespace facebook::react { // in custom implementations of `getDebugChildren` and `getDebugProps`. class DebugStringConvertibleItem : public DebugStringConvertible { public: - DebugStringConvertibleItem(const DebugStringConvertibleItem& item) = default; + DebugStringConvertibleItem(const DebugStringConvertibleItem &item) = default; DebugStringConvertibleItem( std::string name = "", diff --git a/packages/react-native/ReactCommon/react/renderer/debug/debugStringConvertibleUtils.h b/packages/react-native/ReactCommon/react/renderer/debug/debugStringConvertibleUtils.h index 4ffcfca122e..1270f181360 100644 --- a/packages/react-native/ReactCommon/react/renderer/debug/debugStringConvertibleUtils.h +++ b/packages/react-native/ReactCommon/react/renderer/debug/debugStringConvertibleUtils.h @@ -19,59 +19,51 @@ namespace facebook::react { #if RN_DEBUG_STRING_CONVERTIBLE -inline SharedDebugStringConvertible debugStringConvertibleItem( - const std::string& name, - float value, - float defaultValue = {}) { +inline SharedDebugStringConvertible +debugStringConvertibleItem(const std::string &name, float value, float defaultValue = {}) +{ if (floatEquality(value, defaultValue)) { return nullptr; } - return std::make_shared( - name, facebook::react::toString(value)); + return std::make_shared(name, facebook::react::toString(value)); } template -inline SharedDebugStringConvertible debugStringConvertibleItem( - const std::string& name, - T value, - T defaultValue = {}) { +inline SharedDebugStringConvertible debugStringConvertibleItem(const std::string &name, T value, T defaultValue = {}) +{ if (value == defaultValue) { return nullptr; } - return std::make_shared( - name, facebook::react::toString(value)); + return std::make_shared(name, facebook::react::toString(value)); } template -inline SharedDebugStringConvertible debugStringConvertibleItem( - const std::string& name, - std::optional value, - T defaultValue = {}) { +inline SharedDebugStringConvertible +debugStringConvertibleItem(const std::string &name, std::optional value, T defaultValue = {}) +{ if (!value.has_value()) { return nullptr; } - return debugStringConvertibleItem( - name, value.value_or(defaultValue), defaultValue); + return debugStringConvertibleItem(name, value.value_or(defaultValue), defaultValue); } inline SharedDebugStringConvertibleList operator+( - const SharedDebugStringConvertibleList& lhs, - const SharedDebugStringConvertibleList& rhs) { + const SharedDebugStringConvertibleList &lhs, + const SharedDebugStringConvertibleList &rhs) +{ auto result = SharedDebugStringConvertibleList{}; std::move(lhs.begin(), lhs.end(), std::back_inserter(result)); std::move(rhs.begin(), rhs.end(), std::back_inserter(result)); return result; } -inline SharedDebugStringConvertible debugStringConvertibleItem( - const std::string& name, - DebugStringConvertible value, - std::string defaultValue) { - return debugStringConvertibleItem( - name, value.getDebugDescription(), defaultValue); +inline SharedDebugStringConvertible +debugStringConvertibleItem(const std::string &name, DebugStringConvertible value, std::string defaultValue) +{ + return debugStringConvertibleItem(name, value.getDebugDescription(), defaultValue); } #endif diff --git a/packages/react-native/ReactCommon/react/renderer/dom/DOM.h b/packages/react-native/ReactCommon/react/renderer/dom/DOM.h index 1a3a36bffc0..8cdb424a8eb 100644 --- a/packages/react-native/ReactCommon/react/renderer/dom/DOM.h +++ b/packages/react-native/ReactCommon/react/renderer/dom/DOM.h @@ -61,72 +61,54 @@ struct DOMBorderWidthRounded { }; std::shared_ptr getParentNode( - const RootShadowNode::Shared& currentRevision, - const ShadowNode& shadowNode); + const RootShadowNode::Shared ¤tRevision, + const ShadowNode &shadowNode); std::shared_ptr getElementById( - const std::shared_ptr& currentRevision, - const std::string& id); + const std::shared_ptr ¤tRevision, + const std::string &id); std::vector> getChildNodes( - const RootShadowNode::Shared& currentRevision, - const ShadowNode& shadowNode); + const RootShadowNode::Shared ¤tRevision, + const ShadowNode &shadowNode); -bool isConnected( - const RootShadowNode::Shared& currentRevision, - const ShadowNode& shadowNode); +bool isConnected(const RootShadowNode::Shared ¤tRevision, const ShadowNode &shadowNode); uint_fast16_t compareDocumentPosition( - const RootShadowNode::Shared& currentRevision, - const ShadowNode& shadowNode, - const ShadowNode& otherShadowNode); + const RootShadowNode::Shared ¤tRevision, + const ShadowNode &shadowNode, + const ShadowNode &otherShadowNode); -std::string getTextContent( - const RootShadowNode::Shared& currentRevision, - const ShadowNode& shadowNode); +std::string getTextContent(const RootShadowNode::Shared ¤tRevision, const ShadowNode &shadowNode); DOMRect getBoundingClientRect( - const RootShadowNode::Shared& currentRevision, - const ShadowNode& shadowNode, + const RootShadowNode::Shared ¤tRevision, + const ShadowNode &shadowNode, bool includeTransform); -DOMOffset getOffset( - const RootShadowNode::Shared& currentRevision, - const ShadowNode& shadowNode); +DOMOffset getOffset(const RootShadowNode::Shared ¤tRevision, const ShadowNode &shadowNode); -DOMPoint getScrollPosition( - const RootShadowNode::Shared& currentRevision, - const ShadowNode& shadowNode); +DOMPoint getScrollPosition(const RootShadowNode::Shared ¤tRevision, const ShadowNode &shadowNode); -DOMSizeRounded getScrollSize( - const RootShadowNode::Shared& currentRevision, - const ShadowNode& shadowNode); +DOMSizeRounded getScrollSize(const RootShadowNode::Shared ¤tRevision, const ShadowNode &shadowNode); -DOMSizeRounded getInnerSize( - const RootShadowNode::Shared& currentRevision, - const ShadowNode& shadowNode); +DOMSizeRounded getInnerSize(const RootShadowNode::Shared ¤tRevision, const ShadowNode &shadowNode); -DOMBorderWidthRounded getBorderWidth( - const RootShadowNode::Shared& currentRevision, - const ShadowNode& shadowNode); +DOMBorderWidthRounded getBorderWidth(const RootShadowNode::Shared ¤tRevision, const ShadowNode &shadowNode); -std::string getTagName(const ShadowNode& shadowNode); +std::string getTagName(const ShadowNode &shadowNode); // Non-standard methods from React Native -RNMeasureRect measure( - const RootShadowNode::Shared& currentRevision, - const ShadowNode& shadowNode); +RNMeasureRect measure(const RootShadowNode::Shared ¤tRevision, const ShadowNode &shadowNode); -DOMRect measureInWindow( - const RootShadowNode::Shared& currentRevision, - const ShadowNode& shadowNode); +DOMRect measureInWindow(const RootShadowNode::Shared ¤tRevision, const ShadowNode &shadowNode); // This method returns an optional to signal to go through the error callback // instead of going through the success callback with an empty DOMRect. std::optional measureLayout( - const RootShadowNode::Shared& currentRevision, - const ShadowNode& shadowNode, - const ShadowNode& relativeToShadowNode); + const RootShadowNode::Shared ¤tRevision, + const ShadowNode &shadowNode, + const ShadowNode &relativeToShadowNode); } // namespace facebook::react::dom diff --git a/packages/react-native/ReactCommon/react/renderer/element/ComponentBuilder.cpp b/packages/react-native/ReactCommon/react/renderer/element/ComponentBuilder.cpp index a20894390a3..54640d27189 100644 --- a/packages/react-native/ReactCommon/react/renderer/element/ComponentBuilder.cpp +++ b/packages/react-native/ReactCommon/react/renderer/element/ComponentBuilder.cpp @@ -13,7 +13,7 @@ namespace facebook::react { ComponentBuilder::ComponentBuilder( ComponentDescriptorRegistry::Shared componentDescriptorRegistry) - : componentDescriptorRegistry_(std::move(componentDescriptorRegistry)){}; + : componentDescriptorRegistry_(std::move(componentDescriptorRegistry)) {}; std::shared_ptr ComponentBuilder::build( const ElementFragment& elementFragment) const { @@ -26,10 +26,11 @@ std::shared_ptr ComponentBuilder::build( children.push_back(build(childFragment)); } - auto family = componentDescriptor.createFamily(ShadowNodeFamilyFragment{ - .tag = elementFragment.tag, - .surfaceId = elementFragment.surfaceId, - .instanceHandle = nullptr}); + auto family = componentDescriptor.createFamily( + ShadowNodeFamilyFragment{ + .tag = elementFragment.tag, + .surfaceId = elementFragment.surfaceId, + .instanceHandle = nullptr}); auto initialState = componentDescriptor.createInitialState(elementFragment.props, family); diff --git a/packages/react-native/ReactCommon/react/renderer/element/ComponentBuilder.h b/packages/react-native/ReactCommon/react/renderer/element/ComponentBuilder.h index 071ed044dc3..508cd5c0de0 100644 --- a/packages/react-native/ReactCommon/react/renderer/element/ComponentBuilder.h +++ b/packages/react-native/ReactCommon/react/renderer/element/ComponentBuilder.h @@ -24,23 +24,23 @@ namespace facebook::react { */ class ComponentBuilder final { public: - ComponentBuilder( - ComponentDescriptorRegistry::Shared componentDescriptorRegistry); + ComponentBuilder(ComponentDescriptorRegistry::Shared componentDescriptorRegistry); /* * Copyable and movable. */ - ComponentBuilder(const ComponentBuilder& componentBuilder) = default; - ComponentBuilder(ComponentBuilder&& componentBuilder) noexcept = default; - ComponentBuilder& operator=(const ComponentBuilder& other) = default; - ComponentBuilder& operator=(ComponentBuilder&& other) = default; + ComponentBuilder(const ComponentBuilder &componentBuilder) = default; + ComponentBuilder(ComponentBuilder &&componentBuilder) noexcept = default; + ComponentBuilder &operator=(const ComponentBuilder &other) = default; + ComponentBuilder &operator=(ComponentBuilder &&other) = default; /* * Builds a `ShadowNode` tree with given `Element` tree using stored * `ComponentDescriptorRegistry`. */ template - std::shared_ptr build(Element element) const { + std::shared_ptr build(Element element) const + { return std::static_pointer_cast(build(element.fragment_)); } @@ -48,8 +48,7 @@ class ComponentBuilder final { /* * Internal, type-erased version of `build`. */ - std::shared_ptr build( - const ElementFragment& elementFragment) const; + std::shared_ptr build(const ElementFragment &elementFragment) const; ComponentDescriptorRegistry::Shared componentDescriptorRegistry_; }; diff --git a/packages/react-native/ReactCommon/react/renderer/element/Element.h b/packages/react-native/ReactCommon/react/renderer/element/Element.h index 01d94fd31c6..251cb49c49d 100644 --- a/packages/react-native/ReactCommon/react/renderer/element/Element.h +++ b/packages/react-native/ReactCommon/react/renderer/element/Element.h @@ -37,13 +37,13 @@ class Element final { using ConcreteShadowNode = ShadowNodeT; using ConcreteUnsharedShadowNode = std::shared_ptr; - using ConcreteReferenceCallback = - std::function& shadowNode)>; + using ConcreteReferenceCallback = std::function &shadowNode)>; /* * Constructs an `Element`. */ - Element() { + Element() + { fragment_.componentHandle = ShadowNodeT::Handle(); fragment_.componentName = ShadowNodeT::Name(); fragment_.props = ShadowNodeT::defaultSharedProps(); @@ -52,14 +52,16 @@ class Element final { /* * Converts to `ElementFragment` object. */ - operator ElementFragment() { + operator ElementFragment() + { return fragment_; } /* * Sets `tag`. */ - Element& tag(Tag tag) { + Element &tag(Tag tag) + { fragment_.tag = tag; return *this; } @@ -67,7 +69,8 @@ class Element final { /* * Sets `surfaceId`. */ - Element& surfaceId(SurfaceId surfaceId) { + Element &surfaceId(SurfaceId surfaceId) + { fragment_.surfaceId = surfaceId; return *this; } @@ -75,7 +78,8 @@ class Element final { /* * Sets `props`. */ - Element& props(SharedConcreteProps props) { + Element &props(SharedConcreteProps props) + { fragment_.props = props; return *this; } @@ -83,7 +87,8 @@ class Element final { /* * Sets `props` using callback. */ - Element& props(std::function callback) { + Element &props(std::function callback) + { fragment_.props = callback(); return *this; } @@ -91,12 +96,10 @@ class Element final { /* * Sets `state` using callback. */ - Element& stateData(std::function callback) { - fragment_.stateCallback = - [callback = std::move(callback)]( - const State::Shared& state) -> StateData::Shared { - auto stateData = - static_cast(state.get())->getData(); + Element &stateData(std::function callback) + { + fragment_.stateCallback = [callback = std::move(callback)](const State::Shared &state) -> StateData::Shared { + auto stateData = static_cast(state.get())->getData(); callback(stateData); return std::make_shared(stateData); }; @@ -106,10 +109,11 @@ class Element final { /* * Sets children. */ - Element& children(std::vector children) { + Element &children(std::vector children) + { auto fragments = ElementFragment::List{}; fragments.reserve(children.size()); - for (const auto& child : children) { + for (const auto &child : children) { fragments.push_back(child); } fragment_.children = fragments; @@ -120,15 +124,13 @@ class Element final { * Calls the callback during component construction with a pointer to the * component which is being constructed. */ - Element& reference( - std::function - callback) { - fragment_.referenceCallback = - [callback = std::move(callback)]( - const std::shared_ptr& shadowNode) { - callback(std::const_pointer_cast( - std::static_pointer_cast(shadowNode))); - }; + Element &reference(std::function callback) + { + fragment_.referenceCallback = [callback = + std::move(callback)](const std::shared_ptr &shadowNode) { + callback( + std::const_pointer_cast(std::static_pointer_cast(shadowNode))); + }; return *this; } @@ -136,22 +138,22 @@ class Element final { * During component construction, assigns a given pointer to a component * that is being constructed. */ - Element& reference(ConcreteUnsharedShadowNode& outShadowNode) { - fragment_.referenceCallback = - [&](const std::shared_ptr& shadowNode) { - outShadowNode = std::const_pointer_cast( - std::static_pointer_cast(shadowNode)); - }; + Element &reference(ConcreteUnsharedShadowNode &outShadowNode) + { + fragment_.referenceCallback = [&](const std::shared_ptr &shadowNode) { + outShadowNode = + std::const_pointer_cast(std::static_pointer_cast(shadowNode)); + }; return *this; } /* * Calls the callback with a reference to a just constructed component. */ - Element& finalize( - std::function finalizeCallback) { - fragment_.finalizeCallback = [=](ShadowNode& shadowNode) { - return finalizeCallback(static_cast(shadowNode)); + Element &finalize(std::function finalizeCallback) + { + fragment_.finalizeCallback = [=](ShadowNode &shadowNode) { + return finalizeCallback(static_cast(shadowNode)); }; return *this; } diff --git a/packages/react-native/ReactCommon/react/renderer/element/ElementFragment.h b/packages/react-native/ReactCommon/react/renderer/element/ElementFragment.h index 88a7459a44d..316c4256dc2 100644 --- a/packages/react-native/ReactCommon/react/renderer/element/ElementFragment.h +++ b/packages/react-native/ReactCommon/react/renderer/element/ElementFragment.h @@ -26,11 +26,9 @@ class ElementFragment final { using Shared = std::shared_ptr; using List = std::vector; using ListOfShared = std::vector; - using ReferenceCallback = - std::function& shadowNode)>; - using FinalizeCallback = std::function; - using StateCallback = - std::function; + using ReferenceCallback = std::function &shadowNode)>; + using FinalizeCallback = std::function; + using StateCallback = std::function; /* * ComponentDescriptor part (describes the type) diff --git a/packages/react-native/ReactCommon/react/renderer/element/testUtils.h b/packages/react-native/ReactCommon/react/renderer/element/testUtils.h index c6966c1897e..48277f9f2fc 100644 --- a/packages/react-native/ReactCommon/react/renderer/element/testUtils.h +++ b/packages/react-native/ReactCommon/react/renderer/element/testUtils.h @@ -19,31 +19,21 @@ namespace facebook::react { -inline ComponentBuilder simpleComponentBuilder( - std::shared_ptr contextContainer = nullptr) { +inline ComponentBuilder simpleComponentBuilder(std::shared_ptr contextContainer = nullptr) +{ ComponentDescriptorProviderRegistry componentDescriptorProviderRegistry{}; auto eventDispatcher = EventDispatcher::Shared{}; - auto componentDescriptorRegistry = - componentDescriptorProviderRegistry.createComponentDescriptorRegistry( - ComponentDescriptorParameters{ - .eventDispatcher = eventDispatcher, - .contextContainer = std::move(contextContainer), - .flavor = nullptr}); + auto componentDescriptorRegistry = componentDescriptorProviderRegistry.createComponentDescriptorRegistry( + ComponentDescriptorParameters{ + .eventDispatcher = eventDispatcher, .contextContainer = std::move(contextContainer), .flavor = nullptr}); - componentDescriptorProviderRegistry.add( - concreteComponentDescriptorProvider()); - componentDescriptorProviderRegistry.add( - concreteComponentDescriptorProvider()); - componentDescriptorProviderRegistry.add( - concreteComponentDescriptorProvider()); - componentDescriptorProviderRegistry.add( - concreteComponentDescriptorProvider()); - componentDescriptorProviderRegistry.add( - concreteComponentDescriptorProvider()); - componentDescriptorProviderRegistry.add( - concreteComponentDescriptorProvider()); - componentDescriptorProviderRegistry.add( - concreteComponentDescriptorProvider()); + componentDescriptorProviderRegistry.add(concreteComponentDescriptorProvider()); + componentDescriptorProviderRegistry.add(concreteComponentDescriptorProvider()); + componentDescriptorProviderRegistry.add(concreteComponentDescriptorProvider()); + componentDescriptorProviderRegistry.add(concreteComponentDescriptorProvider()); + componentDescriptorProviderRegistry.add(concreteComponentDescriptorProvider()); + componentDescriptorProviderRegistry.add(concreteComponentDescriptorProvider()); + componentDescriptorProviderRegistry.add(concreteComponentDescriptorProvider()); return ComponentBuilder{componentDescriptorRegistry}; } diff --git a/packages/react-native/ReactCommon/react/renderer/graphics/BackgroundImage.h b/packages/react-native/ReactCommon/react/renderer/graphics/BackgroundImage.h index 1945f5e31e0..d156126f251 100644 --- a/packages/react-native/ReactCommon/react/renderer/graphics/BackgroundImage.h +++ b/packages/react-native/ReactCommon/react/renderer/graphics/BackgroundImage.h @@ -15,11 +15,12 @@ namespace facebook::react { using BackgroundImage = std::variant; #ifdef RN_SERIALIZABLE_STATE -folly::dynamic toDynamic(const BackgroundImage& backgroundImage); +folly::dynamic toDynamic(const BackgroundImage &backgroundImage); #endif #if RN_DEBUG_STRING_CONVERTIBLE -inline std::string toString(std::vector& value) { +inline std::string toString(std::vector &value) +{ std::stringstream ss; ss << "["; @@ -28,7 +29,7 @@ inline std::string toString(std::vector& value) { ss << ", "; } - const auto& backgroundImage = value[i]; + const auto &backgroundImage = value[i]; if (std::holds_alternative(backgroundImage)) { std::get(backgroundImage).toString(ss); } else if (std::holds_alternative(backgroundImage)) { diff --git a/packages/react-native/ReactCommon/react/renderer/graphics/BackgroundPosition.h b/packages/react-native/ReactCommon/react/renderer/graphics/BackgroundPosition.h index 1e431718905..97292f4a764 100644 --- a/packages/react-native/ReactCommon/react/renderer/graphics/BackgroundPosition.h +++ b/packages/react-native/ReactCommon/react/renderer/graphics/BackgroundPosition.h @@ -18,12 +18,10 @@ struct BackgroundPosition { std::optional right; std::optional bottom; - BackgroundPosition() - : top(ValueUnit{0.0f, UnitType::Point}), - left(ValueUnit{0.0f, UnitType::Point}) {} + BackgroundPosition() : top(ValueUnit{0.0f, UnitType::Point}), left(ValueUnit{0.0f, UnitType::Point}) {} - bool operator==(const BackgroundPosition& other) const = default; - bool operator!=(const BackgroundPosition& other) const = default; + bool operator==(const BackgroundPosition &other) const = default; + bool operator!=(const BackgroundPosition &other) const = default; }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/graphics/BackgroundRepeat.h b/packages/react-native/ReactCommon/react/renderer/graphics/BackgroundRepeat.h index 966183447fc..c277bd80ff8 100644 --- a/packages/react-native/ReactCommon/react/renderer/graphics/BackgroundRepeat.h +++ b/packages/react-native/ReactCommon/react/renderer/graphics/BackgroundRepeat.h @@ -22,8 +22,8 @@ struct BackgroundRepeat { BackgroundRepeat() {} - bool operator==(const BackgroundRepeat& other) const = default; - bool operator!=(const BackgroundRepeat& other) const = default; + bool operator==(const BackgroundRepeat &other) const = default; + bool operator!=(const BackgroundRepeat &other) const = default; }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/graphics/BackgroundSize.h b/packages/react-native/ReactCommon/react/renderer/graphics/BackgroundSize.h index fbd2bdcc61d..84af42a98ce 100644 --- a/packages/react-native/ReactCommon/react/renderer/graphics/BackgroundSize.h +++ b/packages/react-native/ReactCommon/react/renderer/graphics/BackgroundSize.h @@ -18,21 +18,22 @@ struct BackgroundSizeLengthPercentage { BackgroundSizeLengthPercentage() : x(std::monostate{}), y(std::monostate{}) {} - bool isXAuto() const { + bool isXAuto() const + { return std::holds_alternative(x); } - bool isYAuto() const { + bool isYAuto() const + { return std::holds_alternative(y); } - bool operator==(const BackgroundSizeLengthPercentage& other) const = default; - bool operator!=(const BackgroundSizeLengthPercentage& other) const = default; + bool operator==(const BackgroundSizeLengthPercentage &other) const = default; + bool operator!=(const BackgroundSizeLengthPercentage &other) const = default; }; enum class BackgroundSizeKeyword { Cover, Contain }; // https://www.w3.org/TR/css-backgrounds-3/#background-size -using BackgroundSize = - std::variant; +using BackgroundSize = std::variant; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/graphics/BlendMode.h b/packages/react-native/ReactCommon/react/renderer/graphics/BlendMode.h index e1362717551..246539a929d 100644 --- a/packages/react-native/ReactCommon/react/renderer/graphics/BlendMode.h +++ b/packages/react-native/ReactCommon/react/renderer/graphics/BlendMode.h @@ -31,8 +31,8 @@ enum class BlendMode { Luminosity, }; -inline std::optional blendModeFromString( - std::string_view blendModeName) { +inline std::optional blendModeFromString(std::string_view blendModeName) +{ if (blendModeName == "normal") { return BlendMode::Normal; } else if (blendModeName == "multiply") { @@ -70,7 +70,8 @@ inline std::optional blendModeFromString( } } -inline std::string toString(const BlendMode& blendMode) { +inline std::string toString(const BlendMode &blendMode) +{ switch (blendMode) { case BlendMode::Normal: return "normal"; diff --git a/packages/react-native/ReactCommon/react/renderer/graphics/BoxShadow.h b/packages/react-native/ReactCommon/react/renderer/graphics/BoxShadow.h index b519487ef31..f8be37cc06e 100644 --- a/packages/react-native/ReactCommon/react/renderer/graphics/BoxShadow.h +++ b/packages/react-native/ReactCommon/react/renderer/graphics/BoxShadow.h @@ -13,7 +13,7 @@ namespace facebook::react { struct BoxShadow { - bool operator==(const BoxShadow& other) const = default; + bool operator==(const BoxShadow &other) const = default; Float offsetX{}; Float offsetY{}; @@ -23,7 +23,8 @@ struct BoxShadow { bool inset{}; #ifdef RN_SERIALIZABLE_STATE - folly::dynamic toDynamic() const { + folly::dynamic toDynamic() const + { folly::dynamic result = folly::dynamic::object(); result["offsetX"] = offsetX; result["offsetY"] = offsetY; @@ -37,7 +38,8 @@ struct BoxShadow { }; #ifdef RN_SERIALIZABLE_STATE -inline folly::dynamic toDynamic(const BoxShadow& boxShadow) { +inline folly::dynamic toDynamic(const BoxShadow &boxShadow) +{ return boxShadow.toDynamic(); } #endif diff --git a/packages/react-native/ReactCommon/react/renderer/graphics/Color.h b/packages/react-native/ReactCommon/react/renderer/graphics/Color.h index 76445126b8b..16905f62a3d 100644 --- a/packages/react-native/ReactCommon/react/renderer/graphics/Color.h +++ b/packages/react-native/ReactCommon/react/renderer/graphics/Color.h @@ -33,23 +33,28 @@ class SharedColor { SharedColor(Color color) : color_(color) {} - Color& operator*() { + Color &operator*() + { return color_; } - const Color& operator*() const { + const Color &operator*() const + { return color_; } - bool operator==(const SharedColor& otherColor) const { + bool operator==(const SharedColor &otherColor) const + { return color_ == otherColor.color_; } - bool operator!=(const SharedColor& otherColor) const { + bool operator!=(const SharedColor &otherColor) const + { return color_ != otherColor.color_; } - operator bool() const { + operator bool() const + { return color_ != HostPlatformColor::UndefinedColor; } @@ -59,7 +64,7 @@ class SharedColor { Color color_; }; -bool isColorMeaningful(const SharedColor& color) noexcept; +bool isColorMeaningful(const SharedColor &color) noexcept; SharedColor colorFromComponents(ColorComponents components); ColorComponents colorComponentsFromColor(SharedColor color); @@ -74,7 +79,8 @@ SharedColor blackColor(); SharedColor whiteColor(); #ifdef RN_SERIALIZABLE_STATE -inline folly::dynamic toDynamic(const SharedColor& sharedColor) { +inline folly::dynamic toDynamic(const SharedColor &sharedColor) +{ return *sharedColor; } #endif @@ -83,7 +89,8 @@ inline folly::dynamic toDynamic(const SharedColor& sharedColor) { template <> struct std::hash { - size_t operator()(const facebook::react::SharedColor& color) const { + size_t operator()(const facebook::react::SharedColor &color) const + { return std::hash{}(*color); } }; diff --git a/packages/react-native/ReactCommon/react/renderer/graphics/ColorStop.h b/packages/react-native/ReactCommon/react/renderer/graphics/ColorStop.h index 1ff771bbf91..8914fc81e4e 100644 --- a/packages/react-native/ReactCommon/react/renderer/graphics/ColorStop.h +++ b/packages/react-native/ReactCommon/react/renderer/graphics/ColorStop.h @@ -17,7 +17,7 @@ namespace facebook::react { struct ColorStop { - bool operator==(const ColorStop& other) const = default; + bool operator==(const ColorStop &other) const = default; SharedColor color; ValueUnit position; @@ -26,7 +26,8 @@ struct ColorStop { #endif #if RN_DEBUG_STRING_CONVERTIBLE - void toString(std::stringstream& ss) const { + void toString(std::stringstream &ss) const + { ss << color.toString(); if (position.unit != UnitType::Undefined) { ss << " "; @@ -37,7 +38,7 @@ struct ColorStop { }; struct ProcessedColorStop { - bool operator==(const ProcessedColorStop& other) const = default; + bool operator==(const ProcessedColorStop &other) const = default; SharedColor color; std::optional position; }; diff --git a/packages/react-native/ReactCommon/react/renderer/graphics/Filter.h b/packages/react-native/ReactCommon/react/renderer/graphics/Filter.h index 176d0e54475..24a180ecb5c 100644 --- a/packages/react-native/ReactCommon/react/renderer/graphics/Filter.h +++ b/packages/react-native/ReactCommon/react/renderer/graphics/Filter.h @@ -29,7 +29,8 @@ enum class FilterType { DropShadow }; -inline FilterType filterTypeFromString(std::string_view filterName) { +inline FilterType filterTypeFromString(std::string_view filterName) +{ if (filterName == "blur") { return FilterType::Blur; } else if (filterName == "brightness") { @@ -55,7 +56,8 @@ inline FilterType filterTypeFromString(std::string_view filterName) { } } -inline std::string toString(const FilterType& filterType) { +inline std::string toString(const FilterType &filterType) +{ switch (filterType) { case FilterType::Blur: return "blur"; @@ -81,7 +83,7 @@ inline std::string toString(const FilterType& filterType) { } struct DropShadowParams { - bool operator==(const DropShadowParams& other) const = default; + bool operator==(const DropShadowParams &other) const = default; Float offsetX{}; Float offsetY{}; @@ -89,7 +91,8 @@ struct DropShadowParams { SharedColor color{}; #ifdef RN_SERIALIZABLE_STATE - folly::dynamic toDynamic() const { + folly::dynamic toDynamic() const + { folly::dynamic result = folly::dynamic::object(); result["offsetX"] = offsetX; result["offsetY"] = offsetY; @@ -101,19 +104,20 @@ struct DropShadowParams { }; struct FilterFunction { - bool operator==(const FilterFunction& other) const = default; + bool operator==(const FilterFunction &other) const = default; FilterType type{}; std::variant parameters{}; #ifdef RN_SERIALIZABLE_STATE - folly::dynamic toDynamic() const { + folly::dynamic toDynamic() const + { folly::dynamic result = folly::dynamic::object(); std::string typeKey = toString(type); if (std::holds_alternative(parameters)) { result[typeKey] = std::get(parameters); } else if (std::holds_alternative(parameters)) { - const auto& dropShadowParams = std::get(parameters); + const auto &dropShadowParams = std::get(parameters); result[typeKey] = dropShadowParams.toDynamic(); } return result; @@ -122,7 +126,8 @@ struct FilterFunction { }; #ifdef RN_SERIALIZABLE_STATE -inline folly::dynamic toDynamic(const FilterFunction& filterFunction) { +inline folly::dynamic toDynamic(const FilterFunction &filterFunction) +{ return filterFunction.toDynamic(); } #endif diff --git a/packages/react-native/ReactCommon/react/renderer/graphics/Isolation.h b/packages/react-native/ReactCommon/react/renderer/graphics/Isolation.h index 941c4a1c28a..9b9b2a1e630 100644 --- a/packages/react-native/ReactCommon/react/renderer/graphics/Isolation.h +++ b/packages/react-native/ReactCommon/react/renderer/graphics/Isolation.h @@ -18,8 +18,8 @@ enum class Isolation { Isolate, }; -inline std::optional isolationFromString( - std::string_view isolationSetting) { +inline std::optional isolationFromString(std::string_view isolationSetting) +{ if (isolationSetting == "auto") { return Isolation::Auto; } else if (isolationSetting == "isolate") { diff --git a/packages/react-native/ReactCommon/react/renderer/graphics/LinearGradient.h b/packages/react-native/ReactCommon/react/renderer/graphics/LinearGradient.h index 5d356f7e6ed..6e105009d1f 100644 --- a/packages/react-native/ReactCommon/react/renderer/graphics/LinearGradient.h +++ b/packages/react-native/ReactCommon/react/renderer/graphics/LinearGradient.h @@ -31,7 +31,8 @@ struct GradientDirection { GradientDirectionType type; std::variant value; - bool operator==(const GradientDirection& other) const { + bool operator==(const GradientDirection &other) const + { return type == other.type && value == other.value; } @@ -44,7 +45,8 @@ struct LinearGradient { GradientDirection direction; std::vector colorStops; - bool operator==(const LinearGradient& other) const { + bool operator==(const LinearGradient &other) const + { return direction == other.direction && colorStops == other.colorStops; } @@ -53,7 +55,7 @@ struct LinearGradient { #endif #if RN_DEBUG_STRING_CONVERTIBLE - void toString(std::stringstream& ss) const; + void toString(std::stringstream &ss) const; #endif }; diff --git a/packages/react-native/ReactCommon/react/renderer/graphics/Point.h b/packages/react-native/ReactCommon/react/renderer/graphics/Point.h index 163395844ef..8a05b4d35d2 100644 --- a/packages/react-native/ReactCommon/react/renderer/graphics/Point.h +++ b/packages/react-native/ReactCommon/react/renderer/graphics/Point.h @@ -19,47 +19,53 @@ struct Point { Float x{0}; Float y{0}; - inline Point& operator+=(const Point& point) noexcept { + inline Point &operator+=(const Point &point) noexcept + { x += point.x; y += point.y; return *this; } - inline Point& operator-=(const Point& point) noexcept { + inline Point &operator-=(const Point &point) noexcept + { x -= point.x; y -= point.y; return *this; } - inline Point& operator*=(const Point& point) noexcept { + inline Point &operator*=(const Point &point) noexcept + { x *= point.x; y *= point.y; return *this; } - inline Point operator+(const Point& rhs) const noexcept { + inline Point operator+(const Point &rhs) const noexcept + { return { .x = this->x + rhs.x, .y = this->y + rhs.y, }; } - inline Point operator-(const Point& rhs) const noexcept { + inline Point operator-(const Point &rhs) const noexcept + { return { .x = this->x - rhs.x, .y = this->y - rhs.y, }; } - inline Point operator-() const noexcept { + inline Point operator-() const noexcept + { return { .x = -x, .y = -y, }; } - inline bool operator==(const Point& rhs) const = default; + inline bool operator==(const Point &rhs) const = default; - inline bool operator!=(const Point& rhs) const = default; + inline bool operator!=(const Point &rhs) const = default; }; } // namespace facebook::react @@ -68,7 +74,8 @@ namespace std { template <> struct hash { - inline size_t operator()(const facebook::react::Point& point) const noexcept { + inline size_t operator()(const facebook::react::Point &point) const noexcept + { return facebook::react::hash_combine(point.x, point.y); } }; diff --git a/packages/react-native/ReactCommon/react/renderer/graphics/RadialGradient.h b/packages/react-native/ReactCommon/react/renderer/graphics/RadialGradient.h index 20ff53f48c6..1d33dc40762 100644 --- a/packages/react-native/ReactCommon/react/renderer/graphics/RadialGradient.h +++ b/packages/react-native/ReactCommon/react/renderer/graphics/RadialGradient.h @@ -25,22 +25,19 @@ namespace facebook::react { enum class RadialGradientShape { Circle, Ellipse }; struct RadialGradientSize { - enum class SizeKeyword { - ClosestSide, - FarthestSide, - ClosestCorner, - FarthestCorner - }; + enum class SizeKeyword { ClosestSide, FarthestSide, ClosestCorner, FarthestCorner }; struct Dimensions { ValueUnit x; ValueUnit y; - bool operator==(const Dimensions& other) const { + bool operator==(const Dimensions &other) const + { return x == other.x && y == other.y; } - bool operator!=(const Dimensions& other) const { + bool operator!=(const Dimensions &other) const + { return !(*this == other); } @@ -51,11 +48,13 @@ struct RadialGradientSize { std::variant value; - bool operator==(const RadialGradientSize& other) const { + bool operator==(const RadialGradientSize &other) const + { return value == other.value; } - bool operator!=(const RadialGradientSize& other) const { + bool operator!=(const RadialGradientSize &other) const + { return !(*this == other); } @@ -70,12 +69,13 @@ struct RadialGradientPosition { std::optional right; std::optional bottom; - bool operator==(const RadialGradientPosition& other) const { - return top == other.top && left == other.left && right == other.right && - bottom == other.bottom; + bool operator==(const RadialGradientPosition &other) const + { + return top == other.top && left == other.left && right == other.right && bottom == other.bottom; } - bool operator!=(const RadialGradientPosition& other) const { + bool operator!=(const RadialGradientPosition &other) const + { return !(*this == other); } @@ -90,11 +90,12 @@ struct RadialGradient { RadialGradientPosition position; std::vector colorStops; - bool operator==(const RadialGradient& other) const { - return shape == other.shape && size == other.size && - position == other.position && colorStops == other.colorStops; + bool operator==(const RadialGradient &other) const + { + return shape == other.shape && size == other.size && position == other.position && colorStops == other.colorStops; } - bool operator!=(const RadialGradient& other) const { + bool operator!=(const RadialGradient &other) const + { return !(*this == other); } @@ -103,7 +104,7 @@ struct RadialGradient { #endif #if RN_DEBUG_STRING_CONVERTIBLE - void toString(std::stringstream& ss) const; + void toString(std::stringstream &ss) const; #endif }; }; // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/graphics/Rect.h b/packages/react-native/ReactCommon/react/renderer/graphics/Rect.h index b4835f7a8f4..031f8537399 100644 --- a/packages/react-native/ReactCommon/react/renderer/graphics/Rect.h +++ b/packages/react-native/ReactCommon/react/renderer/graphics/Rect.h @@ -24,37 +24,47 @@ struct Rect { Point origin{.x = 0, .y = 0}; Size size{.width = 0, .height = 0}; - bool operator==(const Rect& rhs) const noexcept { + bool operator==(const Rect &rhs) const noexcept + { return std::tie(this->origin, this->size) == std::tie(rhs.origin, rhs.size); } - bool operator!=(const Rect& rhs) const noexcept { + bool operator!=(const Rect &rhs) const noexcept + { return !(*this == rhs); } - Float getMaxX() const noexcept { + Float getMaxX() const noexcept + { return size.width > 0 ? origin.x + size.width : origin.x; } - Float getMaxY() const noexcept { + Float getMaxY() const noexcept + { return size.height > 0 ? origin.y + size.height : origin.y; } - Float getMinX() const noexcept { + Float getMinX() const noexcept + { return size.width >= 0 ? origin.x : origin.x + size.width; } - Float getMinY() const noexcept { + Float getMinY() const noexcept + { return size.height >= 0 ? origin.y : origin.y + size.height; } - Float getMidX() const noexcept { + Float getMidX() const noexcept + { return origin.x + size.width / 2; } - Float getMidY() const noexcept { + Float getMidY() const noexcept + { return origin.y + size.height / 2; } - Point getCenter() const noexcept { + Point getCenter() const noexcept + { return {.x = getMidX(), .y = getMidY()}; } - void unionInPlace(const Rect& rect) noexcept { + void unionInPlace(const Rect &rect) noexcept + { auto x1 = std::min(getMinX(), rect.getMinX()); auto y1 = std::min(getMinY(), rect.getMinY()); auto x2 = std::max(getMaxX(), rect.getMaxX()); @@ -63,19 +73,18 @@ struct Rect { size = {.width = x2 - x1, .height = y2 - y1}; } - bool containsPoint(Point point) noexcept { - return point.x >= origin.x && point.y >= origin.y && - point.x <= (origin.x + size.width) && + bool containsPoint(Point point) noexcept + { + return point.x >= origin.x && point.y >= origin.y && point.x <= (origin.x + size.width) && point.y <= (origin.y + size.height); } - static Rect intersect(const Rect& rect1, const Rect& rect2) { + static Rect intersect(const Rect &rect1, const Rect &rect2) + { Float x1 = std::max(rect1.origin.x, rect2.origin.x); Float y1 = std::max(rect1.origin.y, rect2.origin.y); - Float x2 = std::min( - rect1.origin.x + rect1.size.width, rect2.origin.x + rect2.size.width); - Float y2 = std::min( - rect1.origin.y + rect1.size.height, rect2.origin.y + rect2.size.height); + Float x2 = std::min(rect1.origin.x + rect1.size.width, rect2.origin.x + rect2.size.width); + Float y2 = std::min(rect1.origin.y + rect1.size.height, rect2.origin.y + rect2.size.height); Float intersectionWidth = x2 - x1; Float intersectionHeight = y2 - y1; @@ -84,16 +93,11 @@ struct Rect { return {}; } - return { - .origin = {.x = x1, .y = y1}, - .size = {.width = intersectionWidth, .height = intersectionHeight}}; + return {.origin = {.x = x1, .y = y1}, .size = {.width = intersectionWidth, .height = intersectionHeight}}; } - static Rect boundingRect( - const Point& a, - const Point& b, - const Point& c, - const Point& d) noexcept { + static Rect boundingRect(const Point &a, const Point &b, const Point &c, const Point &d) noexcept + { auto leftTopPoint = a; auto rightBottomPoint = a; @@ -115,9 +119,7 @@ struct Rect { return { .origin = leftTopPoint, - .size = { - .width = rightBottomPoint.x - leftTopPoint.x, - .height = rightBottomPoint.y - leftTopPoint.y}}; + .size = {.width = rightBottomPoint.x - leftTopPoint.x, .height = rightBottomPoint.y - leftTopPoint.y}}; } }; @@ -127,7 +129,8 @@ namespace std { template <> struct hash { - size_t operator()(const facebook::react::Rect& rect) const noexcept { + size_t operator()(const facebook::react::Rect &rect) const noexcept + { return facebook::react::hash_combine(rect.origin, rect.size); } }; diff --git a/packages/react-native/ReactCommon/react/renderer/graphics/RectangleCorners.h b/packages/react-native/ReactCommon/react/renderer/graphics/RectangleCorners.h index a5c2dd465a4..a46930baef6 100644 --- a/packages/react-native/ReactCommon/react/renderer/graphics/RectangleCorners.h +++ b/packages/react-native/ReactCommon/react/renderer/graphics/RectangleCorners.h @@ -25,22 +25,20 @@ struct RectangleCorners { T bottomLeft{}; T bottomRight{}; - bool operator==(const RectangleCorners& rhs) const noexcept { - return std::tie( - this->topLeft, - this->topRight, - this->bottomLeft, - this->bottomRight) == + bool operator==(const RectangleCorners &rhs) const noexcept + { + return std::tie(this->topLeft, this->topRight, this->bottomLeft, this->bottomRight) == std::tie(rhs.topLeft, rhs.topRight, rhs.bottomLeft, rhs.bottomRight); } - bool operator!=(const RectangleCorners& rhs) const noexcept { + bool operator!=(const RectangleCorners &rhs) const noexcept + { return !(*this == rhs); } - bool isUniform() const noexcept { - return topLeft == topRight && topLeft == bottomLeft && - topLeft == bottomRight; + bool isUniform() const noexcept + { + return topLeft == topRight && topLeft == bottomLeft && topLeft == bottomRight; } }; @@ -55,13 +53,9 @@ namespace std { template struct hash> { - size_t operator()( - const facebook::react::RectangleCorners& corners) const noexcept { - return facebook::react::hash_combine( - corners.topLeft, - corners.bottomLeft, - corners.topRight, - corners.bottomRight); + size_t operator()(const facebook::react::RectangleCorners &corners) const noexcept + { + return facebook::react::hash_combine(corners.topLeft, corners.bottomLeft, corners.topRight, corners.bottomRight); } }; diff --git a/packages/react-native/ReactCommon/react/renderer/graphics/RectangleEdges.h b/packages/react-native/ReactCommon/react/renderer/graphics/RectangleEdges.h index 1f66bbc7662..a46eb1a0189 100644 --- a/packages/react-native/ReactCommon/react/renderer/graphics/RectangleEdges.h +++ b/packages/react-native/ReactCommon/react/renderer/graphics/RectangleEdges.h @@ -26,16 +26,19 @@ struct RectangleEdges { T right{}; T bottom{}; - bool operator==(const RectangleEdges& rhs) const noexcept { + bool operator==(const RectangleEdges &rhs) const noexcept + { return std::tie(this->left, this->top, this->right, this->bottom) == std::tie(rhs.left, rhs.top, rhs.right, rhs.bottom); } - bool operator!=(const RectangleEdges& rhs) const noexcept { + bool operator!=(const RectangleEdges &rhs) const noexcept + { return !(*this == rhs); } - bool isUniform() const noexcept { + bool isUniform() const noexcept + { return left == top && left == right && left == bottom; } @@ -46,25 +49,15 @@ template const RectangleEdges RectangleEdges::ZERO = {}; template -RectangleEdges operator+( - const RectangleEdges& lhs, - const RectangleEdges& rhs) noexcept { - return RectangleEdges{ - lhs.left + rhs.left, - lhs.top + rhs.top, - lhs.right + rhs.right, - lhs.bottom + rhs.bottom}; +RectangleEdges operator+(const RectangleEdges &lhs, const RectangleEdges &rhs) noexcept +{ + return RectangleEdges{lhs.left + rhs.left, lhs.top + rhs.top, lhs.right + rhs.right, lhs.bottom + rhs.bottom}; } template -RectangleEdges operator-( - const RectangleEdges& lhs, - const RectangleEdges& rhs) noexcept { - return RectangleEdges{ - lhs.left - rhs.left, - lhs.top - rhs.top, - lhs.right - rhs.right, - lhs.bottom - rhs.bottom}; +RectangleEdges operator-(const RectangleEdges &lhs, const RectangleEdges &rhs) noexcept +{ + return RectangleEdges{lhs.left - rhs.left, lhs.top - rhs.top, lhs.right - rhs.right, lhs.bottom - rhs.bottom}; } /* @@ -75,10 +68,10 @@ using EdgeInsets = RectangleEdges; /* * Adjusts a rectangle by the given edge insets. */ -inline Rect insetBy(const Rect& rect, const EdgeInsets& insets) noexcept { +inline Rect insetBy(const Rect &rect, const EdgeInsets &insets) noexcept +{ return Rect{ - .origin = - {.x = rect.origin.x + insets.left, .y = rect.origin.y + insets.top}, + .origin = {.x = rect.origin.x + insets.left, .y = rect.origin.y + insets.top}, .size = { .width = rect.size.width - insets.left - insets.right, .height = rect.size.height - insets.top - insets.bottom}}; @@ -87,10 +80,10 @@ inline Rect insetBy(const Rect& rect, const EdgeInsets& insets) noexcept { /* * Adjusts a rectangle by the given edge outsets. */ -inline Rect outsetBy(const Rect& rect, const EdgeInsets& outsets) noexcept { +inline Rect outsetBy(const Rect &rect, const EdgeInsets &outsets) noexcept +{ return Rect{ - .origin = - {.x = rect.origin.x - outsets.left, .y = rect.origin.y - outsets.top}, + .origin = {.x = rect.origin.x - outsets.left, .y = rect.origin.y - outsets.top}, .size = { .width = rect.size.width + outsets.left + outsets.right, .height = rect.size.height + outsets.top + outsets.bottom}}; @@ -102,10 +95,9 @@ namespace std { template struct hash> { - size_t operator()( - const facebook::react::RectangleEdges& edges) const noexcept { - return facebook::react::hash_combine( - edges.left, edges.right, edges.top, edges.bottom); + size_t operator()(const facebook::react::RectangleEdges &edges) const noexcept + { + return facebook::react::hash_combine(edges.left, edges.right, edges.top, edges.bottom); } }; diff --git a/packages/react-native/ReactCommon/react/renderer/graphics/Size.h b/packages/react-native/ReactCommon/react/renderer/graphics/Size.h index 490723cb4eb..7fef01f9ab7 100644 --- a/packages/react-native/ReactCommon/react/renderer/graphics/Size.h +++ b/packages/react-native/ReactCommon/react/renderer/graphics/Size.h @@ -22,24 +22,28 @@ struct Size { Float width{0}; Float height{0}; - Size& operator+=(const Point& point) noexcept { + Size &operator+=(const Point &point) noexcept + { width += point.x; height += point.y; return *this; } - Size& operator*=(const Point& point) noexcept { + Size &operator*=(const Point &point) noexcept + { width *= point.x; height *= point.y; return *this; } }; -inline bool operator==(const Size& rhs, const Size& lhs) noexcept { +inline bool operator==(const Size &rhs, const Size &lhs) noexcept +{ return std::tie(lhs.width, lhs.height) == std::tie(rhs.width, rhs.height); } -inline bool operator!=(const Size& rhs, const Size& lhs) noexcept { +inline bool operator!=(const Size &rhs, const Size &lhs) noexcept +{ return !(lhs == rhs); } @@ -49,7 +53,8 @@ namespace std { template <> struct hash { - size_t operator()(const facebook::react::Size& size) const { + size_t operator()(const facebook::react::Size &size) const + { return facebook::react::hash_combine(size.width, size.height); } }; diff --git a/packages/react-native/ReactCommon/react/renderer/graphics/Transform.cpp b/packages/react-native/ReactCommon/react/renderer/graphics/Transform.cpp index 9c7574c6bc7..024f15dfc8f 100644 --- a/packages/react-native/ReactCommon/react/renderer/graphics/Transform.cpp +++ b/packages/react-native/ReactCommon/react/renderer/graphics/Transform.cpp @@ -30,11 +30,12 @@ namespace facebook::react { /* static */ Transform Transform::Perspective(Float perspective) noexcept { auto transform = Transform{}; auto Zero = ValueUnit(0, UnitType::Point); - transform.operations.push_back(TransformOperation{ - .type = TransformOperationType::Perspective, - .x = ValueUnit(perspective, UnitType::Point), - .y = Zero, - .z = Zero}); + transform.operations.push_back( + TransformOperation{ + .type = TransformOperationType::Perspective, + .x = ValueUnit(perspective, UnitType::Point), + .y = Zero, + .z = Zero}); transform.matrix[11] = -1 / perspective; return transform; } @@ -45,11 +46,12 @@ namespace facebook::react { Float yprime = isZero(y) ? 0 : y; Float zprime = isZero(z) ? 0 : z; if (xprime != 1 || yprime != 1 || zprime != 1) { - transform.operations.push_back(TransformOperation{ - .type = TransformOperationType::Scale, - .x = ValueUnit(xprime, UnitType::Point), - .y = ValueUnit(yprime, UnitType::Point), - .z = ValueUnit(zprime, UnitType::Point)}); + transform.operations.push_back( + TransformOperation{ + .type = TransformOperationType::Scale, + .x = ValueUnit(xprime, UnitType::Point), + .y = ValueUnit(yprime, UnitType::Point), + .z = ValueUnit(zprime, UnitType::Point)}); transform.matrix[0] = xprime; transform.matrix[5] = yprime; transform.matrix[10] = zprime; @@ -64,11 +66,12 @@ Transform::Translate(Float x, Float y, Float z) noexcept { Float yprime = isZero(y) ? 0 : y; Float zprime = isZero(z) ? 0 : z; if (xprime != 0 || yprime != 0 || zprime != 0) { - transform.operations.push_back(TransformOperation{ - .type = TransformOperationType::Translate, - .x = ValueUnit(xprime, UnitType::Point), - .y = ValueUnit(yprime, UnitType::Point), - .z = ValueUnit(zprime, UnitType::Point)}); + transform.operations.push_back( + TransformOperation{ + .type = TransformOperationType::Translate, + .x = ValueUnit(xprime, UnitType::Point), + .y = ValueUnit(yprime, UnitType::Point), + .z = ValueUnit(zprime, UnitType::Point)}); transform.matrix[12] = xprime; transform.matrix[13] = yprime; transform.matrix[14] = zprime; @@ -80,11 +83,12 @@ Transform::Translate(Float x, Float y, Float z) noexcept { auto transform = Transform{}; Float xprime = isZero(x) ? 0 : x; Float yprime = isZero(y) ? 0 : y; - transform.operations.push_back(TransformOperation{ - .type = TransformOperationType::Skew, - .x = ValueUnit(xprime, UnitType::Point), - .y = ValueUnit(yprime, UnitType::Point), - .z = ValueUnit(0, UnitType::Point)}); + transform.operations.push_back( + TransformOperation{ + .type = TransformOperationType::Skew, + .x = ValueUnit(xprime, UnitType::Point), + .y = ValueUnit(yprime, UnitType::Point), + .z = ValueUnit(0, UnitType::Point)}); transform.matrix[4] = std::tan(xprime); transform.matrix[1] = std::tan(yprime); return transform; @@ -94,11 +98,12 @@ Transform::Translate(Float x, Float y, Float z) noexcept { auto transform = Transform{}; if (!isZero(radians)) { auto Zero = ValueUnit(0, UnitType::Point); - transform.operations.push_back(TransformOperation{ - .type = TransformOperationType::Rotate, - .x = ValueUnit(radians, UnitType::Point), - .y = Zero, - .z = Zero}); + transform.operations.push_back( + TransformOperation{ + .type = TransformOperationType::Rotate, + .x = ValueUnit(radians, UnitType::Point), + .y = Zero, + .z = Zero}); transform.matrix[5] = std::cos(radians); transform.matrix[6] = std::sin(radians); transform.matrix[9] = -std::sin(radians); @@ -111,11 +116,12 @@ Transform::Translate(Float x, Float y, Float z) noexcept { auto transform = Transform{}; if (!isZero(radians)) { auto Zero = ValueUnit(0, UnitType::Point); - transform.operations.push_back(TransformOperation{ - .type = TransformOperationType::Rotate, - .x = Zero, - .y = ValueUnit(radians, UnitType::Point), - .z = Zero}); + transform.operations.push_back( + TransformOperation{ + .type = TransformOperationType::Rotate, + .x = Zero, + .y = ValueUnit(radians, UnitType::Point), + .z = Zero}); transform.matrix[0] = std::cos(radians); transform.matrix[2] = -std::sin(radians); transform.matrix[8] = std::sin(radians); @@ -128,11 +134,12 @@ Transform::Translate(Float x, Float y, Float z) noexcept { auto transform = Transform{}; if (!isZero(radians)) { auto Zero = ValueUnit(0, UnitType::Point); - transform.operations.push_back(TransformOperation{ - .type = TransformOperationType::Rotate, - .x = Zero, - .y = Zero, - .z = ValueUnit(radians, UnitType::Point)}); + transform.operations.push_back( + TransformOperation{ + .type = TransformOperationType::Rotate, + .x = Zero, + .y = Zero, + .z = ValueUnit(radians, UnitType::Point)}); transform.matrix[0] = std::cos(radians); transform.matrix[1] = std::sin(radians); transform.matrix[4] = -std::sin(radians); diff --git a/packages/react-native/ReactCommon/react/renderer/graphics/Transform.h b/packages/react-native/ReactCommon/react/renderer/graphics/Transform.h index 438da9020dd..7ee8aab1459 100644 --- a/packages/react-native/ReactCommon/react/renderer/graphics/Transform.h +++ b/packages/react-native/ReactCommon/react/renderer/graphics/Transform.h @@ -25,7 +25,8 @@ namespace facebook::react { -inline bool isZero(Float n) { +inline bool isZero(Float n) +{ // We use this ternary expression instead of abs, fabsf, etc, because // Float can be double or float depending on compilation target. return (n < 0 ? n * (-1) : n) < 0.00001; @@ -36,46 +37,40 @@ inline bool isZero(Float n) { * An "Arbitrary" operation means that the transform was seeded with some * arbitrary initial result. */ -enum class TransformOperationType : uint8_t { - Arbitrary, - Identity, - Perspective, - Scale, - Translate, - Rotate, - Skew -}; +enum class TransformOperationType : uint8_t { Arbitrary, Identity, Perspective, Scale, Translate, Rotate, Skew }; struct TransformOperation { TransformOperationType type; ValueUnit x; ValueUnit y; ValueUnit z; - bool operator==(const TransformOperation& other) const = default; + bool operator==(const TransformOperation &other) const = default; }; struct TransformOrigin { - std::array xy = { - ValueUnit(0.0f, UnitType::Undefined), - ValueUnit(0.0f, UnitType::Undefined)}; + std::array xy = {ValueUnit(0.0f, UnitType::Undefined), ValueUnit(0.0f, UnitType::Undefined)}; float z = 0.0f; - bool operator==(const TransformOrigin& other) const { + bool operator==(const TransformOrigin &other) const + { return xy[0] == other.xy[0] && xy[1] == other.xy[1] && z == other.z; } - bool operator!=(const TransformOrigin& other) const { + bool operator!=(const TransformOrigin &other) const + { return !(*this == other); } - bool isSet() const { - return xy[0].value != 0.0f || xy[0].unit != UnitType::Undefined || - xy[1].value != 0.0f || xy[1].unit != UnitType::Undefined || z != 0.0f; + bool isSet() const + { + return xy[0].value != 0.0f || xy[0].unit != UnitType::Undefined || xy[1].value != 0.0f || + xy[1].unit != UnitType::Undefined || z != 0.0f; } #ifdef RN_SERIALIZABLE_STATE /** * Convert to folly::dynamic. */ - operator folly::dynamic() const { + operator folly::dynamic() const + { return folly::dynamic::array(xy[0].toDynamic(), xy[1].toDynamic(), z); } @@ -88,18 +83,16 @@ struct TransformOrigin { struct Transform { std::vector operations{}; - std::array matrix{ - {1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1}}; + std::array matrix{{1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1}}; /* * Given a TransformOperation, return the proper transform. */ static Transform FromTransformOperation( TransformOperation transformOperation, - const Size& size, - const Transform& transform = Transform::Identity()); - static TransformOperation DefaultTransformOperation( - TransformOperationType type); + const Size &size, + const Transform &transform = Transform::Identity()); + static TransformOperation DefaultTransformOperation(TransformOperationType type); /* * Returns the identity transform (`[1 0 0 0; 0 1 0 0; 0 0 1 0; 0 0 0 1]`). @@ -157,39 +150,36 @@ struct Transform { * @param rhs end of the interpolation * @return the Transformation */ - static Transform Interpolate( - Float animationProgress, - const Transform& lhs, - const Transform& rhs, - const Size& size); + static Transform Interpolate(Float animationProgress, const Transform &lhs, const Transform &rhs, const Size &size); - static bool isVerticalInversion(const Transform& transform) noexcept; - static bool isHorizontalInversion(const Transform& transform) noexcept; + static bool isVerticalInversion(const Transform &transform) noexcept; + static bool isHorizontalInversion(const Transform &transform) noexcept; /* * Equality operators. */ - bool operator==(const Transform& rhs) const noexcept; - bool operator!=(const Transform& rhs) const noexcept; + bool operator==(const Transform &rhs) const noexcept; + bool operator!=(const Transform &rhs) const noexcept; /* * Matrix subscript. */ - Float& at(int i, int j) noexcept; - const Float& at(int i, int j) const noexcept; + Float &at(int i, int j) noexcept; + const Float &at(int i, int j) const noexcept; /* * Concatenates (multiplies) transform matrices. */ - Transform operator*(const Transform& rhs) const; + Transform operator*(const Transform &rhs) const; - Rect applyWithCenter(const Rect& rect, const Point& center) const; + Rect applyWithCenter(const Rect &rect, const Point ¢er) const; /** * Convert to folly::dynamic. */ #ifdef ANDROID - operator folly::dynamic() const { + operator folly::dynamic() const + { return folly::dynamic::array( matrix[0], matrix[1], @@ -214,26 +204,26 @@ struct Transform { /* * Applies transformation to the given point. */ -Point operator*(const Point& point, const Transform& transform); +Point operator*(const Point &point, const Transform &transform); /* * Applies transformation to the given size. */ -Size operator*(const Size& size, const Transform& transform); +Size operator*(const Size &size, const Transform &transform); /* * Applies transformation to the given rect. * ONLY SUPPORTS scale and translation transformation. */ -Rect operator*(const Rect& rect, const Transform& transform); +Rect operator*(const Rect &rect, const Transform &transform); /* * Applies transformation to the given EdgeInsets. * ONLY SUPPORTS scale transformation. */ -EdgeInsets operator*(const EdgeInsets& edgeInsets, const Transform& transform); +EdgeInsets operator*(const EdgeInsets &edgeInsets, const Transform &transform); -Vector operator*(const Transform& transform, const Vector& vector); +Vector operator*(const Transform &transform, const Vector &vector); } // namespace facebook::react @@ -241,7 +231,8 @@ namespace std { template <> struct hash { - size_t operator()(const facebook::react::Transform& transform) const { + size_t operator()(const facebook::react::Transform &transform) const + { return facebook::react::hash_combine( transform.matrix[0], transform.matrix[1], diff --git a/packages/react-native/ReactCommon/react/renderer/graphics/ValueUnit.h b/packages/react-native/ReactCommon/react/renderer/graphics/ValueUnit.h index a7d68fc18ce..f8f2fd420eb 100644 --- a/packages/react-native/ReactCommon/react/renderer/graphics/ValueUnit.h +++ b/packages/react-native/ReactCommon/react/renderer/graphics/ValueUnit.h @@ -29,15 +29,18 @@ struct ValueUnit { ValueUnit() = default; ValueUnit(float v, UnitType u) : value(v), unit(u) {} - bool operator==(const ValueUnit& other) const { + bool operator==(const ValueUnit &other) const + { return value == other.value && unit == other.unit; } - bool operator!=(const ValueUnit& other) const { + bool operator!=(const ValueUnit &other) const + { return !(*this == other); } - constexpr float resolve(float referenceLength) const { + constexpr float resolve(float referenceLength) const + { switch (unit) { case UnitType::Point: return value; @@ -49,7 +52,8 @@ struct ValueUnit { } } - constexpr operator bool() const { + constexpr operator bool() const + { return unit != UnitType::Undefined; } diff --git a/packages/react-native/ReactCommon/react/renderer/graphics/fromRawValueShared.h b/packages/react-native/ReactCommon/react/renderer/graphics/fromRawValueShared.h index 87b8fcab8c6..e6090083010 100644 --- a/packages/react-native/ReactCommon/react/renderer/graphics/fromRawValueShared.h +++ b/packages/react-native/ReactCommon/react/renderer/graphics/fromRawValueShared.h @@ -13,15 +13,15 @@ #pragma once namespace facebook::react { -using parsePlatformColorFn = - SharedColor (*)(const ContextContainer&, int32_t, const RawValue&); +using parsePlatformColorFn = SharedColor (*)(const ContextContainer &, int32_t, const RawValue &); inline void fromRawValueShared( - const ContextContainer& contextContainer, + const ContextContainer &contextContainer, int32_t surfaceId, - const RawValue& value, - SharedColor& result, - parsePlatformColorFn parsePlatformColor) { + const RawValue &value, + SharedColor &result, + parsePlatformColorFn parsePlatformColor) +{ ColorComponents colorComponents = {0, 0, 0, 0}; if (value.hasType()) { @@ -45,7 +45,7 @@ inline void fromRawValueShared( result = colorFromComponents(colorComponents); } else { if (value.hasType>()) { - const auto& items = (std::unordered_map)value; + const auto &items = (std::unordered_map)value; if (items.find("space") != items.end()) { colorComponents.red = (float)items.at("r"); colorComponents.green = (float)items.at("g"); diff --git a/packages/react-native/ReactCommon/react/renderer/graphics/platform/android/react/renderer/graphics/HostPlatformColor.h b/packages/react-native/ReactCommon/react/renderer/graphics/platform/android/react/renderer/graphics/HostPlatformColor.h index 9752be6b7f0..bfbefc3832a 100644 --- a/packages/react-native/ReactCommon/react/renderer/graphics/platform/android/react/renderer/graphics/HostPlatformColor.h +++ b/packages/react-native/ReactCommon/react/renderer/graphics/platform/android/react/renderer/graphics/HostPlatformColor.h @@ -18,20 +18,20 @@ namespace HostPlatformColor { constexpr facebook::react::Color UndefinedColor = 0; } -inline Color -hostPlatformColorFromRGBA(uint8_t r, uint8_t g, uint8_t b, uint8_t a) { +inline Color hostPlatformColorFromRGBA(uint8_t r, uint8_t g, uint8_t b, uint8_t a) +{ return (a & 0xff) << 24 | (r & 0xff) << 16 | (g & 0xff) << 8 | (b & 0xff); } -inline Color hostPlatformColorFromComponents(ColorComponents components) { +inline Color hostPlatformColorFromComponents(ColorComponents components) +{ float ratio = 255; - return ((int)round(components.alpha * ratio) & 0xff) << 24 | - ((int)round(components.red * ratio) & 0xff) << 16 | - ((int)round(components.green * ratio) & 0xff) << 8 | - ((int)round(components.blue * ratio) & 0xff); + return ((int)round(components.alpha * ratio) & 0xff) << 24 | ((int)round(components.red * ratio) & 0xff) << 16 | + ((int)round(components.green * ratio) & 0xff) << 8 | ((int)round(components.blue * ratio) & 0xff); } -inline ColorComponents colorComponentsFromHostPlatformColor(Color color) { +inline ColorComponents colorComponentsFromHostPlatformColor(Color color) +{ float ratio = 255; return ColorComponents{ .red = (float)((color >> 16) & 0xff) / ratio, @@ -40,23 +40,28 @@ inline ColorComponents colorComponentsFromHostPlatformColor(Color color) { .alpha = (float)((color >> 24) & 0xff) / ratio}; } -inline float alphaFromHostPlatformColor(Color color) { +inline float alphaFromHostPlatformColor(Color color) +{ return static_cast((color >> 24) & 0xff); } -inline float redFromHostPlatformColor(Color color) { +inline float redFromHostPlatformColor(Color color) +{ return static_cast((color >> 16) & 0xff); } -inline float greenFromHostPlatformColor(Color color) { +inline float greenFromHostPlatformColor(Color color) +{ return static_cast((color >> 8) & 0xff); } -inline float blueFromHostPlatformColor(Color color) { +inline float blueFromHostPlatformColor(Color color) +{ return static_cast((color >> 0) & 0xff); } -inline bool hostPlatformColorIsColorMeaningful(Color color) noexcept { +inline bool hostPlatformColorIsColorMeaningful(Color color) noexcept +{ return alphaFromHostPlatformColor(color) > 0; } diff --git a/packages/react-native/ReactCommon/react/renderer/graphics/platform/android/react/renderer/graphics/PlatformColorParser.h b/packages/react-native/ReactCommon/react/renderer/graphics/platform/android/react/renderer/graphics/PlatformColorParser.h index 23f24ac2405..b27e586e790 100644 --- a/packages/react-native/ReactCommon/react/renderer/graphics/platform/android/react/renderer/graphics/PlatformColorParser.h +++ b/packages/react-native/ReactCommon/react/renderer/graphics/platform/android/react/renderer/graphics/PlatformColorParser.h @@ -23,26 +23,22 @@ namespace facebook::react { -inline size_t hashGetColourArguments( - int32_t surfaceId, - const std::vector& resourcePaths) { +inline size_t hashGetColourArguments(int32_t surfaceId, const std::vector &resourcePaths) +{ size_t seed = std::hash{}(surfaceId); - for (const auto& path : resourcePaths) { - seed ^= - std::hash{}(path) + 0x9e3779b9 + (seed << 6) + (seed >> 2); + for (const auto &path : resourcePaths) { + seed ^= std::hash{}(path) + 0x9e3779b9 + (seed << 6) + (seed >> 2); } return seed; } -inline SharedColor parsePlatformColor( - const ContextContainer& contextContainer, - int32_t surfaceId, - const RawValue& value) { +inline SharedColor +parsePlatformColor(const ContextContainer &contextContainer, int32_t surfaceId, const RawValue &value) +{ Color color = 0; - if (value.hasType< - std::unordered_map>>()) { + if (value.hasType>>()) { auto map = (std::unordered_map>)value; - auto& resourcePaths = map["resource_paths"]; + auto &resourcePaths = map["resource_paths"]; // JNI calls are time consuming. Let's cache results here to avoid // unnecessary calls. @@ -51,13 +47,10 @@ inline SharedColor parsePlatformColor( // Listen for appearance changes, which should invalidate the cache static std::once_flag setupCacheInvalidation; - std::call_once( - setupCacheInvalidation, - configurePlatformColorCacheInvalidationHook, - [&] { - std::scoped_lock lock(getColorCacheMutex); - getColorCache.clear(); - }); + std::call_once(setupCacheInvalidation, configurePlatformColorCacheInvalidationHook, [&] { + std::scoped_lock lock(getColorCacheMutex); + getColorCache.clear(); + }); auto hash = hashGetColourArguments(surfaceId, resourcePaths); { @@ -66,21 +59,15 @@ inline SharedColor parsePlatformColor( if (iterator != getColorCache.end()) { color = iterator->second; } else { - const auto& fabricUIManager = - contextContainer.at>("FabricUIManager"); + const auto &fabricUIManager = contextContainer.at>("FabricUIManager"); static auto getColorFromJava = - fabricUIManager->getClass() - ->getMethod)>( - "getColor"); - auto javaResourcePaths = - jni::JArrayClass::newArray(resourcePaths.size()); + fabricUIManager->getClass()->getMethod)>("getColor"); + auto javaResourcePaths = jni::JArrayClass::newArray(resourcePaths.size()); for (int i = 0; i < resourcePaths.size(); i++) { - javaResourcePaths->setElement( - i, *jni::make_jstring(resourcePaths[i])); + javaResourcePaths->setElement(i, *jni::make_jstring(resourcePaths[i])); } - color = - getColorFromJava(fabricUIManager, surfaceId, *javaResourcePaths); + color = getColorFromJava(fabricUIManager, surfaceId, *javaResourcePaths); getColorCache.set(hash, color); } } @@ -89,13 +76,10 @@ inline SharedColor parsePlatformColor( return color; } -inline void fromRawValue( - const ContextContainer& contextContainer, - int32_t surfaceId, - const RawValue& value, - SharedColor& result) { - fromRawValueShared( - contextContainer, surfaceId, value, result, parsePlatformColor); +inline void +fromRawValue(const ContextContainer &contextContainer, int32_t surfaceId, const RawValue &value, SharedColor &result) +{ + fromRawValueShared(contextContainer, surfaceId, value, result, parsePlatformColor); } } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/graphics/platform/android/react/renderer/graphics/configurePlatformColorCacheInvalidationHook.h b/packages/react-native/ReactCommon/react/renderer/graphics/platform/android/react/renderer/graphics/configurePlatformColorCacheInvalidationHook.h index 4947fe896aa..0ae822a1f39 100644 --- a/packages/react-native/ReactCommon/react/renderer/graphics/platform/android/react/renderer/graphics/configurePlatformColorCacheInvalidationHook.h +++ b/packages/react-native/ReactCommon/react/renderer/graphics/platform/android/react/renderer/graphics/configurePlatformColorCacheInvalidationHook.h @@ -8,5 +8,5 @@ #include namespace facebook::react { -void configurePlatformColorCacheInvalidationHook(std::function&& hook); +void configurePlatformColorCacheInvalidationHook(std::function &&hook); } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/graphics/platform/cxx/react/renderer/graphics/HostPlatformColor.h b/packages/react-native/ReactCommon/react/renderer/graphics/platform/cxx/react/renderer/graphics/HostPlatformColor.h index 1a88db1c7f2..a1354036342 100644 --- a/packages/react-native/ReactCommon/react/renderer/graphics/platform/cxx/react/renderer/graphics/HostPlatformColor.h +++ b/packages/react-native/ReactCommon/react/renderer/graphics/platform/cxx/react/renderer/graphics/HostPlatformColor.h @@ -19,12 +19,13 @@ namespace HostPlatformColor { constexpr facebook::react::Color UndefinedColor = 0; } -inline Color -hostPlatformColorFromRGBA(uint8_t r, uint8_t g, uint8_t b, uint8_t a) { +inline Color hostPlatformColorFromRGBA(uint8_t r, uint8_t g, uint8_t b, uint8_t a) +{ return (a & 0xff) << 24 | (r & 0xff) << 16 | (g & 0xff) << 8 | (b & 0xff); } -inline Color hostPlatformColorFromComponents(ColorComponents components) { +inline Color hostPlatformColorFromComponents(ColorComponents components) +{ float ratio = 255; return hostPlatformColorFromRGBA( static_cast(std::round(components.red * ratio)), @@ -33,27 +34,33 @@ inline Color hostPlatformColorFromComponents(ColorComponents components) { static_cast(std::round(components.alpha * ratio))); } -inline float alphaFromHostPlatformColor(Color color) { +inline float alphaFromHostPlatformColor(Color color) +{ return static_cast((color >> 24) & 0xff); } -inline float redFromHostPlatformColor(Color color) { +inline float redFromHostPlatformColor(Color color) +{ return static_cast((color >> 16) & 0xff); } -inline float greenFromHostPlatformColor(Color color) { +inline float greenFromHostPlatformColor(Color color) +{ return static_cast((color >> 8) & 0xff); } -inline float blueFromHostPlatformColor(Color color) { +inline float blueFromHostPlatformColor(Color color) +{ return static_cast((color >> 0) & 0xff); } -inline bool hostPlatformColorIsColorMeaningful(Color color) noexcept { +inline bool hostPlatformColorIsColorMeaningful(Color color) noexcept +{ return alphaFromHostPlatformColor(color) > 0; } -inline ColorComponents colorComponentsFromHostPlatformColor(Color color) { +inline ColorComponents colorComponentsFromHostPlatformColor(Color color) +{ float ratio = 255; return ColorComponents{ .red = static_cast(redFromHostPlatformColor(color)) / ratio, diff --git a/packages/react-native/ReactCommon/react/renderer/graphics/platform/cxx/react/renderer/graphics/PlatformColorParser.h b/packages/react-native/ReactCommon/react/renderer/graphics/platform/cxx/react/renderer/graphics/PlatformColorParser.h index 0526f892f48..3a0e863fda0 100644 --- a/packages/react-native/ReactCommon/react/renderer/graphics/platform/cxx/react/renderer/graphics/PlatformColorParser.h +++ b/packages/react-native/ReactCommon/react/renderer/graphics/platform/cxx/react/renderer/graphics/PlatformColorParser.h @@ -15,10 +15,9 @@ namespace facebook::react { -inline SharedColor parsePlatformColor( - const ContextContainer& /*contextContainer*/, - int32_t /*surfaceId*/, - const RawValue& /*value*/) { +inline SharedColor +parsePlatformColor(const ContextContainer & /*contextContainer*/, int32_t /*surfaceId*/, const RawValue & /*value*/) +{ float alpha = 0; float red = 0; float green = 0; @@ -27,13 +26,10 @@ inline SharedColor parsePlatformColor( return {colorFromComponents({red, green, blue, alpha})}; } -inline void fromRawValue( - const ContextContainer& contextContainer, - int32_t surfaceId, - const RawValue& value, - SharedColor& result) { - fromRawValueShared( - contextContainer, surfaceId, value, result, parsePlatformColor); +inline void +fromRawValue(const ContextContainer &contextContainer, int32_t surfaceId, const RawValue &value, SharedColor &result) +{ + fromRawValueShared(contextContainer, surfaceId, value, result, parsePlatformColor); } } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/graphics/platform/ios/react/renderer/graphics/HostPlatformColor.h b/packages/react-native/ReactCommon/react/renderer/graphics/platform/ios/react/renderer/graphics/HostPlatformColor.h index 1979a74ed56..b9535f14e36 100644 --- a/packages/react-native/ReactCommon/react/renderer/graphics/platform/ios/react/renderer/graphics/HostPlatformColor.h +++ b/packages/react-native/ReactCommon/react/renderer/graphics/platform/ios/react/renderer/graphics/HostPlatformColor.h @@ -22,21 +22,23 @@ struct DynamicColor { struct Color { Color(int32_t color); - Color(const DynamicColor& dynamicColor); - Color(const ColorComponents& components); - Color() : uiColor_(nullptr){}; + Color(const DynamicColor &dynamicColor); + Color(const ColorComponents &components); + Color() : uiColor_(nullptr) {}; int32_t getColor() const; std::size_t getUIColorHash() const; - static Color createSemanticColor(std::vector& semanticItems); + static Color createSemanticColor(std::vector &semanticItems); - std::shared_ptr getUIColor() const { + std::shared_ptr getUIColor() const + { return uiColor_; } float getChannel(int channelId) const; - ColorComponents getColorComponents() const { + ColorComponents getColorComponents() const + { float ratio = 255; int32_t primitiveColor = getColor(); return ColorComponents{ @@ -45,9 +47,10 @@ struct Color { .blue = (float)((primitiveColor >> 0) & 0xff) / ratio, .alpha = (float)((primitiveColor >> 24) & 0xff) / ratio}; } - bool operator==(const Color& other) const; - bool operator!=(const Color& other) const; - operator int32_t() const { + bool operator==(const Color &other) const; + bool operator!=(const Color &other) const; + operator int32_t() const + { return getColor(); } @@ -68,8 +71,8 @@ namespace HostPlatformColor { NO_DESTROY static const facebook::react::Color UndefinedColor = Color(); } // namespace HostPlatformColor -inline Color -hostPlatformColorFromRGBA(uint8_t r, uint8_t g, uint8_t b, uint8_t a) { +inline Color hostPlatformColorFromRGBA(uint8_t r, uint8_t g, uint8_t b, uint8_t a) +{ float ratio = 255; const auto colorComponents = ColorComponents{ .red = r / ratio, @@ -80,31 +83,38 @@ hostPlatformColorFromRGBA(uint8_t r, uint8_t g, uint8_t b, uint8_t a) { return Color(colorComponents); } -inline Color hostPlatformColorFromComponents(ColorComponents components) { +inline Color hostPlatformColorFromComponents(ColorComponents components) +{ return Color(components); } -inline ColorComponents colorComponentsFromHostPlatformColor(Color color) { +inline ColorComponents colorComponentsFromHostPlatformColor(Color color) +{ return color.getColorComponents(); } -inline float alphaFromHostPlatformColor(Color color) { +inline float alphaFromHostPlatformColor(Color color) +{ return color.getChannel(3) * 255; } -inline float redFromHostPlatformColor(Color color) { +inline float redFromHostPlatformColor(Color color) +{ return color.getChannel(0) * 255; } -inline float greenFromHostPlatformColor(Color color) { +inline float greenFromHostPlatformColor(Color color) +{ return color.getChannel(1) * 255; } -inline float blueFromHostPlatformColor(Color color) { +inline float blueFromHostPlatformColor(Color color) +{ return color.getChannel(2) * 255; } -inline bool hostPlatformColorIsColorMeaningful(Color color) noexcept { +inline bool hostPlatformColorIsColorMeaningful(Color color) noexcept +{ return alphaFromHostPlatformColor(color) > 0; } @@ -112,7 +122,8 @@ inline bool hostPlatformColorIsColorMeaningful(Color color) noexcept { template <> struct std::hash { - size_t operator()(const facebook::react::Color& color) const { + size_t operator()(const facebook::react::Color &color) const + { return color.getUIColorHash(); } }; diff --git a/packages/react-native/ReactCommon/react/renderer/graphics/platform/ios/react/renderer/graphics/PlatformColorParser.h b/packages/react-native/ReactCommon/react/renderer/graphics/platform/ios/react/renderer/graphics/PlatformColorParser.h index 30ecd79ba1e..3ff2aa38cfd 100644 --- a/packages/react-native/ReactCommon/react/renderer/graphics/platform/ios/react/renderer/graphics/PlatformColorParser.h +++ b/packages/react-native/ReactCommon/react/renderer/graphics/platform/ios/react/renderer/graphics/PlatformColorParser.h @@ -15,18 +15,12 @@ namespace facebook::react { -SharedColor parsePlatformColor( - const ContextContainer& contextContainer, - int32_t surfaceId, - const RawValue& value); +SharedColor parsePlatformColor(const ContextContainer &contextContainer, int32_t surfaceId, const RawValue &value); -inline void fromRawValue( - const ContextContainer& contextContainer, - int32_t surfaceId, - const RawValue& value, - SharedColor& result) { - fromRawValueShared( - contextContainer, surfaceId, value, result, parsePlatformColor); +inline void +fromRawValue(const ContextContainer &contextContainer, int32_t surfaceId, const RawValue &value, SharedColor &result) +{ + fromRawValueShared(contextContainer, surfaceId, value, result, parsePlatformColor); } } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/graphics/platform/ios/react/renderer/graphics/PlatformColorParser.mm b/packages/react-native/ReactCommon/react/renderer/graphics/platform/ios/react/renderer/graphics/PlatformColorParser.mm index 8ba3ec59329..377783f0f19 100644 --- a/packages/react-native/ReactCommon/react/renderer/graphics/platform/ios/react/renderer/graphics/PlatformColorParser.mm +++ b/packages/react-native/ReactCommon/react/renderer/graphics/platform/ios/react/renderer/graphics/PlatformColorParser.mm @@ -42,11 +42,12 @@ inline facebook::react::SharedColor RCTPlatformColorComponentsFromDynamicItems( fromRawValue(contextContainer, surfaceId, dynamicItems.at("highContrastDark"), highContrastDarkSharedColor); } - Color color = Color(DynamicColor{ - .lightColor = (*lightSharedColor).getColor(), - .darkColor = (*darkSharedColor).getColor(), - .highContrastLightColor = (*highContrastLightSharedColor).getColor(), - .highContrastDarkColor = (*highContrastDarkSharedColor).getColor()}); + Color color = Color( + DynamicColor{ + .lightColor = (*lightSharedColor).getColor(), + .darkColor = (*darkSharedColor).getColor(), + .highContrastLightColor = (*highContrastLightSharedColor).getColor(), + .highContrastDarkColor = (*highContrastDarkSharedColor).getColor()}); return SharedColor(color); } diff --git a/packages/react-native/ReactCommon/react/renderer/graphics/platform/ios/react/renderer/graphics/RCTPlatformColorUtils.h b/packages/react-native/ReactCommon/react/renderer/graphics/platform/ios/react/renderer/graphics/RCTPlatformColorUtils.h index e47c504548c..f487564c043 100644 --- a/packages/react-native/ReactCommon/react/renderer/graphics/platform/ios/react/renderer/graphics/RCTPlatformColorUtils.h +++ b/packages/react-native/ReactCommon/react/renderer/graphics/platform/ios/react/renderer/graphics/RCTPlatformColorUtils.h @@ -15,8 +15,6 @@ struct ColorComponents; struct Color; } // namespace facebook::react -facebook::react::ColorComponents RCTPlatformColorComponentsFromSemanticItems( - std::vector& semanticItems); -UIColor* RCTPlatformColorFromSemanticItems( - std::vector& semanticItems); -UIColor* RCTPlatformColorFromColor(const facebook::react::Color& color); +facebook::react::ColorComponents RCTPlatformColorComponentsFromSemanticItems(std::vector &semanticItems); +UIColor *RCTPlatformColorFromSemanticItems(std::vector &semanticItems); +UIColor *RCTPlatformColorFromColor(const facebook::react::Color &color); diff --git a/packages/react-native/ReactCommon/react/renderer/graphics/platform/ios/react/renderer/graphics/RCTPlatformColorUtils.mm b/packages/react-native/ReactCommon/react/renderer/graphics/platform/ios/react/renderer/graphics/RCTPlatformColorUtils.mm index ac83e924565..4a0a53e2b50 100644 --- a/packages/react-native/ReactCommon/react/renderer/graphics/platform/ios/react/renderer/graphics/RCTPlatformColorUtils.mm +++ b/packages/react-native/ReactCommon/react/renderer/graphics/platform/ios/react/renderer/graphics/RCTPlatformColorUtils.mm @@ -163,7 +163,7 @@ static UIColor *_Nullable _UIColorFromSemanticString(NSString *semanticString) } else { Class uiColorClass = [UIColor class]; IMP imp = [uiColorClass methodForSelector:objcColorSelector]; - id (*getUIColor)(id, SEL) = ((id(*)(id, SEL))imp); + id (*getUIColor)(id, SEL) = ((id (*)(id, SEL))imp); id colorObject = getUIColor(uiColorClass, objcColorSelector); if ([colorObject isKindOfClass:[UIColor class]]) { return colorObject; diff --git a/packages/react-native/ReactCommon/react/renderer/graphics/rounding.h b/packages/react-native/ReactCommon/react/renderer/graphics/rounding.h index 09c05339c59..be34277849f 100644 --- a/packages/react-native/ReactCommon/react/renderer/graphics/rounding.h +++ b/packages/react-native/ReactCommon/react/renderer/graphics/rounding.h @@ -23,60 +23,70 @@ namespace facebook::react { * auto crispSize = roundToPixel<&std::ceil>(size, scaleFactor); */ template -Float roundToPixel(Float value, Float scaleFactor) { +Float roundToPixel(Float value, Float scaleFactor) +{ return RoundingFunction(value * scaleFactor) / scaleFactor; } template -Point roundToPixel(Point value, Float scaleFactor) { +Point roundToPixel(Point value, Float scaleFactor) +{ return Point{ - roundToPixel(value.x, scaleFactor), - roundToPixel(value.y, scaleFactor)}; + roundToPixel(value.x, scaleFactor), roundToPixel(value.y, scaleFactor)}; } template -Size roundToPixel(Size value, Float scaleFactor) { +Size roundToPixel(Size value, Float scaleFactor) +{ return Size{ roundToPixel(value.width, scaleFactor), roundToPixel(value.height, scaleFactor)}; } template -Rect roundToPixel(Rect value, Float scaleFactor) { - return Rect{ - roundToPixel(value.origin), - roundToPixel(value.size)}; +Rect roundToPixel(Rect value, Float scaleFactor) +{ + return Rect{roundToPixel(value.origin), roundToPixel(value.size)}; } /* * GCC-based Android NDK does not have rounding functions as part of STL. */ -inline float round(float value) noexcept { +inline float round(float value) noexcept +{ return ::roundf(value); } -inline double round(double value) noexcept { +inline double round(double value) noexcept +{ return ::round(value); } -inline long double round(long double value) noexcept { +inline long double round(long double value) noexcept +{ return ::roundl(value); } -inline float ceil(float value) noexcept { +inline float ceil(float value) noexcept +{ return ::ceilf(value); } -inline double ceil(double value) noexcept { +inline double ceil(double value) noexcept +{ return ::ceil(value); } -inline long double ceil(long double value) noexcept { +inline long double ceil(long double value) noexcept +{ return ::ceill(value); } -inline float floor(float value) noexcept { +inline float floor(float value) noexcept +{ return ::floorf(value); } -inline double floor(double value) noexcept { +inline double floor(double value) noexcept +{ return ::floor(value); } -inline long double floor(long double value) noexcept { +inline long double floor(long double value) noexcept +{ return ::floorl(value); } diff --git a/packages/react-native/ReactCommon/react/renderer/imagemanager/ImageManager.h b/packages/react-native/ReactCommon/react/renderer/imagemanager/ImageManager.h index c8f7629292f..61c90c4efd3 100644 --- a/packages/react-native/ReactCommon/react/renderer/imagemanager/ImageManager.h +++ b/packages/react-native/ReactCommon/react/renderer/imagemanager/ImageManager.h @@ -19,9 +19,7 @@ namespace facebook::react { class ImageManager; -using SharedImageManager - [[deprecated("Use std::shared_ptr instead.")]] = - std::shared_ptr; +using SharedImageManager [[deprecated("Use std::shared_ptr instead.")]] = std::shared_ptr; /* * Cross platform facade for image management (e.g. iOS-specific @@ -29,17 +27,17 @@ using SharedImageManager */ class ImageManager { public: - ImageManager(const std::shared_ptr& contextContainer); + ImageManager(const std::shared_ptr &contextContainer); virtual ~ImageManager(); virtual ImageRequest requestImage( - const ImageSource& imageSource, + const ImageSource &imageSource, SurfaceId surfaceId, - const ImageRequestParams& imageRequestParams = {}, + const ImageRequestParams &imageRequestParams = {}, Tag tag = {}) const; private: - void* self_{}; + void *self_{}; }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/imagemanager/ImageRequest.h b/packages/react-native/ReactCommon/react/renderer/imagemanager/ImageRequest.h index d5fa1c70708..a2901b1a0c3 100644 --- a/packages/react-native/ReactCommon/react/renderer/imagemanager/ImageRequest.h +++ b/packages/react-native/ReactCommon/react/renderer/imagemanager/ImageRequest.h @@ -37,18 +37,18 @@ class ImageRequest final { /* * The move constructor. */ - ImageRequest(ImageRequest&& other) noexcept = default; + ImageRequest(ImageRequest &&other) noexcept = default; /* * Move assignment operator. */ - ImageRequest& operator=(ImageRequest&& other) noexcept = default; + ImageRequest &operator=(ImageRequest &&other) noexcept = default; /* * `ImageRequest` does not support copying by design. */ - ImageRequest(const ImageRequest& other) = delete; - ImageRequest& operator=(const ImageRequest& other) = delete; + ImageRequest(const ImageRequest &other) = delete; + ImageRequest &operator=(const ImageRequest &other) = delete; /* * Destructor @@ -58,27 +58,26 @@ class ImageRequest final { /* * Returns the Image Source associated with the request. */ - const ImageSource& getImageSource() const; + const ImageSource &getImageSource() const; /* * Returns stored observer coordinator as a shared pointer. * Retain this *or* `ImageRequest` to ensure a correct lifetime of the object. */ - const std::shared_ptr& - getSharedObserverCoordinator() const; + const std::shared_ptr &getSharedObserverCoordinator() const; /* * Returns stored observer coordinator as a reference. * Use this if a correct lifetime of the object is ensured in some other way * (e.g. by retaining an `ImageRequest`). */ - const ImageResponseObserverCoordinator& getObserverCoordinator() const; + const ImageResponseObserverCoordinator &getObserverCoordinator() const; /* * Returns stored image telemetry object as a shared pointer. * Retain this *or* `ImageRequest` to ensure a correct lifetime of the object. */ - const std::shared_ptr& getSharedTelemetry() const; + const std::shared_ptr &getSharedTelemetry() const; private: /* diff --git a/packages/react-native/ReactCommon/react/renderer/imagemanager/ImageResponseObserver.h b/packages/react-native/ReactCommon/react/renderer/imagemanager/ImageResponseObserver.h index 70930342ef8..95a1d4f8d30 100644 --- a/packages/react-native/ReactCommon/react/renderer/imagemanager/ImageResponseObserver.h +++ b/packages/react-native/ReactCommon/react/renderer/imagemanager/ImageResponseObserver.h @@ -19,10 +19,9 @@ class ImageResponseObserver { public: virtual ~ImageResponseObserver() noexcept = default; - virtual void didReceiveProgress(float progress, int64_t loaded, int64_t total) - const = 0; - virtual void didReceiveImage(const ImageResponse& imageResponse) const = 0; - virtual void didReceiveFailure(const ImageLoadError& error) const = 0; + virtual void didReceiveProgress(float progress, int64_t loaded, int64_t total) const = 0; + virtual void didReceiveImage(const ImageResponse &imageResponse) const = 0; + virtual void didReceiveFailure(const ImageLoadError &error) const = 0; }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/imagemanager/ImageResponseObserverCoordinator.h b/packages/react-native/ReactCommon/react/renderer/imagemanager/ImageResponseObserverCoordinator.h index f70ac494707..51988cc24df 100644 --- a/packages/react-native/ReactCommon/react/renderer/imagemanager/ImageResponseObserverCoordinator.h +++ b/packages/react-native/ReactCommon/react/renderer/imagemanager/ImageResponseObserverCoordinator.h @@ -24,41 +24,36 @@ namespace facebook::react { */ class ImageResponseObserverCoordinator { public: - ImageResponseObserverCoordinator( - SharedFunction<> resumeFunction, - SharedFunction<> cancelationFunction); + ImageResponseObserverCoordinator(SharedFunction<> resumeFunction, SharedFunction<> cancelationFunction); /* * Interested parties may observe the image response. * If the current image request status is not equal to `Loading`, the observer * will be called immediately. */ - void addObserver(const ImageResponseObserver& observer) const; + void addObserver(const ImageResponseObserver &observer) const; /* * Interested parties may stop observing the image response. */ - void removeObserver(const ImageResponseObserver& observer) const; + void removeObserver(const ImageResponseObserver &observer) const; /* * Platform-specific image loader will call this method with progress updates. */ - void nativeImageResponseProgress( - float progress, - int64_t loaded, - int64_t total) const; + void nativeImageResponseProgress(float progress, int64_t loaded, int64_t total) const; /* * Platform-specific image loader will call this method with a completed image * response. */ - void nativeImageResponseComplete(const ImageResponse& imageResponse) const; + void nativeImageResponseComplete(const ImageResponse &imageResponse) const; /* * Platform-specific image loader will call this method in case of any * failures. */ - void nativeImageResponseFailed(const ImageLoadError& loadError) const; + void nativeImageResponseFailed(const ImageLoadError &loadError) const; private: /* @@ -70,7 +65,7 @@ class ImageResponseObserverCoordinator { * List of observers. * Mutable: protected by mutex_. */ - mutable std::vector observers_; + mutable std::vector observers_; /* * Current status of image loading. diff --git a/packages/react-native/ReactCommon/react/renderer/imagemanager/ImageTelemetry.h b/packages/react-native/ReactCommon/react/renderer/imagemanager/ImageTelemetry.h index 430e0e62e73..1d207c286cb 100644 --- a/packages/react-native/ReactCommon/react/renderer/imagemanager/ImageTelemetry.h +++ b/packages/react-native/ReactCommon/react/renderer/imagemanager/ImageTelemetry.h @@ -18,7 +18,8 @@ namespace facebook::react { */ class ImageTelemetry final { public: - ImageTelemetry(const SurfaceId surfaceId) : surfaceId_(surfaceId) { + ImageTelemetry(const SurfaceId surfaceId) : surfaceId_(surfaceId) + { willRequestUrlTime_ = telemetryTimePointNow(); } diff --git a/packages/react-native/ReactCommon/react/renderer/imagemanager/platform/android/react/renderer/imagemanager/ImageFetcher.cpp b/packages/react-native/ReactCommon/react/renderer/imagemanager/platform/android/react/renderer/imagemanager/ImageFetcher.cpp index 463e909205e..7d783036921 100644 --- a/packages/react-native/ReactCommon/react/renderer/imagemanager/platform/android/react/renderer/imagemanager/ImageFetcher.cpp +++ b/packages/react-native/ReactCommon/react/renderer/imagemanager/platform/android/react/renderer/imagemanager/ImageFetcher.cpp @@ -21,10 +21,11 @@ ImageRequest ImageFetcher::requestImage( SurfaceId surfaceId, const ImageRequestParams& imageRequestParams, Tag tag) { - items_[surfaceId].emplace_back(ImageRequestItem{ - .imageSource = imageSource, - .imageRequestParams = imageRequestParams, - .tag = tag}); + items_[surfaceId].emplace_back( + ImageRequestItem{ + .imageSource = imageSource, + .imageRequestParams = imageRequestParams, + .tag = tag}); auto telemetry = std::make_shared(surfaceId); diff --git a/packages/react-native/ReactCommon/react/renderer/imagemanager/platform/android/react/renderer/imagemanager/ImageFetcher.h b/packages/react-native/ReactCommon/react/renderer/imagemanager/platform/android/react/renderer/imagemanager/ImageFetcher.h index 41ba732f269..d2703995e24 100644 --- a/packages/react-native/ReactCommon/react/renderer/imagemanager/platform/android/react/renderer/imagemanager/ImageFetcher.h +++ b/packages/react-native/ReactCommon/react/renderer/imagemanager/platform/android/react/renderer/imagemanager/ImageFetcher.h @@ -20,15 +20,15 @@ class ImageFetcher { public: ImageFetcher(std::shared_ptr contextContainer); ~ImageFetcher() = default; - ImageFetcher(const ImageFetcher&) = delete; - ImageFetcher& operator=(const ImageFetcher&) = delete; - ImageFetcher(ImageFetcher&&) = delete; - ImageFetcher& operator=(ImageFetcher&&) = delete; + ImageFetcher(const ImageFetcher &) = delete; + ImageFetcher &operator=(const ImageFetcher &) = delete; + ImageFetcher(ImageFetcher &&) = delete; + ImageFetcher &operator=(ImageFetcher &&) = delete; ImageRequest requestImage( - const ImageSource& imageSource, + const ImageSource &imageSource, SurfaceId surfaceId, - const ImageRequestParams& imageRequestParams, + const ImageRequestParams &imageRequestParams, Tag tag); private: diff --git a/packages/react-native/ReactCommon/react/renderer/imagemanager/platform/android/react/renderer/imagemanager/ImageRequestParams.h b/packages/react-native/ReactCommon/react/renderer/imagemanager/platform/android/react/renderer/imagemanager/ImageRequestParams.h index 8efb0e4a669..87116f8cf0b 100644 --- a/packages/react-native/ReactCommon/react/renderer/imagemanager/platform/android/react/renderer/imagemanager/ImageRequestParams.h +++ b/packages/react-native/ReactCommon/react/renderer/imagemanager/platform/android/react/renderer/imagemanager/ImageRequestParams.h @@ -42,7 +42,9 @@ class ImageRequestParams { fadeDuration(fadeDuration), progressiveRenderingEnabled(progressiveRenderingEnabled), loadingIndicatorSource(std::move(loadingIndicatorSource)), - analyticTag(std::move(analyticTag)) {} + analyticTag(std::move(analyticTag)) + { + } Float blurRadius{}; ImageSource defaultSource{}; @@ -57,7 +59,8 @@ class ImageRequestParams { ImageSource loadingIndicatorSource{}; std::string analyticTag{}; - bool operator==(const ImageRequestParams& rhs) const { + bool operator==(const ImageRequestParams &rhs) const + { return std::tie( this->blurRadius, this->defaultSource, @@ -86,7 +89,8 @@ class ImageRequestParams { rhs.analyticTag); } - bool operator!=(const ImageRequestParams& rhs) const { + bool operator!=(const ImageRequestParams &rhs) const + { return !(*this == rhs); } }; diff --git a/packages/react-native/ReactCommon/react/renderer/imagemanager/platform/android/react/renderer/imagemanager/conversions.h b/packages/react-native/ReactCommon/react/renderer/imagemanager/platform/android/react/renderer/imagemanager/conversions.h index 605239603a1..1326fc29be7 100644 --- a/packages/react-native/ReactCommon/react/renderer/imagemanager/platform/android/react/renderer/imagemanager/conversions.h +++ b/packages/react-native/ReactCommon/react/renderer/imagemanager/platform/android/react/renderer/imagemanager/conversions.h @@ -36,50 +36,35 @@ constexpr MapBuffer::Key IS_KEY_LOADING_INDICATOR_SRC = 13; constexpr MapBuffer::Key IS_KEY_ANALYTIC_TAG = 14; constexpr MapBuffer::Key IS_KEY_TAG = 15; -inline void serializeImageSource( - MapBufferBuilder& builder, - const ImageSource& imageSource) { +inline void serializeImageSource(MapBufferBuilder &builder, const ImageSource &imageSource) +{ builder.putString(IS_KEY_URI, imageSource.uri); - builder.putInt( - IS_KEY_VIEW_WIDTH, static_cast(imageSource.size.width)); - builder.putInt( - IS_KEY_VIEW_HEIGHT, static_cast(imageSource.size.height)); + builder.putInt(IS_KEY_VIEW_WIDTH, static_cast(imageSource.size.width)); + builder.putInt(IS_KEY_VIEW_HEIGHT, static_cast(imageSource.size.height)); } -inline void serializeImageRequestParams( - MapBufferBuilder& builder, - const ImageRequestParams& imageRequestParams) { +inline void serializeImageRequestParams(MapBufferBuilder &builder, const ImageRequestParams &imageRequestParams) +{ builder.putString(IS_KEY_DEFAULT_SRC, imageRequestParams.defaultSource.uri); - builder.putInt( - IS_KEY_RESIZE_MODE, to_underlying(imageRequestParams.resizeMode)); + builder.putInt(IS_KEY_RESIZE_MODE, to_underlying(imageRequestParams.resizeMode)); builder.putString(IS_KEY_RESIZE_METHOD, imageRequestParams.resizeMethod); builder.putDouble(IS_KEY_BLUR_RADIUS, imageRequestParams.blurRadius); - builder.putDouble( - IS_KEY_RESIZE_MULTIPLIER, imageRequestParams.resizeMultiplier); - builder.putBool( - IS_KEY_SHOULD_NOTIFY_LOAD_EVENTS, - imageRequestParams.shouldNotifyLoadEvents); + builder.putDouble(IS_KEY_RESIZE_MULTIPLIER, imageRequestParams.resizeMultiplier); + builder.putBool(IS_KEY_SHOULD_NOTIFY_LOAD_EVENTS, imageRequestParams.shouldNotifyLoadEvents); if (isColorMeaningful(imageRequestParams.overlayColor)) { - builder.putInt( - IS_KEY_OVERLAY_COLOR, toAndroidRepr(imageRequestParams.overlayColor)); + builder.putInt(IS_KEY_OVERLAY_COLOR, toAndroidRepr(imageRequestParams.overlayColor)); } if (isColorMeaningful(imageRequestParams.tintColor)) { - builder.putInt( - IS_KEY_TINT_COLOR, toAndroidRepr(imageRequestParams.tintColor)); + builder.putInt(IS_KEY_TINT_COLOR, toAndroidRepr(imageRequestParams.tintColor)); } - builder.putInt( - IS_KEY_FADE_DURATION, - static_cast(imageRequestParams.fadeDuration)); - builder.putBool( - IS_KEY_PROGRESSIVE_RENDERING_ENABLED, - imageRequestParams.progressiveRenderingEnabled); - builder.putString( - IS_KEY_LOADING_INDICATOR_SRC, - imageRequestParams.loadingIndicatorSource.uri); + builder.putInt(IS_KEY_FADE_DURATION, static_cast(imageRequestParams.fadeDuration)); + builder.putBool(IS_KEY_PROGRESSIVE_RENDERING_ENABLED, imageRequestParams.progressiveRenderingEnabled); + builder.putString(IS_KEY_LOADING_INDICATOR_SRC, imageRequestParams.loadingIndicatorSource.uri); builder.putString(IS_KEY_ANALYTIC_TAG, imageRequestParams.analyticTag); } -inline MapBuffer serializeImageRequest(const ImageRequestItem& item) { +inline MapBuffer serializeImageRequest(const ImageRequestItem &item) +{ auto builder = MapBufferBuilder(); serializeImageSource(builder, item.imageSource); serializeImageRequestParams(builder, item.imageRequestParams); @@ -89,11 +74,11 @@ inline MapBuffer serializeImageRequest(const ImageRequestItem& item) { } // namespace -inline MapBuffer serializeImageRequests( - const std::vector& items) { +inline MapBuffer serializeImageRequests(const std::vector &items) +{ std::vector mapBufferList; mapBufferList.reserve(items.size()); - for (const auto& item : items) { + for (const auto &item : items) { mapBufferList.emplace_back(serializeImageRequest(item)); } MapBufferBuilder builder; diff --git a/packages/react-native/ReactCommon/react/renderer/imagemanager/platform/cxx/react/renderer/imagemanager/ImageRequestParams.h b/packages/react-native/ReactCommon/react/renderer/imagemanager/platform/cxx/react/renderer/imagemanager/ImageRequestParams.h index 8f1edd7ed96..7c99c2be0aa 100644 --- a/packages/react-native/ReactCommon/react/renderer/imagemanager/platform/cxx/react/renderer/imagemanager/ImageRequestParams.h +++ b/packages/react-native/ReactCommon/react/renderer/imagemanager/platform/cxx/react/renderer/imagemanager/ImageRequestParams.h @@ -18,11 +18,13 @@ class ImageRequestParams { Float blurRadius{}; - bool operator==(const ImageRequestParams& rhs) const { + bool operator==(const ImageRequestParams &rhs) const + { return this->blurRadius == rhs.blurRadius; } - bool operator!=(const ImageRequestParams& rhs) const { + bool operator!=(const ImageRequestParams &rhs) const + { return !(*this == rhs); } }; diff --git a/packages/react-native/ReactCommon/react/renderer/imagemanager/platform/ios/react/renderer/imagemanager/ImageRequestParams.h b/packages/react-native/ReactCommon/react/renderer/imagemanager/platform/ios/react/renderer/imagemanager/ImageRequestParams.h index b10d38148b6..f36da30bcf5 100644 --- a/packages/react-native/ReactCommon/react/renderer/imagemanager/platform/ios/react/renderer/imagemanager/ImageRequestParams.h +++ b/packages/react-native/ReactCommon/react/renderer/imagemanager/platform/ios/react/renderer/imagemanager/ImageRequestParams.h @@ -18,11 +18,13 @@ class ImageRequestParams { Float blurRadius{}; - bool operator==(const ImageRequestParams& rhs) const { + bool operator==(const ImageRequestParams &rhs) const + { return this->blurRadius == rhs.blurRadius; } - bool operator!=(const ImageRequestParams& rhs) const { + bool operator!=(const ImageRequestParams &rhs) const + { return !(*this == rhs); } }; diff --git a/packages/react-native/ReactCommon/react/renderer/imagemanager/platform/ios/react/renderer/imagemanager/RCTSyncImageManager.mm b/packages/react-native/ReactCommon/react/renderer/imagemanager/platform/ios/react/renderer/imagemanager/RCTSyncImageManager.mm index b5c2dc83bd8..3d857bee311 100644 --- a/packages/react-native/ReactCommon/react/renderer/imagemanager/platform/ios/react/renderer/imagemanager/RCTSyncImageManager.mm +++ b/packages/react-native/ReactCommon/react/renderer/imagemanager/platform/ios/react/renderer/imagemanager/RCTSyncImageManager.mm @@ -85,7 +85,7 @@ using namespace facebook::react; priority:RCTImageLoaderPriorityImmediate attribution:{ .surfaceId = surfaceId, - } + } progressBlock:progressBlock partialLoadBlock:nil completionBlock:completionBlock]; diff --git a/packages/react-native/ReactCommon/react/renderer/imagemanager/primitives.h b/packages/react-native/ReactCommon/react/renderer/imagemanager/primitives.h index 0b897676a1d..01b118f763c 100644 --- a/packages/react-native/ReactCommon/react/renderer/imagemanager/primitives.h +++ b/packages/react-native/ReactCommon/react/renderer/imagemanager/primitives.h @@ -33,16 +33,19 @@ class ImageSource { CacheStategy cache = CacheStategy::Default; std::vector> headers{}; - bool operator==(const ImageSource& rhs) const { + bool operator==(const ImageSource &rhs) const + { return std::tie(this->type, this->uri) == std::tie(rhs.type, rhs.uri); } - bool operator!=(const ImageSource& rhs) const { + bool operator!=(const ImageSource &rhs) const + { return !(*this == rhs); } #ifdef RN_SERIALIZABLE_STATE - folly::dynamic toDynamic() const { + folly::dynamic toDynamic() const + { folly::dynamic imageSourceResult = folly::dynamic::object(); switch (type) { case ImageSource::Type::Invalid: @@ -84,7 +87,7 @@ class ImageSource { } folly::dynamic headersObject = folly::dynamic::object(); - for (const auto& header : headers) { + for (const auto &header : headers) { headersObject[header.first] = header.second; } imageSourceResult["headers"] = headersObject; @@ -94,41 +97,30 @@ class ImageSource { #endif #if RN_DEBUG_STRING_CONVERTIBLE - SharedDebugStringConvertibleList getDebugProps( - const std::string& prefix) const { + SharedDebugStringConvertibleList getDebugProps(const std::string &prefix) const + { ImageSource imageSource{}; SharedDebugStringConvertibleList headersList; - for (const auto& header : headers) { - headersList.push_back(debugStringConvertibleItem( - prefix + "-header-" + header.first, header.second)); + for (const auto &header : headers) { + headersList.push_back(debugStringConvertibleItem(prefix + "-header-" + header.first, header.second)); } return headersList + SharedDebugStringConvertibleList{ - debugStringConvertibleItem( - prefix + "-type", toString(type), toString(imageSource.type)), + debugStringConvertibleItem(prefix + "-type", toString(type), toString(imageSource.type)), debugStringConvertibleItem(prefix + "-uri", uri, imageSource.uri), - debugStringConvertibleItem( - prefix + "-bundle", bundle, imageSource.bundle), - debugStringConvertibleItem( - prefix + "-scale", scale, imageSource.scale), - debugStringConvertibleItem( - prefix + "-size", - react::toString(size), - react::toString(imageSource.size)), - debugStringConvertibleItem( - prefix + "-body", body, imageSource.body), - debugStringConvertibleItem( - prefix + "-method", method, imageSource.method), - debugStringConvertibleItem( - prefix + "-cache", - toString(cache), - toString(imageSource.cache)), + debugStringConvertibleItem(prefix + "-bundle", bundle, imageSource.bundle), + debugStringConvertibleItem(prefix + "-scale", scale, imageSource.scale), + debugStringConvertibleItem(prefix + "-size", react::toString(size), react::toString(imageSource.size)), + debugStringConvertibleItem(prefix + "-body", body, imageSource.body), + debugStringConvertibleItem(prefix + "-method", method, imageSource.method), + debugStringConvertibleItem(prefix + "-cache", toString(cache), toString(imageSource.cache)), }; } - std::string toString(const Type& typeValue) const { + std::string toString(const Type &typeValue) const + { switch (typeValue) { case ImageSource::Type::Invalid: return "invalid"; @@ -139,7 +131,8 @@ class ImageSource { } } - std::string toString(const CacheStategy& cacheValue) const { + std::string toString(const CacheStategy &cacheValue) const + { switch (cacheValue) { case ImageSource::CacheStategy::Default: return "default"; @@ -155,7 +148,8 @@ class ImageSource { }; #ifdef RN_SERIALIZABLE_STATE -inline folly::dynamic toDynamic(const ImageSource& imageSource) { +inline folly::dynamic toDynamic(const ImageSource &imageSource) +{ return imageSource.toDynamic(); } #endif diff --git a/packages/react-native/ReactCommon/react/renderer/leakchecker/LeakChecker.h b/packages/react-native/ReactCommon/react/renderer/leakchecker/LeakChecker.h index a967ed7bf40..091aa836917 100644 --- a/packages/react-native/ReactCommon/react/renderer/leakchecker/LeakChecker.h +++ b/packages/react-native/ReactCommon/react/renderer/leakchecker/LeakChecker.h @@ -21,8 +21,7 @@ class LeakChecker final { public: LeakChecker(RuntimeExecutor runtimeExecutor); - void uiManagerDidCreateShadowNodeFamily( - const ShadowNodeFamily::Shared& shadowNodeFamily) const; + void uiManagerDidCreateShadowNodeFamily(const ShadowNodeFamily::Shared &shadowNodeFamily) const; void stopSurface(SurfaceId surfaceId); private: diff --git a/packages/react-native/ReactCommon/react/renderer/leakchecker/WeakFamilyRegistry.h b/packages/react-native/ReactCommon/react/renderer/leakchecker/WeakFamilyRegistry.h index 474d97da7ae..18f18811a5e 100644 --- a/packages/react-native/ReactCommon/react/renderer/leakchecker/WeakFamilyRegistry.h +++ b/packages/react-native/ReactCommon/react/renderer/leakchecker/WeakFamilyRegistry.h @@ -18,7 +18,7 @@ class WeakFamilyRegistry final { public: using WeakFamilies = std::vector; - void add(const ShadowNodeFamily::Shared& shadowNodeFamily) const; + void add(const ShadowNodeFamily::Shared &shadowNodeFamily) const; void removeFamiliesWithSurfaceId(SurfaceId surfaceId) const; WeakFamilies weakFamiliesForSurfaceId(SurfaceId surfaceId) const; diff --git a/packages/react-native/ReactCommon/react/renderer/mapbuffer/MapBuffer.h b/packages/react-native/ReactCommon/react/renderer/mapbuffer/MapBuffer.h index 968747ee64f..dcc449a7b99 100644 --- a/packages/react-native/ReactCommon/react/renderer/mapbuffer/MapBuffer.h +++ b/packages/react-native/ReactCommon/react/renderer/mapbuffer/MapBuffer.h @@ -85,8 +85,7 @@ class MapBuffer { uint16_t type; uint64_t data; - Bucket(Key key, uint16_t type, uint64_t data) - : key(key), type(type), data(data) {} + Bucket(Key key, uint16_t type, uint64_t data) : key(key), type(type), data(data) {} }; #pragma pack(pop) @@ -109,13 +108,13 @@ class MapBuffer { explicit MapBuffer(std::vector data); - MapBuffer(const MapBuffer& buffer) = delete; + MapBuffer(const MapBuffer &buffer) = delete; - MapBuffer& operator=(const MapBuffer& other) = delete; + MapBuffer &operator=(const MapBuffer &other) = delete; - MapBuffer(MapBuffer&& buffer) = default; + MapBuffer(MapBuffer &&buffer) = default; - MapBuffer& operator=(MapBuffer&& other) = default; + MapBuffer &operator=(MapBuffer &&other) = default; int32_t getInt(MapBuffer::Key key) const; @@ -134,7 +133,7 @@ class MapBuffer { size_t size() const; - const uint8_t* data() const; + const uint8_t *data() const; uint16_t count() const; diff --git a/packages/react-native/ReactCommon/react/renderer/mapbuffer/MapBufferBuilder.h b/packages/react-native/ReactCommon/react/renderer/mapbuffer/MapBufferBuilder.h index 2260e690a2d..af054da5578 100644 --- a/packages/react-native/ReactCommon/react/renderer/mapbuffer/MapBufferBuilder.h +++ b/packages/react-native/ReactCommon/react/renderer/mapbuffer/MapBufferBuilder.h @@ -33,13 +33,11 @@ class MapBufferBuilder { void putDouble(MapBuffer::Key key, double value); - void putString(MapBuffer::Key key, const std::string& value); + void putString(MapBuffer::Key key, const std::string &value); - void putMapBuffer(MapBuffer::Key key, const MapBuffer& map); + void putMapBuffer(MapBuffer::Key key, const MapBuffer &map); - void putMapBufferList( - MapBuffer::Key key, - const std::vector& mapBufferList); + void putMapBufferList(MapBuffer::Key key, const std::vector &mapBufferList); MapBuffer build(); @@ -54,11 +52,7 @@ class MapBufferBuilder { bool needsSort_{false}; - void storeKeyValue( - MapBuffer::Key key, - MapBuffer::DataType type, - const uint8_t* value, - uint32_t valueSize); + void storeKeyValue(MapBuffer::Key key, MapBuffer::DataType type, const uint8_t *value, uint32_t valueSize); }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/mounting/Differentiator.cpp b/packages/react-native/ReactCommon/react/renderer/mounting/Differentiator.cpp index 611180e6a20..dff263a3498 100644 --- a/packages/react-native/ReactCommon/react/renderer/mounting/Differentiator.cpp +++ b/packages/react-native/ReactCommon/react/renderer/mounting/Differentiator.cpp @@ -1381,8 +1381,9 @@ ShadowViewMutation::List calculateShadowViewMutations( auto newRootShadowView = ShadowView(newRootShadowNode); if (oldRootShadowView != newRootShadowView) { - mutations.push_back(ShadowViewMutation::UpdateMutation( - oldRootShadowView, newRootShadowView, {})); + mutations.push_back( + ShadowViewMutation::UpdateMutation( + oldRootShadowView, newRootShadowView, {})); } auto sliceOne = sliceChildShadowNodeViewPairs( diff --git a/packages/react-native/ReactCommon/react/renderer/mounting/Differentiator.h b/packages/react-native/ReactCommon/react/renderer/mounting/Differentiator.h index f0305dfcf5c..e764498b476 100644 --- a/packages/react-native/ReactCommon/react/renderer/mounting/Differentiator.h +++ b/packages/react-native/ReactCommon/react/renderer/mounting/Differentiator.h @@ -18,7 +18,7 @@ namespace facebook::react { * The list of mutations might be and might not be optimal. */ ShadowViewMutation::List calculateShadowViewMutations( - const ShadowNode& oldRootShadowNode, - const ShadowNode& newRootShadowNode); + const ShadowNode &oldRootShadowNode, + const ShadowNode &newRootShadowNode); } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/mounting/MountingCoordinator.h b/packages/react-native/ReactCommon/react/renderer/mounting/MountingCoordinator.h index 229e74897eb..5040e63d9ae 100644 --- a/packages/react-native/ReactCommon/react/renderer/mounting/MountingCoordinator.h +++ b/packages/react-native/ReactCommon/react/renderer/mounting/MountingCoordinator.h @@ -37,7 +37,7 @@ class MountingCoordinator final { * The constructor is meant to be used only inside `ShadowTree`, and it's * `public` only to enable using with `std::make_shared<>`. */ - MountingCoordinator(const ShadowTreeRevision& baseRevision); + MountingCoordinator(const ShadowTreeRevision &baseRevision); /* * Returns the id of the surface that the coordinator belongs to. @@ -61,8 +61,7 @@ class MountingCoordinator final { * If this is `true`, then `hasPendingTransactions` will continue returning * `true` until `didPerformAsyncTransactions` is called. */ - std::optional pullTransaction( - bool willPerformAsynchronously = false) const; + std::optional pullTransaction(bool willPerformAsynchronously = false) const; /* * This method is used to notify that transactions that weren't performed @@ -93,7 +92,7 @@ class MountingCoordinator final { */ bool waitForTransaction(std::chrono::duration timeout) const; - const TelemetryController& getTelemetryController() const; + const TelemetryController &getTelemetryController() const; ShadowTreeRevision getBaseRevision() const; @@ -102,11 +101,10 @@ class MountingCoordinator final { * `MountingOverrideDelegate` only. */ public: - void updateBaseRevision(const ShadowTreeRevision& baseRevision) const; + void updateBaseRevision(const ShadowTreeRevision &baseRevision) const; void resetLatestRevision() const; - void setMountingOverrideDelegate( - std::weak_ptr delegate) const; + void setMountingOverrideDelegate(std::weak_ptr delegate) const; /* * Methods from this section are meant to be used by `ShadowTree` only. @@ -136,8 +134,7 @@ class MountingCoordinator final { mutable std::optional lastRevision_{}; mutable MountingTransaction::Number number_{0}; mutable std::condition_variable signal_; - mutable std::vector> - mountingOverrideDelegates_; + mutable std::vector> mountingOverrideDelegates_; TelemetryController telemetryController_; diff --git a/packages/react-native/ReactCommon/react/renderer/mounting/MountingOverrideDelegate.h b/packages/react-native/ReactCommon/react/renderer/mounting/MountingOverrideDelegate.h index c6e57993dd4..1e96eff3679 100644 --- a/packages/react-native/ReactCommon/react/renderer/mounting/MountingOverrideDelegate.h +++ b/packages/react-native/ReactCommon/react/renderer/mounting/MountingOverrideDelegate.h @@ -39,7 +39,7 @@ class MountingOverrideDelegate { virtual std::optional pullTransaction( SurfaceId surfaceId, MountingTransaction::Number number, - const TransactionTelemetry& telemetry, + const TransactionTelemetry &telemetry, ShadowViewMutationList mutations) const = 0; }; diff --git a/packages/react-native/ReactCommon/react/renderer/mounting/MountingTransaction.h b/packages/react-native/ReactCommon/react/renderer/mounting/MountingTransaction.h index 277e9f4e307..7841b5a2a64 100644 --- a/packages/react-native/ReactCommon/react/renderer/mounting/MountingTransaction.h +++ b/packages/react-native/ReactCommon/react/renderer/mounting/MountingTransaction.h @@ -35,7 +35,7 @@ class MountingTransaction final { MountingTransaction( SurfaceId surfaceId, Number number, - ShadowViewMutationList&& mutations, + ShadowViewMutationList &&mutations, TransactionTelemetry telemetry); /* @@ -43,28 +43,26 @@ class MountingTransaction final { * Copying of MountingTransaction is expensive, so copy-constructor is * explicit and copy-assignment is deleted to prevent accidental copying. */ - explicit MountingTransaction(const MountingTransaction& mountingTransaction) = - default; - MountingTransaction& operator=(const MountingTransaction& other) = delete; + explicit MountingTransaction(const MountingTransaction &mountingTransaction) = default; + MountingTransaction &operator=(const MountingTransaction &other) = delete; /* * Move semantic. */ - MountingTransaction(MountingTransaction&& mountingTransaction) noexcept = - default; - MountingTransaction& operator=(MountingTransaction&& other) = default; + MountingTransaction(MountingTransaction &&mountingTransaction) noexcept = default; + MountingTransaction &operator=(MountingTransaction &&other) = default; /* * Returns a list of mutations that represent the transaction. The list can be * empty (theoretically). */ - const ShadowViewMutationList& getMutations() const&; + const ShadowViewMutationList &getMutations() const &; ShadowViewMutationList getMutations() &&; /* * Returns telemetry associated with this transaction. */ - TransactionTelemetry& getTelemetry() const; + TransactionTelemetry &getTelemetry() const; /* * Returns the id of the surface that the transaction belongs to. @@ -83,7 +81,7 @@ class MountingTransaction final { * This is required for Android UI, which needs to separately apply * each ShadowTree mutation due to differences in props representation. */ - void mergeWith(MountingTransaction&& transaction); + void mergeWith(MountingTransaction &&transaction); private: SurfaceId surfaceId_; diff --git a/packages/react-native/ReactCommon/react/renderer/mounting/ShadowTree.h b/packages/react-native/ReactCommon/react/renderer/mounting/ShadowTree.h index 33e10e102a8..3b44d6e49ca 100644 --- a/packages/react-native/ReactCommon/react/renderer/mounting/ShadowTree.h +++ b/packages/react-native/ReactCommon/react/renderer/mounting/ShadowTree.h @@ -23,8 +23,7 @@ namespace facebook::react { -using ShadowTreeCommitTransaction = std::function; +using ShadowTreeCommitTransaction = std::function; /* * Represents a result of a `commit` operation. @@ -86,10 +85,10 @@ class ShadowTree final { */ ShadowTree( SurfaceId surfaceId, - const LayoutConstraints& layoutConstraints, - const LayoutContext& layoutContext, - const ShadowTreeDelegate& delegate, - const ContextContainer& contextContainer); + const LayoutConstraints &layoutConstraints, + const LayoutContext &layoutContext, + const ShadowTreeDelegate &delegate, + const ContextContainer &contextContainer); ~ShadowTree(); @@ -111,16 +110,12 @@ class ShadowTree final { * and expecting a `newRootShadowNode` as a return value. * The `transaction` function can cancel commit returning `nullptr`. */ - CommitStatus tryCommit( - const ShadowTreeCommitTransaction& transaction, - const CommitOptions& commitOptions) const; + CommitStatus tryCommit(const ShadowTreeCommitTransaction &transaction, const CommitOptions &commitOptions) const; /* * Calls `tryCommit` in a loop until it finishes successfully. */ - CommitStatus commit( - const ShadowTreeCommitTransaction& transaction, - const CommitOptions& commitOptions) const; + CommitStatus commit(const ShadowTreeCommitTransaction &transaction, const CommitOptions &commitOptions) const; /* * Returns a `ShadowTreeRevision` representing the momentary state of @@ -146,24 +141,18 @@ class ShadowTree final { void mount(ShadowTreeRevision revision, bool mountSynchronously) const; - void emitLayoutEvents( - std::vector& affectedLayoutableNodes) const; + void emitLayoutEvents(std::vector &affectedLayoutableNodes) const; const SurfaceId surfaceId_; - const ShadowTreeDelegate& delegate_; + const ShadowTreeDelegate &delegate_; mutable std::shared_mutex commitMutex_; mutable std::recursive_mutex commitMutexRecursive_; - mutable CommitMode commitMode_{ - CommitMode::Normal}; // Protected by `commitMutex_`. + mutable CommitMode commitMode_{CommitMode::Normal}; // Protected by `commitMutex_`. mutable ShadowTreeRevision currentRevision_; // Protected by `commitMutex_`. std::shared_ptr mountingCoordinator_; - using UniqueLock = std::variant< - std::unique_lock, - std::unique_lock>; - using SharedLock = std::variant< - std::shared_lock, - std::unique_lock>; + using UniqueLock = std::variant, std::unique_lock>; + using SharedLock = std::variant, std::unique_lock>; inline UniqueLock uniqueCommitLock() const; inline SharedLock sharedCommitLock() const; diff --git a/packages/react-native/ReactCommon/react/renderer/mounting/ShadowTreeDelegate.h b/packages/react-native/ReactCommon/react/renderer/mounting/ShadowTreeDelegate.h index 14402722045..650d898a6f3 100644 --- a/packages/react-native/ReactCommon/react/renderer/mounting/ShadowTreeDelegate.h +++ b/packages/react-native/ReactCommon/react/renderer/mounting/ShadowTreeDelegate.h @@ -26,10 +26,10 @@ class ShadowTreeDelegate { * Returning a `nullptr` cancels the commit. */ virtual RootShadowNode::Unshared shadowTreeWillCommit( - const ShadowTree& shadowTree, - const RootShadowNode::Shared& oldRootShadowNode, - const RootShadowNode::Unshared& newRootShadowNode, - const ShadowTreeCommitOptions& commitOptions) const = 0; + const ShadowTree &shadowTree, + const RootShadowNode::Shared &oldRootShadowNode, + const RootShadowNode::Unshared &newRootShadowNode, + const ShadowTreeCommitOptions &commitOptions) const = 0; /* * Called right after Shadow Tree commit a new state of the tree. diff --git a/packages/react-native/ReactCommon/react/renderer/mounting/ShadowTreeRegistry.h b/packages/react-native/ReactCommon/react/renderer/mounting/ShadowTreeRegistry.h index 92d824e7f65..73cf5af6992 100644 --- a/packages/react-native/ReactCommon/react/renderer/mounting/ShadowTreeRegistry.h +++ b/packages/react-native/ReactCommon/react/renderer/mounting/ShadowTreeRegistry.h @@ -28,7 +28,7 @@ class ShadowTreeRegistry final { * The ownership of the instance is also transferred to the registry. * Can be called from any thread. */ - void add(std::unique_ptr&& shadowTree) const; + void add(std::unique_ptr &&shadowTree) const; /* * Removes a `ShadowTree` instance with given `surfaceId` from the registry @@ -47,23 +47,18 @@ class ShadowTreeRegistry final { * `surfaceId`, otherwise returns `false` without calling the `callback`. * Can be called from any thread. */ - bool visit( - SurfaceId surfaceId, - const std::function& callback) const; + bool visit(SurfaceId surfaceId, const std::function &callback) const; /* * Enumerates all stored shadow trees. * Set `stop` to `true` to interrupt the enumeration. * Can be called from any thread. */ - void enumerate( - const std::function& - callback) const; + void enumerate(const std::function &callback) const; private: mutable std::shared_mutex mutex_; - mutable std::unordered_map> - registry_; // Protected by `mutex_`. + mutable std::unordered_map> registry_; // Protected by `mutex_`. }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/mounting/ShadowView.h b/packages/react-native/ReactCommon/react/renderer/mounting/ShadowView.h index 36dd55d37a5..b78b4cfeca1 100644 --- a/packages/react-native/ReactCommon/react/renderer/mounting/ShadowView.h +++ b/packages/react-native/ReactCommon/react/renderer/mounting/ShadowView.h @@ -23,19 +23,19 @@ namespace facebook::react { */ struct ShadowView final { ShadowView() = default; - ShadowView(const ShadowView& shadowView) = default; - ShadowView(ShadowView&& shadowView) noexcept = default; + ShadowView(const ShadowView &shadowView) = default; + ShadowView(ShadowView &&shadowView) noexcept = default; /* * Constructs a `ShadowView` from given `ShadowNode`. */ - explicit ShadowView(const ShadowNode& shadowNode); + explicit ShadowView(const ShadowNode &shadowNode); - ShadowView& operator=(const ShadowView& other) = default; - ShadowView& operator=(ShadowView&& other) = default; + ShadowView &operator=(const ShadowView &other) = default; + ShadowView &operator=(ShadowView &&other) = default; - bool operator==(const ShadowView& rhs) const; - bool operator!=(const ShadowView& rhs) const; + bool operator==(const ShadowView &rhs) const; + bool operator!=(const ShadowView &rhs) const; ComponentName componentName{}; ComponentHandle componentHandle{}; @@ -50,9 +50,9 @@ struct ShadowView final { #if RN_DEBUG_STRING_CONVERTIBLE -std::string getDebugName(const ShadowView& object); +std::string getDebugName(const ShadowView &object); std::vector getDebugProps( - const ShadowView& object, + const ShadowView &object, DebugStringConvertibleOptions options); #endif @@ -63,7 +63,8 @@ namespace std { template <> struct hash { - size_t operator()(const facebook::react::ShadowView& shadowView) const { + size_t operator()(const facebook::react::ShadowView &shadowView) const + { return facebook::react::hash_combine( 0, shadowView.surfaceId, diff --git a/packages/react-native/ReactCommon/react/renderer/mounting/ShadowViewMutation.h b/packages/react-native/ReactCommon/react/renderer/mounting/ShadowViewMutation.h index 0aef25d1225..a34f9654b7e 100644 --- a/packages/react-native/ReactCommon/react/renderer/mounting/ShadowViewMutation.h +++ b/packages/react-native/ReactCommon/react/renderer/mounting/ShadowViewMutation.h @@ -39,55 +39,44 @@ struct ShadowViewMutation final { /** * Creates and returns an `Insert` mutation. */ - static ShadowViewMutation - InsertMutation(Tag parentTag, ShadowView childShadowView, int index); + static ShadowViewMutation InsertMutation(Tag parentTag, ShadowView childShadowView, int index); /** * Creates and returns an `Insert` mutation. * @deprecated Pass parentTag instead of parentShadowView. */ - static ShadowViewMutation InsertMutation( - const ShadowView& parentShadowView, - ShadowView childShadowView, - int index) { + static ShadowViewMutation InsertMutation(const ShadowView &parentShadowView, ShadowView childShadowView, int index) + { return InsertMutation(parentShadowView.tag, childShadowView, index); } /** * Creates and returns a `Remove` mutation. */ - static ShadowViewMutation - RemoveMutation(Tag parentTag, ShadowView childShadowView, int index); + static ShadowViewMutation RemoveMutation(Tag parentTag, ShadowView childShadowView, int index); /** * Creates and returns a `Remove` mutation. * @deprecated Pass parentTag instead of parentShadowView. */ - static ShadowViewMutation RemoveMutation( - const ShadowView& parentShadowView, - ShadowView childShadowView, - int index) { + static ShadowViewMutation RemoveMutation(const ShadowView &parentShadowView, ShadowView childShadowView, int index) + { return RemoveMutation(parentShadowView.tag, childShadowView, index); } /** * Creates and returns an `Update` mutation. */ - static ShadowViewMutation UpdateMutation( - ShadowView oldChildShadowView, - ShadowView newChildShadowView, - Tag parentTag); + static ShadowViewMutation UpdateMutation(ShadowView oldChildShadowView, ShadowView newChildShadowView, Tag parentTag); /** * Creates and returns an `Update` mutation. * @deprecated Pass parentTag instead of parentShadowView. */ - static ShadowViewMutation UpdateMutation( - ShadowView oldChildShadowView, - ShadowView newChildShadowView, - const ShadowView& parentShadowView) { - return UpdateMutation( - oldChildShadowView, newChildShadowView, parentShadowView.tag); + static ShadowViewMutation + UpdateMutation(ShadowView oldChildShadowView, ShadowView newChildShadowView, const ShadowView &parentShadowView) + { + return UpdateMutation(oldChildShadowView, newChildShadowView, parentShadowView.tag); } #pragma mark - Type @@ -116,21 +105,16 @@ struct ShadowViewMutation final { bool mutatedViewIsVirtual() const; private: - ShadowViewMutation( - Type type, - Tag parentTag, - ShadowView oldChildShadowView, - ShadowView newChildShadowView, - int index); + ShadowViewMutation(Type type, Tag parentTag, ShadowView oldChildShadowView, ShadowView newChildShadowView, int index); }; using ShadowViewMutationList = std::vector; #if RN_DEBUG_STRING_CONVERTIBLE -std::string getDebugName(const ShadowViewMutation& mutation); +std::string getDebugName(const ShadowViewMutation &mutation); std::vector getDebugProps( - const ShadowViewMutation& mutation, + const ShadowViewMutation &mutation, DebugStringConvertibleOptions options); #endif diff --git a/packages/react-native/ReactCommon/react/renderer/mounting/TelemetryController.h b/packages/react-native/ReactCommon/react/renderer/mounting/TelemetryController.h index f28af1a1d9f..dddca1e0da9 100644 --- a/packages/react-native/ReactCommon/react/renderer/mounting/TelemetryController.h +++ b/packages/react-native/ReactCommon/react/renderer/mounting/TelemetryController.h @@ -17,9 +17,8 @@ namespace facebook::react { class MountingCoordinator; -using MountingTransactionCallback = std::function; +using MountingTransactionCallback = + std::function; /* * Provides convenient tools for aggregating and accessing telemetry data @@ -31,26 +30,25 @@ class TelemetryController final { /* * To be used by `MountingCoordinator`. */ - TelemetryController(const MountingCoordinator& mountingCoordinator) noexcept; + TelemetryController(const MountingCoordinator &mountingCoordinator) noexcept; /* * Not copyable. */ - TelemetryController(const TelemetryController& other) noexcept = delete; - TelemetryController& operator=(const TelemetryController& other) noexcept = - delete; + TelemetryController(const TelemetryController &other) noexcept = delete; + TelemetryController &operator=(const TelemetryController &other) noexcept = delete; public: /* * Calls `MountingCoordinator::pullTransaction()` and aggregates telemetry. */ bool pullTransaction( - const MountingTransactionCallback& willMount, - const MountingTransactionCallback& doMount, - const MountingTransactionCallback& didMount) const; + const MountingTransactionCallback &willMount, + const MountingTransactionCallback &doMount, + const MountingTransactionCallback &didMount) const; private: - const MountingCoordinator& mountingCoordinator_; + const MountingCoordinator &mountingCoordinator_; mutable SurfaceTelemetry compoundTelemetry_{}; mutable std::mutex mutex_; }; diff --git a/packages/react-native/ReactCommon/react/renderer/mounting/internal/CullingContext.h b/packages/react-native/ReactCommon/react/renderer/mounting/internal/CullingContext.h index 7b3ab79152f..b1f005d128a 100644 --- a/packages/react-native/ReactCommon/react/renderer/mounting/internal/CullingContext.h +++ b/packages/react-native/ReactCommon/react/renderer/mounting/internal/CullingContext.h @@ -20,10 +20,9 @@ struct CullingContext { bool shouldConsiderCulling() const; - CullingContext adjustCullingContextIfNeeded( - const ShadowViewNodePair& pair) const; + CullingContext adjustCullingContextIfNeeded(const ShadowViewNodePair &pair) const; - bool operator==(const CullingContext& rhs) const = default; + bool operator==(const CullingContext &rhs) const = default; }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/mounting/internal/ShadowViewNodePair.h b/packages/react-native/ReactCommon/react/renderer/mounting/internal/ShadowViewNodePair.h index e6c8170b398..e32dc713202 100644 --- a/packages/react-native/ReactCommon/react/renderer/mounting/internal/ShadowViewNodePair.h +++ b/packages/react-native/ReactCommon/react/renderer/mounting/internal/ShadowViewNodePair.h @@ -19,7 +19,7 @@ namespace facebook::react { */ struct ShadowViewNodePair final { ShadowView shadowView{}; - const ShadowNode* shadowNode; + const ShadowNode *shadowNode; /** * The ShadowNode does not form a stacking context, and the native views @@ -41,20 +41,23 @@ struct ShadowViewNodePair final { * rely on this more heavily to simplify the diffing algorithm * overall? */ - mutable const ShadowViewNodePair* otherTreePair{nullptr}; + mutable const ShadowViewNodePair *otherTreePair{nullptr}; /* * The stored pointer to `ShadowNode` represents an identity of the pair. */ - bool operator==(const ShadowViewNodePair& rhs) const { + bool operator==(const ShadowViewNodePair &rhs) const + { return this->shadowNode == rhs.shadowNode; } - bool operator!=(const ShadowViewNodePair& rhs) const { + bool operator!=(const ShadowViewNodePair &rhs) const + { return !(*this == rhs); } - bool inOtherTree() const { + bool inOtherTree() const + { return this->otherTreePair != nullptr; } }; diff --git a/packages/react-native/ReactCommon/react/renderer/mounting/internal/TinyMap.h b/packages/react-native/ReactCommon/react/renderer/mounting/internal/TinyMap.h index 99b37e2cd5c..445071d4468 100644 --- a/packages/react-native/ReactCommon/react/renderer/mounting/internal/TinyMap.h +++ b/packages/react-native/ReactCommon/react/renderer/mounting/internal/TinyMap.h @@ -36,12 +36,13 @@ template class TinyMap final { public: using Pair = std::pair; - using Iterator = Pair*; + using Iterator = Pair *; /** * This must strictly only be called from outside of this class. */ - inline Iterator begin() { + inline Iterator begin() + { // Force a clean so that iterating over this TinyMap doesn't iterate over // erased elements. If all elements erased are at the front of the vector, // then we don't need to clean. @@ -56,7 +57,8 @@ class TinyMap final { return nullptr; } - inline Iterator end() { + inline Iterator end() + { // `back()` asserts on the vector being non-empty if (vector_.empty() || numErased_ == vector_.size()) { return nullptr; @@ -65,7 +67,8 @@ class TinyMap final { return &vector_.back() + 1; } - inline Iterator find(KeyT key) { + inline Iterator find(KeyT key) + { cleanVector(); react_native_assert(key != 0); @@ -83,12 +86,14 @@ class TinyMap final { return end(); } - inline void insert(Pair pair) { + inline void insert(Pair pair) + { react_native_assert(pair.first != 0); vector_.push_back(pair); } - inline void erase(Iterator iterator) { + inline void erase(Iterator iterator) + { // Invalidate tag. iterator->first = 0; @@ -103,7 +108,8 @@ class TinyMap final { /** * Same as begin() but doesn't call cleanVector at the beginning. */ - inline Iterator begin_() { + inline Iterator begin_() + { // `front()` asserts on the vector being non-empty if (vector_.empty() || vector_.size() == numErased_) { return nullptr; @@ -117,9 +123,10 @@ class TinyMap final { * We only modify the vector if erased elements are at least half of the * vector. */ - inline void cleanVector(bool forceClean = false) { - if ((numErased_ < (vector_.size() / 2) && !forceClean) || vector_.empty() || - numErased_ == 0 || numErased_ == erasedAtFront_) { + inline void cleanVector(bool forceClean = false) + { + if ((numErased_ < (vector_.size() / 2) && !forceClean) || vector_.empty() || numErased_ == 0 || + numErased_ == erasedAtFront_) { return; } @@ -127,10 +134,7 @@ class TinyMap final { vector_.clear(); } else { vector_.erase( - std::remove_if( - vector_.begin(), - vector_.end(), - [](const auto& item) { return item.first == 0; }), + std::remove_if(vector_.begin(), vector_.end(), [](const auto &item) { return item.first == 0; }), vector_.end()); } numErased_ = 0; diff --git a/packages/react-native/ReactCommon/react/renderer/mounting/internal/sliceChildShadowNodeViewPairs.h b/packages/react-native/ReactCommon/react/renderer/mounting/internal/sliceChildShadowNodeViewPairs.h index 278be011446..869da1d5de1 100644 --- a/packages/react-native/ReactCommon/react/renderer/mounting/internal/sliceChildShadowNodeViewPairs.h +++ b/packages/react-native/ReactCommon/react/renderer/mounting/internal/sliceChildShadowNodeViewPairs.h @@ -43,11 +43,11 @@ using ViewNodePairScope = std::deque; * flattened view hierarchy. The V2 version preserves nodes even if they do * not form views and their children are flattened. */ -std::vector sliceChildShadowNodeViewPairs( - const ShadowViewNodePair& shadowNodePair, - ViewNodePairScope& viewNodePairScope, +std::vector sliceChildShadowNodeViewPairs( + const ShadowViewNodePair &shadowNodePair, + ViewNodePairScope &viewNodePairScope, bool allowFlattened, Point layoutOffset, - const CullingContext& cullingContext); + const CullingContext &cullingContext); } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/mounting/stubs/StubView.h b/packages/react-native/ReactCommon/react/renderer/mounting/stubs/StubView.h index 7d7b5137bda..690dd7353c6 100644 --- a/packages/react-native/ReactCommon/react/renderer/mounting/stubs/StubView.h +++ b/packages/react-native/ReactCommon/react/renderer/mounting/stubs/StubView.h @@ -24,11 +24,11 @@ class StubView final { using Shared = std::shared_ptr; StubView() = default; - StubView(const StubView& stubView) = default; + StubView(const StubView &stubView) = default; operator ShadowView() const; - void update(const ShadowView& shadowView); + void update(const ShadowView &shadowView); ComponentName componentName; ComponentHandle componentHandle; @@ -43,19 +43,17 @@ class StubView final { Tag parentTag{NO_VIEW_TAG}; }; -bool operator==(const StubView& lhs, const StubView& rhs); -bool operator!=(const StubView& lhs, const StubView& rhs); +bool operator==(const StubView &lhs, const StubView &rhs); +bool operator!=(const StubView &lhs, const StubView &rhs); #if RN_DEBUG_STRING_CONVERTIBLE -std::string getDebugName(const StubView& stubView); +std::string getDebugName(const StubView &stubView); std::vector getDebugProps( - const StubView& stubView, - DebugStringConvertibleOptions options); -std::vector getDebugChildren( - const StubView& stubView, + const StubView &stubView, DebugStringConvertibleOptions options); +std::vector getDebugChildren(const StubView &stubView, DebugStringConvertibleOptions options); #endif diff --git a/packages/react-native/ReactCommon/react/renderer/mounting/stubs/StubViewTree.h b/packages/react-native/ReactCommon/react/renderer/mounting/stubs/StubViewTree.h index e34ac9fbb3c..f6e92cef4c0 100644 --- a/packages/react-native/ReactCommon/react/renderer/mounting/stubs/StubViewTree.h +++ b/packages/react-native/ReactCommon/react/renderer/mounting/stubs/StubViewTree.h @@ -18,21 +18,18 @@ namespace facebook::react { class StubViewTree { public: StubViewTree() = default; - StubViewTree(const ShadowView& shadowView); + StubViewTree(const ShadowView &shadowView); - void mutate(const ShadowViewMutationList& mutations); + void mutate(const ShadowViewMutationList &mutations); - void dispatchCommand( - const ShadowView& shadowView, - const std::string& commandName, - const folly::dynamic& args); + void dispatchCommand(const ShadowView &shadowView, const std::string &commandName, const folly::dynamic &args); - const StubView& getRootStubView() const; + const StubView &getRootStubView() const; /* * Returns a view with given tag. */ - const StubView& getStubView(Tag tag) const; + const StubView &getStubView(Tag tag) const; /* * Returns the total amount of views in the tree. @@ -44,7 +41,8 @@ class StubViewTree { */ std::vector takeMountingLogs(); - bool hasTag(Tag tag) const { + bool hasTag(Tag tag) const + { return registry_.find(tag) != registry_.end(); } @@ -53,17 +51,17 @@ class StubViewTree { std::unordered_map registry_{}; std::vector mountingLogs_{}; - friend bool operator==(const StubViewTree& lhs, const StubViewTree& rhs); - friend bool operator!=(const StubViewTree& lhs, const StubViewTree& rhs); + friend bool operator==(const StubViewTree &lhs, const StubViewTree &rhs); + friend bool operator!=(const StubViewTree &lhs, const StubViewTree &rhs); - std::ostream& dumpTags(std::ostream& stream) const; + std::ostream &dumpTags(std::ostream &stream) const; std::string getNativeId(Tag tag); - std::string getNativeId(const ShadowView& shadowView); - void recordMutation(const ShadowViewMutation& mutation); + std::string getNativeId(const ShadowView &shadowView); + void recordMutation(const ShadowViewMutation &mutation); }; -bool operator==(const StubViewTree& lhs, const StubViewTree& rhs); -bool operator!=(const StubViewTree& lhs, const StubViewTree& rhs); +bool operator==(const StubViewTree &lhs, const StubViewTree &rhs); +bool operator!=(const StubViewTree &lhs, const StubViewTree &rhs); } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/mounting/stubs/stubs.cpp b/packages/react-native/ReactCommon/react/renderer/mounting/stubs/stubs.cpp index 168040b7eae..2b1a1f82ee1 100644 --- a/packages/react-native/ReactCommon/react/renderer/mounting/stubs/stubs.cpp +++ b/packages/react-native/ReactCommon/react/renderer/mounting/stubs/stubs.cpp @@ -56,10 +56,11 @@ static void calculateShadowViewMutationsForNewTree( mutations.push_back( ShadowViewMutation::CreateMutation(newChildPair->shadowView)); - mutations.push_back(ShadowViewMutation::InsertMutation( - parentShadowView.tag, - newChildPair->shadowView, - static_cast(newChildPair->mountIndex))); + mutations.push_back( + ShadowViewMutation::InsertMutation( + parentShadowView.tag, + newChildPair->shadowView, + static_cast(newChildPair->mountIndex))); auto newGrandChildPairs = sliceChildShadowNodeViewPairs(*newChildPair, scope, false, {}, {}); @@ -82,9 +83,10 @@ StubViewTree buildStubViewTreeWithoutUsingDifferentiator( ShadowView(rootShadowNode), sliceChildShadowNodeViewPairs(rootShadowNodePair, scope, false, {}, {})); - auto emptyRootShadowNode = rootShadowNode.clone(ShadowNodeFragment{ - .props = ShadowNodeFragment::propsPlaceholder(), - .children = ShadowNode::emptySharedShadowNodeSharedList()}); + auto emptyRootShadowNode = rootShadowNode.clone( + ShadowNodeFragment{ + .props = ShadowNodeFragment::propsPlaceholder(), + .children = ShadowNode::emptySharedShadowNodeSharedList()}); auto stubViewTree = StubViewTree(ShadowView(*emptyRootShadowNode)); stubViewTree.mutate(mutations); @@ -93,9 +95,10 @@ StubViewTree buildStubViewTreeWithoutUsingDifferentiator( StubViewTree buildStubViewTreeUsingDifferentiator( const ShadowNode& rootShadowNode) { - auto emptyRootShadowNode = rootShadowNode.clone(ShadowNodeFragment{ - .props = ShadowNodeFragment::propsPlaceholder(), - .children = ShadowNode::emptySharedShadowNodeSharedList()}); + auto emptyRootShadowNode = rootShadowNode.clone( + ShadowNodeFragment{ + .props = ShadowNodeFragment::propsPlaceholder(), + .children = ShadowNode::emptySharedShadowNodeSharedList()}); auto mutations = calculateShadowViewMutations(*emptyRootShadowNode, rootShadowNode); diff --git a/packages/react-native/ReactCommon/react/renderer/mounting/stubs/stubs.h b/packages/react-native/ReactCommon/react/renderer/mounting/stubs/stubs.h index d0829f339e6..0e03e715196 100644 --- a/packages/react-native/ReactCommon/react/renderer/mounting/stubs/stubs.h +++ b/packages/react-native/ReactCommon/react/renderer/mounting/stubs/stubs.h @@ -17,14 +17,12 @@ namespace facebook::react { * Builds a ShadowView tree from given root ShadowNode using custom built-in * implementation (*without* using Differentiator). */ -StubViewTree buildStubViewTreeWithoutUsingDifferentiator( - const ShadowNode& rootShadowNode); +StubViewTree buildStubViewTreeWithoutUsingDifferentiator(const ShadowNode &rootShadowNode); /* * Builds a ShadowView tree from given root ShadowNode using Differentiator by * generating mutation instructions between empty and final trees. */ -StubViewTree buildStubViewTreeUsingDifferentiator( - const ShadowNode& rootShadowNode); +StubViewTree buildStubViewTreeUsingDifferentiator(const ShadowNode &rootShadowNode); } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/mounting/tests/ShadowTreeLifeCycleTest.cpp b/packages/react-native/ReactCommon/react/renderer/mounting/tests/ShadowTreeLifeCycleTest.cpp index d599438fca0..fb22e2372cc 100644 --- a/packages/react-native/ReactCommon/react/renderer/mounting/tests/ShadowTreeLifeCycleTest.cpp +++ b/packages/react-native/ReactCommon/react/renderer/mounting/tests/ShadowTreeLifeCycleTest.cpp @@ -79,12 +79,13 @@ static void testShadowNodeTreeLifeCycle( // Injecting a tree into the root node. auto currentRootNode = std::static_pointer_cast( - emptyRootNode->ShadowNode::clone(ShadowNodeFragment{ - .props = ShadowNodeFragment::propsPlaceholder(), - .children = std::make_shared< - std::vector>>( - std::vector>{ - singleRootChildNode})})); + emptyRootNode->ShadowNode::clone( + ShadowNodeFragment{ + .props = ShadowNodeFragment::propsPlaceholder(), + .children = std::make_shared< + std::vector>>( + std::vector>{ + singleRootChildNode})})); // Building an initial view hierarchy. auto viewTree = StubViewTree(ShadowView(*emptyRootNode)); @@ -236,12 +237,13 @@ static void testShadowNodeTreeLifeCycleExtensiveFlatteningUnflattening( // Injecting a tree into the root node. auto currentRootNode = std::static_pointer_cast( - emptyRootNode->ShadowNode::clone(ShadowNodeFragment{ - .props = ShadowNodeFragment::propsPlaceholder(), - .children = std::make_shared< - std::vector>>( - std::vector>{ - singleRootChildNode})})); + emptyRootNode->ShadowNode::clone( + ShadowNodeFragment{ + .props = ShadowNodeFragment::propsPlaceholder(), + .children = std::make_shared< + std::vector>>( + std::vector>{ + singleRootChildNode})})); // Building an initial view hierarchy. auto viewTree = buildStubViewTreeWithoutUsingDifferentiator(*emptyRootNode); diff --git a/packages/react-native/ReactCommon/react/renderer/mounting/updateMountedFlag.h b/packages/react-native/ReactCommon/react/renderer/mounting/updateMountedFlag.h index eb03317bdf4..8d290e84aaa 100644 --- a/packages/react-native/ReactCommon/react/renderer/mounting/updateMountedFlag.h +++ b/packages/react-native/ReactCommon/react/renderer/mounting/updateMountedFlag.h @@ -15,7 +15,7 @@ namespace facebook::react { * Traverses the shadow tree and updates the `mounted` flag on all nodes. */ void updateMountedFlag( - const std::vector>& oldChildren, - const std::vector>& newChildren, + const std::vector> &oldChildren, + const std::vector> &newChildren, ShadowTreeCommitSource commitSource); } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/observers/events/EventPerformanceLogger.h b/packages/react-native/ReactCommon/react/renderer/observers/events/EventPerformanceLogger.h index 162ee030df8..8181a8079e7 100644 --- a/packages/react-native/ReactCommon/react/renderer/observers/events/EventPerformanceLogger.h +++ b/packages/react-native/ReactCommon/react/renderer/observers/events/EventPerformanceLogger.h @@ -24,16 +24,14 @@ class EventPerformanceLogger : public EventLogger, public RuntimeSchedulerEventTimingDelegate, public UIManagerMountHook { public: - explicit EventPerformanceLogger( - std::weak_ptr performanceEntryReporter); + explicit EventPerformanceLogger(std::weak_ptr performanceEntryReporter); #pragma mark - EventLogger EventTag onEventStart( std::string_view name, SharedEventTarget target, - std::optional eventStartTimeStamp = - std::nullopt) override; + std::optional eventStartTimeStamp = std::nullopt) override; void onEventProcessingStart(EventTag tag) override; void onEventProcessingEnd(EventTag tag) override; @@ -41,14 +39,11 @@ class EventPerformanceLogger : public EventLogger, void dispatchPendingEventTimingEntries( HighResTimeStamp taskEndTime, - const std::unordered_set& - surfaceIdsWithPendingRenderingUpdates) override; + const std::unordered_set &surfaceIdsWithPendingRenderingUpdates) override; #pragma mark - UIManagerMountHook - void shadowTreeDidMount( - const RootShadowNode::Shared& rootShadowNode, - HighResTimeStamp mountTime) noexcept override; + void shadowTreeDidMount(const RootShadowNode::Shared &rootShadowNode, HighResTimeStamp mountTime) noexcept override; private: struct EventEntry { @@ -65,7 +60,8 @@ class EventPerformanceLogger : public EventLogger, // (T141358175) PerformanceEntryInteractionId interactionId{0}; - bool isWaitingForDispatch() { + bool isWaitingForDispatch() + { return !processingEndTime.has_value(); } }; diff --git a/packages/react-native/ReactCommon/react/renderer/observers/intersection/IntersectionObserver.h b/packages/react-native/ReactCommon/react/renderer/observers/intersection/IntersectionObserver.h index ca77b70ea6f..4a689f18469 100644 --- a/packages/react-native/ReactCommon/react/renderer/observers/intersection/IntersectionObserver.h +++ b/packages/react-native/ReactCommon/react/renderer/observers/intersection/IntersectionObserver.h @@ -28,8 +28,7 @@ struct MarginValue { // "top right bottom left" where each value is either "Npx" or "N%" // The string is already validated and normalized by JS. // Returns a vector of 4 MarginValue structures (top, right, bottom, left). -std::vector parseNormalizedRootMargin( - const std::string& marginStr); +std::vector parseNormalizedRootMargin(const std::string &marginStr); struct IntersectionObserverEntry { IntersectionObserverObserverId intersectionObserverId; @@ -40,10 +39,9 @@ struct IntersectionObserverEntry { bool isIntersectingAboveThresholds; HighResTimeStamp time; - bool sameShadowNodeFamily( - const ShadowNodeFamily& otherShadowNodeFamily) const { - return std::addressof(*shadowNodeFamily) == - std::addressof(otherShadowNodeFamily); + bool sameShadowNodeFamily(const ShadowNodeFamily &otherShadowNodeFamily) const + { + return std::addressof(*shadowNodeFamily) == std::addressof(otherShadowNodeFamily); } }; @@ -60,37 +58,39 @@ class IntersectionObserver { // Partially equivalent to // https://w3c.github.io/IntersectionObserver/#update-intersection-observations-algo std::optional updateIntersectionObservation( - const RootShadowNode& rootShadowNode, + const RootShadowNode &rootShadowNode, HighResTimeStamp time); - std::optional - updateIntersectionObservationForSurfaceUnmount(HighResTimeStamp time); + std::optional updateIntersectionObservationForSurfaceUnmount(HighResTimeStamp time); - IntersectionObserverObserverId getIntersectionObserverId() const { + IntersectionObserverObserverId getIntersectionObserverId() const + { return intersectionObserverId_; } - ShadowNodeFamily::Shared getTargetShadowNodeFamily() const { + ShadowNodeFamily::Shared getTargetShadowNodeFamily() const + { return targetShadowNodeFamily_; } - std::vector getThresholds() const { + std::vector getThresholds() const + { return thresholds_; } private: std::optional setIntersectingState( - const Rect& rootBoundingRect, - const Rect& targetBoundingRect, - const Rect& intersectionRect, + const Rect &rootBoundingRect, + const Rect &targetBoundingRect, + const Rect &intersectionRect, Float threshold, Float rootThreshold, HighResTimeStamp time); std::optional setNotIntersectingState( - const Rect& rootBoundingRect, - const Rect& targetBoundingRect, - const Rect& intersectionRect, + const Rect &rootBoundingRect, + const Rect &targetBoundingRect, + const Rect &intersectionRect, HighResTimeStamp time); IntersectionObserverObserverId intersectionObserverId_; @@ -100,8 +100,7 @@ class IntersectionObserver { std::optional> rootThresholds_; // Parsed and expanded rootMargin values (top, right, bottom, left) std::vector rootMargins_; - mutable IntersectionObserverState state_ = - IntersectionObserverState::Initial(); + mutable IntersectionObserverState state_ = IntersectionObserverState::Initial(); }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/observers/intersection/IntersectionObserverManager.cpp b/packages/react-native/ReactCommon/react/renderer/observers/intersection/IntersectionObserverManager.cpp index e4d6bb86f19..7369935a9b4 100644 --- a/packages/react-native/ReactCommon/react/renderer/observers/intersection/IntersectionObserverManager.cpp +++ b/packages/react-native/ReactCommon/react/renderer/observers/intersection/IntersectionObserverManager.cpp @@ -60,13 +60,14 @@ void IntersectionObserverManager::observe( auto parsedRootMargin = parseNormalizedRootMargin(rootMargin.value_or("0px 0px 0px 0px")); - observers.emplace_back(std::make_unique( - intersectionObserverId, - observationRootShadowNodeFamily, - shadowNodeFamily, - std::move(thresholds), - std::move(rootThresholds), - std::move(parsedRootMargin))); + observers.emplace_back( + std::make_unique( + intersectionObserverId, + observationRootShadowNodeFamily, + shadowNodeFamily, + std::move(thresholds), + std::move(rootThresholds), + std::move(parsedRootMargin))); observersPendingInitialization_.emplace_back(observers.back().get()); } diff --git a/packages/react-native/ReactCommon/react/renderer/observers/intersection/IntersectionObserverManager.h b/packages/react-native/ReactCommon/react/renderer/observers/intersection/IntersectionObserverManager.h index c68dde1ce1c..06e7daa0a70 100644 --- a/packages/react-native/ReactCommon/react/renderer/observers/intersection/IntersectionObserverManager.h +++ b/packages/react-native/ReactCommon/react/renderer/observers/intersection/IntersectionObserverManager.h @@ -19,65 +19,55 @@ namespace facebook::react { -class IntersectionObserverManager final - : public UIManagerMountHook, - public RuntimeSchedulerIntersectionObserverDelegate { +class IntersectionObserverManager final : public UIManagerMountHook, + public RuntimeSchedulerIntersectionObserverDelegate { public: IntersectionObserverManager(); void observe( IntersectionObserverObserverId intersectionObserverId, - const std::optional& observationRootShadowNode, - const ShadowNodeFamily::Shared& shadowNode, + const std::optional &observationRootShadowNode, + const ShadowNodeFamily::Shared &shadowNode, std::vector thresholds, std::optional> rootThresholds, std::optional rootMargin, - const UIManager& uiManager); + const UIManager &uiManager); - void unobserve( - IntersectionObserverObserverId intersectionObserverId, - const ShadowNodeFamily::Shared& shadowNode); + void unobserve(IntersectionObserverObserverId intersectionObserverId, const ShadowNodeFamily::Shared &shadowNode); void connect( - RuntimeScheduler& runtimeScheduler, - UIManager& uiManager, + RuntimeScheduler &runtimeScheduler, + UIManager &uiManager, std::function notifyIntersectionObserversCallback); - void disconnect(RuntimeScheduler& runtimeScheduler, UIManager& uiManager); + void disconnect(RuntimeScheduler &runtimeScheduler, UIManager &uiManager); std::vector takeRecords(); #pragma mark - RuntimeSchedulerIntersectionObserverDelegate void updateIntersectionObservations( - const std::unordered_set& - surfaceIdsWithPendingRenderingUpdates) override; + const std::unordered_set &surfaceIdsWithPendingRenderingUpdates) override; #pragma mark - UIManagerMountHook - void shadowTreeDidMount( - const RootShadowNode::Shared& rootShadowNode, - HighResTimeStamp time) noexcept override; + void shadowTreeDidMount(const RootShadowNode::Shared &rootShadowNode, HighResTimeStamp time) noexcept override; - void shadowTreeDidUnmount(SurfaceId surfaceId, HighResTimeStamp time) noexcept - override; + void shadowTreeDidUnmount(SurfaceId surfaceId, HighResTimeStamp time) noexcept override; private: - mutable std::unordered_map< - SurfaceId, - std::vector>> - observersBySurfaceId_; + mutable std::unordered_map>> observersBySurfaceId_; mutable std::shared_mutex observersMutex_; // This is defined as a list of pointers to keep the ownership of the // observers in the map. - std::vector observersPendingInitialization_; + std::vector observersPendingInitialization_; // This is only accessed from the JS thread at the end of the event loop tick, // so it is safe to retain it as a raw pointer. // We need to retain it here because the RuntimeScheduler does not provide // it when calling `updateIntersectionObservations`. - const ShadowTreeRegistry* shadowTreeRegistry_{nullptr}; + const ShadowTreeRegistry *shadowTreeRegistry_{nullptr}; mutable std::function notifyIntersectionObserversCallback_; @@ -92,12 +82,9 @@ class IntersectionObserverManager final // Equivalent to // https://w3c.github.io/IntersectionObserver/#update-intersection-observations-algo - void updateIntersectionObservations( - SurfaceId surfaceId, - const RootShadowNode* rootShadowNode, - HighResTimeStamp time); + void updateIntersectionObservations(SurfaceId surfaceId, const RootShadowNode *rootShadowNode, HighResTimeStamp time); - const IntersectionObserver& getRegisteredIntersectionObserver( + const IntersectionObserver &getRegisteredIntersectionObserver( SurfaceId surfaceId, IntersectionObserverObserverId observerId) const; }; diff --git a/packages/react-native/ReactCommon/react/renderer/observers/intersection/IntersectionObserverState.h b/packages/react-native/ReactCommon/react/renderer/observers/intersection/IntersectionObserverState.h index 56b0a4048c5..14ba6c64237 100644 --- a/packages/react-native/ReactCommon/react/renderer/observers/intersection/IntersectionObserverState.h +++ b/packages/react-native/ReactCommon/react/renderer/observers/intersection/IntersectionObserverState.h @@ -25,22 +25,17 @@ class IntersectionObserverState { static IntersectionObserverState Initial(); static IntersectionObserverState NotIntersecting(); static IntersectionObserverState Intersecting(Float threshold); - static IntersectionObserverState Intersecting( - Float threshold, - Float rootThreshold); + static IntersectionObserverState Intersecting(Float threshold, Float rootThreshold); bool isIntersecting() const; - bool operator==(const IntersectionObserverState& other) const; - bool operator!=(const IntersectionObserverState& other) const; + bool operator==(const IntersectionObserverState &other) const; + bool operator!=(const IntersectionObserverState &other) const; private: explicit IntersectionObserverState(IntersectionObserverStateType state); - IntersectionObserverState( - IntersectionObserverStateType state, - Float threshold, - Float rootThreshold); + IntersectionObserverState(IntersectionObserverStateType state, Float threshold, Float rootThreshold); IntersectionObserverStateType state_; diff --git a/packages/react-native/ReactCommon/react/renderer/observers/mutation/MutationObserver.cpp b/packages/react-native/ReactCommon/react/renderer/observers/mutation/MutationObserver.cpp index 7d98dcc7628..146bf6b7b14 100644 --- a/packages/react-native/ReactCommon/react/renderer/observers/mutation/MutationObserver.cpp +++ b/packages/react-native/ReactCommon/react/renderer/observers/mutation/MutationObserver.cpp @@ -175,11 +175,12 @@ void MutationObserver::recordMutationsInSubtrees( } if (!addedNodes.empty() || !removedNodes.empty()) { - recordedMutations.emplace_back(MutationRecord{ - .mutationObserverId = mutationObserverId_, - .targetShadowNode = oldNode, - .addedShadowNodes = std::move(addedNodes), - .removedShadowNodes = std::move(removedNodes)}); + recordedMutations.emplace_back( + MutationRecord{ + .mutationObserverId = mutationObserverId_, + .targetShadowNode = oldNode, + .addedShadowNodes = std::move(addedNodes), + .removedShadowNodes = std::move(removedNodes)}); } } diff --git a/packages/react-native/ReactCommon/react/renderer/observers/mutation/MutationObserver.h b/packages/react-native/ReactCommon/react/renderer/observers/mutation/MutationObserver.h index 2af8e29bd13..becead06d14 100644 --- a/packages/react-native/ReactCommon/react/renderer/observers/mutation/MutationObserver.h +++ b/packages/react-native/ReactCommon/react/renderer/observers/mutation/MutationObserver.h @@ -27,49 +27,45 @@ class MutationObserver { explicit MutationObserver(MutationObserverId mutationObserverId); // delete copy constructor - MutationObserver(const MutationObserver&) = delete; + MutationObserver(const MutationObserver &) = delete; // delete copy assignment - MutationObserver& operator=(const MutationObserver&) = delete; + MutationObserver &operator=(const MutationObserver &) = delete; // allow move constructor - MutationObserver(MutationObserver&&) = default; + MutationObserver(MutationObserver &&) = default; // allow move assignment - MutationObserver& operator=(MutationObserver&&) = default; + MutationObserver &operator=(MutationObserver &&) = default; - void observe( - std::shared_ptr targetShadowNodeFamily, - bool observeSubtree); + void observe(std::shared_ptr targetShadowNodeFamily, bool observeSubtree); void recordMutations( - const RootShadowNode& oldRootShadowNode, - const RootShadowNode& newRootShadowNode, - std::vector& recordedMutations) const; + const RootShadowNode &oldRootShadowNode, + const RootShadowNode &newRootShadowNode, + std::vector &recordedMutations) const; private: MutationObserverId mutationObserverId_; - std::vector> - deeplyObservedShadowNodeFamilies_; - std::vector> - shallowlyObservedShadowNodeFamilies_; + std::vector> deeplyObservedShadowNodeFamilies_; + std::vector> shallowlyObservedShadowNodeFamilies_; - using SetOfShadowNodePointers = std::unordered_set; + using SetOfShadowNodePointers = std::unordered_set; void recordMutationsInTarget( - const ShadowNodeFamily& targetShadowNodeFamily, - const RootShadowNode& oldRootShadowNode, - const RootShadowNode& newRootShadowNode, + const ShadowNodeFamily &targetShadowNodeFamily, + const RootShadowNode &oldRootShadowNode, + const RootShadowNode &newRootShadowNode, bool observeSubtree, - std::vector& recordedMutations, - SetOfShadowNodePointers& processedNodes) const; + std::vector &recordedMutations, + SetOfShadowNodePointers &processedNodes) const; void recordMutationsInSubtrees( - const std::shared_ptr& oldNode, - const std::shared_ptr& newNode, + const std::shared_ptr &oldNode, + const std::shared_ptr &newNode, bool observeSubtree, - std::vector& recordedMutations, - SetOfShadowNodePointers& processedNodes) const; + std::vector &recordedMutations, + SetOfShadowNodePointers &processedNodes) const; }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/observers/mutation/MutationObserverManager.h b/packages/react-native/ReactCommon/react/renderer/observers/mutation/MutationObserverManager.h index 53021433069..587bc526fa9 100644 --- a/packages/react-native/ReactCommon/react/renderer/observers/mutation/MutationObserverManager.h +++ b/packages/react-native/ReactCommon/react/renderer/observers/mutation/MutationObserverManager.h @@ -16,7 +16,7 @@ namespace facebook::react { -using OnMutations = std::function&)>; +using OnMutations = std::function &)>; class MutationObserverManager final : public UIManagerCommitHook { public: @@ -26,38 +26,35 @@ class MutationObserverManager final : public UIManagerCommitHook { MutationObserverId mutationObserverId, std::shared_ptr shadowNode, bool observeSubtree, - const UIManager& uiManager); + const UIManager &uiManager); void unobserveAll(MutationObserverId mutationObserverId); - void connect(UIManager& uiManager, OnMutations&& onMutations); + void connect(UIManager &uiManager, OnMutations &&onMutations); - void disconnect(UIManager& uiManager); + void disconnect(UIManager &uiManager); #pragma mark - UIManagerCommitHook - void commitHookWasRegistered(const UIManager& uiManager) noexcept override; - void commitHookWasUnregistered(const UIManager& uiManager) noexcept override; + void commitHookWasRegistered(const UIManager &uiManager) noexcept override; + void commitHookWasUnregistered(const UIManager &uiManager) noexcept override; RootShadowNode::Unshared shadowTreeWillCommit( - const ShadowTree& shadowTree, - const RootShadowNode::Shared& oldRootShadowNode, - const RootShadowNode::Unshared& newRootShadowNode, - const ShadowTree::CommitOptions& commitOptions) noexcept override; + const ShadowTree &shadowTree, + const RootShadowNode::Shared &oldRootShadowNode, + const RootShadowNode::Unshared &newRootShadowNode, + const ShadowTree::CommitOptions &commitOptions) noexcept override; private: - std::unordered_map< - SurfaceId, - std::unordered_map> - observersBySurfaceId_; + std::unordered_map> observersBySurfaceId_; OnMutations onMutations_; bool commitHookRegistered_{}; void runMutationObservations( - const ShadowTree& shadowTree, - const RootShadowNode& oldRootShadowNode, - const RootShadowNode& newRootShadowNode); + const ShadowTree &shadowTree, + const RootShadowNode &oldRootShadowNode, + const RootShadowNode &newRootShadowNode); }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeScheduler.h b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeScheduler.h index 813537ec7ae..ded6174907f 100644 --- a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeScheduler.h +++ b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeScheduler.h @@ -21,8 +21,7 @@ namespace facebook::react { using RuntimeSchedulerRenderingUpdate = std::function; using SurfaceId = int32_t; -using RuntimeSchedulerTaskErrorHandler = - std::function; +using RuntimeSchedulerTaskErrorHandler = std::function; extern const char RuntimeSchedulerKey[]; @@ -31,39 +30,27 @@ extern const char RuntimeSchedulerKey[]; class RuntimeSchedulerBase { public: virtual ~RuntimeSchedulerBase() = default; - virtual void scheduleWork(RawCallback&& callback) noexcept = 0; - virtual void executeNowOnTheSameThread(RawCallback&& callback) = 0; - virtual std::shared_ptr scheduleTask( - SchedulerPriority priority, - jsi::Function&& callback) noexcept = 0; - virtual std::shared_ptr scheduleTask( - SchedulerPriority priority, - RawCallback&& callback) noexcept = 0; + virtual void scheduleWork(RawCallback &&callback) noexcept = 0; + virtual void executeNowOnTheSameThread(RawCallback &&callback) = 0; + virtual std::shared_ptr scheduleTask(SchedulerPriority priority, jsi::Function &&callback) noexcept = 0; + virtual std::shared_ptr scheduleTask(SchedulerPriority priority, RawCallback &&callback) noexcept = 0; virtual std::shared_ptr scheduleIdleTask( - jsi::Function&& callback, - HighResDuration timeout = timeoutForSchedulerPriority( - SchedulerPriority::IdlePriority)) noexcept = 0; + jsi::Function &&callback, + HighResDuration timeout = timeoutForSchedulerPriority(SchedulerPriority::IdlePriority)) noexcept = 0; virtual std::shared_ptr scheduleIdleTask( - RawCallback&& callback, - HighResDuration timeout = timeoutForSchedulerPriority( - SchedulerPriority::IdlePriority)) noexcept = 0; - virtual void cancelTask(Task& task) noexcept = 0; + RawCallback &&callback, + HighResDuration timeout = timeoutForSchedulerPriority(SchedulerPriority::IdlePriority)) noexcept = 0; + virtual void cancelTask(Task &task) noexcept = 0; virtual bool getShouldYield() noexcept = 0; virtual SchedulerPriority getCurrentPriorityLevel() const noexcept = 0; virtual HighResTimeStamp now() const noexcept = 0; - virtual void callExpiredTasks(jsi::Runtime& runtime) = 0; - virtual void scheduleRenderingUpdate( - SurfaceId surfaceId, - RuntimeSchedulerRenderingUpdate&& renderingUpdate) = 0; - virtual void setShadowTreeRevisionConsistencyManager( - ShadowTreeRevisionConsistencyManager* provider) = 0; - virtual void setPerformanceEntryReporter( - PerformanceEntryReporter* reporter) = 0; - virtual void setEventTimingDelegate( - RuntimeSchedulerEventTimingDelegate* eventTimingDelegate) = 0; + virtual void callExpiredTasks(jsi::Runtime &runtime) = 0; + virtual void scheduleRenderingUpdate(SurfaceId surfaceId, RuntimeSchedulerRenderingUpdate &&renderingUpdate) = 0; + virtual void setShadowTreeRevisionConsistencyManager(ShadowTreeRevisionConsistencyManager *provider) = 0; + virtual void setPerformanceEntryReporter(PerformanceEntryReporter *reporter) = 0; + virtual void setEventTimingDelegate(RuntimeSchedulerEventTimingDelegate *eventTimingDelegate) = 0; virtual void setIntersectionObserverDelegate( - RuntimeSchedulerIntersectionObserverDelegate* - intersectionObserverDelegate) = 0; + RuntimeSchedulerIntersectionObserverDelegate *intersectionObserverDelegate) = 0; }; // This is a proxy for RuntimeScheduler implementation, which will be selected @@ -78,16 +65,16 @@ class RuntimeScheduler final : RuntimeSchedulerBase { /* * Not copyable. */ - RuntimeScheduler(const RuntimeScheduler&) = delete; - RuntimeScheduler& operator=(const RuntimeScheduler&) = delete; + RuntimeScheduler(const RuntimeScheduler &) = delete; + RuntimeScheduler &operator=(const RuntimeScheduler &) = delete; /* * Not movable. */ - RuntimeScheduler(RuntimeScheduler&&) = delete; - RuntimeScheduler& operator=(RuntimeScheduler&&) = delete; + RuntimeScheduler(RuntimeScheduler &&) = delete; + RuntimeScheduler &operator=(RuntimeScheduler &&) = delete; - void scheduleWork(RawCallback&& callback) noexcept override; + void scheduleWork(RawCallback &&callback) noexcept override; /* * Grants access to the runtime synchronously on the caller's thread. @@ -96,7 +83,7 @@ class RuntimeScheduler final : RuntimeSchedulerBase { * by dispatching a synchronous event via event emitter in your native * component. */ - void executeNowOnTheSameThread(RawCallback&& callback) override; + void executeNowOnTheSameThread(RawCallback &&callback) override; /* * Adds a JavaScript callback to priority queue with given priority. @@ -104,23 +91,17 @@ class RuntimeScheduler final : RuntimeSchedulerBase { * * Thread synchronization must be enforced externally. */ - std::shared_ptr scheduleTask( - SchedulerPriority priority, - jsi::Function&& callback) noexcept override; + std::shared_ptr scheduleTask(SchedulerPriority priority, jsi::Function &&callback) noexcept override; - std::shared_ptr scheduleTask( - SchedulerPriority priority, - RawCallback&& callback) noexcept override; + std::shared_ptr scheduleTask(SchedulerPriority priority, RawCallback &&callback) noexcept override; std::shared_ptr scheduleIdleTask( - jsi::Function&& callback, - HighResDuration timeout = timeoutForSchedulerPriority( - SchedulerPriority::IdlePriority)) noexcept override; + jsi::Function &&callback, + HighResDuration timeout = timeoutForSchedulerPriority(SchedulerPriority::IdlePriority)) noexcept override; std::shared_ptr scheduleIdleTask( - RawCallback&& callback, - HighResDuration timeout = timeoutForSchedulerPriority( - SchedulerPriority::IdlePriority)) noexcept override; + RawCallback &&callback, + HighResDuration timeout = timeoutForSchedulerPriority(SchedulerPriority::IdlePriority)) noexcept override; /* * Cancelled task will never be executed. @@ -128,7 +109,7 @@ class RuntimeScheduler final : RuntimeSchedulerBase { * Operates on JSI object. * Thread synchronization must be enforced externally. */ - void cancelTask(Task& task) noexcept override; + void cancelTask(Task &task) noexcept override; /* * Return value indicates if host platform has a pending access to the @@ -161,33 +142,26 @@ class RuntimeScheduler final : RuntimeSchedulerBase { * * Thread synchronization must be enforced externally. */ - void callExpiredTasks(jsi::Runtime& runtime) override; + void callExpiredTasks(jsi::Runtime &runtime) override; - void scheduleRenderingUpdate( - SurfaceId surfaceId, - RuntimeSchedulerRenderingUpdate&& renderingUpdate) override; + void scheduleRenderingUpdate(SurfaceId surfaceId, RuntimeSchedulerRenderingUpdate &&renderingUpdate) override; void setShadowTreeRevisionConsistencyManager( - ShadowTreeRevisionConsistencyManager* - shadowTreeRevisionConsistencyManager) override; + ShadowTreeRevisionConsistencyManager *shadowTreeRevisionConsistencyManager) override; - void setPerformanceEntryReporter(PerformanceEntryReporter* reporter) override; + void setPerformanceEntryReporter(PerformanceEntryReporter *reporter) override; - void setEventTimingDelegate( - RuntimeSchedulerEventTimingDelegate* eventTimingDelegate) override; + void setEventTimingDelegate(RuntimeSchedulerEventTimingDelegate *eventTimingDelegate) override; void setIntersectionObserverDelegate( - RuntimeSchedulerIntersectionObserverDelegate* - intersectionObserverDelegate) override; + RuntimeSchedulerIntersectionObserverDelegate *intersectionObserverDelegate) override; private: // Actual implementation, stored as a unique pointer to simplify memory // management. std::unique_ptr runtimeSchedulerImpl_; - static void handleTaskErrorDefault( - jsi::Runtime& runtime, - jsi::JSError& error); + static void handleTaskErrorDefault(jsi::Runtime &runtime, jsi::JSError &error); }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeSchedulerBinding.cpp b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeSchedulerBinding.cpp index 4adbcccb570..69c9e16d564 100644 --- a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeSchedulerBinding.cpp +++ b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeSchedulerBinding.cpp @@ -127,7 +127,7 @@ jsi::Value RuntimeSchedulerBinding::get( name, 0, [](jsi::Runtime&, const jsi::Value&, const jsi::Value*, size_t) noexcept - -> jsi::Value { + -> jsi::Value { // RequestPaint is left empty by design. return jsi::Value::undefined(); }); diff --git a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeSchedulerBinding.h b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeSchedulerBinding.h index 1987b1146f9..6e1c2a79c91 100644 --- a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeSchedulerBinding.h +++ b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeSchedulerBinding.h @@ -27,15 +27,14 @@ class RuntimeSchedulerBinding : public jsi::HostObject { * installed, returns that. */ static std::shared_ptr createAndInstallIfNeeded( - jsi::Runtime& runtime, - const std::shared_ptr& runtimeScheduler); + jsi::Runtime &runtime, + const std::shared_ptr &runtimeScheduler); /* * Returns a shared pointer to RuntimeSchedulerBinding previously installed * into a runtime. Thread synchronization must be enforced externally. */ - static std::shared_ptr getBinding( - jsi::Runtime& runtime); + static std::shared_ptr getBinding(jsi::Runtime &runtime); /* * Returns shared pointer to RuntimeScheduler for use in native modules @@ -45,7 +44,7 @@ class RuntimeSchedulerBinding : public jsi::HostObject { /* * `jsi::HostObject` specific overloads. */ - jsi::Value get(jsi::Runtime& runtime, const jsi::PropNameID& name) override; + jsi::Value get(jsi::Runtime &runtime, const jsi::PropNameID &name) override; private: std::shared_ptr runtimeScheduler_; diff --git a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeSchedulerCallInvoker.h b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeSchedulerCallInvoker.h index e66eb643e2a..590b27a7048 100644 --- a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeSchedulerCallInvoker.h +++ b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeSchedulerCallInvoker.h @@ -21,10 +21,9 @@ class RuntimeSchedulerCallInvoker : public CallInvoker { public: RuntimeSchedulerCallInvoker(std::weak_ptr runtimeScheduler); - void invokeAsync(CallFunc&& func) noexcept override; - void invokeSync(CallFunc&& func) override; - void invokeAsync(SchedulerPriority priority, CallFunc&& func) noexcept - override; + void invokeAsync(CallFunc &&func) noexcept override; + void invokeSync(CallFunc &&func) override; + void invokeAsync(SchedulerPriority priority, CallFunc &&func) noexcept override; private: /* diff --git a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeSchedulerEventTimingDelegate.h b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeSchedulerEventTimingDelegate.h index 309ead75b11..5900c33a9f4 100644 --- a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeSchedulerEventTimingDelegate.h +++ b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeSchedulerEventTimingDelegate.h @@ -20,8 +20,7 @@ class RuntimeSchedulerEventTimingDelegate { virtual void dispatchPendingEventTimingEntries( HighResTimeStamp taskEndTime, - const std::unordered_set& - surfaceIdsWithPendingRenderingUpdates) = 0; + const std::unordered_set &surfaceIdsWithPendingRenderingUpdates) = 0; }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeSchedulerIntersectionObserverDelegate.h b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeSchedulerIntersectionObserverDelegate.h index be58f754aaa..614aed82e81 100644 --- a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeSchedulerIntersectionObserverDelegate.h +++ b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeSchedulerIntersectionObserverDelegate.h @@ -18,8 +18,7 @@ class RuntimeSchedulerIntersectionObserverDelegate { virtual ~RuntimeSchedulerIntersectionObserverDelegate() = default; virtual void updateIntersectionObservations( - const std::unordered_set& - surfaceIdsWithPendingRenderingUpdates) = 0; + const std::unordered_set &surfaceIdsWithPendingRenderingUpdates) = 0; }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeScheduler_Legacy.h b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeScheduler_Legacy.h index 3856a0645ba..d5519bfcb4e 100644 --- a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeScheduler_Legacy.h +++ b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeScheduler_Legacy.h @@ -27,16 +27,16 @@ class RuntimeScheduler_Legacy final : public RuntimeSchedulerBase { /* * Not copyable. */ - RuntimeScheduler_Legacy(const RuntimeScheduler_Legacy&) = delete; - RuntimeScheduler_Legacy& operator=(const RuntimeScheduler_Legacy&) = delete; + RuntimeScheduler_Legacy(const RuntimeScheduler_Legacy &) = delete; + RuntimeScheduler_Legacy &operator=(const RuntimeScheduler_Legacy &) = delete; /* * Not movable. */ - RuntimeScheduler_Legacy(RuntimeScheduler_Legacy&&) = delete; - RuntimeScheduler_Legacy& operator=(RuntimeScheduler_Legacy&&) = delete; + RuntimeScheduler_Legacy(RuntimeScheduler_Legacy &&) = delete; + RuntimeScheduler_Legacy &operator=(RuntimeScheduler_Legacy &&) = delete; - void scheduleWork(RawCallback&& callback) noexcept override; + void scheduleWork(RawCallback &&callback) noexcept override; /* * Grants access to the runtime synchronously on the caller's thread. @@ -45,7 +45,7 @@ class RuntimeScheduler_Legacy final : public RuntimeSchedulerBase { * by dispatching a synchronous event via event emitter in your native * component. */ - void executeNowOnTheSameThread(RawCallback&& callback) override; + void executeNowOnTheSameThread(RawCallback &&callback) override; /* * Adds a JavaScript callback to priority queue with given priority. @@ -53,31 +53,25 @@ class RuntimeScheduler_Legacy final : public RuntimeSchedulerBase { * * Thread synchronization must be enforced externally. */ - std::shared_ptr scheduleTask( - SchedulerPriority priority, - jsi::Function&& callback) noexcept override; + std::shared_ptr scheduleTask(SchedulerPriority priority, jsi::Function &&callback) noexcept override; - std::shared_ptr scheduleTask( - SchedulerPriority priority, - RawCallback&& callback) noexcept override; + std::shared_ptr scheduleTask(SchedulerPriority priority, RawCallback &&callback) noexcept override; /* * Adds a JavaScript callback to the idle queue with the given timeout. * Triggers workloop if needed. */ std::shared_ptr scheduleIdleTask( - jsi::Function&& callback, - HighResDuration timeout = timeoutForSchedulerPriority( - SchedulerPriority::IdlePriority)) noexcept override; + jsi::Function &&callback, + HighResDuration timeout = timeoutForSchedulerPriority(SchedulerPriority::IdlePriority)) noexcept override; /* * Adds a custom callback to the idle queue with the given timeout. * Triggers workloop if needed. */ std::shared_ptr scheduleIdleTask( - RawCallback&& callback, - HighResDuration timeout = timeoutForSchedulerPriority( - SchedulerPriority::IdlePriority)) noexcept override; + RawCallback &&callback, + HighResDuration timeout = timeoutForSchedulerPriority(SchedulerPriority::IdlePriority)) noexcept override; /* * Cancelled task will never be executed. @@ -85,7 +79,7 @@ class RuntimeScheduler_Legacy final : public RuntimeSchedulerBase { * Operates on JSI object. * Thread synchronization must be enforced externally. */ - void cancelTask(Task& task) noexcept override; + void cancelTask(Task &task) noexcept override; /* * Return value indicates if host platform has a pending access to the @@ -118,32 +112,22 @@ class RuntimeScheduler_Legacy final : public RuntimeSchedulerBase { * * Thread synchronization must be enforced externally. */ - void callExpiredTasks(jsi::Runtime& runtime) override; + void callExpiredTasks(jsi::Runtime &runtime) override; - void scheduleRenderingUpdate( - SurfaceId surfaceId, - RuntimeSchedulerRenderingUpdate&& renderingUpdate) override; + void scheduleRenderingUpdate(SurfaceId surfaceId, RuntimeSchedulerRenderingUpdate &&renderingUpdate) override; void setShadowTreeRevisionConsistencyManager( - ShadowTreeRevisionConsistencyManager* - shadowTreeRevisionConsistencyManager) override; + ShadowTreeRevisionConsistencyManager *shadowTreeRevisionConsistencyManager) override; - void setPerformanceEntryReporter( - PerformanceEntryReporter* performanceEntryReporter) override; + void setPerformanceEntryReporter(PerformanceEntryReporter *performanceEntryReporter) override; - void setEventTimingDelegate( - RuntimeSchedulerEventTimingDelegate* eventTimingDelegate) override; + void setEventTimingDelegate(RuntimeSchedulerEventTimingDelegate *eventTimingDelegate) override; void setIntersectionObserverDelegate( - RuntimeSchedulerIntersectionObserverDelegate* - intersectionObserverDelegate) override; + RuntimeSchedulerIntersectionObserverDelegate *intersectionObserverDelegate) override; private: - std::priority_queue< - std::shared_ptr, - std::vector>, - TaskPriorityComparer> - taskQueue_; + std::priority_queue, std::vector>, TaskPriorityComparer> taskQueue_; const RuntimeExecutor runtimeExecutor_; SchedulerPriority currentPriority_{SchedulerPriority::NormalPriority}; @@ -155,7 +139,7 @@ class RuntimeScheduler_Legacy final : public RuntimeSchedulerBase { std::atomic_bool isSynchronous_{false}; - void startWorkLoop(jsi::Runtime& runtime); + void startWorkLoop(jsi::Runtime &runtime); /* * Schedules a work loop unless it has been already scheduled @@ -163,10 +147,7 @@ class RuntimeScheduler_Legacy final : public RuntimeSchedulerBase { */ void scheduleWorkLoopIfNecessary(); - void executeTask( - jsi::Runtime& runtime, - const std::shared_ptr& task, - bool didUserCallbackTimeout); + void executeTask(jsi::Runtime &runtime, const std::shared_ptr &task, bool didUserCallbackTimeout); /* * Returns a time point representing the current point in time. May be called @@ -185,8 +166,7 @@ class RuntimeScheduler_Legacy final : public RuntimeSchedulerBase { */ std::atomic_bool isPerformingWork_{false}; - std::atomic - shadowTreeRevisionConsistencyManager_{nullptr}; + std::atomic shadowTreeRevisionConsistencyManager_{nullptr}; RuntimeSchedulerTaskErrorHandler onTaskError_; }; diff --git a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeScheduler_Modern.h b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeScheduler_Modern.h index cf471f8867c..05ba08896f1 100644 --- a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeScheduler_Modern.h +++ b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeScheduler_Modern.h @@ -28,14 +28,14 @@ class RuntimeScheduler_Modern final : public RuntimeSchedulerBase { /* * Not copyable. */ - RuntimeScheduler_Modern(const RuntimeScheduler_Modern&) = delete; - RuntimeScheduler_Modern& operator=(const RuntimeScheduler_Modern&) = delete; + RuntimeScheduler_Modern(const RuntimeScheduler_Modern &) = delete; + RuntimeScheduler_Modern &operator=(const RuntimeScheduler_Modern &) = delete; /* * Not movable. */ - RuntimeScheduler_Modern(RuntimeScheduler_Modern&&) = delete; - RuntimeScheduler_Modern& operator=(RuntimeScheduler_Modern&&) = delete; + RuntimeScheduler_Modern(RuntimeScheduler_Modern &&) = delete; + RuntimeScheduler_Modern &operator=(RuntimeScheduler_Modern &&) = delete; /* * Alias for scheduleTask with immediate priority. @@ -43,7 +43,7 @@ class RuntimeScheduler_Modern final : public RuntimeSchedulerBase { * To be removed when we finish testing this implementation. * All callers should use scheduleTask with the right priority after that. */ - void scheduleWork(RawCallback&& callback) noexcept override; + void scheduleWork(RawCallback &&callback) noexcept override; /* * Grants access to the runtime synchronously on the caller's thread. @@ -52,41 +52,35 @@ class RuntimeScheduler_Modern final : public RuntimeSchedulerBase { * by dispatching a synchronous event via event emitter in your native * component. */ - void executeNowOnTheSameThread(RawCallback&& callback) override; + void executeNowOnTheSameThread(RawCallback &&callback) override; /* * Adds a JavaScript callback to the priority queue with the given priority. * Triggers event loop if needed. */ - std::shared_ptr scheduleTask( - SchedulerPriority priority, - jsi::Function&& callback) noexcept override; + std::shared_ptr scheduleTask(SchedulerPriority priority, jsi::Function &&callback) noexcept override; /* * Adds a custom callback to the priority queue with the given priority. * Triggers event loop if needed. */ - std::shared_ptr scheduleTask( - SchedulerPriority priority, - RawCallback&& callback) noexcept override; + std::shared_ptr scheduleTask(SchedulerPriority priority, RawCallback &&callback) noexcept override; /* * Adds a JavaScript callback to the idle queue with the given timeout. * Triggers event loop if needed. */ std::shared_ptr scheduleIdleTask( - jsi::Function&& callback, - HighResDuration customTimeout = timeoutForSchedulerPriority( - SchedulerPriority::IdlePriority)) noexcept override; + jsi::Function &&callback, + HighResDuration customTimeout = timeoutForSchedulerPriority(SchedulerPriority::IdlePriority)) noexcept override; /* * Adds a custom callback to the idle queue with the given timeout. * Triggers event loop if needed. */ std::shared_ptr scheduleIdleTask( - RawCallback&& callback, - HighResDuration customTimeout = timeoutForSchedulerPriority( - SchedulerPriority::IdlePriority)) noexcept override; + RawCallback &&callback, + HighResDuration customTimeout = timeoutForSchedulerPriority(SchedulerPriority::IdlePriority)) noexcept override; /* * Cancelled task will never be executed. @@ -94,7 +88,7 @@ class RuntimeScheduler_Modern final : public RuntimeSchedulerBase { * Operates on JSI object. * Thread synchronization must be enforced externally. */ - void cancelTask(Task& task) noexcept override; + void cancelTask(Task &task) noexcept override; /* * Return value indicates if host platform has a pending access to the @@ -129,7 +123,7 @@ class RuntimeScheduler_Modern final : public RuntimeSchedulerBase { * * TODO remove when we add support for microtasks */ - void callExpiredTasks(jsi::Runtime& runtime) override; + void callExpiredTasks(jsi::Runtime &runtime) override; /** * Schedules a function that notifies or applies UI changes in the host @@ -137,34 +131,24 @@ class RuntimeScheduler_Modern final : public RuntimeSchedulerBase { * event loop. If the step is not enabled, the function is executed * immediately. */ - void scheduleRenderingUpdate( - SurfaceId surfaceId, - RuntimeSchedulerRenderingUpdate&& renderingUpdate) override; + void scheduleRenderingUpdate(SurfaceId surfaceId, RuntimeSchedulerRenderingUpdate &&renderingUpdate) override; void setShadowTreeRevisionConsistencyManager( - ShadowTreeRevisionConsistencyManager* - shadowTreeRevisionConsistencyManager) override; + ShadowTreeRevisionConsistencyManager *shadowTreeRevisionConsistencyManager) override; - void setPerformanceEntryReporter( - PerformanceEntryReporter* performanceEntryReporter) override; + void setPerformanceEntryReporter(PerformanceEntryReporter *performanceEntryReporter) override; - void setEventTimingDelegate( - RuntimeSchedulerEventTimingDelegate* eventTimingDelegate) override; + void setEventTimingDelegate(RuntimeSchedulerEventTimingDelegate *eventTimingDelegate) override; void setIntersectionObserverDelegate( - RuntimeSchedulerIntersectionObserverDelegate* - intersectionObserverDelegate) override; + RuntimeSchedulerIntersectionObserverDelegate *intersectionObserverDelegate) override; private: std::atomic syncTaskRequests_{0}; - std::priority_queue< - std::shared_ptr, - std::vector>, - TaskPriorityComparer> - taskQueue_; + std::priority_queue, std::vector>, TaskPriorityComparer> taskQueue_; - Task* currentTask_{}; + Task *currentTask_{}; HighResTimeStamp lastYieldingOpportunity_; HighResDuration longestPeriodWithoutYieldingOpportunity_; @@ -179,7 +163,7 @@ class RuntimeScheduler_Modern final : public RuntimeSchedulerBase { SchedulerPriority currentPriority_{SchedulerPriority::NormalPriority}; void scheduleEventLoop(); - void runEventLoop(jsi::Runtime& runtime); + void runEventLoop(jsi::Runtime &runtime); std::shared_ptr selectTask(); @@ -191,22 +175,16 @@ class RuntimeScheduler_Modern final : public RuntimeSchedulerBase { * In the future, this will include other steps in the Web event loop, like * updating the UI in native, executing resize observer callbacks, etc. */ - void runEventLoopTick(jsi::Runtime& runtime, Task& task); + void runEventLoopTick(jsi::Runtime &runtime, Task &task); - void executeTask( - jsi::Runtime& runtime, - Task& task, - bool didUserCallbackTimeout) const; + void executeTask(jsi::Runtime &runtime, Task &task, bool didUserCallbackTimeout) const; void updateRendering(HighResTimeStamp taskEndTime); bool performingMicrotaskCheckpoint_{false}; - void performMicrotaskCheckpoint(jsi::Runtime& runtime); + void performMicrotaskCheckpoint(jsi::Runtime &runtime); - void reportLongTasks( - const Task& task, - HighResTimeStamp startTime, - HighResTimeStamp endTime); + void reportLongTasks(const Task &task, HighResTimeStamp startTime, HighResTimeStamp endTime); /* * Returns a time point representing the current point in time. May be called @@ -226,14 +204,11 @@ class RuntimeScheduler_Modern final : public RuntimeSchedulerBase { // TODO(T227212654) eventTimingDelegate_ is only set once during startup, so // the real fix here would be to delay runEventLoop until // setEventTimingDelegate. - std::atomic - shadowTreeRevisionConsistencyManager_{nullptr}; - std::atomic eventTimingDelegate_{ - nullptr}; + std::atomic shadowTreeRevisionConsistencyManager_{nullptr}; + std::atomic eventTimingDelegate_{nullptr}; - PerformanceEntryReporter* performanceEntryReporter_{nullptr}; - RuntimeSchedulerIntersectionObserverDelegate* intersectionObserverDelegate_{ - nullptr}; + PerformanceEntryReporter *performanceEntryReporter_{nullptr}; + RuntimeSchedulerIntersectionObserverDelegate *intersectionObserverDelegate_{nullptr}; RuntimeSchedulerTaskErrorHandler onTaskError_; }; diff --git a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/SchedulerPriorityUtils.h b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/SchedulerPriorityUtils.h index 68523e4a26b..df109665581 100644 --- a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/SchedulerPriorityUtils.h +++ b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/SchedulerPriorityUtils.h @@ -14,13 +14,13 @@ namespace facebook::react { -static constexpr std::underlying_type::type serialize( - SchedulerPriority schedulerPriority) { - return static_cast::type>( - schedulerPriority); +static constexpr std::underlying_type::type serialize(SchedulerPriority schedulerPriority) +{ + return static_cast::type>(schedulerPriority); } -static inline SchedulerPriority fromRawValue(double value) { +static inline SchedulerPriority fromRawValue(double value) +{ switch ((int)value) { case 1: return SchedulerPriority::ImmediatePriority; @@ -38,8 +38,8 @@ static inline SchedulerPriority fromRawValue(double value) { } } -static inline HighResDuration timeoutForSchedulerPriority( - SchedulerPriority schedulerPriority) noexcept { +static inline HighResDuration timeoutForSchedulerPriority(SchedulerPriority schedulerPriority) noexcept +{ switch (schedulerPriority) { case SchedulerPriority::ImmediatePriority: return HighResDuration::fromChrono(std::chrono::milliseconds(0)); diff --git a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/Task.h b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/Task.h index 4c56c8c4d05..e1a91f57303 100644 --- a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/Task.h +++ b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/Task.h @@ -21,18 +21,12 @@ class RuntimeScheduler_Legacy; class RuntimeScheduler_Modern; class TaskPriorityComparer; -using RawCallback = std::function; +using RawCallback = std::function; struct Task final : public jsi::NativeState { - Task( - SchedulerPriority priority, - jsi::Function&& callback, - HighResTimeStamp expirationTime); + Task(SchedulerPriority priority, jsi::Function &&callback, HighResTimeStamp expirationTime); - Task( - SchedulerPriority priority, - RawCallback&& callback, - HighResTimeStamp expirationTime); + Task(SchedulerPriority priority, RawCallback &&callback, HighResTimeStamp expirationTime); private: friend RuntimeScheduler_Legacy; @@ -44,14 +38,13 @@ struct Task final : public jsi::NativeState { HighResTimeStamp expirationTime; uint64_t id; - jsi::Value execute(jsi::Runtime& runtime, bool didUserCallbackTimeout); + jsi::Value execute(jsi::Runtime &runtime, bool didUserCallbackTimeout); }; class TaskPriorityComparer { public: - inline bool operator()( - const std::shared_ptr& lhs, - const std::shared_ptr& rhs) { + inline bool operator()(const std::shared_ptr &lhs, const std::shared_ptr &rhs) + { return lhs->expirationTime > rhs->expirationTime; } }; diff --git a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/primitives.h b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/primitives.h index 85cfd7f1679..b5e52894ba1 100644 --- a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/primitives.h +++ b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/primitives.h @@ -12,17 +12,15 @@ namespace facebook::react { -inline static jsi::Value valueFromTask( - jsi::Runtime& runtime, - std::shared_ptr task) { +inline static jsi::Value valueFromTask(jsi::Runtime &runtime, std::shared_ptr task) +{ jsi::Object obj(runtime); obj.setNativeState(runtime, std::move(task)); return obj; } -inline static std::shared_ptr taskFromValue( - jsi::Runtime& runtime, - const jsi::Value& value) { +inline static std::shared_ptr taskFromValue(jsi::Runtime &runtime, const jsi::Value &value) +{ if (value.isNull()) { return nullptr; } diff --git a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/tests/StubClock.h b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/tests/StubClock.h index a93767e5957..55c763f2a57 100644 --- a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/tests/StubClock.h +++ b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/tests/StubClock.h @@ -13,19 +13,23 @@ namespace facebook::react { class StubClock { public: - HighResTimeStamp getNow() const { + HighResTimeStamp getNow() const + { return timePoint_; } - void setTimePoint(HighResTimeStamp timePoint) { + void setTimePoint(HighResTimeStamp timePoint) + { timePoint_ = timePoint; } - HighResTimeStamp getTimePoint() { + HighResTimeStamp getTimePoint() + { return timePoint_; } - void advanceTimeBy(HighResDuration duration) { + void advanceTimeBy(HighResDuration duration) + { timePoint_ += duration; } diff --git a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/tests/StubErrorUtils.h b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/tests/StubErrorUtils.h index a0c838c0eb5..4d82dc1df68 100644 --- a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/tests/StubErrorUtils.h +++ b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/tests/StubErrorUtils.h @@ -17,17 +17,15 @@ namespace facebook::react { */ class StubErrorUtils : public jsi::HostObject { public: - static std::shared_ptr createAndInstallIfNeeded( - jsi::Runtime& runtime) { + static std::shared_ptr createAndInstallIfNeeded(jsi::Runtime &runtime) + { auto errorUtilsModuleName = "ErrorUtils"; - auto errorUtilsValue = - runtime.global().getProperty(runtime, errorUtilsModuleName); + auto errorUtilsValue = runtime.global().getProperty(runtime, errorUtilsModuleName); if (errorUtilsValue.isUndefined()) { auto stubErrorUtils = std::make_shared(); auto object = jsi::Object::createFromHostObject(runtime, stubErrorUtils); - runtime.global().setProperty( - runtime, errorUtilsModuleName, std::move(object)); + runtime.global().setProperty(runtime, errorUtilsModuleName, std::move(object)); return stubErrorUtils; } @@ -38,7 +36,8 @@ class StubErrorUtils : public jsi::HostObject { /* * `jsi::HostObject` specific overloads. */ - jsi::Value get(jsi::Runtime& runtime, const jsi::PropNameID& name) override { + jsi::Value get(jsi::Runtime &runtime, const jsi::PropNameID &name) override + { auto propertyName = name.utf8(runtime); if (propertyName == "reportFatalError") { @@ -47,10 +46,7 @@ class StubErrorUtils : public jsi::HostObject { name, 1, [this]( - jsi::Runtime& runtime, - const jsi::Value&, - const jsi::Value* arguments, - size_t) noexcept -> jsi::Value { + jsi::Runtime &runtime, const jsi::Value &, const jsi::Value *arguments, size_t) noexcept -> jsi::Value { reportFatalCallCount_++; return jsi::Value::undefined(); }); @@ -59,7 +55,8 @@ class StubErrorUtils : public jsi::HostObject { return jsi::Value::undefined(); } - int getReportFatalCallCount() const { + int getReportFatalCallCount() const + { return reportFatalCallCount_; } diff --git a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/tests/StubQueue.h b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/tests/StubQueue.h index 2f190c5f79a..95a8e16f7ce 100644 --- a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/tests/StubQueue.h +++ b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/tests/StubQueue.h @@ -12,7 +12,8 @@ class StubQueue { public: - void runOnQueue(std::function&& func) { + void runOnQueue(std::function &&func) + { { std::lock_guard lock(mutex_); callbackQueue_.push(func); @@ -21,13 +22,15 @@ class StubQueue { signal_.notify_one(); } - void flush() { + void flush() + { while (size() > 0) { tick(); } } - void tick() { + void tick() + { std::function callback; { std::lock_guard lock(mutex_); @@ -42,22 +45,23 @@ class StubQueue { } } - size_t size() const { + size_t size() const + { std::lock_guard lock(mutex_); return callbackQueue_.size(); } - bool waitForTask() const { + bool waitForTask() const + { std::unique_lock lock(mutex_); - return signal_.wait_for( - lock, StubQueue::timeout, [this]() { return !callbackQueue_.empty(); }); + return signal_.wait_for(lock, StubQueue::timeout, [this]() { return !callbackQueue_.empty(); }); } - bool waitForTasks(std::size_t numberOfTasks) const { + bool waitForTasks(std::size_t numberOfTasks) const + { std::unique_lock lock(mutex_); - return signal_.wait_for(lock, StubQueue::timeout, [this, numberOfTasks]() { - return numberOfTasks == callbackQueue_.size(); - }); + return signal_.wait_for( + lock, StubQueue::timeout, [this, numberOfTasks]() { return numberOfTasks == callbackQueue_.size(); }); } private: @@ -65,6 +69,5 @@ class StubQueue { mutable std::mutex mutex_; std::queue> callbackQueue_; - static constexpr std::chrono::duration timeout = - std::chrono::milliseconds(100); + static constexpr std::chrono::duration timeout = std::chrono::milliseconds(100); }; diff --git a/packages/react-native/ReactCommon/react/renderer/scheduler/Scheduler.h b/packages/react-native/ReactCommon/react/renderer/scheduler/Scheduler.h index bd7dad014ba..6ff88adc797 100644 --- a/packages/react-native/ReactCommon/react/renderer/scheduler/Scheduler.h +++ b/packages/react-native/ReactCommon/react/renderer/scheduler/Scheduler.h @@ -36,9 +36,9 @@ namespace facebook::react { class Scheduler final : public UIManagerDelegate { public: Scheduler( - const SchedulerToolbox& schedulerToolbox, - UIManagerAnimationDelegate* animationDelegate, - SchedulerDelegate* delegate); + const SchedulerToolbox &schedulerToolbox, + UIManagerAnimationDelegate *animationDelegate, + SchedulerDelegate *delegate); ~Scheduler() override; #pragma mark - Surface Management @@ -48,17 +48,15 @@ class Scheduler final : public UIManagerDelegate { * All registered `SurfaceHandler` objects must be unregistered * (with the same `Scheduler`) before their deallocation. */ - void registerSurface(const SurfaceHandler& surfaceHandler) const noexcept; - void unregisterSurface(const SurfaceHandler& surfaceHandler) const noexcept; + void registerSurface(const SurfaceHandler &surfaceHandler) const noexcept; + void unregisterSurface(const SurfaceHandler &surfaceHandler) const noexcept; /* * This is broken. Please do not use. * `ComponentDescriptor`s are not designed to be used outside of `UIManager`, * there is no any guarantees about their lifetime. */ - const ComponentDescriptor* - findComponentDescriptorByHandle_DO_NOT_USE_THIS_IS_BROKEN( - ComponentHandle handle) const; + const ComponentDescriptor *findComponentDescriptorByHandle_DO_NOT_USE_THIS_IS_BROKEN(ComponentHandle handle) const; #pragma mark - Delegate @@ -67,8 +65,8 @@ class Scheduler final : public UIManagerDelegate { * If you requesting a ComponentDescriptor and unsure that it's there, you are * doing something wrong. */ - void setDelegate(SchedulerDelegate* delegate); - SchedulerDelegate* getDelegate() const; + void setDelegate(SchedulerDelegate *delegate); + SchedulerDelegate *getDelegate() const; #pragma mark - UIManagerAnimationDelegate // This is not needed on iOS or any platform that has a "pull" instead of @@ -82,28 +80,23 @@ class Scheduler final : public UIManagerDelegate { void uiManagerDidFinishTransaction( std::shared_ptr mountingCoordinator, bool mountSynchronously) override; - void uiManagerDidCreateShadowNode(const ShadowNode& shadowNode) override; + void uiManagerDidCreateShadowNode(const ShadowNode &shadowNode) override; void uiManagerDidDispatchCommand( - const std::shared_ptr& shadowNode, - const std::string& commandName, - const folly::dynamic& args) override; + const std::shared_ptr &shadowNode, + const std::string &commandName, + const folly::dynamic &args) override; void uiManagerDidSendAccessibilityEvent( - const std::shared_ptr& shadowNode, - const std::string& eventType) override; + const std::shared_ptr &shadowNode, + const std::string &eventType) override; void uiManagerDidSetIsJSResponder( - const std::shared_ptr& shadowNode, + const std::shared_ptr &shadowNode, bool isJSResponder, bool blockNativeResponder) override; - void uiManagerShouldSynchronouslyUpdateViewOnUIThread( - Tag tag, - const folly::dynamic& props) override; - void uiManagerDidUpdateShadowTree( - const std::unordered_map& tagToProps) override; - void uiManagerShouldAddEventListener( - std::shared_ptr listener) final; - void uiManagerShouldRemoveEventListener( - const std::shared_ptr& listener) final; - void uiManagerDidStartSurface(const ShadowTree& shadowTree) override; + void uiManagerShouldSynchronouslyUpdateViewOnUIThread(Tag tag, const folly::dynamic &props) override; + void uiManagerDidUpdateShadowTree(const std::unordered_map &tagToProps) override; + void uiManagerShouldAddEventListener(std::shared_ptr listener) final; + void uiManagerShouldRemoveEventListener(const std::shared_ptr &listener) final; + void uiManagerDidStartSurface(const ShadowTree &shadowTree) override; #pragma mark - ContextContainer std::shared_ptr getContextContainer() const; @@ -115,17 +108,15 @@ class Scheduler final : public UIManagerDelegate { #pragma mark - Event listeners void addEventListener(std::shared_ptr listener); - void removeEventListener( - const std::shared_ptr& listener); + void removeEventListener(const std::shared_ptr &listener); #pragma mark - Surface start callback - void uiManagerShouldSetOnSurfaceStartCallback( - OnSurfaceStartCallback&& callback) override; + void uiManagerShouldSetOnSurfaceStartCallback(OnSurfaceStartCallback &&callback) override; private: friend class SurfaceHandler; - SchedulerDelegate* delegate_; + SchedulerDelegate *delegate_; SharedComponentDescriptorRegistry componentDescriptorRegistry_; RuntimeExecutor runtimeExecutor_; std::shared_ptr uiManager_; @@ -151,7 +142,7 @@ class Scheduler final : public UIManagerDelegate { */ std::shared_ptr contextContainer_; - RuntimeScheduler* runtimeScheduler_{nullptr}; + RuntimeScheduler *runtimeScheduler_{nullptr}; mutable std::shared_mutex onSurfaceStartCallbackMutex_; OnSurfaceStartCallback onSurfaceStartCallback_; diff --git a/packages/react-native/ReactCommon/react/renderer/scheduler/SchedulerDelegate.h b/packages/react-native/ReactCommon/react/renderer/scheduler/SchedulerDelegate.h index 0a88e243393..afa2d57de65 100644 --- a/packages/react-native/ReactCommon/react/renderer/scheduler/SchedulerDelegate.h +++ b/packages/react-native/ReactCommon/react/renderer/scheduler/SchedulerDelegate.h @@ -25,9 +25,7 @@ class SchedulerDelegate { * of the tree and calculated a set of mutations which are sufficient * to construct a new one. */ - virtual void schedulerDidFinishTransaction( - const std::shared_ptr& - mountingCoordinator) = 0; + virtual void schedulerDidFinishTransaction(const std::shared_ptr &mountingCoordinator) = 0; /* * Called when the runtime scheduler decides that one-or-more previously @@ -38,38 +36,29 @@ class SchedulerDelegate { * correctly apply changes, due to changes in Props representation. */ virtual void schedulerShouldRenderTransactions( - const std::shared_ptr& - mountingCoordinator) = 0; + const std::shared_ptr &mountingCoordinator) = 0; /* * Called right after a new ShadowNode was created. */ - virtual void schedulerDidRequestPreliminaryViewAllocation( - const ShadowNode& shadowNode) = 0; + virtual void schedulerDidRequestPreliminaryViewAllocation(const ShadowNode &shadowNode) = 0; virtual void schedulerDidDispatchCommand( - const ShadowView& shadowView, - const std::string& commandName, - const folly::dynamic& args) = 0; + const ShadowView &shadowView, + const std::string &commandName, + const folly::dynamic &args) = 0; - virtual void schedulerDidSendAccessibilityEvent( - const ShadowView& shadowView, - const std::string& eventType) = 0; + virtual void schedulerDidSendAccessibilityEvent(const ShadowView &shadowView, const std::string &eventType) = 0; /* * Set JS responder for a view */ - virtual void schedulerDidSetIsJSResponder( - const ShadowView& shadowView, - bool isJSResponder, - bool blockNativeResponder) = 0; + virtual void + schedulerDidSetIsJSResponder(const ShadowView &shadowView, bool isJSResponder, bool blockNativeResponder) = 0; - virtual void schedulerShouldSynchronouslyUpdateViewOnUIThread( - Tag tag, - const folly::dynamic& props) = 0; + virtual void schedulerShouldSynchronouslyUpdateViewOnUIThread(Tag tag, const folly::dynamic &props) = 0; - virtual void schedulerDidUpdateShadowTree( - const std::unordered_map& tagToProps) = 0; + virtual void schedulerDidUpdateShadowTree(const std::unordered_map &tagToProps) = 0; virtual ~SchedulerDelegate() noexcept = default; }; diff --git a/packages/react-native/ReactCommon/react/renderer/scheduler/SurfaceHandler.h b/packages/react-native/ReactCommon/react/renderer/scheduler/SurfaceHandler.h index 9a4f0195eb0..b93caa204f6 100644 --- a/packages/react-native/ReactCommon/react/renderer/scheduler/SurfaceHandler.h +++ b/packages/react-native/ReactCommon/react/renderer/scheduler/SurfaceHandler.h @@ -62,25 +62,24 @@ class SurfaceHandler { /* * Can be constructed anytime with a `moduleName` and a `surfaceId`. */ - SurfaceHandler(const std::string& moduleName, SurfaceId surfaceId) noexcept; + SurfaceHandler(const std::string &moduleName, SurfaceId surfaceId) noexcept; virtual ~SurfaceHandler() noexcept; /* * Movable-only. */ - SurfaceHandler(SurfaceHandler&& other) noexcept; - SurfaceHandler(const SurfaceHandler& SurfaceHandler) noexcept = delete; - SurfaceHandler& operator=(SurfaceHandler&& other) noexcept; - SurfaceHandler& operator=(const SurfaceHandler& other) noexcept = delete; + SurfaceHandler(SurfaceHandler &&other) noexcept; + SurfaceHandler(const SurfaceHandler &SurfaceHandler) noexcept = delete; + SurfaceHandler &operator=(SurfaceHandler &&other) noexcept; + SurfaceHandler &operator=(const SurfaceHandler &other) noexcept = delete; #pragma mark - Surface Life-Cycle Management /* * Must be called before surface is started. */ - void setContextContainer( - std::shared_ptr contextContainer) const noexcept; + void setContextContainer(std::shared_ptr contextContainer) const noexcept; /* * Returns a momentum value of the status. @@ -113,7 +112,7 @@ class SurfaceHandler { * Provides access for surface props. * Props can be changed anytime (even for `Unregistered` surface). */ - void setProps(const folly::dynamic& props) const noexcept; + void setProps(const folly::dynamic &props) const noexcept; folly::dynamic getProps() const noexcept; /* @@ -121,8 +120,7 @@ class SurfaceHandler { * Can be not be called when the status is `Unregistered`. * The returning value cannot be `nullptr`. */ - std::shared_ptr getMountingCoordinator() - const noexcept; + std::shared_ptr getMountingCoordinator() const noexcept; #pragma mark - Layout @@ -130,16 +128,12 @@ class SurfaceHandler { * Measures the surface with given layout constraints and layout context. * Returns zero size if called on the stopped or unregistered surface. */ - Size measure( - const LayoutConstraints& layoutConstraints, - const LayoutContext& layoutContext) const; + Size measure(const LayoutConstraints &layoutConstraints, const LayoutContext &layoutContext) const; /* * Sets layout constraints and layout context for the surface. */ - void constraintLayout( - const LayoutConstraints& layoutConstraints, - const LayoutContext& layoutContext) const; + void constraintLayout(const LayoutConstraints &layoutConstraints, const LayoutContext &layoutContext) const; /* * Returns layout constraints and layout context associated with the surface. @@ -153,16 +147,15 @@ class SurfaceHandler { /* * Must be called by `Scheduler` during registration process. */ - void setUIManager(const UIManager* uiManager) const noexcept; + void setUIManager(const UIManager *uiManager) const noexcept; void applyDisplayMode(DisplayMode displayMode) const; /* * An utility for dirtying all measurable shadow nodes present in the tree. */ - void dirtyMeasurableNodes(ShadowNode& root) const; - std::shared_ptr dirtyMeasurableNodesRecursive( - std::shared_ptr node) const; + void dirtyMeasurableNodes(ShadowNode &root) const; + std::shared_ptr dirtyMeasurableNodesRecursive(std::shared_ptr node) const; #pragma mark - Link & Parameters @@ -197,8 +190,8 @@ class SurfaceHandler { */ struct Link { Status status{Status::Unregistered}; - const UIManager* uiManager{}; - const ShadowTree* shadowTree{}; + const UIManager *uiManager{}; + const ShadowTree *shadowTree{}; }; /* diff --git a/packages/react-native/ReactCommon/react/renderer/scheduler/SurfaceManager.h b/packages/react-native/ReactCommon/react/renderer/scheduler/SurfaceManager.h index e8709a7cd7b..75ef5692b2a 100644 --- a/packages/react-native/ReactCommon/react/renderer/scheduler/SurfaceManager.h +++ b/packages/react-native/ReactCommon/react/renderer/scheduler/SurfaceManager.h @@ -27,7 +27,7 @@ namespace facebook::react { */ class SurfaceManager final { public: - explicit SurfaceManager(const Scheduler& scheduler) noexcept; + explicit SurfaceManager(const Scheduler &scheduler) noexcept; ~SurfaceManager() noexcept; /* SurfaceProps contain information about running surfaces */ @@ -43,10 +43,10 @@ class SurfaceManager final { void startSurface( SurfaceId surfaceId, - const std::string& moduleName, - const folly::dynamic& props, - const LayoutConstraints& layoutConstraints = {}, - const LayoutContext& layoutContext = {}) noexcept; + const std::string &moduleName, + const folly::dynamic &props, + const LayoutConstraints &layoutConstraints = {}, + const LayoutContext &layoutContext = {}) noexcept; void stopSurface(SurfaceId surfaceId) noexcept; @@ -56,29 +56,25 @@ class SurfaceManager final { std::unordered_set getRunningSurfaces() const noexcept; - std::optional getSurfaceProps( - SurfaceId surfaceId) const noexcept; + std::optional getSurfaceProps(SurfaceId surfaceId) const noexcept; Size measureSurface( SurfaceId surfaceId, - const LayoutConstraints& layoutConstraints, - const LayoutContext& layoutContext) const noexcept; + const LayoutConstraints &layoutConstraints, + const LayoutContext &layoutContext) const noexcept; void constraintSurfaceLayout( SurfaceId surfaceId, - const LayoutConstraints& layoutConstraints, - const LayoutContext& layoutContext) const noexcept; + const LayoutConstraints &layoutConstraints, + const LayoutContext &layoutContext) const noexcept; - std::shared_ptr findMountingCoordinator( - SurfaceId surfaceId) const noexcept; + std::shared_ptr findMountingCoordinator(SurfaceId surfaceId) const noexcept; private: - void visit( - SurfaceId surfaceId, - const std::function& callback) + void visit(SurfaceId surfaceId, const std::function &callback) const noexcept; - const Scheduler& scheduler_; + const Scheduler &scheduler_; mutable std::shared_mutex mutex_; // Protects `registry_`. std::unordered_map registry_{}; }; diff --git a/packages/react-native/ReactCommon/react/renderer/telemetry/SurfaceTelemetry.h b/packages/react-native/ReactCommon/react/renderer/telemetry/SurfaceTelemetry.h index 47cb304eb84..71cda639548 100644 --- a/packages/react-native/ReactCommon/react/renderer/telemetry/SurfaceTelemetry.h +++ b/packages/react-native/ReactCommon/react/renderer/telemetry/SurfaceTelemetry.h @@ -42,9 +42,7 @@ class SurfaceTelemetry final { * Incorporate data from given transaction telemetry into aggregated data * for the Surface. */ - void incorporate( - const TransactionTelemetry& telemetry, - int numberOfMutations); + void incorporate(const TransactionTelemetry &telemetry, int numberOfMutations); private: TelemetryDuration layoutTime_{}; diff --git a/packages/react-native/ReactCommon/react/renderer/telemetry/TransactionTelemetry.h b/packages/react-native/ReactCommon/react/renderer/telemetry/TransactionTelemetry.h index a6a293f78e3..40639078a93 100644 --- a/packages/react-native/ReactCommon/react/renderer/telemetry/TransactionTelemetry.h +++ b/packages/react-native/ReactCommon/react/renderer/telemetry/TransactionTelemetry.h @@ -24,7 +24,7 @@ class TransactionTelemetry final { /* * Thread-local Telemetry instance */ - static TransactionTelemetry* threadLocalTelemetry(); + static TransactionTelemetry *threadLocalTelemetry(); TransactionTelemetry(); TransactionTelemetry(std::function now); diff --git a/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/TextLayoutContext.h b/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/TextLayoutContext.h index 5ef1901ef07..dd8a74b79e0 100644 --- a/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/TextLayoutContext.h +++ b/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/TextLayoutContext.h @@ -30,7 +30,7 @@ struct TextLayoutContext { */ SurfaceId surfaceId{-1}; - bool operator==(const TextLayoutContext& rhs) const = default; + bool operator==(const TextLayoutContext &rhs) const = default; }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/TextLayoutManagerExtended.h b/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/TextLayoutManagerExtended.h index c4b350fb0ed..72d268091ac 100644 --- a/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/TextLayoutManagerExtended.h +++ b/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/TextLayoutManagerExtended.h @@ -28,12 +28,10 @@ concept TextLayoutManagerWithPreparedLayout = requires( typename TextLayoutManagerT::PreparedLayout preparedLayout) { sizeof(typename TextLayoutManagerT::PreparedLayout); { - textLayoutManager.prepareLayout( - attributedString, paragraphAttributes, layoutContext, layoutConstraints) + textLayoutManager.prepareLayout(attributedString, paragraphAttributes, layoutContext, layoutConstraints) } -> std::same_as; { - textLayoutManager.measurePreparedLayout( - preparedLayout, layoutContext, layoutConstraints) + textLayoutManager.measurePreparedLayout(preparedLayout, layoutContext, layoutConstraints) } -> std::same_as; }; @@ -57,69 +55,64 @@ struct PreparedLayoutT { template class TextLayoutManagerExtended { public: - static constexpr bool supportsLineMeasurement() { + static constexpr bool supportsLineMeasurement() + { return requires(TextLayoutManagerT textLayoutManager) { { - textLayoutManager.measureLines( - AttributedStringBox{}, ParagraphAttributes{}, Size{}) + textLayoutManager.measureLines(AttributedStringBox{}, ParagraphAttributes{}, Size{}) } -> std::same_as; }; } - static constexpr bool supportsPreparedLayout() { + static constexpr bool supportsPreparedLayout() + { return TextLayoutManagerWithPreparedLayout; } using PreparedLayout = typename PreparedLayoutT::type; - TextLayoutManagerExtended(const TextLayoutManagerT& textLayoutManager) - : textLayoutManager_(textLayoutManager) {} + TextLayoutManagerExtended(const TextLayoutManagerT &textLayoutManager) : textLayoutManager_(textLayoutManager) {} LinesMeasurements measureLines( - const AttributedStringBox& attributedStringBox, - const ParagraphAttributes& paragraphAttributes, - const Size& size) { + const AttributedStringBox &attributedStringBox, + const ParagraphAttributes ¶graphAttributes, + const Size &size) + { if constexpr (supportsLineMeasurement()) { - return textLayoutManager_.measureLines( - attributedStringBox, paragraphAttributes, size); + return textLayoutManager_.measureLines(attributedStringBox, paragraphAttributes, size); } LOG(FATAL) << "Platform TextLayoutManager does not support measureLines"; } PreparedLayout prepareLayout( - const AttributedString& attributedString, - const ParagraphAttributes& paragraphAttributes, - const TextLayoutContext& layoutContext, - const LayoutConstraints& layoutConstraints) const { + const AttributedString &attributedString, + const ParagraphAttributes ¶graphAttributes, + const TextLayoutContext &layoutContext, + const LayoutConstraints &layoutConstraints) const + { if constexpr (supportsPreparedLayout()) { - return textLayoutManager_.prepareLayout( - attributedString, - paragraphAttributes, - layoutContext, - layoutConstraints); + return textLayoutManager_.prepareLayout(attributedString, paragraphAttributes, layoutContext, layoutConstraints); } LOG(FATAL) << "Platform TextLayoutManager does not support prepareLayout"; } TextMeasurement measurePreparedLayout( - const PreparedLayout& layout, - const TextLayoutContext& layoutContext, - const LayoutConstraints& layoutConstraints) const { + const PreparedLayout &layout, + const TextLayoutContext &layoutContext, + const LayoutConstraints &layoutConstraints) const + { if constexpr (supportsPreparedLayout()) { - return textLayoutManager_.measurePreparedLayout( - layout, layoutContext, layoutConstraints); + return textLayoutManager_.measurePreparedLayout(layout, layoutContext, layoutConstraints); } - LOG(FATAL) - << "Platform TextLayoutManager does not support measurePreparedLayout"; + LOG(FATAL) << "Platform TextLayoutManager does not support measurePreparedLayout"; } private: - const TextLayoutManagerT& textLayoutManager_; + const TextLayoutManagerT &textLayoutManager_; }; } // namespace detail -using TextLayoutManagerExtended = - detail::TextLayoutManagerExtended; +using TextLayoutManagerExtended = detail::TextLayoutManagerExtended; struct MeasuredPreparedLayout { LayoutConstraints layoutConstraints; diff --git a/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/TextMeasureCache.h b/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/TextMeasureCache.h index 962eca68005..b4becb8f2e1 100644 --- a/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/TextMeasureCache.h +++ b/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/TextMeasureCache.h @@ -24,19 +24,14 @@ struct LineMeasurement { Float ascender; Float xHeight; - LineMeasurement( - std::string text, - Rect frame, - Float descender, - Float capHeight, - Float ascender, - Float xHeight); + LineMeasurement(std::string text, Rect frame, Float descender, Float capHeight, Float ascender, Float xHeight); - LineMeasurement(const folly::dynamic& data); + LineMeasurement(const folly::dynamic &data); - bool operator==(const LineMeasurement& rhs) const; + bool operator==(const LineMeasurement &rhs) const; - static inline Float baseline(const std::vector& lines) { + static inline Float baseline(const std::vector &lines) + { if (!lines.empty()) { return lines[0].ascender; } @@ -105,23 +100,16 @@ constexpr auto kSimpleThreadSafeCacheSizeCap = size_t{1024}; * Thread-safe, evicting hash table designed to store text measurement * information. */ -using TextMeasureCache = SimpleThreadSafeCache< - TextMeasureCacheKey, - TextMeasurement, - kSimpleThreadSafeCacheSizeCap>; +using TextMeasureCache = SimpleThreadSafeCache; /* * Thread-safe, evicting hash table designed to store line measurement * information. */ -using LineMeasureCache = SimpleThreadSafeCache< - LineMeasureCacheKey, - LinesMeasurements, - kSimpleThreadSafeCacheSizeCap>; +using LineMeasureCache = SimpleThreadSafeCache; -inline bool areTextAttributesEquivalentLayoutWise( - const TextAttributes& lhs, - const TextAttributes& rhs) { +inline bool areTextAttributesEquivalentLayoutWise(const TextAttributes &lhs, const TextAttributes &rhs) +{ // Here we check all attributes that affect layout metrics and don't check any // attributes that affect only a decorative aspect of displayed text (like // colors). @@ -141,14 +129,12 @@ inline bool areTextAttributesEquivalentLayoutWise( rhs.allowFontScaling, rhs.dynamicTypeRamp, rhs.alignment) && - floatEquality(lhs.fontSize, rhs.fontSize) && - floatEquality(lhs.fontSizeMultiplier, rhs.fontSizeMultiplier) && - floatEquality(lhs.letterSpacing, rhs.letterSpacing) && - floatEquality(lhs.lineHeight, rhs.lineHeight); + floatEquality(lhs.fontSize, rhs.fontSize) && floatEquality(lhs.fontSizeMultiplier, rhs.fontSizeMultiplier) && + floatEquality(lhs.letterSpacing, rhs.letterSpacing) && floatEquality(lhs.lineHeight, rhs.lineHeight); } -inline size_t textAttributesHashLayoutWise( - const TextAttributes& textAttributes) { +inline size_t textAttributesHashLayoutWise(const TextAttributes &textAttributes) +{ // Taking into account the same props as // `areTextAttributesEquivalentLayoutWise` mentions. return facebook::react::hash_combine( @@ -166,52 +152,45 @@ inline size_t textAttributesHashLayoutWise( } inline bool areAttributedStringFragmentsEquivalentLayoutWise( - const AttributedString::Fragment& lhs, - const AttributedString::Fragment& rhs) { - return lhs.string == rhs.string && - areTextAttributesEquivalentLayoutWise( - lhs.textAttributes, rhs.textAttributes) && + const AttributedString::Fragment &lhs, + const AttributedString::Fragment &rhs) +{ + return lhs.string == rhs.string && areTextAttributesEquivalentLayoutWise(lhs.textAttributes, rhs.textAttributes) && // LayoutMetrics of an attachment fragment affects the size of a measured // attributed string. - (!lhs.isAttachment() || - (lhs.parentShadowView.layoutMetrics == - rhs.parentShadowView.layoutMetrics)); + (!lhs.isAttachment() || (lhs.parentShadowView.layoutMetrics == rhs.parentShadowView.layoutMetrics)); } inline bool areAttributedStringFragmentsEquivalentDisplayWise( - const AttributedString::Fragment& lhs, - const AttributedString::Fragment& rhs) { + const AttributedString::Fragment &lhs, + const AttributedString::Fragment &rhs) +{ return lhs.isContentEqual(rhs) && // LayoutMetrics of an attachment fragment affects the size of a measured // attributed string. - (!lhs.isAttachment() || - (lhs.parentShadowView.layoutMetrics == - rhs.parentShadowView.layoutMetrics)); + (!lhs.isAttachment() || (lhs.parentShadowView.layoutMetrics == rhs.parentShadowView.layoutMetrics)); } -inline size_t attributedStringFragmentHashLayoutWise( - const AttributedString::Fragment& fragment) { +inline size_t attributedStringFragmentHashLayoutWise(const AttributedString::Fragment &fragment) +{ // Here we are not taking `isAttachment` and `layoutMetrics` into account // because they are logically interdependent and this can break an invariant // between hash and equivalence functions (and cause cache misses). - return facebook::react::hash_combine( - fragment.string, textAttributesHashLayoutWise(fragment.textAttributes)); + return facebook::react::hash_combine(fragment.string, textAttributesHashLayoutWise(fragment.textAttributes)); } -inline size_t attributedStringFragmentHashDisplayWise( - const AttributedString::Fragment& fragment) { +inline size_t attributedStringFragmentHashDisplayWise(const AttributedString::Fragment &fragment) +{ // Here we are not taking `isAttachment` and `layoutMetrics` into account // because they are logically interdependent and this can break an invariant // between hash and equivalence functions (and cause cache misses). - return facebook::react::hash_combine( - fragment.string, fragment.textAttributes); + return facebook::react::hash_combine(fragment.string, fragment.textAttributes); } -inline bool areAttributedStringsEquivalentLayoutWise( - const AttributedString& lhs, - const AttributedString& rhs) { - auto& lhsFragment = lhs.getFragments(); - auto& rhsFragment = rhs.getFragments(); +inline bool areAttributedStringsEquivalentLayoutWise(const AttributedString &lhs, const AttributedString &rhs) +{ + auto &lhsFragment = lhs.getFragments(); + auto &rhsFragment = rhs.getFragments(); if (lhsFragment.size() != rhsFragment.size()) { return false; @@ -219,8 +198,7 @@ inline bool areAttributedStringsEquivalentLayoutWise( auto size = lhsFragment.size(); for (auto i = size_t{0}; i < size; i++) { - if (!areAttributedStringFragmentsEquivalentLayoutWise( - lhsFragment.at(i), rhsFragment.at(i))) { + if (!areAttributedStringFragmentsEquivalentLayoutWise(lhsFragment.at(i), rhsFragment.at(i))) { return false; } } @@ -228,11 +206,10 @@ inline bool areAttributedStringsEquivalentLayoutWise( return true; } -inline bool areAttributedStringsEquivalentDisplayWise( - const AttributedString& lhs, - const AttributedString& rhs) { - auto& lhsFragment = lhs.getFragments(); - auto& rhsFragment = rhs.getFragments(); +inline bool areAttributedStringsEquivalentDisplayWise(const AttributedString &lhs, const AttributedString &rhs) +{ + auto &lhsFragment = lhs.getFragments(); + auto &rhsFragment = rhs.getFragments(); if (lhsFragment.size() != rhsFragment.size()) { return false; @@ -240,8 +217,7 @@ inline bool areAttributedStringsEquivalentDisplayWise( auto size = lhsFragment.size(); for (size_t i = 0; i < size; i++) { - if (!areAttributedStringFragmentsEquivalentDisplayWise( - lhsFragment.at(i), rhsFragment.at(i))) { + if (!areAttributedStringFragmentsEquivalentDisplayWise(lhsFragment.at(i), rhsFragment.at(i))) { return false; } } @@ -249,55 +225,44 @@ inline bool areAttributedStringsEquivalentDisplayWise( return true; } -inline size_t attributedStringHashLayoutWise( - const AttributedString& attributedString) { +inline size_t attributedStringHashLayoutWise(const AttributedString &attributedString) +{ auto seed = size_t{0}; - for (const auto& fragment : attributedString.getFragments()) { - facebook::react::hash_combine( - seed, attributedStringFragmentHashLayoutWise(fragment)); + for (const auto &fragment : attributedString.getFragments()) { + facebook::react::hash_combine(seed, attributedStringFragmentHashLayoutWise(fragment)); } return seed; } -inline size_t attributedStringHashDisplayWise( - const AttributedString& attributedString) { +inline size_t attributedStringHashDisplayWise(const AttributedString &attributedString) +{ size_t seed = 0; - for (const auto& fragment : attributedString.getFragments()) { - facebook::react::hash_combine( - seed, attributedStringFragmentHashDisplayWise(fragment)); + for (const auto &fragment : attributedString.getFragments()) { + facebook::react::hash_combine(seed, attributedStringFragmentHashDisplayWise(fragment)); } return seed; } -inline bool operator==( - const TextMeasureCacheKey& lhs, - const TextMeasureCacheKey& rhs) { - return areAttributedStringsEquivalentLayoutWise( - lhs.attributedString, rhs.attributedString) && - lhs.paragraphAttributes == rhs.paragraphAttributes && - lhs.layoutConstraints == rhs.layoutConstraints; +inline bool operator==(const TextMeasureCacheKey &lhs, const TextMeasureCacheKey &rhs) +{ + return areAttributedStringsEquivalentLayoutWise(lhs.attributedString, rhs.attributedString) && + lhs.paragraphAttributes == rhs.paragraphAttributes && lhs.layoutConstraints == rhs.layoutConstraints; } -inline bool operator==( - const LineMeasureCacheKey& lhs, - const LineMeasureCacheKey& rhs) { - return areAttributedStringsEquivalentLayoutWise( - lhs.attributedString, rhs.attributedString) && - lhs.paragraphAttributes == rhs.paragraphAttributes && - lhs.size == rhs.size; +inline bool operator==(const LineMeasureCacheKey &lhs, const LineMeasureCacheKey &rhs) +{ + return areAttributedStringsEquivalentLayoutWise(lhs.attributedString, rhs.attributedString) && + lhs.paragraphAttributes == rhs.paragraphAttributes && lhs.size == rhs.size; } -inline bool operator==( - const PreparedTextCacheKey& lhs, - const PreparedTextCacheKey& rhs) { - return areAttributedStringsEquivalentDisplayWise( - lhs.attributedString, rhs.attributedString) && - lhs.paragraphAttributes == rhs.paragraphAttributes && - lhs.layoutConstraints == rhs.layoutConstraints; +inline bool operator==(const PreparedTextCacheKey &lhs, const PreparedTextCacheKey &rhs) +{ + return areAttributedStringsEquivalentDisplayWise(lhs.attributedString, rhs.attributedString) && + lhs.paragraphAttributes == rhs.paragraphAttributes && lhs.layoutConstraints == rhs.layoutConstraints; } } // namespace facebook::react @@ -306,31 +271,28 @@ namespace std { template <> struct hash { - size_t operator()(const facebook::react::TextMeasureCacheKey& key) const { + size_t operator()(const facebook::react::TextMeasureCacheKey &key) const + { return facebook::react::hash_combine( - attributedStringHashLayoutWise(key.attributedString), - key.paragraphAttributes, - key.layoutConstraints); + attributedStringHashLayoutWise(key.attributedString), key.paragraphAttributes, key.layoutConstraints); } }; template <> struct hash { - size_t operator()(const facebook::react::LineMeasureCacheKey& key) const { + size_t operator()(const facebook::react::LineMeasureCacheKey &key) const + { return facebook::react::hash_combine( - attributedStringHashLayoutWise(key.attributedString), - key.paragraphAttributes, - key.size); + attributedStringHashLayoutWise(key.attributedString), key.paragraphAttributes, key.size); } }; template <> struct hash { - size_t operator()(const facebook::react::PreparedTextCacheKey& key) const { + size_t operator()(const facebook::react::PreparedTextCacheKey &key) const + { return facebook::react::hash_combine( - attributedStringHashDisplayWise(key.attributedString), - key.paragraphAttributes, - key.layoutConstraints); + attributedStringHashDisplayWise(key.attributedString), key.paragraphAttributes, key.layoutConstraints); } }; diff --git a/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/platform/android/react/renderer/textlayoutmanager/JPreparedLayout.h b/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/platform/android/react/renderer/textlayoutmanager/JPreparedLayout.h index e3cfc765694..db78f56d578 100644 --- a/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/platform/android/react/renderer/textlayoutmanager/JPreparedLayout.h +++ b/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/platform/android/react/renderer/textlayoutmanager/JPreparedLayout.h @@ -13,8 +13,7 @@ namespace facebook::react { class JPreparedLayout : public jni::JavaClass { public: - static auto constexpr kJavaDescriptor = - "Lcom/facebook/react/views/text/PreparedLayout;"; + static auto constexpr kJavaDescriptor = "Lcom/facebook/react/views/text/PreparedLayout;"; }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/platform/android/react/renderer/textlayoutmanager/TextLayoutManager.cpp b/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/platform/android/react/renderer/textlayoutmanager/TextLayoutManager.cpp index 7c1782826b6..cbcfbbedd02 100644 --- a/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/platform/android/react/renderer/textlayoutmanager/TextLayoutManager.cpp +++ b/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/platform/android/react/renderer/textlayoutmanager/TextLayoutManager.cpp @@ -159,8 +159,9 @@ TextLayoutManager::TextLayoutManager( : contextContainer_(std::move(contextContainer)), textMeasureCache_(kSimpleThreadSafeCacheSizeCap), lineMeasureCache_(kSimpleThreadSafeCacheSizeCap), - preparedTextCache_(static_cast( - ReactNativeFeatureFlags::preparedTextCacheSize())) {} + preparedTextCache_( + static_cast( + ReactNativeFeatureFlags::preparedTextCacheSize())) {} TextMeasurement TextLayoutManager::measure( const AttributedStringBox& attributedStringBox, @@ -423,11 +424,12 @@ TextMeasurement TextLayoutManager::measurePreparedLayout( textMeasurement.attachments.push_back( TextMeasurement::Attachment{.frame = Rect{}, .isClipped = true}); } else { - textMeasurement.attachments.push_back(TextMeasurement::Attachment{ - .frame = - {.origin = {.x = left, .y = top}, - .size = {.width = width, .height = height}}, - .isClipped = false}); + textMeasurement.attachments.push_back( + TextMeasurement::Attachment{ + .frame = + {.origin = {.x = left, .y = top}, + .size = {.width = width, .height = height}}, + .isClipped = false}); } } } diff --git a/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/platform/android/react/renderer/textlayoutmanager/TextLayoutManager.h b/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/platform/android/react/renderer/textlayoutmanager/TextLayoutManager.h index 0205fff33e2..eec36fb06b8 100644 --- a/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/platform/android/react/renderer/textlayoutmanager/TextLayoutManager.h +++ b/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/platform/android/react/renderer/textlayoutmanager/TextLayoutManager.h @@ -31,29 +31,28 @@ class TextLayoutManager { public: using PreparedLayout = SafeReleaseJniRef>; - TextLayoutManager( - const std::shared_ptr& contextContainer); + TextLayoutManager(const std::shared_ptr &contextContainer); /* * Not copyable. */ - TextLayoutManager(const TextLayoutManager&) = delete; - TextLayoutManager& operator=(const TextLayoutManager&) = delete; + TextLayoutManager(const TextLayoutManager &) = delete; + TextLayoutManager &operator=(const TextLayoutManager &) = delete; /* * Not movable. */ - TextLayoutManager(TextLayoutManager&&) = delete; - TextLayoutManager& operator=(TextLayoutManager&&) = delete; + TextLayoutManager(TextLayoutManager &&) = delete; + TextLayoutManager &operator=(TextLayoutManager &&) = delete; /* * Measures `attributedString` using native text rendering infrastructure. */ TextMeasurement measure( - const AttributedStringBox& attributedStringBox, - const ParagraphAttributes& paragraphAttributes, - const TextLayoutContext& layoutContext, - const LayoutConstraints& layoutConstraints) const; + const AttributedStringBox &attributedStringBox, + const ParagraphAttributes ¶graphAttributes, + const TextLayoutContext &layoutContext, + const LayoutConstraints &layoutConstraints) const; /** * Measures an AttributedString on the platform, as identified by some @@ -61,46 +60,42 @@ class TextLayoutManager { */ TextMeasurement measureCachedSpannableById( int64_t cacheId, - const ParagraphAttributes& paragraphAttributes, - const TextLayoutContext& layoutContext, - const LayoutConstraints& layoutConstraints) const; + const ParagraphAttributes ¶graphAttributes, + const TextLayoutContext &layoutContext, + const LayoutConstraints &layoutConstraints) const; /* * Measures lines of `attributedString` using native text rendering * infrastructure. */ LinesMeasurements measureLines( - const AttributedStringBox& attributedStringBox, - const ParagraphAttributes& paragraphAttributes, - const Size& size) const; + const AttributedStringBox &attributedStringBox, + const ParagraphAttributes ¶graphAttributes, + const Size &size) const; /** * Create a platform representation of fully laid out text, to later be * reused. */ PreparedLayout prepareLayout( - const AttributedString& attributedString, - const ParagraphAttributes& paragraphAttributes, - const TextLayoutContext& layoutContext, - const LayoutConstraints& layoutConstraints) const; + const AttributedString &attributedString, + const ParagraphAttributes ¶graphAttributes, + const TextLayoutContext &layoutContext, + const LayoutConstraints &layoutConstraints) const; /** * Derive text and attachment measurements from a PreparedLayout. */ TextMeasurement measurePreparedLayout( - const PreparedLayout& layout, - const TextLayoutContext& layoutContext, - const LayoutConstraints& layoutConstraints) const; + const PreparedLayout &layout, + const TextLayoutContext &layoutContext, + const LayoutConstraints &layoutConstraints) const; private: std::shared_ptr contextContainer_; TextMeasureCache textMeasureCache_; LineMeasureCache lineMeasureCache_; - SimpleThreadSafeCache< - PreparedTextCacheKey, - PreparedLayout, - -1 /* Set dynamically*/> - preparedTextCache_; + SimpleThreadSafeCache preparedTextCache_; }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/platform/cxx/react/renderer/textlayoutmanager/TextLayoutManager.cpp b/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/platform/cxx/react/renderer/textlayoutmanager/TextLayoutManager.cpp index 8806384bc57..0444a94b25c 100644 --- a/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/platform/cxx/react/renderer/textlayoutmanager/TextLayoutManager.cpp +++ b/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/platform/cxx/react/renderer/textlayoutmanager/TextLayoutManager.cpp @@ -21,10 +21,12 @@ TextMeasurement TextLayoutManager::measure( TextMeasurement::Attachments attachments; for (const auto& fragment : attributedStringBox.getValue().getFragments()) { if (fragment.isAttachment()) { - attachments.push_back(TextMeasurement::Attachment{ - .frame = - {.origin = {.x = 0, .y = 0}, .size = {.width = 0, .height = 0}}, - .isClipped = false}); + attachments.push_back( + TextMeasurement::Attachment{ + .frame = + {.origin = {.x = 0, .y = 0}, + .size = {.width = 0, .height = 0}}, + .isClipped = false}); } } return TextMeasurement{ diff --git a/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/platform/cxx/react/renderer/textlayoutmanager/TextLayoutManager.h b/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/platform/cxx/react/renderer/textlayoutmanager/TextLayoutManager.h index 4c69793c228..63f2c1afcbc 100644 --- a/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/platform/cxx/react/renderer/textlayoutmanager/TextLayoutManager.h +++ b/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/platform/cxx/react/renderer/textlayoutmanager/TextLayoutManager.h @@ -25,30 +25,29 @@ class TextLayoutManager; */ class TextLayoutManager { public: - explicit TextLayoutManager( - const std::shared_ptr& contextContainer); + explicit TextLayoutManager(const std::shared_ptr &contextContainer); virtual ~TextLayoutManager() = default; /* * Not copyable. */ - TextLayoutManager(const TextLayoutManager&) = delete; - TextLayoutManager& operator=(const TextLayoutManager&) = delete; + TextLayoutManager(const TextLayoutManager &) = delete; + TextLayoutManager &operator=(const TextLayoutManager &) = delete; /* * Not movable. */ - TextLayoutManager(TextLayoutManager&&) = delete; - TextLayoutManager& operator=(TextLayoutManager&&) = delete; + TextLayoutManager(TextLayoutManager &&) = delete; + TextLayoutManager &operator=(TextLayoutManager &&) = delete; /* * Measures `attributedString` using native text rendering infrastructure. */ virtual TextMeasurement measure( - const AttributedStringBox& attributedStringBox, - const ParagraphAttributes& paragraphAttributes, - const TextLayoutContext& layoutContext, - const LayoutConstraints& layoutConstraints) const; + const AttributedStringBox &attributedStringBox, + const ParagraphAttributes ¶graphAttributes, + const TextLayoutContext &layoutContext, + const LayoutConstraints &layoutConstraints) const; protected: std::shared_ptr contextContainer_; diff --git a/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/platform/ios/react/renderer/textlayoutmanager/RCTAttributedTextUtils.mm b/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/platform/ios/react/renderer/textlayoutmanager/RCTAttributedTextUtils.mm index 97d8451b2d1..520a24c28f7 100644 --- a/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/platform/ios/react/renderer/textlayoutmanager/RCTAttributedTextUtils.mm +++ b/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/platform/ios/react/renderer/textlayoutmanager/RCTAttributedTextUtils.mm @@ -23,16 +23,15 @@ inline static UIFontWeight RCTUIFontWeightFromInteger(NSInteger fontWeight) assert(fontWeight > 50); assert(fontWeight < 950); - static auto weights = std::to_array( - {/* ~100 */ UIFontWeightUltraLight, - /* ~200 */ UIFontWeightThin, - /* ~300 */ UIFontWeightLight, - /* ~400 */ UIFontWeightRegular, - /* ~500 */ UIFontWeightMedium, - /* ~600 */ UIFontWeightSemibold, - /* ~700 */ UIFontWeightBold, - /* ~800 */ UIFontWeightHeavy, - /* ~900 */ UIFontWeightBlack}); + static auto weights = std::to_array({/* ~100 */ UIFontWeightUltraLight, + /* ~200 */ UIFontWeightThin, + /* ~300 */ UIFontWeightLight, + /* ~400 */ UIFontWeightRegular, + /* ~500 */ UIFontWeightMedium, + /* ~600 */ UIFontWeightSemibold, + /* ~700 */ UIFontWeightBold, + /* ~800 */ UIFontWeightHeavy, + /* ~900 */ UIFontWeightBlack}); // The expression is designed to convert something like 760 or 830 to 7. return weights[(fontWeight + 50) / 100 - 1]; } diff --git a/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/platform/ios/react/renderer/textlayoutmanager/RCTTextLayoutManager.mm b/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/platform/ios/react/renderer/textlayoutmanager/RCTTextLayoutManager.mm index 3b4109c44ae..ef50487f912 100644 --- a/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/platform/ios/react/renderer/textlayoutmanager/RCTTextLayoutManager.mm +++ b/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/platform/ios/react/renderer/textlayoutmanager/RCTTextLayoutManager.mm @@ -388,9 +388,8 @@ static NSLineBreakMode RCTNSLineBreakModeFromEllipsizeMode(EllipsizeMode ellipsi size.height = enumeratedLinesHeight; } - size = (CGSize){ - ceil(size.width * layoutContext.pointScaleFactor) / layoutContext.pointScaleFactor, - ceil(size.height * layoutContext.pointScaleFactor) / layoutContext.pointScaleFactor}; + size = (CGSize){ceil(size.width * layoutContext.pointScaleFactor) / layoutContext.pointScaleFactor, + ceil(size.height * layoutContext.pointScaleFactor) / layoutContext.pointScaleFactor}; __block auto attachments = TextMeasurement::Attachments{}; diff --git a/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/platform/ios/react/renderer/textlayoutmanager/TextLayoutManager.h b/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/platform/ios/react/renderer/textlayoutmanager/TextLayoutManager.h index 2e3b262c72b..ce564b01254 100644 --- a/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/platform/ios/react/renderer/textlayoutmanager/TextLayoutManager.h +++ b/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/platform/ios/react/renderer/textlayoutmanager/TextLayoutManager.h @@ -23,38 +23,37 @@ namespace facebook::react { */ class TextLayoutManager { public: - TextLayoutManager( - const std::shared_ptr& contextContainer); + TextLayoutManager(const std::shared_ptr &contextContainer); /* * Not copyable. */ - TextLayoutManager(const TextLayoutManager&) = delete; - TextLayoutManager& operator=(const TextLayoutManager&) = delete; + TextLayoutManager(const TextLayoutManager &) = delete; + TextLayoutManager &operator=(const TextLayoutManager &) = delete; /* * Not movable. */ - TextLayoutManager(TextLayoutManager&&) = delete; - TextLayoutManager& operator=(TextLayoutManager&&) = delete; + TextLayoutManager(TextLayoutManager &&) = delete; + TextLayoutManager &operator=(TextLayoutManager &&) = delete; /* * Measures `attributedString` using native text rendering infrastructure. */ TextMeasurement measure( - const AttributedStringBox& attributedStringBox, - const ParagraphAttributes& paragraphAttributes, - const TextLayoutContext& layoutContext, - const LayoutConstraints& layoutConstraints) const; + const AttributedStringBox &attributedStringBox, + const ParagraphAttributes ¶graphAttributes, + const TextLayoutContext &layoutContext, + const LayoutConstraints &layoutConstraints) const; /* * Measures lines of `attributedString` using native text rendering * infrastructure. */ LinesMeasurements measureLines( - const AttributedStringBox& attributedStringBox, - const ParagraphAttributes& paragraphAttributes, - const Size& size) const; + const AttributedStringBox &attributedStringBox, + const ParagraphAttributes ¶graphAttributes, + const Size &size) const; /* * Returns an opaque pointer to platform-specific TextLayoutManager. diff --git a/packages/react-native/ReactCommon/react/renderer/uimanager/AppRegistryBinding.h b/packages/react-native/ReactCommon/react/renderer/uimanager/AppRegistryBinding.h index cd596e920ca..f71565b9149 100644 --- a/packages/react-native/ReactCommon/react/renderer/uimanager/AppRegistryBinding.h +++ b/packages/react-native/ReactCommon/react/renderer/uimanager/AppRegistryBinding.h @@ -22,10 +22,10 @@ class AppRegistryBinding final { * Thread synchronization must be enforced externally. */ static void startSurface( - jsi::Runtime& runtime, + jsi::Runtime &runtime, SurfaceId surfaceId, - const std::string& moduleName, - const folly::dynamic& initialProps, + const std::string &moduleName, + const folly::dynamic &initialProps, DisplayMode displayMode); /* @@ -34,17 +34,17 @@ class AppRegistryBinding final { * Thread synchronization must be enforced externally. */ static void setSurfaceProps( - jsi::Runtime& runtime, + jsi::Runtime &runtime, SurfaceId surfaceId, - const std::string& moduleName, - const folly::dynamic& initialProps, + const std::string &moduleName, + const folly::dynamic &initialProps, DisplayMode displayMode); /* * Stops React Native Surface with given id. * Thread synchronization must be enforced externally. */ - static void stopSurface(jsi::Runtime& runtime, SurfaceId surfaceId); + static void stopSurface(jsi::Runtime &runtime, SurfaceId surfaceId); }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/uimanager/PointerEventsProcessor.h b/packages/react-native/ReactCommon/react/renderer/uimanager/PointerEventsProcessor.h index 64920da9b34..7c392a1b6cb 100644 --- a/packages/react-native/ReactCommon/react/renderer/uimanager/PointerEventsProcessor.h +++ b/packages/react-native/ReactCommon/react/renderer/uimanager/PointerEventsProcessor.h @@ -34,55 +34,46 @@ struct ActivePointer { }; using DispatchEvent = std::function; + const EventPayload &payload)>; using PointerIdentifier = int32_t; -using CaptureTargetOverrideRegistry = - std::unordered_map>; +using CaptureTargetOverrideRegistry = std::unordered_map>; -using ActivePointerRegistry = - std::unordered_map; -using PointerHoverTrackerRegistry = - std::unordered_map; +using ActivePointerRegistry = std::unordered_map; +using PointerHoverTrackerRegistry = std::unordered_map; class PointerEventsProcessor final { public: static std::shared_ptr getShadowNodeFromEventTarget( - jsi::Runtime& runtime, - const EventTarget* target); + jsi::Runtime &runtime, + const EventTarget *target); void interceptPointerEvent( - const std::shared_ptr& target, - const std::string& type, + const std::shared_ptr &target, + const std::string &type, ReactEventPriority priority, - const PointerEvent& event, - const DispatchEvent& eventDispatcher, - const UIManager& uiManager); + const PointerEvent &event, + const DispatchEvent &eventDispatcher, + const UIManager &uiManager); - void setPointerCapture( - PointerIdentifier pointerId, - const std::shared_ptr& shadowNode); - void releasePointerCapture( - PointerIdentifier pointerId, - const ShadowNode* shadowNode); - bool hasPointerCapture( - PointerIdentifier pointerId, - const ShadowNode* shadowNode); + void setPointerCapture(PointerIdentifier pointerId, const std::shared_ptr &shadowNode); + void releasePointerCapture(PointerIdentifier pointerId, const ShadowNode *shadowNode); + bool hasPointerCapture(PointerIdentifier pointerId, const ShadowNode *shadowNode); private: - ActivePointer* getActivePointer(PointerIdentifier pointerId); + ActivePointer *getActivePointer(PointerIdentifier pointerId); - void registerActivePointer(const PointerEvent& event); - void updateActivePointer(const PointerEvent& event); - void unregisterActivePointer(const PointerEvent& event); + void registerActivePointer(const PointerEvent &event); + void updateActivePointer(const PointerEvent &event); + void unregisterActivePointer(const PointerEvent &event); void processPendingPointerCapture( - const PointerEvent& event, - const DispatchEvent& eventDispatcher, - const UIManager& uiManager); + const PointerEvent &event, + const DispatchEvent &eventDispatcher, + const UIManager &uiManager); ActivePointerRegistry activePointers_; @@ -100,10 +91,10 @@ class PointerEventsProcessor final { * screen entirely) */ void handleIncomingPointerEventOnNode( - const PointerEvent& event, - const std::shared_ptr& targetNode, - const DispatchEvent& eventDispatcher, - const UIManager& uiManager); + const PointerEvent &event, + const std::shared_ptr &targetNode, + const DispatchEvent &eventDispatcher, + const UIManager &uiManager); PointerHoverTrackerRegistry previousHoverTrackersPerPointer_; }; diff --git a/packages/react-native/ReactCommon/react/renderer/uimanager/PointerHoverTracker.h b/packages/react-native/ReactCommon/react/renderer/uimanager/PointerHoverTracker.h index 336b9dbdd74..712a3cdfffc 100644 --- a/packages/react-native/ReactCommon/react/renderer/uimanager/PointerHoverTracker.h +++ b/packages/react-native/ReactCommon/react/renderer/uimanager/PointerHoverTracker.h @@ -23,15 +23,12 @@ class PointerHoverTracker { using Unique = std::unique_ptr; using EventPath = std::vector>; - PointerHoverTracker( - std::shared_ptr target, - const UIManager& uiManager); + PointerHoverTracker(std::shared_ptr target, const UIManager &uiManager); - const ShadowNode* getTarget(const UIManager& uiManager) const; - bool hasSameTarget(const PointerHoverTracker& other) const; - bool areAnyTargetsListeningToEvents( - std::initializer_list eventTypes, - const UIManager& uiManager) const; + const ShadowNode *getTarget(const UIManager &uiManager) const; + bool hasSameTarget(const PointerHoverTracker &other) const; + bool areAnyTargetsListeningToEvents(std::initializer_list eventTypes, const UIManager &uiManager) + const; /** * Performs a diff between the current and given trackers and returns a tuple @@ -39,9 +36,7 @@ class PointerHoverTracker { * have been added. Note that the order of these lists are from parents -> * children. */ - std::tuple diffEventPath( - const PointerHoverTracker& other, - const UIManager& uiManager) const; + std::tuple diffEventPath(const PointerHoverTracker &other, const UIManager &uiManager) const; void markAsOld(); @@ -59,9 +54,7 @@ class PointerHoverTracker { * A thin wrapper around `UIManager::getNewestCloneOfShadowNode` that only * actually gets the newest clone only if the tracker is marked as "old". */ - const ShadowNode* getLatestNode( - const ShadowNode& node, - const UIManager& uiManager) const; + const ShadowNode *getLatestNode(const ShadowNode &node, const UIManager &uiManager) const; /** * Retrieves the list of shadow node references in the event's path starting diff --git a/packages/react-native/ReactCommon/react/renderer/uimanager/SurfaceRegistryBinding.h b/packages/react-native/ReactCommon/react/renderer/uimanager/SurfaceRegistryBinding.h index 5d9b6400971..a3d3b67f6f4 100644 --- a/packages/react-native/ReactCommon/react/renderer/uimanager/SurfaceRegistryBinding.h +++ b/packages/react-native/ReactCommon/react/renderer/uimanager/SurfaceRegistryBinding.h @@ -7,7 +7,6 @@ #pragma once -#warning \ - "The SurfaceRegistryBinding.h header has been renamed to AppRegistryBinding.h" +#warning "The SurfaceRegistryBinding.h header has been renamed to AppRegistryBinding.h" #include diff --git a/packages/react-native/ReactCommon/react/renderer/uimanager/UIManager.h b/packages/react-native/ReactCommon/react/renderer/uimanager/UIManager.h index ebdc1d260f7..794a5559a55 100644 --- a/packages/react-native/ReactCommon/react/renderer/uimanager/UIManager.h +++ b/packages/react-native/ReactCommon/react/renderer/uimanager/UIManager.h @@ -40,35 +40,31 @@ class UIManagerMountHook; class UIManager final : public ShadowTreeDelegate { public: - UIManager( - const RuntimeExecutor& runtimeExecutor, - std::shared_ptr contextContainer); + UIManager(const RuntimeExecutor &runtimeExecutor, std::shared_ptr contextContainer); ~UIManager() override; - void setComponentDescriptorRegistry( - const SharedComponentDescriptorRegistry& componentDescriptorRegistry); + void setComponentDescriptorRegistry(const SharedComponentDescriptorRegistry &componentDescriptorRegistry); /* * Sets and gets the UIManager's delegate. * The delegate is stored as a raw pointer, so the owner must null * the pointer before being destroyed. */ - void setDelegate(UIManagerDelegate* delegate); - UIManagerDelegate* getDelegate(); + void setDelegate(UIManagerDelegate *delegate); + UIManagerDelegate *getDelegate(); /** * Sets and gets the UIManager's Animation APIs delegate. * The delegate is stored as a raw pointer, so the owner must null * the pointer before being destroyed. */ - void setAnimationDelegate(UIManagerAnimationDelegate* delegate); + void setAnimationDelegate(UIManagerAnimationDelegate *delegate); /** * Sets and gets UIManager's AnimationBackend reference. */ - void unstable_setAnimationBackend( - std::weak_ptr animationBackend); + void unstable_setAnimationBackend(std::weak_ptr animationBackend); std::weak_ptr unstable_getAnimationBackend(); /** @@ -76,12 +72,11 @@ class UIManager final : public ShadowTreeDelegate { */ void stopSurfaceForAnimationDelegate(SurfaceId surfaceId) const; - void setNativeAnimatedDelegate( - std::weak_ptr delegate); + void setNativeAnimatedDelegate(std::weak_ptr delegate); void animationTick() const; - void synchronouslyUpdateViewOnUIThread(Tag tag, const folly::dynamic& props); + void synchronouslyUpdateViewOnUIThread(Tag tag, const folly::dynamic &props); /* * Provides access to a UIManagerBindging. @@ -90,43 +85,40 @@ class UIManager final : public ShadowTreeDelegate { * The callback is called synchronously on the same thread. */ void visitBinding( - const std::function& - callback, - jsi::Runtime& runtime) const; + const std::function &callback, + jsi::Runtime &runtime) const; /* * Registers and unregisters a commit hook. */ - void registerCommitHook(UIManagerCommitHook& commitHook); - void unregisterCommitHook(UIManagerCommitHook& commitHook); + void registerCommitHook(UIManagerCommitHook &commitHook); + void unregisterCommitHook(UIManagerCommitHook &commitHook); /* * Registers and unregisters a mount hook. */ - void registerMountHook(UIManagerMountHook& mountHook); - void unregisterMountHook(UIManagerMountHook& mountHook); + void registerMountHook(UIManagerMountHook &mountHook); + void unregisterMountHook(UIManagerMountHook &mountHook); - std::shared_ptr getNewestCloneOfShadowNode( - const ShadowNode& shadowNode) const; + std::shared_ptr getNewestCloneOfShadowNode(const ShadowNode &shadowNode) const; - ShadowTreeRevisionConsistencyManager* - getShadowTreeRevisionConsistencyManager(); - ShadowTreeRevisionProvider* getShadowTreeRevisionProvider(); + ShadowTreeRevisionConsistencyManager *getShadowTreeRevisionConsistencyManager(); + ShadowTreeRevisionProvider *getShadowTreeRevisionProvider(); #pragma mark - Surface Start & Stop void startSurface( - ShadowTree::Unique&& shadowTree, - const std::string& moduleName, - const folly::dynamic& props, + ShadowTree::Unique &&shadowTree, + const std::string &moduleName, + const folly::dynamic &props, DisplayMode displayMode) const noexcept; - void startEmptySurface(ShadowTree::Unique&& shadowTree) const noexcept; + void startEmptySurface(ShadowTree::Unique &&shadowTree) const noexcept; void setSurfaceProps( SurfaceId surfaceId, - const std::string& moduleName, - const folly::dynamic& props, + const std::string &moduleName, + const folly::dynamic &props, DisplayMode displayMode) const noexcept; ShadowTree::Unique stopSurface(SurfaceId surfaceId) const; @@ -138,40 +130,37 @@ class UIManager final : public ShadowTreeDelegate { bool mountSynchronously) const override; RootShadowNode::Unshared shadowTreeWillCommit( - const ShadowTree& shadowTree, - const RootShadowNode::Shared& oldRootShadowNode, - const RootShadowNode::Unshared& newRootShadowNode, - const ShadowTree::CommitOptions& commitOptions) const override; + const ShadowTree &shadowTree, + const RootShadowNode::Shared &oldRootShadowNode, + const RootShadowNode::Unshared &newRootShadowNode, + const ShadowTree::CommitOptions &commitOptions) const override; std::shared_ptr createNode( Tag tag, - const std::string& componentName, + const std::string &componentName, SurfaceId surfaceId, RawProps props, InstanceHandle::Shared instanceHandle) const; - std::shared_ptr cloneNode( - const ShadowNode& shadowNode, - const ShadowNode::SharedListOfShared& children, - RawProps rawProps) const; + std::shared_ptr + cloneNode(const ShadowNode &shadowNode, const ShadowNode::SharedListOfShared &children, RawProps rawProps) const; void appendChild( - const std::shared_ptr& parentShadowNode, - const std::shared_ptr& childShadowNode) const; + const std::shared_ptr &parentShadowNode, + const std::shared_ptr &childShadowNode) const; void completeSurface( SurfaceId surfaceId, - const ShadowNode::UnsharedListOfShared& rootChildren, + const ShadowNode::UnsharedListOfShared &rootChildren, ShadowTree::CommitOptions commitOptions); void setIsJSResponder( - const std::shared_ptr& shadowNode, + const std::shared_ptr &shadowNode, bool isJSResponder, bool blockNativeResponder) const; - std::shared_ptr findNodeAtPoint( - const std::shared_ptr& shadowNode, - Point point) const; + std::shared_ptr findNodeAtPoint(const std::shared_ptr &shadowNode, Point point) + const; /* * Returns layout metrics of given `shadowNode` relative to @@ -179,28 +168,24 @@ class UIManager final : public ShadowTreeDelegate { * `ancestorShadowNode` is nullptr). */ LayoutMetrics getRelativeLayoutMetrics( - const ShadowNode& shadowNode, - const ShadowNode* ancestorShadowNode, + const ShadowNode &shadowNode, + const ShadowNode *ancestorShadowNode, LayoutableShadowNode::LayoutInspectingPolicy policy) const; /* * Creates a new shadow node with given state data, clones what's necessary * and performs a commit. */ - void updateState(const StateUpdate& stateUpdate) const; + void updateState(const StateUpdate &stateUpdate) const; void dispatchCommand( - const std::shared_ptr& shadowNode, - const std::string& commandName, - const folly::dynamic& args) const; + const std::shared_ptr &shadowNode, + const std::string &commandName, + const folly::dynamic &args) const; - void setNativeProps_DEPRECATED( - const std::shared_ptr& shadowNode, - RawProps rawProps) const; + void setNativeProps_DEPRECATED(const std::shared_ptr &shadowNode, RawProps rawProps) const; - void sendAccessibilityEvent( - const std::shared_ptr& shadowNode, - const std::string& eventType); + void sendAccessibilityEvent(const std::shared_ptr &shadowNode, const std::string &eventType); /* * Iterates over all shadow nodes which are parts of all registered surfaces @@ -208,25 +193,22 @@ class UIManager final : public ShadowTreeDelegate { * wasn't found. This is a temporary workaround that should not be used in * any core functionality. */ - std::shared_ptr findShadowNodeByTag_DEPRECATED( - Tag tag) const; + std::shared_ptr findShadowNodeByTag_DEPRECATED(Tag tag) const; - const ShadowTreeRegistry& getShadowTreeRegistry() const; + const ShadowTreeRegistry &getShadowTreeRegistry() const; void reportMount(SurfaceId surfaceId) const; - void updateShadowTree(std::unordered_map&& tagToProps); + void updateShadowTree(std::unordered_map &&tagToProps); #pragma mark - Add & Remove event listener void addEventListener(std::shared_ptr listener); - void removeEventListener( - const std::shared_ptr& listener); + void removeEventListener(const std::shared_ptr &listener); #pragma mark - Set on surface start callback - void setOnSurfaceStartCallback( - UIManagerDelegate::OnSurfaceStartCallback&& callback); + void setOnSurfaceStartCallback(UIManagerDelegate::OnSurfaceStartCallback &&callback); private: friend class UIManagerBinding; @@ -238,18 +220,18 @@ class UIManager final : public ShadowTreeDelegate { * This API configures a global LayoutAnimation starting from the root node. */ void configureNextLayoutAnimation( - jsi::Runtime& runtime, - const RawValue& config, - const jsi::Value& successCallback, - const jsi::Value& failureCallback) const; + jsi::Runtime &runtime, + const RawValue &config, + const jsi::Value &successCallback, + const jsi::Value &failureCallback) const; std::shared_ptr getShadowNodeInSubtree( - const ShadowNode& shadowNode, - const std::shared_ptr& ancestorShadowNode) const; + const ShadowNode &shadowNode, + const std::shared_ptr &ancestorShadowNode) const; SharedComponentDescriptorRegistry componentDescriptorRegistry_; - UIManagerDelegate* delegate_{}; - UIManagerAnimationDelegate* animationDelegate_{nullptr}; + UIManagerDelegate *delegate_{}; + UIManagerAnimationDelegate *animationDelegate_{nullptr}; std::weak_ptr nativeAnimatedDelegate_; const RuntimeExecutor runtimeExecutor_{}; @@ -257,15 +239,14 @@ class UIManager final : public ShadowTreeDelegate { std::shared_ptr contextContainer_; mutable std::shared_mutex commitHookMutex_; - mutable std::vector commitHooks_; + mutable std::vector commitHooks_; mutable std::shared_mutex mountHookMutex_; - mutable std::vector mountHooks_; + mutable std::vector mountHooks_; std::unique_ptr leakChecker_; - std::unique_ptr - lazyShadowTreeRevisionConsistencyManager_; + std::unique_ptr lazyShadowTreeRevisionConsistencyManager_; std::weak_ptr animationBackend_; }; diff --git a/packages/react-native/ReactCommon/react/renderer/uimanager/UIManagerAnimationDelegate.h b/packages/react-native/ReactCommon/react/renderer/uimanager/UIManagerAnimationDelegate.h index 09c2d0661b5..ac310eb4ad9 100644 --- a/packages/react-native/ReactCommon/react/renderer/uimanager/UIManagerAnimationDelegate.h +++ b/packages/react-native/ReactCommon/react/renderer/uimanager/UIManagerAnimationDelegate.h @@ -23,18 +23,17 @@ class UIManagerAnimationDelegate { * TODO: need SurfaceId here */ virtual void uiManagerDidConfigureNextLayoutAnimation( - jsi::Runtime& runtime, - const RawValue& config, - const jsi::Value& successCallback, - const jsi::Value& failureCallback) const = 0; + jsi::Runtime &runtime, + const RawValue &config, + const jsi::Value &successCallback, + const jsi::Value &failureCallback) const = 0; /** * Set ComponentDescriptor registry. * * @param componentDescriptorRegistry the registry of componentDescriptors */ - virtual void setComponentDescriptorRegistry( - const SharedComponentDescriptorRegistry& componentDescriptorRegistry) = 0; + virtual void setComponentDescriptorRegistry(const SharedComponentDescriptorRegistry &componentDescriptorRegistry) = 0; /** * Only needed on Android to drive animations. diff --git a/packages/react-native/ReactCommon/react/renderer/uimanager/UIManagerBinding.h b/packages/react-native/ReactCommon/react/renderer/uimanager/UIManagerBinding.h index ef6c682df00..1155fd6e797 100644 --- a/packages/react-native/ReactCommon/react/renderer/uimanager/UIManagerBinding.h +++ b/packages/react-native/ReactCommon/react/renderer/uimanager/UIManagerBinding.h @@ -26,15 +26,13 @@ class UIManagerBinding : public jsi::HostObject { * Creates and sets `UIManagerBinding` into the global namespace. * Thread synchronization must be enforced externally. */ - static void createAndInstallIfNeeded( - jsi::Runtime& runtime, - const std::shared_ptr& uiManager); + static void createAndInstallIfNeeded(jsi::Runtime &runtime, const std::shared_ptr &uiManager); /* * Returns a pointer to UIManagerBinding previously installed into a runtime. * Thread synchronization must be enforced externally. */ - static std::shared_ptr getBinding(jsi::Runtime& runtime); + static std::shared_ptr getBinding(jsi::Runtime &runtime); UIManagerBinding(std::shared_ptr uiManager); @@ -45,11 +43,11 @@ class UIManagerBinding : public jsi::HostObject { * Thread synchronization must be enforced externally. */ void dispatchEvent( - jsi::Runtime& runtime, - const EventTarget* eventTarget, - const std::string& type, + jsi::Runtime &runtime, + const EventTarget *eventTarget, + const std::string &type, ReactEventPriority priority, - const EventPayload& payload) const; + const EventPayload &payload) const; /* * Invalidates the binding and underlying UIManager. @@ -63,10 +61,10 @@ class UIManagerBinding : public jsi::HostObject { /* * `jsi::HostObject` specific overloads. */ - jsi::Value get(jsi::Runtime& runtime, const jsi::PropNameID& name) override; + jsi::Value get(jsi::Runtime &runtime, const jsi::PropNameID &name) override; - UIManager& getUIManager(); - PointerEventsProcessor& getPointerEventsProcessor(); + UIManager &getUIManager(); + PointerEventsProcessor &getPointerEventsProcessor(); private: /* @@ -74,11 +72,11 @@ class UIManagerBinding : public jsi::HostObject { * UIManagerBinding::dispatchEvent. */ void dispatchEventToJS( - jsi::Runtime& runtime, - const EventTarget* eventTarget, - const std::string& type, + jsi::Runtime &runtime, + const EventTarget *eventTarget, + const std::string &type, ReactEventPriority priority, - const EventPayload& payload) const; + const EventPayload &payload) const; std::shared_ptr uiManager_; std::unique_ptr eventHandler_; diff --git a/packages/react-native/ReactCommon/react/renderer/uimanager/UIManagerCommitHook.h b/packages/react-native/ReactCommon/react/renderer/uimanager/UIManagerCommitHook.h index 2e15c6ca89e..8c34b59ac03 100644 --- a/packages/react-native/ReactCommon/react/renderer/uimanager/UIManagerCommitHook.h +++ b/packages/react-native/ReactCommon/react/renderer/uimanager/UIManagerCommitHook.h @@ -23,9 +23,8 @@ class UIManagerCommitHook { /* * Called right after the commit hook is registered or unregistered. */ - virtual void commitHookWasRegistered(const UIManager& uiManager) noexcept = 0; - virtual void commitHookWasUnregistered( - const UIManager& uiManager) noexcept = 0; + virtual void commitHookWasRegistered(const UIManager &uiManager) noexcept = 0; + virtual void commitHookWasUnregistered(const UIManager &uiManager) noexcept = 0; /* * Called right before a `ShadowTree` commits a new tree. @@ -33,12 +32,12 @@ class UIManagerCommitHook { * from `ShadowTreeDelegate`. */ virtual RootShadowNode::Unshared shadowTreeWillCommit( - const ShadowTree& shadowTree, - const RootShadowNode::Shared& oldRootShadowNode, - const RootShadowNode::Unshared& newRootShadowNode, - const ShadowTreeCommitOptions& /*commitOptions*/) noexcept { - return shadowTreeWillCommit( - shadowTree, oldRootShadowNode, newRootShadowNode); + const ShadowTree &shadowTree, + const RootShadowNode::Shared &oldRootShadowNode, + const RootShadowNode::Unshared &newRootShadowNode, + const ShadowTreeCommitOptions & /*commitOptions*/) noexcept + { + return shadowTreeWillCommit(shadowTree, oldRootShadowNode, newRootShadowNode); } /* @@ -46,9 +45,10 @@ class UIManagerCommitHook { * backward compatibility. */ virtual RootShadowNode::Unshared shadowTreeWillCommit( - const ShadowTree& /*shadowTree*/, - const RootShadowNode::Shared& /*oldRootShadowNode*/, - const RootShadowNode::Unshared& newRootShadowNode) noexcept { + const ShadowTree & /*shadowTree*/, + const RootShadowNode::Shared & /*oldRootShadowNode*/, + const RootShadowNode::Unshared &newRootShadowNode) noexcept + { // No longer a pure method as subclasses are expected to implement the other // flavor instead. return newRootShadowNode; diff --git a/packages/react-native/ReactCommon/react/renderer/uimanager/UIManagerDelegate.h b/packages/react-native/ReactCommon/react/renderer/uimanager/UIManagerDelegate.h index e649a273742..32df5c92f10 100644 --- a/packages/react-native/ReactCommon/react/renderer/uimanager/UIManagerDelegate.h +++ b/packages/react-native/ReactCommon/react/renderer/uimanager/UIManagerDelegate.h @@ -32,15 +32,15 @@ class UIManagerDelegate { * might use this to optimistically allocate a new native view * instances. */ - virtual void uiManagerDidCreateShadowNode(const ShadowNode& shadowNode) = 0; + virtual void uiManagerDidCreateShadowNode(const ShadowNode &shadowNode) = 0; /* * Called when UIManager wants to dispatch a command to the mounting layer. */ virtual void uiManagerDidDispatchCommand( - const std::shared_ptr& shadowNode, - const std::string& commandName, - const folly::dynamic& args) = 0; + const std::shared_ptr &shadowNode, + const std::string &commandName, + const folly::dynamic &args) = 0; /* * Called when UIManager wants to dispatch some accessibility event @@ -48,51 +48,44 @@ class UIManagerDelegate { * platforms will necessarily implement the same set of events. */ virtual void uiManagerDidSendAccessibilityEvent( - const std::shared_ptr& shadowNode, - const std::string& eventType) = 0; + const std::shared_ptr &shadowNode, + const std::string &eventType) = 0; /* * Set JS responder for a view. */ virtual void uiManagerDidSetIsJSResponder( - const std::shared_ptr& shadowNode, + const std::shared_ptr &shadowNode, bool isJSResponder, bool blockNativeResponder) = 0; /* * Synchronous view update. */ - virtual void uiManagerShouldSynchronouslyUpdateViewOnUIThread( - Tag tag, - const folly::dynamic& props) = 0; + virtual void uiManagerShouldSynchronouslyUpdateViewOnUIThread(Tag tag, const folly::dynamic &props) = 0; /* * Called after updateShadowTree is invoked. */ - virtual void uiManagerDidUpdateShadowTree( - const std::unordered_map& tagToProps) = 0; + virtual void uiManagerDidUpdateShadowTree(const std::unordered_map &tagToProps) = 0; /* * Add event listener. */ - virtual void uiManagerShouldAddEventListener( - std::shared_ptr listener) = 0; + virtual void uiManagerShouldAddEventListener(std::shared_ptr listener) = 0; /* * Remove event listener. */ - virtual void uiManagerShouldRemoveEventListener( - const std::shared_ptr& listener) = 0; + virtual void uiManagerShouldRemoveEventListener(const std::shared_ptr &listener) = 0; /* * Start surface. */ - virtual void uiManagerDidStartSurface(const ShadowTree& shadowTree) = 0; + virtual void uiManagerDidStartSurface(const ShadowTree &shadowTree) = 0; - using OnSurfaceStartCallback = - std::function; - virtual void uiManagerShouldSetOnSurfaceStartCallback( - OnSurfaceStartCallback&& callback) = 0; + using OnSurfaceStartCallback = std::function; + virtual void uiManagerShouldSetOnSurfaceStartCallback(OnSurfaceStartCallback &&callback) = 0; virtual ~UIManagerDelegate() noexcept = default; }; diff --git a/packages/react-native/ReactCommon/react/renderer/uimanager/UIManagerMountHook.h b/packages/react-native/ReactCommon/react/renderer/uimanager/UIManagerMountHook.h index 1a014411d85..763efb8b353 100644 --- a/packages/react-native/ReactCommon/react/renderer/uimanager/UIManagerMountHook.h +++ b/packages/react-native/ReactCommon/react/renderer/uimanager/UIManagerMountHook.h @@ -25,12 +25,11 @@ class UIManagerMountHook { * Called right after a `ShadowTree` is mounted in the host platform. */ virtual void shadowTreeDidMount( - const RootShadowNode::Shared& rootShadowNode, + const RootShadowNode::Shared &rootShadowNode, HighResTimeStamp mountTime) noexcept = 0; - virtual void shadowTreeDidUnmount( - SurfaceId /*surfaceId*/, - HighResTimeStamp /*unmountTime*/) noexcept { + virtual void shadowTreeDidUnmount(SurfaceId /*surfaceId*/, HighResTimeStamp /*unmountTime*/) noexcept + { // Default no-op implementation for backwards compatibility. } diff --git a/packages/react-native/ReactCommon/react/renderer/uimanager/consistency/LazyShadowTreeRevisionConsistencyManager.h b/packages/react-native/ReactCommon/react/renderer/uimanager/consistency/LazyShadowTreeRevisionConsistencyManager.h index 527e6bde1d3..96c7537ed28 100644 --- a/packages/react-native/ReactCommon/react/renderer/uimanager/consistency/LazyShadowTreeRevisionConsistencyManager.h +++ b/packages/react-native/ReactCommon/react/renderer/uimanager/consistency/LazyShadowTreeRevisionConsistencyManager.h @@ -23,16 +23,12 @@ namespace facebook::react { * tree for a given surface ID, only updating it when React commits a new tree * or between JS tasks. */ -class LazyShadowTreeRevisionConsistencyManager - : public ShadowTreeRevisionConsistencyManager, - public ShadowTreeRevisionProvider { +class LazyShadowTreeRevisionConsistencyManager : public ShadowTreeRevisionConsistencyManager, + public ShadowTreeRevisionProvider { public: - explicit LazyShadowTreeRevisionConsistencyManager( - ShadowTreeRegistry& shadowTreeRegistry); + explicit LazyShadowTreeRevisionConsistencyManager(ShadowTreeRegistry &shadowTreeRegistry); - void updateCurrentRevision( - SurfaceId surfaceId, - RootShadowNode::Shared rootShadowNode); + void updateCurrentRevision(SurfaceId surfaceId, RootShadowNode::Shared rootShadowNode); #pragma mark - ShadowTreeRevisionProvider @@ -45,9 +41,8 @@ class LazyShadowTreeRevisionConsistencyManager private: std::mutex capturedRootShadowNodesForConsistencyMutex_; - std::unordered_map - capturedRootShadowNodesForConsistency_; - ShadowTreeRegistry& shadowTreeRegistry_; + std::unordered_map capturedRootShadowNodesForConsistency_; + ShadowTreeRegistry &shadowTreeRegistry_; uint_fast32_t lockCount{0}; }; diff --git a/packages/react-native/ReactCommon/react/renderer/uimanager/primitives.h b/packages/react-native/ReactCommon/react/renderer/uimanager/primitives.h index 70cb2a1cbcb..2d93f164a23 100644 --- a/packages/react-native/ReactCommon/react/renderer/uimanager/primitives.h +++ b/packages/react-native/ReactCommon/react/renderer/uimanager/primitives.h @@ -16,12 +16,10 @@ namespace facebook::react { -using BackgroundExecutor = - std::function&& callback)>; +using BackgroundExecutor = std::function &&callback)>; struct ShadowNodeListWrapper : public jsi::NativeState { - ShadowNodeListWrapper(ShadowNode::UnsharedListOfShared shadowNodeList) - : shadowNodeList(std::move(shadowNodeList)) {} + ShadowNodeListWrapper(ShadowNode::UnsharedListOfShared shadowNodeList) : shadowNodeList(std::move(shadowNodeList)) {} // The below method needs to be implemented out-of-line in order for the class // to have at least one "key function" (see @@ -32,16 +30,15 @@ struct ShadowNodeListWrapper : public jsi::NativeState { }; inline static jsi::Value valueFromShadowNode( - jsi::Runtime& runtime, + jsi::Runtime &runtime, std::shared_ptr shadowNode, - bool assignRuntimeShadowNodeReference = false) { + bool assignRuntimeShadowNodeReference = false) +{ // Wrap the shadow node so that we can update JS references from native - auto wrappedShadowNode = - std::make_shared(std::move(shadowNode)); + auto wrappedShadowNode = std::make_shared(std::move(shadowNode)); if (assignRuntimeShadowNodeReference) { - wrappedShadowNode->shadowNode->setRuntimeShadowNodeReference( - wrappedShadowNode); + wrappedShadowNode->shadowNode->setRuntimeShadowNodeReference(wrappedShadowNode); } jsi::Object obj(runtime); @@ -51,23 +48,20 @@ inline static jsi::Value valueFromShadowNode( // TODO: once we no longer need to mutate the return value (appendChildToSet) // make this a SharedListOfShared -inline static ShadowNode::UnsharedListOfShared shadowNodeListFromValue( - jsi::Runtime& runtime, - const jsi::Value& value) { +inline static ShadowNode::UnsharedListOfShared shadowNodeListFromValue(jsi::Runtime &runtime, const jsi::Value &value) +{ // TODO: cleanup when passChildrenWhenCloningPersistedNodes is rolled out jsi::Object object = value.asObject(runtime); if (object.isArray(runtime)) { auto jsArray = std::move(object).asArray(runtime); size_t jsArrayLen = jsArray.length(runtime); if (jsArrayLen > 0) { - auto shadowNodeArray = - std::make_shared>>(); + auto shadowNodeArray = std::make_shared>>(); shadowNodeArray->reserve(jsArrayLen); for (size_t i = 0; i < jsArrayLen; i++) { shadowNodeArray->push_back( - Bridging>::fromJs( - runtime, jsArray.getValueAtIndex(runtime, i))); + Bridging>::fromJs(runtime, jsArray.getValueAtIndex(runtime, i))); } return shadowNodeArray; } else { @@ -77,16 +71,13 @@ inline static ShadowNode::UnsharedListOfShared shadowNodeListFromValue( ; } } else { - return object.getNativeState(runtime) - ->shadowNodeList; + return object.getNativeState(runtime)->shadowNodeList; } } -inline static jsi::Value valueFromShadowNodeList( - jsi::Runtime& runtime, - ShadowNode::UnsharedListOfShared shadowNodeList) { - auto wrapper = - std::make_shared(std::move(shadowNodeList)); +inline static jsi::Value valueFromShadowNodeList(jsi::Runtime &runtime, ShadowNode::UnsharedListOfShared shadowNodeList) +{ + auto wrapper = std::make_shared(std::move(shadowNodeList)); // Use the wrapper for NativeState too, otherwise we can't implement // the marker interface. Could be simplified to a simple struct wrapper. jsi::Object obj(runtime); @@ -95,10 +86,10 @@ inline static jsi::Value valueFromShadowNodeList( } inline static ShadowNode::UnsharedListOfShared shadowNodeListFromWeakList( - const ShadowNode::UnsharedListOfWeak& weakShadowNodeList) { - auto result = - std::make_shared>>(); - for (const auto& weakShadowNode : *weakShadowNodeList) { + const ShadowNode::UnsharedListOfWeak &weakShadowNodeList) +{ + auto result = std::make_shared>>(); + for (const auto &weakShadowNode : *weakShadowNodeList) { auto sharedShadowNode = weakShadowNode.lock(); if (!sharedShadowNode) { return nullptr; @@ -108,41 +99,38 @@ inline static ShadowNode::UnsharedListOfShared shadowNodeListFromWeakList( return result; } -inline static ShadowNode::UnsharedListOfWeak weakShadowNodeListFromValue( - jsi::Runtime& runtime, - const jsi::Value& value) { +inline static ShadowNode::UnsharedListOfWeak weakShadowNodeListFromValue(jsi::Runtime &runtime, const jsi::Value &value) +{ auto shadowNodeList = shadowNodeListFromValue(runtime, value); - auto weakShadowNodeList = - std::make_shared>>(); - for (const auto& shadowNode : *shadowNodeList) { + auto weakShadowNodeList = std::make_shared>>(); + for (const auto &shadowNode : *shadowNodeList) { weakShadowNodeList->push_back(shadowNode); } return weakShadowNodeList; } -inline static Tag tagFromValue(const jsi::Value& value) { +inline static Tag tagFromValue(const jsi::Value &value) +{ return (Tag)value.getNumber(); } -inline static InstanceHandle::Shared instanceHandleFromValue( - jsi::Runtime& runtime, - const jsi::Value& instanceHandleValue, - const jsi::Value& tagValue) { +inline static InstanceHandle::Shared +instanceHandleFromValue(jsi::Runtime &runtime, const jsi::Value &instanceHandleValue, const jsi::Value &tagValue) +{ react_native_assert(!instanceHandleValue.isNull()); if (instanceHandleValue.isNull()) { return nullptr; } - return std::make_shared( - runtime, instanceHandleValue, tagFromValue(tagValue)); + return std::make_shared(runtime, instanceHandleValue, tagFromValue(tagValue)); } -inline static SurfaceId surfaceIdFromValue( - jsi::Runtime& runtime, - const jsi::Value& value) { +inline static SurfaceId surfaceIdFromValue(jsi::Runtime &runtime, const jsi::Value &value) +{ return (SurfaceId)value.getNumber(); } -inline static int displayModeToInt(const DisplayMode value) { +inline static int displayModeToInt(const DisplayMode value) +{ // the result of this method should be in sync with // Libraries/ReactNative/DisplayMode.js switch (value) { @@ -158,15 +146,13 @@ inline static int displayModeToInt(const DisplayMode value) { } } -inline static std::string stringFromValue( - jsi::Runtime& runtime, - const jsi::Value& value) { +inline static std::string stringFromValue(jsi::Runtime &runtime, const jsi::Value &value) +{ return value.getString(runtime).utf8(runtime); } -inline static folly::dynamic commandArgsFromValue( - jsi::Runtime& runtime, - const jsi::Value& value) { +inline static folly::dynamic commandArgsFromValue(jsi::Runtime &runtime, const jsi::Value &value) +{ return jsi::dynamicFromValue(runtime, value); } } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/runtime/BindingsInstaller.h b/packages/react-native/ReactCommon/react/runtime/BindingsInstaller.h index 2934685f0a3..fb4226f5069 100644 --- a/packages/react-native/ReactCommon/react/runtime/BindingsInstaller.h +++ b/packages/react-native/ReactCommon/react/runtime/BindingsInstaller.h @@ -13,7 +13,8 @@ namespace facebook::react { class BindingsInstaller { public: - virtual ReactInstance::BindingsInstallFunc getBindingsInstallFunc() { + virtual ReactInstance::BindingsInstallFunc getBindingsInstallFunc() + { return nullptr; } }; diff --git a/packages/react-native/ReactCommon/react/runtime/BridgelessNativeMethodCallInvoker.h b/packages/react-native/ReactCommon/react/runtime/BridgelessNativeMethodCallInvoker.h index d707f2f4860..57dc1999b6f 100644 --- a/packages/react-native/ReactCommon/react/runtime/BridgelessNativeMethodCallInvoker.h +++ b/packages/react-native/ReactCommon/react/runtime/BridgelessNativeMethodCallInvoker.h @@ -15,13 +15,9 @@ namespace facebook::react { class BridgelessNativeMethodCallInvoker : public NativeMethodCallInvoker { public: - explicit BridgelessNativeMethodCallInvoker( - std::shared_ptr messageQueueThread); - void invokeAsync( - const std::string& methodName, - NativeMethodCallFunc&& func) noexcept override; - void invokeSync(const std::string& methodName, NativeMethodCallFunc&& func) - override; + explicit BridgelessNativeMethodCallInvoker(std::shared_ptr messageQueueThread); + void invokeAsync(const std::string &methodName, NativeMethodCallFunc &&func) noexcept override; + void invokeSync(const std::string &methodName, NativeMethodCallFunc &&func) override; private: std::shared_ptr messageQueueThread_; diff --git a/packages/react-native/ReactCommon/react/runtime/BufferedRuntimeExecutor.h b/packages/react-native/ReactCommon/react/runtime/BufferedRuntimeExecutor.h index 6606e492ec5..274015587fd 100644 --- a/packages/react-native/ReactCommon/react/runtime/BufferedRuntimeExecutor.h +++ b/packages/react-native/ReactCommon/react/runtime/BufferedRuntimeExecutor.h @@ -17,13 +17,14 @@ namespace facebook::react { class BufferedRuntimeExecutor { public: - using Work = std::function; + using Work = std::function; // A utility structure to track pending work in the order of when they arrive. struct BufferedWork { uint64_t index_; Work work_; - bool operator<(const BufferedWork& rhs) const { + bool operator<(const BufferedWork &rhs) const + { // Higher index has lower priority, so this inverted comparison puts // the smaller index on top of the queue. return index_ > rhs.index_; @@ -32,7 +33,7 @@ class BufferedRuntimeExecutor { BufferedRuntimeExecutor(RuntimeExecutor runtimeExecutor); - void execute(Work&& callback); + void execute(Work &&callback); // Flush buffered JS calls and then diable JS buffering void flush(); diff --git a/packages/react-native/ReactCommon/react/runtime/ReactInstance.h b/packages/react-native/ReactCommon/react/runtime/ReactInstance.h index fabc67d538d..a138c2e1fc5 100644 --- a/packages/react-native/ReactCommon/react/runtime/ReactInstance.h +++ b/packages/react-native/ReactCommon/react/runtime/ReactInstance.h @@ -23,14 +23,14 @@ namespace facebook::react { class ReactInstance final : private jsinspector_modern::InstanceTargetDelegate { public: - using BindingsInstallFunc = std::function; + using BindingsInstallFunc = std::function; ReactInstance( std::unique_ptr runtime, std::shared_ptr jsMessageQueueThread, std::shared_ptr timerManager, JsErrorHandler::OnJsError onJsError, - jsinspector_modern::HostTarget* parentInspectorTarget = nullptr); + jsinspector_modern::HostTarget *parentInspectorTarget = nullptr); RuntimeExecutor getUnbufferedRuntimeExecutor() noexcept; @@ -43,22 +43,17 @@ class ReactInstance final : private jsinspector_modern::InstanceTargetDelegate { const std::string runtimeDiagnosticFlags = {}; }; - void initializeRuntime( - JSRuntimeFlags options, - BindingsInstallFunc bindingsInstallFunc) noexcept; + void initializeRuntime(JSRuntimeFlags options, BindingsInstallFunc bindingsInstallFunc) noexcept; void loadScript( std::unique_ptr script, - const std::string& sourceURL, - std::function&& beforeLoad = nullptr, - std::function&& afterLoad = nullptr); + const std::string &sourceURL, + std::function &&beforeLoad = nullptr, + std::function &&afterLoad = nullptr); - void registerSegment(uint32_t segmentId, const std::string& segmentPath); + void registerSegment(uint32_t segmentId, const std::string &segmentPath); - void callFunctionOnModule( - const std::string& moduleName, - const std::string& methodName, - folly::dynamic&& args); + void callFunctionOnModule(const std::string &moduleName, const std::string &methodName, folly::dynamic &&args); void handleMemoryPressureJs(int pressureLevel); @@ -68,21 +63,20 @@ class ReactInstance final : private jsinspector_modern::InstanceTargetDelegate { */ void unregisterFromInspector(); - void* getJavaScriptContext(); + void *getJavaScriptContext(); private: std::shared_ptr runtime_; std::shared_ptr jsMessageQueueThread_; std::shared_ptr bufferedRuntimeExecutor_; std::shared_ptr timerManager_; - std::unordered_map> - callableModules_; + std::unordered_map> callableModules_; std::shared_ptr runtimeScheduler_; std::shared_ptr jsErrorHandler_; - jsinspector_modern::InstanceTarget* inspectorTarget_{nullptr}; - jsinspector_modern::RuntimeTarget* runtimeInspectorTarget_{nullptr}; - jsinspector_modern::HostTarget* parentInspectorTarget_{nullptr}; + jsinspector_modern::InstanceTarget *inspectorTarget_{nullptr}; + jsinspector_modern::RuntimeTarget *runtimeInspectorTarget_{nullptr}; + jsinspector_modern::HostTarget *parentInspectorTarget_{nullptr}; }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/runtime/TimerManager.h b/packages/react-native/ReactCommon/react/runtime/TimerManager.h index 914dec0b167..08e6512d146 100644 --- a/packages/react-native/ReactCommon/react/runtime/TimerManager.h +++ b/packages/react-native/ReactCommon/react/runtime/TimerManager.h @@ -18,12 +18,7 @@ namespace facebook::react { using TimerHandle = int; -enum class TimerSource { - Unknown, - SetTimeout, - SetInterval, - RequestAnimationFrame -}; +enum class TimerSource { Unknown, SetTimeout, SetInterval, RequestAnimationFrame }; /* * Wraps a jsi::Function to make it copyable so we can pass it into a lambda. @@ -34,12 +29,12 @@ struct TimerCallback { std::vector args, bool repeat, TimerSource source = TimerSource::Unknown) - : callback_(std::move(callback)), - args_(std::move(args)), - repeat(repeat), - source(source) {} + : callback_(std::move(callback)), args_(std::move(args)), repeat(repeat), source(source) + { + } - void invoke(jsi::Runtime& runtime) { + void invoke(jsi::Runtime &runtime) + { callback_.call(runtime, args_.data(), args_.size()); } @@ -51,39 +46,36 @@ struct TimerCallback { class TimerManager { public: - explicit TimerManager( - std::unique_ptr platformTimerRegistry) noexcept; + explicit TimerManager(std::unique_ptr platformTimerRegistry) noexcept; void setRuntimeExecutor(RuntimeExecutor runtimeExecutor) noexcept; - void callReactNativeMicrotasks(jsi::Runtime& runtime); + void callReactNativeMicrotasks(jsi::Runtime &runtime); void callTimer(TimerHandle handle); - void attachGlobals(jsi::Runtime& runtime); + void attachGlobals(jsi::Runtime &runtime); private: - TimerHandle createReactNativeMicrotask( - jsi::Function&& callback, - std::vector&& args); + TimerHandle createReactNativeMicrotask(jsi::Function &&callback, std::vector &&args); - void deleteReactNativeMicrotask(jsi::Runtime& runtime, TimerHandle handle); + void deleteReactNativeMicrotask(jsi::Runtime &runtime, TimerHandle handle); TimerHandle createTimer( - jsi::Function&& callback, - std::vector&& args, + jsi::Function &&callback, + std::vector &&args, double delay, TimerSource source = TimerSource::Unknown); - void deleteTimer(jsi::Runtime& runtime, TimerHandle handle); + void deleteTimer(jsi::Runtime &runtime, TimerHandle handle); TimerHandle createRecurringTimer( - jsi::Function&& callback, - std::vector&& args, + jsi::Function &&callback, + std::vector &&args, double delay, TimerSource source = TimerSource::Unknown); - void deleteRecurringTimer(jsi::Runtime& runtime, TimerHandle handle); + void deleteRecurringTimer(jsi::Runtime &runtime, TimerHandle handle); RuntimeExecutor runtimeExecutor_; std::unique_ptr platformTimerRegistry_; diff --git a/packages/react-native/ReactCommon/react/runtime/nativeviewconfig/LegacyUIManagerConstantsProviderBinding.h b/packages/react-native/ReactCommon/react/runtime/nativeviewconfig/LegacyUIManagerConstantsProviderBinding.h index d7758a45bf2..bdbce193016 100644 --- a/packages/react-native/ReactCommon/react/runtime/nativeviewconfig/LegacyUIManagerConstantsProviderBinding.h +++ b/packages/react-native/ReactCommon/react/runtime/nativeviewconfig/LegacyUIManagerConstantsProviderBinding.h @@ -16,12 +16,9 @@ namespace facebook::react::LegacyUIManagerConstantsProviderBinding { * runtime. It is supposed to be used as a substitute to UIManager.getConstants * in bridgeless mode. */ +void install(jsi::Runtime &runtime, const std::string &name, std::function &&provider); void install( - jsi::Runtime& runtime, - const std::string& name, - std::function&& provider); -void install( - jsi::Runtime& runtime, - const std::string& name, - std::function&& provider); + jsi::Runtime &runtime, + const std::string &name, + std::function &&provider); } // namespace facebook::react::LegacyUIManagerConstantsProviderBinding diff --git a/packages/react-native/ReactCommon/react/runtime/platform/ios/ReactCommon/RCTHermesInstance.h b/packages/react-native/ReactCommon/react/runtime/platform/ios/ReactCommon/RCTHermesInstance.h index 250f89f0106..c7bc46026c5 100644 --- a/packages/react-native/ReactCommon/react/runtime/platform/ios/ReactCommon/RCTHermesInstance.h +++ b/packages/react-native/ReactCommon/react/runtime/platform/ios/ReactCommon/RCTHermesInstance.h @@ -13,25 +13,24 @@ namespace facebook::react { class MessageQueueThread; -using CrashManagerProvider = - std::function()>; +using CrashManagerProvider = std::function()>; // ObjC++ wrapper for HermesInstance.cpp class RCTHermesInstance : public JSRuntimeFactory { public: RCTHermesInstance() : RCTHermesInstance(nullptr, false) {} RCTHermesInstance(CrashManagerProvider crashManagerProvider) - : RCTHermesInstance(std::move(crashManagerProvider), false) {} - RCTHermesInstance( - CrashManagerProvider crashManagerProvider, - bool allocInOldGenBeforeTTI) - : _crashManagerProvider(std::move(crashManagerProvider)), - _allocInOldGenBeforeTTI(allocInOldGenBeforeTTI) {} + : RCTHermesInstance(std::move(crashManagerProvider), false) + { + } + RCTHermesInstance(CrashManagerProvider crashManagerProvider, bool allocInOldGenBeforeTTI) + : _crashManagerProvider(std::move(crashManagerProvider)), _allocInOldGenBeforeTTI(allocInOldGenBeforeTTI) + { + } - std::unique_ptr createJSRuntime( - std::shared_ptr msgQueueThread) noexcept override; + std::unique_ptr createJSRuntime(std::shared_ptr msgQueueThread) noexcept override; - ~RCTHermesInstance() override{}; + ~RCTHermesInstance() override {}; private: CrashManagerProvider _crashManagerProvider; diff --git a/packages/react-native/ReactCommon/react/runtime/platform/ios/ReactCommon/RCTJscInstance.h b/packages/react-native/ReactCommon/react/runtime/platform/ios/ReactCommon/RCTJscInstance.h index 5732d3e41af..e0da9c1fd6a 100644 --- a/packages/react-native/ReactCommon/react/runtime/platform/ios/ReactCommon/RCTJscInstance.h +++ b/packages/react-native/ReactCommon/react/runtime/platform/ios/ReactCommon/RCTJscInstance.h @@ -15,9 +15,8 @@ class RCTJscInstance : public JSRuntimeFactory { public: RCTJscInstance(); - std::unique_ptr createJSRuntime( - std::shared_ptr msgQueueThread) noexcept override; + std::unique_ptr createJSRuntime(std::shared_ptr msgQueueThread) noexcept override; - ~RCTJscInstance(){}; + ~RCTJscInstance() {}; }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/runtime/platform/ios/ReactCommon/RCTLegacyUIManagerConstantsProvider.h b/packages/react-native/ReactCommon/react/runtime/platform/ios/ReactCommon/RCTLegacyUIManagerConstantsProvider.h index 041752ba5e9..9359df209c0 100644 --- a/packages/react-native/ReactCommon/react/runtime/platform/ios/ReactCommon/RCTLegacyUIManagerConstantsProvider.h +++ b/packages/react-native/ReactCommon/react/runtime/platform/ios/ReactCommon/RCTLegacyUIManagerConstantsProvider.h @@ -15,5 +15,5 @@ namespace facebook::react { * to implement UIManager.getConstants in bridgeless mode. The constants object * contains view configs for every legacy native component. */ -void installLegacyUIManagerConstantsProviderBinding(jsi::Runtime& runtime); +void installLegacyUIManagerConstantsProviderBinding(jsi::Runtime &runtime); } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/test_utils/Entropy.h b/packages/react-native/ReactCommon/react/test_utils/Entropy.h index a858bada731..e4c9f524508 100644 --- a/packages/react-native/ReactCommon/react/test_utils/Entropy.h +++ b/packages/react-native/ReactCommon/react/test_utils/Entropy.h @@ -24,7 +24,8 @@ class Entropy final { /* * Creates an instance seeded with a real, not pseudo-random, number. */ - Entropy() { + Entropy() + { std::random_device device; seed_ = device(); generator_ = std::mt19937(seed_); @@ -33,12 +34,14 @@ class Entropy final { /* * Creates an instance seeded with a given number. */ - Entropy(uint_fast32_t seed) { + Entropy(uint_fast32_t seed) + { seed_ = seed; generator_ = std::mt19937(seed_); } - uint_fast32_t getSeed() const { + uint_fast32_t getSeed() const + { return seed_; } @@ -47,39 +50,41 @@ class Entropy final { * within a specified range. */ template - bool random() const { + bool random() const + { T result; generateRandomValue(generator_, result); return result; } template - T random(Arg1 arg1) const { + T random(Arg1 arg1) const + { T result; generateRandomValue(generator_, result, arg1); return result; } template - T random(Arg1 arg1, Arg2 arg2) const { + T random(Arg1 arg1, Arg2 arg2) const + { T result; generateRandomValue(generator_, result, arg1, arg2); return result; } - void generateRandomValue( - Generator& generator, - bool& result, - double ratio = 0.5) const { + void generateRandomValue(Generator &generator, bool &result, double ratio = 0.5) const + { result = generator() % 10000 < 10000 * ratio; } - void generateRandomValue(Generator& generator, int& result) const { + void generateRandomValue(Generator &generator, int &result) const + { result = generator(); } - void generateRandomValue(Generator& generator, int& result, int min, int max) - const { + void generateRandomValue(Generator &generator, int &result, int min, int max) const + { std::uniform_int_distribution distribution(min, max); result = distribution(generator); } @@ -88,7 +93,8 @@ class Entropy final { * Shuffles `std::vector` in place. */ template - void shuffle(T array) const { + void shuffle(T array) const + { std::shuffle(array.begin(), array.end(), generator_); } @@ -97,15 +103,15 @@ class Entropy final { * distribution and given `deviation`. */ template - std::vector> distribute(std::vector items, double deviation) - const { + std::vector> distribute(std::vector items, double deviation) const + { std::normal_distribution<> distribution{0, deviation}; auto deviationLimit = int(deviation * 10); auto spreadResult = std::vector>(deviationLimit * 2); std::fill(spreadResult.begin(), spreadResult.end(), std::vector{}); - for (const auto& item : items) { + for (const auto &item : items) { auto position = int(distribution(generator_) + deviationLimit); position = std::max(0, std::min(position, deviationLimit * 2)); @@ -115,7 +121,7 @@ class Entropy final { } auto result = std::vector>{}; - for (const auto& chunk : spreadResult) { + for (const auto &chunk : spreadResult) { if (chunk.size() == 0) { continue; } diff --git a/packages/react-native/ReactCommon/react/test_utils/MockClock.h b/packages/react-native/ReactCommon/react/test_utils/MockClock.h index 7455d120fe7..88e6c8bc5fc 100644 --- a/packages/react-native/ReactCommon/react/test_utils/MockClock.h +++ b/packages/react-native/ReactCommon/react/test_utils/MockClock.h @@ -11,15 +11,16 @@ class MockClock { public: - using time_point = std::chrono:: - time_point; + using time_point = std::chrono::time_point; - static time_point now() noexcept { + static time_point now() noexcept + { return time_; } template - static void advance_by(const TDuration duration) { + static void advance_by(const TDuration duration) + { time_ += duration; } diff --git a/packages/react-native/ReactCommon/react/test_utils/MockSurfaceHandler.h b/packages/react-native/ReactCommon/react/test_utils/MockSurfaceHandler.h index 61e977467ba..09b27b02f38 100644 --- a/packages/react-native/ReactCommon/react/test_utils/MockSurfaceHandler.h +++ b/packages/react-native/ReactCommon/react/test_utils/MockSurfaceHandler.h @@ -15,7 +15,7 @@ namespace facebook::react { class MockSurfaceHandler : public SurfaceHandler { public: - MockSurfaceHandler() : SurfaceHandler("moduleName", 0){}; + MockSurfaceHandler() : SurfaceHandler("moduleName", 0) {}; MOCK_METHOD(void, setDisplayMode, (DisplayMode), (const, noexcept)); MOCK_METHOD(SurfaceId, getSurfaceId, (), (const, noexcept)); diff --git a/packages/react-native/ReactCommon/react/test_utils/ios/RCTSwizzleHelpers.h b/packages/react-native/ReactCommon/react/test_utils/ios/RCTSwizzleHelpers.h index 79ca15d2a65..199dd544151 100644 --- a/packages/react-native/ReactCommon/react/test_utils/ios/RCTSwizzleHelpers.h +++ b/packages/react-native/ReactCommon/react/test_utils/ios/RCTSwizzleHelpers.h @@ -11,9 +11,6 @@ RCT_EXTERN_C_BEGIN -void RCTSwizzleInstanceSelector( - Class targetClass, - Class swizzleClass, - SEL selector); +void RCTSwizzleInstanceSelector(Class targetClass, Class swizzleClass, SEL selector); RCT_EXTERN_C_END diff --git a/packages/react-native/ReactCommon/react/test_utils/ios/Shims/ShimRCTInstance.mm b/packages/react-native/ReactCommon/react/test_utils/ios/Shims/ShimRCTInstance.mm index 52566073359..96b06aee00c 100644 --- a/packages/react-native/ReactCommon/react/test_utils/ios/Shims/ShimRCTInstance.mm +++ b/packages/react-native/ReactCommon/react/test_utils/ios/Shims/ShimRCTInstance.mm @@ -22,9 +22,10 @@ static __weak ShimRCTInstance *weakShim = nil; RCTSwizzleInstanceSelector( [RCTInstance class], [ShimRCTInstance class], - @selector(initWithDelegate: - jsRuntimeFactory:bundleManager:turboModuleManagerDelegate:moduleRegistry:parentInspectorTarget - :launchOptions:devMenuConfiguration:)); + @selector + (initWithDelegate: + jsRuntimeFactory:bundleManager:turboModuleManagerDelegate:moduleRegistry:parentInspectorTarget:launchOptions + :devMenuConfiguration:)); RCTSwizzleInstanceSelector([RCTInstance class], [ShimRCTInstance class], @selector(invalidate)); RCTSwizzleInstanceSelector( [RCTInstance class], [ShimRCTInstance class], @selector(callFunctionOnJSModule:method:args:)); @@ -38,9 +39,10 @@ static __weak ShimRCTInstance *weakShim = nil; RCTSwizzleInstanceSelector( [RCTInstance class], [ShimRCTInstance class], - @selector(initWithDelegate: - jsRuntimeFactory:bundleManager:turboModuleManagerDelegate:moduleRegistry:parentInspectorTarget - :launchOptions:devMenuConfiguration:)); + @selector + (initWithDelegate: + jsRuntimeFactory:bundleManager:turboModuleManagerDelegate:moduleRegistry:parentInspectorTarget:launchOptions + :devMenuConfiguration:)); RCTSwizzleInstanceSelector([RCTInstance class], [ShimRCTInstance class], @selector(invalidate)); RCTSwizzleInstanceSelector( [RCTInstance class], [ShimRCTInstance class], @selector(callFunctionOnJSModule:method:args:)); diff --git a/packages/react-native/ReactCommon/react/test_utils/shadowTreeGeneration.h b/packages/react-native/ReactCommon/react/test_utils/shadowTreeGeneration.h index 57029706d6b..95390ef3ca8 100644 --- a/packages/react-native/ReactCommon/react/test_utils/shadowTreeGeneration.h +++ b/packages/react-native/ReactCommon/react/test_utils/shadowTreeGeneration.h @@ -20,7 +20,8 @@ namespace facebook::react { -static Tag generateReactTag() { +static Tag generateReactTag() +{ static Tag tag = 1000; return tag++; } @@ -33,11 +34,11 @@ class ShadowTreeEdge final { }; static bool traverseShadowTree( - const std::shared_ptr& parentShadowNode, - const std::function& - callback) { + const std::shared_ptr &parentShadowNode, + const std::function &callback) +{ auto index = int{0}; - for (const auto& childNode : parentShadowNode->getChildren()) { + for (const auto &childNode : parentShadowNode->getChildren()) { auto stop = bool{false}; callback(ShadowTreeEdge{childNode, parentShadowNode, index}, stop); @@ -55,24 +56,21 @@ static bool traverseShadowTree( return false; } -static int countShadowNodes( - const std::shared_ptr& rootShadowNode) { +static int countShadowNodes(const std::shared_ptr &rootShadowNode) +{ auto counter = int{0}; - traverseShadowTree( - rootShadowNode, - [&](const ShadowTreeEdge& edge, bool& stop) { counter++; }); + traverseShadowTree(rootShadowNode, [&](const ShadowTreeEdge &edge, bool &stop) { counter++; }); return counter; } -static ShadowTreeEdge findShadowNodeWithIndex( - const std::shared_ptr& rootNode, - int index) { +static ShadowTreeEdge findShadowNodeWithIndex(const std::shared_ptr &rootNode, int index) +{ auto counter = int{0}; auto result = ShadowTreeEdge{}; - traverseShadowTree(rootNode, [&](const ShadowTreeEdge& edge, bool& stop) { + traverseShadowTree(rootNode, [&](const ShadowTreeEdge &edge, bool &stop) { if (index == counter) { result = edge; } @@ -84,61 +82,56 @@ static ShadowTreeEdge findShadowNodeWithIndex( } static ShadowTreeEdge findRandomShadowNode( - const Entropy& entropy, - const std::shared_ptr& rootShadowNode) { + const Entropy &entropy, + const std::shared_ptr &rootShadowNode) +{ auto count = countShadowNodes(rootShadowNode); - return findShadowNodeWithIndex( - rootShadowNode, - entropy.random(1 /* Excluding a root node */, count - 1)); + return findShadowNodeWithIndex(rootShadowNode, entropy.random(1 /* Excluding a root node */, count - 1)); } -static ShadowNode::ListOfShared cloneSharedShadowNodeList( - const ShadowNode::ListOfShared& list) { +static ShadowNode::ListOfShared cloneSharedShadowNodeList(const ShadowNode::ListOfShared &list) +{ auto result = ShadowNode::ListOfShared{}; result.reserve(list.size()); - for (const auto& shadowNode : list) { + for (const auto &shadowNode : list) { result.push_back(shadowNode->clone({})); } return result; } -static inline std::shared_ptr messWithChildren( - const Entropy& entropy, - const ShadowNode& shadowNode) { +static inline std::shared_ptr messWithChildren(const Entropy &entropy, const ShadowNode &shadowNode) +{ auto children = shadowNode.getChildren(); children = cloneSharedShadowNodeList(children); entropy.shuffle(children); return shadowNode.clone( - {ShadowNodeFragment::propsPlaceholder(), - std::make_shared(children)}); + {ShadowNodeFragment::propsPlaceholder(), std::make_shared(children)}); } static inline std::shared_ptr messWithLayoutableOnlyFlag( - const Entropy& entropy, - const ShadowNode& shadowNode) { + const Entropy &entropy, + const ShadowNode &shadowNode) +{ auto oldProps = shadowNode.getProps(); ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - auto newProps = shadowNode.getComponentDescriptor().cloneProps( - parserContext, oldProps, RawProps(folly::dynamic::object())); + auto newProps = + shadowNode.getComponentDescriptor().cloneProps(parserContext, oldProps, RawProps(folly::dynamic::object())); - auto& viewProps = - const_cast(static_cast(*newProps)); + auto &viewProps = const_cast(static_cast(*newProps)); if (entropy.random(0.1)) { viewProps.nativeId = entropy.random() ? "42" : ""; } if (entropy.random(0.1)) { - viewProps.backgroundColor = - entropy.random() ? SharedColor() : whiteColor(); + viewProps.backgroundColor = entropy.random() ? SharedColor() : whiteColor(); } if (entropy.random(0.1)) { - viewProps.shadowColor = - entropy.random() ? SharedColor() : blackColor(); + viewProps.shadowColor = entropy.random() ? SharedColor() : blackColor(); } if (entropy.random(0.1)) { @@ -150,13 +143,11 @@ static inline std::shared_ptr messWithLayoutableOnlyFlag( } if (entropy.random(0.1)) { - viewProps.pointerEvents = entropy.random() ? PointerEventsMode::Auto - : PointerEventsMode::None; + viewProps.pointerEvents = entropy.random() ? PointerEventsMode::Auto : PointerEventsMode::None; } if (entropy.random(0.1)) { - viewProps.transform = entropy.random() ? Transform::Identity() - : Transform::Perspective(42); + viewProps.transform = entropy.random() ? Transform::Identity() : Transform::Perspective(42); } #ifdef ANDROID @@ -171,17 +162,17 @@ static inline std::shared_ptr messWithLayoutableOnlyFlag( // Similar to `messWithLayoutableOnlyFlag` but has a 50/50 chance of flattening // (or unflattening) a node's children. static inline std::shared_ptr messWithNodeFlattenednessFlags( - const Entropy& entropy, - const ShadowNode& shadowNode) { + const Entropy &entropy, + const ShadowNode &shadowNode) +{ ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; auto oldProps = shadowNode.getProps(); - auto newProps = shadowNode.getComponentDescriptor().cloneProps( - parserContext, oldProps, RawProps(folly::dynamic::object())); + auto newProps = + shadowNode.getComponentDescriptor().cloneProps(parserContext, oldProps, RawProps(folly::dynamic::object())); - auto& viewProps = - const_cast(static_cast(*newProps)); + auto &viewProps = const_cast(static_cast(*newProps)); if (entropy.random(0.5)) { viewProps.nativeId = ""; @@ -211,9 +202,8 @@ static inline std::shared_ptr messWithNodeFlattenednessFlags( return shadowNode.clone({newProps}); } -static inline std::shared_ptr messWithYogaStyles( - const Entropy& entropy, - const ShadowNode& shadowNode) { +static inline std::shared_ptr messWithYogaStyles(const Entropy &entropy, const ShadowNode &shadowNode) +{ folly::dynamic dynamic = folly::dynamic::object(); if (entropy.random()) { @@ -221,11 +211,9 @@ static inline std::shared_ptr messWithYogaStyles( } std::vector properties = { - "flex", "flexGrow", "flexShrink", "flexBasis", - "left", "top", "marginLeft", "marginTop", - "marginRight", "marginBottom", "paddingLeft", "paddingTop", - "paddingRight", "paddingBottom", "width", "height", - "maxWidth", "maxHeight", "minWidth", "minHeight", + "flex", "flexGrow", "flexShrink", "flexBasis", "left", "top", "marginLeft", + "marginTop", "marginRight", "marginBottom", "paddingLeft", "paddingTop", "paddingRight", "paddingBottom", + "width", "height", "maxWidth", "maxHeight", "minWidth", "minHeight", }; // It is not safe to add new Yoga properties to this list. Unit tests @@ -233,7 +221,7 @@ static inline std::shared_ptr messWithYogaStyles( // failures if the size of properties also changes. EXPECT_EQ(properties.size(), 20); - for (const auto& property : properties) { + for (const auto &property : properties) { if (entropy.random(0.1)) { dynamic[property] = entropy.random(0, 1024); } @@ -244,55 +232,49 @@ static inline std::shared_ptr messWithYogaStyles( PropsParserContext parserContext{-1, contextContainer}; auto oldProps = shadowNode.getProps(); - auto newProps = shadowNode.getComponentDescriptor().cloneProps( - parserContext, oldProps, RawProps(dynamic)); + auto newProps = shadowNode.getComponentDescriptor().cloneProps(parserContext, oldProps, RawProps(dynamic)); return shadowNode.clone({newProps}); } -using ShadowNodeAlteration = std::function( - const Entropy& entropy, - const ShadowNode& shadowNode)>; +using ShadowNodeAlteration = + std::function(const Entropy &entropy, const ShadowNode &shadowNode)>; -static inline void alterShadowTree( - const Entropy& entropy, - RootShadowNode::Shared& rootShadowNode, - ShadowNodeAlteration alteration) { +static inline void +alterShadowTree(const Entropy &entropy, RootShadowNode::Shared &rootShadowNode, ShadowNodeAlteration alteration) +{ auto edge = findRandomShadowNode(entropy, rootShadowNode); - rootShadowNode = - std::static_pointer_cast(rootShadowNode->cloneTree( - edge.shadowNode->getFamily(), [&](const ShadowNode& oldShadowNode) { - return alteration(entropy, oldShadowNode); - })); + rootShadowNode = std::static_pointer_cast(rootShadowNode->cloneTree( + edge.shadowNode->getFamily(), + [&](const ShadowNode &oldShadowNode) { return alteration(entropy, oldShadowNode); })); } static inline void alterShadowTree( - const Entropy& entropy, - RootShadowNode::Shared& rootShadowNode, - std::vector alterations) { + const Entropy &entropy, + RootShadowNode::Shared &rootShadowNode, + std::vector alterations) +{ auto i = entropy.random(0, alterations.size() - 1); alterShadowTree(entropy, rootShadowNode, alterations[i]); } -static SharedViewProps generateDefaultProps( - const ComponentDescriptor& componentDescriptor) { +static SharedViewProps generateDefaultProps(const ComponentDescriptor &componentDescriptor) +{ ContextContainer contextContainer{}; PropsParserContext parserContext{-1, contextContainer}; - return std::static_pointer_cast( - componentDescriptor.cloneProps(parserContext, nullptr, RawProps{})); + return std::static_pointer_cast(componentDescriptor.cloneProps(parserContext, nullptr, RawProps{})); } static inline std::shared_ptr generateShadowNodeTree( - const Entropy& entropy, - const ComponentDescriptor& componentDescriptor, + const Entropy &entropy, + const ComponentDescriptor &componentDescriptor, int size, - int deviation = 3) { + int deviation = 3) +{ if (size <= 1) { - auto family = componentDescriptor.createFamily( - {generateReactTag(), SurfaceId(1), nullptr}); - return componentDescriptor.createShadowNode( - ShadowNodeFragment{generateDefaultProps(componentDescriptor)}, family); + auto family = componentDescriptor.createFamily({generateReactTag(), SurfaceId(1), nullptr}); + return componentDescriptor.createShadowNode(ShadowNodeFragment{generateDefaultProps(componentDescriptor)}, family); } auto items = std::vector(size); @@ -300,17 +282,14 @@ static inline std::shared_ptr generateShadowNodeTree( auto chunks = entropy.distribute(items, deviation); auto children = ShadowNode::ListOfShared{}; - for (const auto& chunk : chunks) { - children.push_back( - generateShadowNodeTree(entropy, componentDescriptor, chunk.size())); + for (const auto &chunk : chunks) { + children.push_back(generateShadowNodeTree(entropy, componentDescriptor, chunk.size())); } - auto family = componentDescriptor.createFamily( - {generateReactTag(), SurfaceId(1), nullptr}); + auto family = componentDescriptor.createFamily({generateReactTag(), SurfaceId(1), nullptr}); return componentDescriptor.createShadowNode( ShadowNodeFragment{ - generateDefaultProps(componentDescriptor), - std::make_shared(children)}, + generateDefaultProps(componentDescriptor), std::make_shared(children)}, family); } diff --git a/packages/react-native/ReactCommon/react/timing/primitives.h b/packages/react-native/ReactCommon/react/timing/primitives.h index 6328be8b703..0e5a93aedb8 100644 --- a/packages/react-native/ReactCommon/react/timing/primitives.h +++ b/packages/react-native/ReactCommon/react/timing/primitives.h @@ -23,157 +23,165 @@ class HighResTimeStamp; */ class HighResDuration { friend class HighResTimeStamp; - friend constexpr HighResDuration operator-( - const HighResTimeStamp& lhs, - const HighResTimeStamp& rhs); - friend constexpr HighResTimeStamp operator+( - const HighResTimeStamp& lhs, - const HighResDuration& rhs); - friend constexpr HighResTimeStamp operator-( - const HighResTimeStamp& lhs, - const HighResDuration& rhs); + friend constexpr HighResDuration operator-(const HighResTimeStamp &lhs, const HighResTimeStamp &rhs); + friend constexpr HighResTimeStamp operator+(const HighResTimeStamp &lhs, const HighResDuration &rhs); + friend constexpr HighResTimeStamp operator-(const HighResTimeStamp &lhs, const HighResDuration &rhs); public: - constexpr HighResDuration() - : chronoDuration_(std::chrono::steady_clock::duration()) {} + constexpr HighResDuration() : chronoDuration_(std::chrono::steady_clock::duration()) {} - static constexpr HighResDuration zero() { + static constexpr HighResDuration zero() + { return HighResDuration(std::chrono::steady_clock::duration::zero()); } - static constexpr HighResDuration fromChrono( - std::chrono::steady_clock::duration chronoDuration) { + static constexpr HighResDuration fromChrono(std::chrono::steady_clock::duration chronoDuration) + { return HighResDuration(chronoDuration); } - static constexpr HighResDuration fromNanoseconds(int64_t units) { + static constexpr HighResDuration fromNanoseconds(int64_t units) + { return HighResDuration(std::chrono::nanoseconds(units)); } - static constexpr HighResDuration fromMilliseconds(int64_t units) { + static constexpr HighResDuration fromMilliseconds(int64_t units) + { return HighResDuration(std::chrono::milliseconds(units)); } - constexpr int64_t toNanoseconds() const { - return std::chrono::duration_cast(chronoDuration_) - .count(); + constexpr int64_t toNanoseconds() const + { + return std::chrono::duration_cast(chronoDuration_).count(); } // @see https://developer.mozilla.org/en-US/docs/Web/API/DOMHighResTimeStamp - static constexpr HighResDuration fromDOMHighResTimeStamp(double units) { + static constexpr HighResDuration fromDOMHighResTimeStamp(double units) + { auto nanoseconds = static_cast(units * 1e6); return fromNanoseconds(nanoseconds); } // @see https://developer.mozilla.org/en-US/docs/Web/API/DOMHighResTimeStamp - constexpr double toDOMHighResTimeStamp() const { - return static_cast>( - chronoDuration_) - .count(); + constexpr double toDOMHighResTimeStamp() const + { + return static_cast>(chronoDuration_).count(); } - constexpr HighResDuration operator+(const HighResDuration& rhs) const { + constexpr HighResDuration operator+(const HighResDuration &rhs) const + { return HighResDuration(chronoDuration_ + rhs.chronoDuration_); } - constexpr HighResDuration operator+( - const std::chrono::steady_clock::duration& rhs) const { + constexpr HighResDuration operator+(const std::chrono::steady_clock::duration &rhs) const + { return HighResDuration(chronoDuration_ + rhs); } - constexpr HighResDuration operator-(const HighResDuration& rhs) const { + constexpr HighResDuration operator-(const HighResDuration &rhs) const + { return HighResDuration(chronoDuration_ - rhs.chronoDuration_); } - constexpr HighResDuration operator-( - const std::chrono::steady_clock::duration& rhs) const { + constexpr HighResDuration operator-(const std::chrono::steady_clock::duration &rhs) const + { return HighResDuration(chronoDuration_ - rhs); } - constexpr HighResDuration& operator+=(const HighResDuration& rhs) { + constexpr HighResDuration &operator+=(const HighResDuration &rhs) + { chronoDuration_ += rhs.chronoDuration_; return *this; } - constexpr HighResDuration& operator+=( - const std::chrono::steady_clock::duration& rhs) { + constexpr HighResDuration &operator+=(const std::chrono::steady_clock::duration &rhs) + { chronoDuration_ += rhs; return *this; } - constexpr HighResDuration& operator-=(const HighResDuration& rhs) { + constexpr HighResDuration &operator-=(const HighResDuration &rhs) + { chronoDuration_ -= rhs.chronoDuration_; return *this; } - constexpr HighResDuration& operator-=( - const std::chrono::steady_clock::duration& rhs) { + constexpr HighResDuration &operator-=(const std::chrono::steady_clock::duration &rhs) + { chronoDuration_ -= rhs; return *this; } - constexpr bool operator==(const HighResDuration& rhs) const { + constexpr bool operator==(const HighResDuration &rhs) const + { return chronoDuration_ == rhs.chronoDuration_; } - constexpr bool operator==( - const std::chrono::steady_clock::duration& rhs) const { + constexpr bool operator==(const std::chrono::steady_clock::duration &rhs) const + { return chronoDuration_ == rhs; } - constexpr bool operator!=(const HighResDuration& rhs) const { + constexpr bool operator!=(const HighResDuration &rhs) const + { return chronoDuration_ != rhs.chronoDuration_; } - constexpr bool operator!=( - const std::chrono::steady_clock::duration& rhs) const { + constexpr bool operator!=(const std::chrono::steady_clock::duration &rhs) const + { return chronoDuration_ != rhs; } - constexpr bool operator<(const HighResDuration& rhs) const { + constexpr bool operator<(const HighResDuration &rhs) const + { return chronoDuration_ < rhs.chronoDuration_; } - constexpr bool operator<( - const std::chrono::steady_clock::duration& rhs) const { + constexpr bool operator<(const std::chrono::steady_clock::duration &rhs) const + { return chronoDuration_ < rhs; } - constexpr bool operator<=(const HighResDuration& rhs) const { + constexpr bool operator<=(const HighResDuration &rhs) const + { return chronoDuration_ <= rhs.chronoDuration_; } - constexpr bool operator<=( - const std::chrono::steady_clock::duration& rhs) const { + constexpr bool operator<=(const std::chrono::steady_clock::duration &rhs) const + { return chronoDuration_ <= rhs; } - constexpr bool operator>(const HighResDuration& rhs) const { + constexpr bool operator>(const HighResDuration &rhs) const + { return chronoDuration_ > rhs.chronoDuration_; } - constexpr bool operator>( - const std::chrono::steady_clock::duration& rhs) const { + constexpr bool operator>(const std::chrono::steady_clock::duration &rhs) const + { return chronoDuration_ > rhs; } - constexpr bool operator>=(const HighResDuration& rhs) const { + constexpr bool operator>=(const HighResDuration &rhs) const + { return chronoDuration_ >= rhs.chronoDuration_; } - constexpr bool operator>=( - const std::chrono::steady_clock::duration& rhs) const { + constexpr bool operator>=(const std::chrono::steady_clock::duration &rhs) const + { return chronoDuration_ >= rhs; } - constexpr operator std::chrono::steady_clock::duration() const { + constexpr operator std::chrono::steady_clock::duration() const + { return chronoDuration_; } private: - explicit constexpr HighResDuration( - std::chrono::steady_clock::duration chronoDuration) - : chronoDuration_(chronoDuration) {} + explicit constexpr HighResDuration(std::chrono::steady_clock::duration chronoDuration) + : chronoDuration_(chronoDuration) + { + } std::chrono::steady_clock::duration chronoDuration_; }; @@ -184,154 +192,158 @@ class HighResDuration { * @see __docs__/README.md for more information. */ class HighResTimeStamp { - friend constexpr HighResDuration operator-( - const HighResTimeStamp& lhs, - const HighResTimeStamp& rhs); - friend constexpr HighResTimeStamp operator+( - const HighResTimeStamp& lhs, - const HighResDuration& rhs); - friend constexpr HighResTimeStamp operator-( - const HighResTimeStamp& lhs, - const HighResDuration& rhs); + friend constexpr HighResDuration operator-(const HighResTimeStamp &lhs, const HighResTimeStamp &rhs); + friend constexpr HighResTimeStamp operator+(const HighResTimeStamp &lhs, const HighResDuration &rhs); + friend constexpr HighResTimeStamp operator-(const HighResTimeStamp &lhs, const HighResDuration &rhs); public: HighResTimeStamp() noexcept : chronoTimePoint_(chronoNow()) {} - static HighResTimeStamp now() noexcept { + static HighResTimeStamp now() noexcept + { return HighResTimeStamp(chronoNow()); } - static HighResDuration unsafeOriginFromUnixTimeStamp() noexcept { + static HighResDuration unsafeOriginFromUnixTimeStamp() noexcept + { static auto origin = computeUnsafeOriginFromUnixTimeStamp(); return origin; } - static constexpr HighResTimeStamp min() noexcept { + static constexpr HighResTimeStamp min() noexcept + { return HighResTimeStamp(std::chrono::steady_clock::time_point::min()); } - static constexpr HighResTimeStamp max() noexcept { + static constexpr HighResTimeStamp max() noexcept + { return HighResTimeStamp(std::chrono::steady_clock::time_point::max()); } // @see https://developer.mozilla.org/en-US/docs/Web/API/DOMHighResTimeStamp - static constexpr HighResTimeStamp fromDOMHighResTimeStamp(double units) { + static constexpr HighResTimeStamp fromDOMHighResTimeStamp(double units) + { auto nanoseconds = static_cast(units * 1e6); - return HighResTimeStamp(std::chrono::steady_clock::time_point( - std::chrono::nanoseconds(nanoseconds))); + return HighResTimeStamp(std::chrono::steady_clock::time_point(std::chrono::nanoseconds(nanoseconds))); } // @see https://developer.mozilla.org/en-US/docs/Web/API/DOMHighResTimeStamp - constexpr double toDOMHighResTimeStamp() const { - return HighResDuration(chronoTimePoint_.time_since_epoch()) - .toDOMHighResTimeStamp(); + constexpr double toDOMHighResTimeStamp() const + { + return HighResDuration(chronoTimePoint_.time_since_epoch()).toDOMHighResTimeStamp(); } // This method is expected to be used only when converting time stamps from // external systems. static constexpr HighResTimeStamp fromChronoSteadyClockTimePoint( - std::chrono::steady_clock::time_point chronoTimePoint) { + std::chrono::steady_clock::time_point chronoTimePoint) + { return HighResTimeStamp(chronoTimePoint); } #ifdef REACT_NATIVE_DEBUG - static void setTimeStampProviderForTesting( - std::function&& - timeStampProvider) { + static void setTimeStampProviderForTesting(std::function &&timeStampProvider) + { getTimeStampProvider() = std::move(timeStampProvider); } #endif // This method is provided for convenience, if you need to convert // HighResTimeStamp to some common epoch with time stamps from other sources. - constexpr std::chrono::steady_clock::time_point toChronoSteadyClockTimePoint() - const { + constexpr std::chrono::steady_clock::time_point toChronoSteadyClockTimePoint() const + { return chronoTimePoint_; } - constexpr bool operator==(const HighResTimeStamp& rhs) const { + constexpr bool operator==(const HighResTimeStamp &rhs) const + { return chronoTimePoint_ == rhs.chronoTimePoint_; } - constexpr bool operator!=(const HighResTimeStamp& rhs) const { + constexpr bool operator!=(const HighResTimeStamp &rhs) const + { return chronoTimePoint_ != rhs.chronoTimePoint_; } - constexpr bool operator<(const HighResTimeStamp& rhs) const { + constexpr bool operator<(const HighResTimeStamp &rhs) const + { return chronoTimePoint_ < rhs.chronoTimePoint_; } - constexpr bool operator<=(const HighResTimeStamp& rhs) const { + constexpr bool operator<=(const HighResTimeStamp &rhs) const + { return chronoTimePoint_ <= rhs.chronoTimePoint_; } - constexpr bool operator>(const HighResTimeStamp& rhs) const { + constexpr bool operator>(const HighResTimeStamp &rhs) const + { return chronoTimePoint_ > rhs.chronoTimePoint_; } - constexpr bool operator>=(const HighResTimeStamp& rhs) const { + constexpr bool operator>=(const HighResTimeStamp &rhs) const + { return chronoTimePoint_ >= rhs.chronoTimePoint_; } - constexpr HighResTimeStamp& operator+=(const HighResDuration& rhs) { + constexpr HighResTimeStamp &operator+=(const HighResDuration &rhs) + { chronoTimePoint_ += rhs.chronoDuration_; return *this; } - constexpr HighResTimeStamp& operator-=(const HighResDuration& rhs) { + constexpr HighResTimeStamp &operator-=(const HighResDuration &rhs) + { chronoTimePoint_ -= rhs.chronoDuration_; return *this; } private: - explicit constexpr HighResTimeStamp( - std::chrono::steady_clock::time_point chronoTimePoint) - : chronoTimePoint_(chronoTimePoint) {} + explicit constexpr HighResTimeStamp(std::chrono::steady_clock::time_point chronoTimePoint) + : chronoTimePoint_(chronoTimePoint) + { + } std::chrono::steady_clock::time_point chronoTimePoint_; - static HighResDuration computeUnsafeOriginFromUnixTimeStamp() noexcept { + static HighResDuration computeUnsafeOriginFromUnixTimeStamp() noexcept + { auto systemNow = std::chrono::system_clock::now(); auto steadyNow = std::chrono::steady_clock::now(); - return HighResDuration( - systemNow.time_since_epoch() - steadyNow.time_since_epoch()); + return HighResDuration(systemNow.time_since_epoch() - steadyNow.time_since_epoch()); } #ifdef REACT_NATIVE_DEBUG - static std::function& - getTimeStampProvider() { - static std::function - timeStampProvider = nullptr; + static std::function &getTimeStampProvider() + { + static std::function timeStampProvider = nullptr; return timeStampProvider; } - static std::chrono::steady_clock::time_point chronoNow() { - auto& timeStampProvider = getTimeStampProvider(); - return timeStampProvider != nullptr ? timeStampProvider() - : std::chrono::steady_clock::now(); + static std::chrono::steady_clock::time_point chronoNow() + { + auto &timeStampProvider = getTimeStampProvider(); + return timeStampProvider != nullptr ? timeStampProvider() : std::chrono::steady_clock::now(); } #else - inline static std::chrono::steady_clock::time_point chronoNow() { + inline static std::chrono::steady_clock::time_point chronoNow() + { return std::chrono::steady_clock::now(); } #endif }; -inline constexpr HighResDuration operator-( - const HighResTimeStamp& lhs, - const HighResTimeStamp& rhs) { +inline constexpr HighResDuration operator-(const HighResTimeStamp &lhs, const HighResTimeStamp &rhs) +{ return HighResDuration(lhs.chronoTimePoint_ - rhs.chronoTimePoint_); } -inline constexpr HighResTimeStamp operator+( - const HighResTimeStamp& lhs, - const HighResDuration& rhs) { +inline constexpr HighResTimeStamp operator+(const HighResTimeStamp &lhs, const HighResDuration &rhs) +{ return HighResTimeStamp(lhs.chronoTimePoint_ + rhs.chronoDuration_); } -inline constexpr HighResTimeStamp operator-( - const HighResTimeStamp& lhs, - const HighResDuration& rhs) { +inline constexpr HighResTimeStamp operator-(const HighResTimeStamp &lhs, const HighResDuration &rhs) +{ return HighResTimeStamp(lhs.chronoTimePoint_ - rhs.chronoDuration_); } diff --git a/packages/react-native/ReactCommon/react/utils/ContextContainer.h b/packages/react-native/ReactCommon/react/utils/ContextContainer.h index b0e8b62ed08..8e776687333 100644 --- a/packages/react-native/ReactCommon/react/utils/ContextContainer.h +++ b/packages/react-native/ReactCommon/react/utils/ContextContainer.h @@ -25,9 +25,8 @@ namespace facebook::react { */ class ContextContainer final { public: - using Shared - [[deprecated("Use std::shared_ptr instead.")]] = - std::shared_ptr; + using Shared [[deprecated("Use std::shared_ptr instead.")]] = + std::shared_ptr; /* * Registers an instance of the particular type `T` in the container * using the provided `key`. Only one instance can be registered per key. @@ -40,7 +39,8 @@ class ContextContainer final { *`ReactNativeConfig`. */ template - void insert(const std::string& key, const T& instance) const { + void insert(const std::string &key, const T &instance) const + { std::unique_lock lock(mutex_); instances_.insert({key, std::make_shared(instance)}); @@ -50,7 +50,8 @@ class ContextContainer final { * Removes an instance stored for a given `key`. * Does nothing if the instance was not found. */ - void erase(const std::string& key) const { + void erase(const std::string &key) const + { std::unique_lock lock(mutex_); instances_.erase(key); @@ -61,10 +62,11 @@ class ContextContainer final { * Values with keys that already exist in the container will be replaced with * values from the given container. */ - void update(const ContextContainer& contextContainer) const { + void update(const ContextContainer &contextContainer) const + { std::unique_lock lock(mutex_); - for (const auto& pair : contextContainer.instances_) { + for (const auto &pair : contextContainer.instances_) { instances_.erase(pair.first); instances_.insert(pair); } @@ -76,13 +78,13 @@ class ContextContainer final { * Throws an exception if the instance could not be found. */ template - T at(const std::string& key) const { + T at(const std::string &key) const + { std::shared_lock lock(mutex_); react_native_assert( - instances_.find(key) != instances_.end() && - "ContextContainer doesn't have an instance for given key."); - return *static_cast(instances_.at(key).get()); + instances_.find(key) != instances_.end() && "ContextContainer doesn't have an instance for given key."); + return *static_cast(instances_.at(key).get()); } /* @@ -91,7 +93,8 @@ class ContextContainer final { * Returns an empty optional if the instance could not be found. */ template - std::optional find(const std::string& key) const { + std::optional find(const std::string &key) const + { std::shared_lock lock(mutex_); auto iterator = instances_.find(key); @@ -99,7 +102,7 @@ class ContextContainer final { return {}; } - return *static_cast(iterator->second.get()); + return *static_cast(iterator->second.get()); } private: diff --git a/packages/react-native/ReactCommon/react/utils/FloatComparison.h b/packages/react-native/ReactCommon/react/utils/FloatComparison.h index 75c6ec80897..f53ada84bc2 100644 --- a/packages/react-native/ReactCommon/react/utils/FloatComparison.h +++ b/packages/react-native/ReactCommon/react/utils/FloatComparison.h @@ -14,10 +14,9 @@ namespace facebook::react { constexpr float kDefaultEpsilon = 0.005f; template -inline bool -floatEquality(T a, T b, T epsilon = static_cast(kDefaultEpsilon)) { - return (std::isnan(a) && std::isnan(b)) || - (!std::isnan(a) && !std::isnan(b) && std::abs(a - b) < epsilon); +inline bool floatEquality(T a, T b, T epsilon = static_cast(kDefaultEpsilon)) +{ + return (std::isnan(a) && std::isnan(b)) || (!std::isnan(a) && !std::isnan(b) && std::abs(a - b) < epsilon); } } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/utils/OnScopeExit.h b/packages/react-native/ReactCommon/react/utils/OnScopeExit.h index 73db32e1155..633471daf82 100644 --- a/packages/react-native/ReactCommon/react/utils/OnScopeExit.h +++ b/packages/react-native/ReactCommon/react/utils/OnScopeExit.h @@ -14,18 +14,18 @@ namespace facebook::react { template class OnScopeExit { public: - explicit OnScopeExit(const Lambda&& lambda) noexcept - : lambda_(std::move(lambda)) {} + explicit OnScopeExit(const Lambda &&lambda) noexcept : lambda_(std::move(lambda)) {} // Non-movable - OnScopeExit(const OnScopeExit&) = delete; - OnScopeExit(OnScopeExit&&) = delete; + OnScopeExit(const OnScopeExit &) = delete; + OnScopeExit(OnScopeExit &&) = delete; // Non-copyable - OnScopeExit& operator=(const OnScopeExit&) = delete; - OnScopeExit& operator=(OnScopeExit&&) = delete; + OnScopeExit &operator=(const OnScopeExit &) = delete; + OnScopeExit &operator=(OnScopeExit &&) = delete; - ~OnScopeExit() noexcept { + ~OnScopeExit() noexcept + { lambda_(); } diff --git a/packages/react-native/ReactCommon/react/utils/PackTraits.h b/packages/react-native/ReactCommon/react/utils/PackTraits.h index 4415fec8be5..675cdc06ed9 100644 --- a/packages/react-native/ReactCommon/react/utils/PackTraits.h +++ b/packages/react-native/ReactCommon/react/utils/PackTraits.h @@ -12,15 +12,16 @@ namespace facebook::react::traits { template -static constexpr bool containsType() { +static constexpr bool containsType() +{ return false; } template -static constexpr bool containsType() { +static constexpr bool containsType() +{ if constexpr (sizeof...(RestT) > 0) { - return std::is_same_v || - containsType(); + return std::is_same_v || containsType(); } else { return std::is_same_v; } diff --git a/packages/react-native/ReactCommon/react/utils/RunLoopObserver.h b/packages/react-native/ReactCommon/react/utils/RunLoopObserver.h index 6e0e5bc9d77..d226bcb5ccb 100644 --- a/packages/react-native/ReactCommon/react/utils/RunLoopObserver.h +++ b/packages/react-native/ReactCommon/react/utils/RunLoopObserver.h @@ -61,15 +61,12 @@ class RunLoopObserver { * is retained during this call. * Will be called on the thread associated with the run loop. */ - virtual void activityDidChange(const Delegate* delegate, Activity activity) - const noexcept = 0; + virtual void activityDidChange(const Delegate *delegate, Activity activity) const noexcept = 0; virtual ~Delegate() noexcept = default; }; - using Factory = std::function( - Activity activities, - const WeakOwner& owner)>; + using Factory = std::function(Activity activities, const WeakOwner &owner)>; /* * Constructs a run loop observer. @@ -81,7 +78,7 @@ class RunLoopObserver { * Sets the delegate. * Must be called just once. */ - void setDelegate(const Delegate* delegate) const noexcept; + void setDelegate(const Delegate *delegate) const noexcept; /* * Enables or disables run loop observing. @@ -118,7 +115,7 @@ class RunLoopObserver { const Activity activities_{}; const WeakOwner owner_; - mutable const Delegate* delegate_{nullptr}; + mutable const Delegate *delegate_{nullptr}; mutable std::atomic enabled_{false}; }; diff --git a/packages/react-native/ReactCommon/react/utils/SharedFunction.h b/packages/react-native/ReactCommon/react/utils/SharedFunction.h index b94b9eac24b..04ea9e7f05a 100644 --- a/packages/react-native/ReactCommon/react/utils/SharedFunction.h +++ b/packages/react-native/ReactCommon/react/utils/SharedFunction.h @@ -29,27 +29,28 @@ class SharedFunction { using T = void(ArgumentT...); struct Pair { - Pair(std::function&& function) : function(std::move(function)) {} + Pair(std::function &&function) : function(std::move(function)) {} std::function function; std::shared_mutex mutex{}; }; public: - SharedFunction(std::function&& function = nullptr) - : pair_(std::make_shared(std::move(function))) {} + SharedFunction(std::function &&function = nullptr) : pair_(std::make_shared(std::move(function))) {} - SharedFunction(const SharedFunction& other) = default; - SharedFunction(SharedFunction&& other) noexcept = default; + SharedFunction(const SharedFunction &other) = default; + SharedFunction(SharedFunction &&other) noexcept = default; - SharedFunction& operator=(const SharedFunction& other) = default; - SharedFunction& operator=(SharedFunction&& other) noexcept = default; + SharedFunction &operator=(const SharedFunction &other) = default; + SharedFunction &operator=(SharedFunction &&other) noexcept = default; - void assign(std::function function) const { + void assign(std::function function) const + { std::unique_lock lock(pair_->mutex); pair_->function = function; } - void operator()(ArgumentT... args) const { + void operator()(ArgumentT... args) const + { std::shared_lock lock(pair_->mutex); if (pair_->function) { pair_->function(args...); diff --git a/packages/react-native/ReactCommon/react/utils/SimpleThreadSafeCache.h b/packages/react-native/ReactCommon/react/utils/SimpleThreadSafeCache.h index 0ed2f8589ab..e5c8994b1b8 100644 --- a/packages/react-native/ReactCommon/react/utils/SimpleThreadSafeCache.h +++ b/packages/react-native/ReactCommon/react/utils/SimpleThreadSafeCache.h @@ -15,8 +15,7 @@ namespace facebook::react { template -concept CacheGeneratorFunction = std::invocable && - std::same_as, ValueT>; +concept CacheGeneratorFunction = std::invocable && std::same_as, ValueT>; /* * Simple thread-safe LRU cache. @@ -36,8 +35,8 @@ class SimpleThreadSafeCache { * generator function, stores it inside a cache and returns it. * Can be called from any thread. */ - ValueT get(const KeyT& key, CacheGeneratorFunction auto generator) - const { + ValueT get(const KeyT &key, CacheGeneratorFunction auto generator) const + { return getMapIterator(key, std::move(generator))->second->second; } @@ -47,9 +46,9 @@ class SimpleThreadSafeCache { * generator function, stores it inside a cache and returns it. * Can be called from any thread. */ - std::pair getWithKey( - const KeyT& key, - CacheGeneratorFunction auto generator) const { + std::pair getWithKey(const KeyT &key, CacheGeneratorFunction auto generator) + const + { auto it = getMapIterator(key, std::move(generator)); return std::make_pair(&it->first, &it->second->second); } @@ -59,7 +58,8 @@ class SimpleThreadSafeCache { * If the value wasn't found in the cache, returns empty optional. * Can be called from any thread. */ - std::optional get(const KeyT& key) const { + std::optional get(const KeyT &key) const + { std::lock_guard lock(mutex_); if (auto it = map_.find(key); it != map_.end()) { @@ -75,9 +75,8 @@ class SimpleThreadSafeCache { using EntryT = std::pair; using iterator = typename std::list::iterator; - auto getMapIterator( - const KeyT& key, - CacheGeneratorFunction auto generator) const { + auto getMapIterator(const KeyT &key, CacheGeneratorFunction auto generator) const + { std::lock_guard lock(mutex_); if (auto it = map_.find(key); it != map_.end()) { diff --git a/packages/react-native/ReactCommon/react/utils/Telemetry.h b/packages/react-native/ReactCommon/react/utils/Telemetry.h index 7c1562ae43a..ac4c6a1eec8 100644 --- a/packages/react-native/ReactCommon/react/utils/Telemetry.h +++ b/packages/react-native/ReactCommon/react/utils/Telemetry.h @@ -30,13 +30,13 @@ using TelemetryDuration = std::chrono::nanoseconds; /* * Represents a time point which never happens. */ -static const TelemetryTimePoint kTelemetryUndefinedTimePoint = - TelemetryTimePoint::max(); +static const TelemetryTimePoint kTelemetryUndefinedTimePoint = TelemetryTimePoint::max(); /* * Returns a time point representing the current point in time. */ -static inline TelemetryTimePoint telemetryTimePointNow() { +static inline TelemetryTimePoint telemetryTimePointNow() +{ return TelemetryClock::now(); } @@ -45,28 +45,23 @@ static inline TelemetryTimePoint telemetryTimePointNow() { * point to a given time point. The epoch starting time point is not specified * but stays the same for an application run. */ -static inline int64_t telemetryTimePointToMilliseconds( - TelemetryTimePoint timePoint) { - return std::chrono::duration_cast( - timePoint - TelemetryTimePoint{}) - .count(); +static inline int64_t telemetryTimePointToMilliseconds(TelemetryTimePoint timePoint) +{ + return std::chrono::duration_cast(timePoint - TelemetryTimePoint{}).count(); } /* * Returns a number of seconds that passed from "Steady Clock" epoch starting * time point to a given time point. */ -static inline double telemetryTimePointToSteadyClockSeconds( - TelemetryTimePoint timePoint) { +static inline double telemetryTimePointToSteadyClockSeconds(TelemetryTimePoint timePoint) +{ static_assert( - std::is_same:: - value, + std::is_same::value, "`TelemetryClock` must be `std::chrono::steady_clock` to make the " "following implementation work correctly."); - auto nanoseconds = std::chrono::duration_cast( - timePoint.time_since_epoch()) - .count(); + auto nanoseconds = std::chrono::duration_cast(timePoint.time_since_epoch()).count(); return (double)nanoseconds / 1.0e9; } @@ -78,7 +73,8 @@ template < typename SourceTimePointT, typename DestnationClockT = typename DestinationTimePointT::clock, typename SourceClockT = typename SourceTimePointT::clock> -DestinationTimePointT clockCast(SourceTimePointT timePoint) { +DestinationTimePointT clockCast(SourceTimePointT timePoint) +{ auto sourseClockNow = SourceClockT::now(); auto destinationClockNow = DestnationClockT::now(); return std::chrono::time_point_cast( @@ -90,13 +86,10 @@ DestinationTimePointT clockCast(SourceTimePointT timePoint) { * point to a given time point. * Also known as POSIX time or UNIX Timestamp. */ -static inline double telemetryTimePointToSecondsSinceEpoch( - TelemetryTimePoint timePoint) { - auto systemClockTimePoint = - clockCast( - timePoint); - return (double)std::chrono::duration_cast( - systemClockTimePoint.time_since_epoch()) +static inline double telemetryTimePointToSecondsSinceEpoch(TelemetryTimePoint timePoint) +{ + auto systemClockTimePoint = clockCast(timePoint); + return (double)std::chrono::duration_cast(systemClockTimePoint.time_since_epoch()) .count() / 1000000.0; } @@ -104,10 +97,9 @@ static inline double telemetryTimePointToSecondsSinceEpoch( /* * Returns a number of milliseconds that represents the given duration object. */ -static inline int64_t telemetryDurationToMilliseconds( - TelemetryDuration duration) { - return std::chrono::duration_cast(duration) - .count(); +static inline int64_t telemetryDurationToMilliseconds(TelemetryDuration duration) +{ + return std::chrono::duration_cast(duration).count(); } } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/utils/TemplateStringLiteral.h b/packages/react-native/ReactCommon/react/utils/TemplateStringLiteral.h index 106d14f8c42..94508ae7ed4 100644 --- a/packages/react-native/ReactCommon/react/utils/TemplateStringLiteral.h +++ b/packages/react-native/ReactCommon/react/utils/TemplateStringLiteral.h @@ -19,12 +19,13 @@ namespace facebook::react { */ template struct TemplateStringLiteral { - /* implicit */ constexpr TemplateStringLiteral( - const char (&str)[N]) { // NOLINT(modernize-avoid-c-arrays) + /* implicit */ constexpr TemplateStringLiteral(const char (&str)[N]) + { // NOLINT(modernize-avoid-c-arrays) std::copy_n(str, N, value.data()); } - constexpr operator std::string_view() const { + constexpr operator std::string_view() const + { return {value.begin(), value.end() - 1}; } diff --git a/packages/react-native/ReactCommon/react/utils/fnv1a.h b/packages/react-native/ReactCommon/react/utils/fnv1a.h index 4a945d968f7..6b5a5efbfd1 100644 --- a/packages/react-native/ReactCommon/react/utils/fnv1a.h +++ b/packages/react-native/ReactCommon/react/utils/fnv1a.h @@ -24,25 +24,27 @@ namespace facebook::react { * constexpr. */ template -constexpr uint32_t fnv1a(std::string_view string) noexcept { +constexpr uint32_t fnv1a(std::string_view string) noexcept +{ constexpr uint32_t offset_basis = 2166136261; uint32_t hash = offset_basis; - for (const auto& c : string) { + for (const auto &c : string) { hash ^= static_cast(CharTransformT{}(c)); // Using shifts and adds instead of multiplication with a prime number. // This is faster when compiled with optimizations. - hash += - (hash << 1) + (hash << 4) + (hash << 7) + (hash << 8) + (hash << 24); + hash += (hash << 1) + (hash << 4) + (hash << 7) + (hash << 8) + (hash << 24); } return hash; } -constexpr uint32_t fnv1aLowercase(std::string_view string) { +constexpr uint32_t fnv1aLowercase(std::string_view string) +{ struct LowerCaseTransform { - constexpr char operator()(char c) const { + constexpr char operator()(char c) const + { return toLower(c); } }; diff --git a/packages/react-native/ReactCommon/react/utils/hash_combine.h b/packages/react-native/ReactCommon/react/utils/hash_combine.h index dab82ca53aa..e6ffd2983f7 100644 --- a/packages/react-native/ReactCommon/react/utils/hash_combine.h +++ b/packages/react-native/ReactCommon/react/utils/hash_combine.h @@ -13,18 +13,20 @@ namespace facebook::react { template -concept Hashable = !std::is_same_v && (requires(T a) { +concept Hashable = !std::is_same_v && (requires(T a) { { std::hash{}(a) } -> std::convertible_to; }); template -void hash_combine(std::size_t& seed, const T& v, const Rest&... rest) { +void hash_combine(std::size_t &seed, const T &v, const Rest &...rest) +{ seed ^= std::hash{}(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2); (hash_combine(seed, rest), ...); } template -std::size_t hash_combine(const T& v, const Args&... args) { +std::size_t hash_combine(const T &v, const Args &...args) +{ std::size_t seed = 0; hash_combine(seed, v, args...); return seed; diff --git a/packages/react-native/ReactCommon/react/utils/iequals.h b/packages/react-native/ReactCommon/react/utils/iequals.h index b577d559600..ff1ea60733e 100644 --- a/packages/react-native/ReactCommon/react/utils/iequals.h +++ b/packages/react-native/ReactCommon/react/utils/iequals.h @@ -15,7 +15,8 @@ namespace facebook::react { /** * constexpr check for case insensitive equality of two strings. */ -constexpr bool iequals(std::string_view a, std::string_view b) { +constexpr bool iequals(std::string_view a, std::string_view b) +{ if (a.size() != b.size()) { return false; } diff --git a/packages/react-native/ReactCommon/react/utils/jsi-utils.h b/packages/react-native/ReactCommon/react/utils/jsi-utils.h index 2459b8917db..d907339b42b 100644 --- a/packages/react-native/ReactCommon/react/utils/jsi-utils.h +++ b/packages/react-native/ReactCommon/react/utils/jsi-utils.h @@ -23,9 +23,6 @@ namespace facebook::react { * value: value * }) */ -void defineReadOnlyGlobal( - jsi::Runtime& runtime, - const std::string& propName, - jsi::Value&& value); +void defineReadOnlyGlobal(jsi::Runtime &runtime, const std::string &propName, jsi::Value &&value); } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/utils/platform/android/react/utils/LowPriorityExecutor.cpp b/packages/react-native/ReactCommon/react/utils/platform/android/react/utils/LowPriorityExecutor.cpp index d79eb426211..ee32cd68a53 100644 --- a/packages/react-native/ReactCommon/react/utils/platform/android/react/utils/LowPriorityExecutor.cpp +++ b/packages/react-native/ReactCommon/react/utils/platform/android/react/utils/LowPriorityExecutor.cpp @@ -18,7 +18,7 @@ namespace facebook::react::LowPriorityExecutor { struct LowPriorityExecutorThread { LowPriorityExecutorThread() : thread_{std::thread([this] { run(); })} { pthread_t hThread = thread_.native_handle(); - struct sched_param param {}; + struct sched_param param{}; param.sched_priority = 19; // Higher value means lower priority pthread_setschedparam(hThread, SCHED_OTHER, ¶m); } diff --git a/packages/react-native/ReactCommon/react/utils/platform/android/react/utils/LowPriorityExecutor.h b/packages/react-native/ReactCommon/react/utils/platform/android/react/utils/LowPriorityExecutor.h index c09398d28e3..160efadb16a 100644 --- a/packages/react-native/ReactCommon/react/utils/platform/android/react/utils/LowPriorityExecutor.h +++ b/packages/react-native/ReactCommon/react/utils/platform/android/react/utils/LowPriorityExecutor.h @@ -9,6 +9,6 @@ namespace facebook::react::LowPriorityExecutor { -void execute(std::function&& workItem); +void execute(std::function &&workItem); } // namespace facebook::react::LowPriorityExecutor diff --git a/packages/react-native/ReactCommon/react/utils/platform/cxx/react/utils/LowPriorityExecutor.h b/packages/react-native/ReactCommon/react/utils/platform/cxx/react/utils/LowPriorityExecutor.h index eca44655e04..d70ae6edca2 100644 --- a/packages/react-native/ReactCommon/react/utils/platform/cxx/react/utils/LowPriorityExecutor.h +++ b/packages/react-native/ReactCommon/react/utils/platform/cxx/react/utils/LowPriorityExecutor.h @@ -11,7 +11,8 @@ namespace facebook::react::LowPriorityExecutor { -inline void execute(std::function&& workItem) { +inline void execute(std::function &&workItem) +{ workItem(); } diff --git a/packages/react-native/ReactCommon/react/utils/platform/ios/react/utils/LowPriorityExecutor.h b/packages/react-native/ReactCommon/react/utils/platform/ios/react/utils/LowPriorityExecutor.h index 49c69ee48d5..3517cac7510 100644 --- a/packages/react-native/ReactCommon/react/utils/platform/ios/react/utils/LowPriorityExecutor.h +++ b/packages/react-native/ReactCommon/react/utils/platform/ios/react/utils/LowPriorityExecutor.h @@ -11,6 +11,6 @@ namespace facebook::react::LowPriorityExecutor { -void execute(std::function&& workItem); +void execute(std::function &&workItem); } // namespace facebook::react::LowPriorityExecutor diff --git a/packages/react-native/ReactCommon/react/utils/toLower.h b/packages/react-native/ReactCommon/react/utils/toLower.h index 27212d006dc..766d8d8791e 100644 --- a/packages/react-native/ReactCommon/react/utils/toLower.h +++ b/packages/react-native/ReactCommon/react/utils/toLower.h @@ -12,7 +12,8 @@ namespace facebook::react { /** * constexpr version of tolower */ -constexpr char toLower(char c) { +constexpr char toLower(char c) +{ if (c >= 'A' && c <= 'Z') { return static_cast(c + 32); } diff --git a/packages/react-native/ReactCommon/react/utils/to_underlying.h b/packages/react-native/ReactCommon/react/utils/to_underlying.h index 6d8d19d2b34..2b68a2377c9 100644 --- a/packages/react-native/ReactCommon/react/utils/to_underlying.h +++ b/packages/react-native/ReactCommon/react/utils/to_underlying.h @@ -15,7 +15,8 @@ namespace facebook::react { * Polyfill of C++ 23 to_underlying() * https://en.cppreference.com/w/cpp/utility/to_underlying */ -constexpr auto to_underlying(auto e) noexcept { +constexpr auto to_underlying(auto e) noexcept +{ return static_cast>(e); } diff --git a/packages/react-native/ReactCommon/reactperflogger/fusebox/FuseboxTracer.cpp b/packages/react-native/ReactCommon/reactperflogger/fusebox/FuseboxTracer.cpp index 848b164b1b9..9f2b25d906f 100644 --- a/packages/react-native/ReactCommon/reactperflogger/fusebox/FuseboxTracer.cpp +++ b/packages/react-native/ReactCommon/reactperflogger/fusebox/FuseboxTracer.cpp @@ -52,16 +52,18 @@ bool FuseboxTracer::stopTracing( auto traceEvents = folly::dynamic::array(); // Register "Main" process - traceEvents.push_back(folly::dynamic::object( - "args", folly::dynamic::object("name", "Main"))("cat", "__metadata")( - "name", "process_name")("ph", "M")("pid", PID)("tid", 0)("ts", 0)); + traceEvents.push_back( + folly::dynamic::object("args", folly::dynamic::object("name", "Main"))( + "cat", "__metadata")("name", "process_name")("ph", "M")("pid", PID)( + "tid", 0)("ts", 0)); // Register "Timings" track // NOTE: This is a hack to make the trace viewer show a "Timings" track // adjacent to custom tracks in our current build of Chrome DevTools. // In future, we should align events exactly. - traceEvents.push_back(folly::dynamic::object( - "args", folly::dynamic::object("name", "Timings"))("cat", "__metadata")( - "name", "thread_name")("ph", "M")("pid", PID)("tid", 1000)("ts", 0)); + traceEvents.push_back( + folly::dynamic::object("args", folly::dynamic::object("name", "Timings"))( + "cat", "__metadata")("name", "thread_name")("ph", "M")("pid", PID)( + "tid", 1000)("ts", 0)); auto savedBuffer = std::move(buffer_); buffer_.clear(); @@ -73,20 +75,22 @@ bool FuseboxTracer::stopTracing( if (!event.track.empty() && !trackIdMap.contains(event.track)) { auto trackId = nextTrack++; trackIdMap[event.track] = trackId; - traceEvents.push_back(folly::dynamic::object( - "args", folly::dynamic::object("name", event.track))( - "cat", "__metadata")("name", "thread_name")("ph", "M")("pid", PID)( - "tid", trackId)("ts", 0)); + traceEvents.push_back( + folly::dynamic::object( + "args", folly::dynamic::object("name", event.track))( + "cat", "__metadata")("name", "thread_name")("ph", "M")( + "pid", PID)("tid", trackId)("ts", 0)); } auto trackId = trackIdMap.contains(event.track) ? trackIdMap[event.track] : 1000; // Emit "blink.user_timing" trace event - traceEvents.push_back(folly::dynamic::object( - "args", folly::dynamic::object())("cat", "blink.user_timing")( - "dur", (event.end - event.start) * 1000)("name", event.name)("ph", "X")( - "ts", event.start * 1000)("pid", PID)("tid", trackId)); + traceEvents.push_back( + folly::dynamic::object("args", folly::dynamic::object())( + "cat", "blink.user_timing")( + "dur", (event.end - event.start) * 1000)("name", event.name)( + "ph", "X")("ts", event.start * 1000)("pid", PID)("tid", trackId)); if (traceEvents.size() >= 1000) { resultCallback(traceEvents); @@ -109,11 +113,12 @@ void FuseboxTracer::addEvent( if (!tracing_) { return; } - buffer_.push_back(BufferEvent{ - .start = start, - .end = end, - .name = std::string(name), - .track = std::string(track.value_or(""))}); + buffer_.push_back( + BufferEvent{ + .start = start, + .end = end, + .name = std::string(name), + .track = std::string(track.value_or(""))}); } bool FuseboxTracer::stopTracingAndWriteToFile(const std::string& path) { diff --git a/packages/react-native/ReactCommon/reactperflogger/fusebox/FuseboxTracer.h b/packages/react-native/ReactCommon/reactperflogger/fusebox/FuseboxTracer.h index 0c415154e7a..17fb757772b 100644 --- a/packages/react-native/ReactCommon/reactperflogger/fusebox/FuseboxTracer.h +++ b/packages/react-native/ReactCommon/reactperflogger/fusebox/FuseboxTracer.h @@ -28,7 +28,7 @@ struct BufferEvent { */ class FuseboxTracer { public: - FuseboxTracer(const FuseboxTracer&) = delete; + FuseboxTracer(const FuseboxTracer &) = delete; bool isTracing(); // Verifies that tracing isn't started and starts tracing all in one step. @@ -37,16 +37,12 @@ class FuseboxTracer { // Verifies that we're tracing and dumps the trace all in one step to avoid // TOCTOU bugs. Returns false if we're not tracing. No result callbacks // are expected in that scenario. - bool stopTracing(const std::function& - resultCallback); - bool stopTracingAndWriteToFile(const std::string& path); - void addEvent( - const std::string_view& name, - uint64_t start, - uint64_t end, - const std::optional& track); + bool stopTracing(const std::function &resultCallback); + bool stopTracingAndWriteToFile(const std::string &path); + void + addEvent(const std::string_view &name, uint64_t start, uint64_t end, const std::optional &track); - static FuseboxTracer& getFuseboxTracer(); + static FuseboxTracer &getFuseboxTracer(); private: FuseboxTracer() {} diff --git a/packages/react-native/ReactCommon/reactperflogger/reactperflogger/BridgeNativeModulePerfLogger.h b/packages/react-native/ReactCommon/reactperflogger/reactperflogger/BridgeNativeModulePerfLogger.h index 16b42625299..1d024ab0d34 100644 --- a/packages/react-native/ReactCommon/reactperflogger/reactperflogger/BridgeNativeModulePerfLogger.h +++ b/packages/react-native/ReactCommon/reactperflogger/reactperflogger/BridgeNativeModulePerfLogger.h @@ -10,71 +10,57 @@ #include "NativeModulePerfLogger.h" namespace facebook::react::BridgeNativeModulePerfLogger { -void enableLogging(std::unique_ptr&& logger); +void enableLogging(std::unique_ptr &&logger); void disableLogging(); -void moduleDataCreateStart(const char* moduleName, int32_t id); -void moduleDataCreateEnd(const char* moduleName, int32_t id); +void moduleDataCreateStart(const char *moduleName, int32_t id); +void moduleDataCreateEnd(const char *moduleName, int32_t id); /** * Create NativeModule platform object */ -void moduleCreateStart(const char* moduleName, int32_t id); -void moduleCreateCacheHit(const char* moduleName, int32_t id); -void moduleCreateConstructStart(const char* moduleName, int32_t id); -void moduleCreateConstructEnd(const char* moduleName, int32_t id); -void moduleCreateSetUpStart(const char* moduleName, int32_t id); -void moduleCreateSetUpEnd(const char* moduleName, int32_t id); -void moduleCreateEnd(const char* moduleName, int32_t id); -void moduleCreateFail(const char* moduleName, int32_t id); +void moduleCreateStart(const char *moduleName, int32_t id); +void moduleCreateCacheHit(const char *moduleName, int32_t id); +void moduleCreateConstructStart(const char *moduleName, int32_t id); +void moduleCreateConstructEnd(const char *moduleName, int32_t id); +void moduleCreateSetUpStart(const char *moduleName, int32_t id); +void moduleCreateSetUpEnd(const char *moduleName, int32_t id); +void moduleCreateEnd(const char *moduleName, int32_t id); +void moduleCreateFail(const char *moduleName, int32_t id); /** * JS require beginning */ -void moduleJSRequireBeginningStart(const char* moduleName); -void moduleJSRequireBeginningCacheHit(const char* moduleName); -void moduleJSRequireBeginningEnd(const char* moduleName); -void moduleJSRequireBeginningFail(const char* moduleName); +void moduleJSRequireBeginningStart(const char *moduleName); +void moduleJSRequireBeginningCacheHit(const char *moduleName); +void moduleJSRequireBeginningEnd(const char *moduleName); +void moduleJSRequireBeginningFail(const char *moduleName); /** * JS require ending */ -void moduleJSRequireEndingStart(const char* moduleName); -void moduleJSRequireEndingEnd(const char* moduleName); -void moduleJSRequireEndingFail(const char* moduleName); +void moduleJSRequireEndingStart(const char *moduleName); +void moduleJSRequireEndingEnd(const char *moduleName); +void moduleJSRequireEndingFail(const char *moduleName); // Sync method calls -void syncMethodCallStart(const char* moduleName, const char* methodName); -void syncMethodCallArgConversionStart( - const char* moduleName, - const char* methodName); -void syncMethodCallArgConversionEnd( - const char* moduleName, - const char* methodName); -void syncMethodCallExecutionStart( - const char* moduleName, - const char* methodName); -void syncMethodCallExecutionEnd(const char* moduleName, const char* methodName); -void syncMethodCallReturnConversionStart( - const char* moduleName, - const char* methodName); -void syncMethodCallReturnConversionEnd( - const char* moduleName, - const char* methodName); -void syncMethodCallEnd(const char* moduleName, const char* methodName); -void syncMethodCallFail(const char* moduleName, const char* methodName); +void syncMethodCallStart(const char *moduleName, const char *methodName); +void syncMethodCallArgConversionStart(const char *moduleName, const char *methodName); +void syncMethodCallArgConversionEnd(const char *moduleName, const char *methodName); +void syncMethodCallExecutionStart(const char *moduleName, const char *methodName); +void syncMethodCallExecutionEnd(const char *moduleName, const char *methodName); +void syncMethodCallReturnConversionStart(const char *moduleName, const char *methodName); +void syncMethodCallReturnConversionEnd(const char *moduleName, const char *methodName); +void syncMethodCallEnd(const char *moduleName, const char *methodName); +void syncMethodCallFail(const char *moduleName, const char *methodName); // Async method calls -void asyncMethodCallStart(const char* moduleName, const char* methodName); -void asyncMethodCallArgConversionStart( - const char* moduleName, - const char* methodName); -void asyncMethodCallArgConversionEnd( - const char* moduleName, - const char* methodName); -void asyncMethodCallDispatch(const char* moduleName, const char* methodName); -void asyncMethodCallEnd(const char* moduleName, const char* methodName); -void asyncMethodCallFail(const char* moduleName, const char* methodName); +void asyncMethodCallStart(const char *moduleName, const char *methodName); +void asyncMethodCallArgConversionStart(const char *moduleName, const char *methodName); +void asyncMethodCallArgConversionEnd(const char *moduleName, const char *methodName); +void asyncMethodCallDispatch(const char *moduleName, const char *methodName); +void asyncMethodCallEnd(const char *moduleName, const char *methodName); +void asyncMethodCallFail(const char *moduleName, const char *methodName); /** * Pre-processing async method call batch @@ -83,25 +69,10 @@ void asyncMethodCallBatchPreprocessStart(); void asyncMethodCallBatchPreprocessEnd(int batchSize); // Async method call execution -void asyncMethodCallExecutionStart( - const char* moduleName, - const char* methodName, - int32_t id); -void asyncMethodCallExecutionArgConversionStart( - const char* moduleName, - const char* methodName, - int32_t id); -void asyncMethodCallExecutionArgConversionEnd( - const char* moduleName, - const char* methodName, - int32_t id); -void asyncMethodCallExecutionEnd( - const char* moduleName, - const char* methodName, - int32_t id); -void asyncMethodCallExecutionFail( - const char* moduleName, - const char* methodName, - int32_t id); +void asyncMethodCallExecutionStart(const char *moduleName, const char *methodName, int32_t id); +void asyncMethodCallExecutionArgConversionStart(const char *moduleName, const char *methodName, int32_t id); +void asyncMethodCallExecutionArgConversionEnd(const char *moduleName, const char *methodName, int32_t id); +void asyncMethodCallExecutionEnd(const char *moduleName, const char *methodName, int32_t id); +void asyncMethodCallExecutionFail(const char *moduleName, const char *methodName, int32_t id); } // namespace facebook::react::BridgeNativeModulePerfLogger diff --git a/packages/react-native/ReactCommon/reactperflogger/reactperflogger/FuseboxPerfettoDataSource.h b/packages/react-native/ReactCommon/reactperflogger/reactperflogger/FuseboxPerfettoDataSource.h index da0936a4a05..a470efc8c7a 100644 --- a/packages/react-native/ReactCommon/reactperflogger/reactperflogger/FuseboxPerfettoDataSource.h +++ b/packages/react-native/ReactCommon/reactperflogger/reactperflogger/FuseboxPerfettoDataSource.h @@ -19,30 +19,28 @@ namespace facebook::react { * trace) while we wait for Fusebox to be supported in release builds. * Once it's supported we'll probably want to deprecate this data source. */ -class FuseboxPerfettoDataSource - : public perfetto::DataSource { +class FuseboxPerfettoDataSource : public perfetto::DataSource { public: - void OnSetup(const SetupArgs&) override {} + void OnSetup(const SetupArgs &) override {} - void OnStart(const StartArgs&) override; + void OnStart(const StartArgs &) override; - void OnFlush(const FlushArgs&) override; + void OnFlush(const FlushArgs &) override; - void OnStop(const StopArgs& a) override; + void OnStop(const StopArgs &a) override; - static void RegisterDataSource() { + static void RegisterDataSource() + { perfetto::DataSourceDescriptor dsd; dsd.set_name("com.facebook.react.fusebox.profiler"); FuseboxPerfettoDataSource::Register(dsd); } - constexpr static perfetto::BufferExhaustedPolicy kBufferExhaustedPolicy = - perfetto::BufferExhaustedPolicy::kStall; + constexpr static perfetto::BufferExhaustedPolicy kBufferExhaustedPolicy = perfetto::BufferExhaustedPolicy::kStall; }; } // namespace facebook::react -PERFETTO_DECLARE_DATA_SOURCE_STATIC_MEMBERS( - facebook::react::FuseboxPerfettoDataSource); +PERFETTO_DECLARE_DATA_SOURCE_STATIC_MEMBERS(facebook::react::FuseboxPerfettoDataSource); #endif // WITH_PERFETTO diff --git a/packages/react-native/ReactCommon/reactperflogger/reactperflogger/HermesPerfettoDataSource.h b/packages/react-native/ReactCommon/reactperflogger/reactperflogger/HermesPerfettoDataSource.h index 265bd63607b..025450d1bda 100644 --- a/packages/react-native/ReactCommon/reactperflogger/reactperflogger/HermesPerfettoDataSource.h +++ b/packages/react-native/ReactCommon/reactperflogger/reactperflogger/HermesPerfettoDataSource.h @@ -13,30 +13,28 @@ namespace facebook::react { -class HermesPerfettoDataSource - : public perfetto::DataSource { +class HermesPerfettoDataSource : public perfetto::DataSource { public: - void OnSetup(const SetupArgs&) override {} + void OnSetup(const SetupArgs &) override {} - void OnStart(const StartArgs&) override; + void OnStart(const StartArgs &) override; - void OnFlush(const FlushArgs&) override; + void OnFlush(const FlushArgs &) override; - void OnStop(const StopArgs& a) override; + void OnStop(const StopArgs &a) override; - static void RegisterDataSource() { + static void RegisterDataSource() + { perfetto::DataSourceDescriptor dsd; dsd.set_name("com.facebook.hermes.profiler"); HermesPerfettoDataSource::Register(dsd); } - constexpr static perfetto::BufferExhaustedPolicy kBufferExhaustedPolicy = - perfetto::BufferExhaustedPolicy::kStall; + constexpr static perfetto::BufferExhaustedPolicy kBufferExhaustedPolicy = perfetto::BufferExhaustedPolicy::kStall; }; } // namespace facebook::react -PERFETTO_DECLARE_DATA_SOURCE_STATIC_MEMBERS( - facebook::react::HermesPerfettoDataSource); +PERFETTO_DECLARE_DATA_SOURCE_STATIC_MEMBERS(facebook::react::HermesPerfettoDataSource); #endif // WITH_PERFETTO diff --git a/packages/react-native/ReactCommon/reactperflogger/reactperflogger/NativeModulePerfLogger.h b/packages/react-native/ReactCommon/reactperflogger/reactperflogger/NativeModulePerfLogger.h index 861778fa24c..ac1c27553c8 100644 --- a/packages/react-native/ReactCommon/reactperflogger/reactperflogger/NativeModulePerfLogger.h +++ b/packages/react-native/ReactCommon/reactperflogger/reactperflogger/NativeModulePerfLogger.h @@ -38,24 +38,22 @@ class NativeModulePerfLogger { * - moduleDataCreateStart: very beginning of first phase. * - moduleDataCreateEnd: after RCTModuleData has been created. */ - virtual void moduleDataCreateStart(const char* moduleName, int32_t id) = 0; - virtual void moduleDataCreateEnd(const char* moduleName, int32_t id) = 0; + virtual void moduleDataCreateStart(const char *moduleName, int32_t id) = 0; + virtual void moduleDataCreateEnd(const char *moduleName, int32_t id) = 0; /** * How long does it take to create the platform NativeModule object? * - moduleCreateStart: start creating platform NativeModule * - moduleCreateEnd: stop creating platform NativeModule */ - virtual void moduleCreateStart(const char* moduleName, int32_t id) = 0; - virtual void moduleCreateCacheHit(const char* moduleName, int32_t id) = 0; - virtual void moduleCreateConstructStart( - const char* moduleName, - int32_t id) = 0; - virtual void moduleCreateConstructEnd(const char* moduleName, int32_t id) = 0; - virtual void moduleCreateSetUpStart(const char* moduleName, int32_t id) = 0; - virtual void moduleCreateSetUpEnd(const char* moduleName, int32_t id) = 0; - virtual void moduleCreateEnd(const char* moduleName, int32_t id) = 0; - virtual void moduleCreateFail(const char* moduleName, int32_t id) = 0; + virtual void moduleCreateStart(const char *moduleName, int32_t id) = 0; + virtual void moduleCreateCacheHit(const char *moduleName, int32_t id) = 0; + virtual void moduleCreateConstructStart(const char *moduleName, int32_t id) = 0; + virtual void moduleCreateConstructEnd(const char *moduleName, int32_t id) = 0; + virtual void moduleCreateSetUpStart(const char *moduleName, int32_t id) = 0; + virtual void moduleCreateSetUpEnd(const char *moduleName, int32_t id) = 0; + virtual void moduleCreateEnd(const char *moduleName, int32_t id) = 0; + virtual void moduleCreateFail(const char *moduleName, int32_t id) = 0; /** * How long, after starting JS require, does it take to start creating the @@ -63,10 +61,10 @@ class NativeModulePerfLogger { * - moduleJSRequireBeginningStart: start of JS require * - moduleJSRequireBeginningEnd: start creating platform NativeModule */ - virtual void moduleJSRequireBeginningStart(const char* moduleName) = 0; - virtual void moduleJSRequireBeginningCacheHit(const char* moduleName) = 0; - virtual void moduleJSRequireBeginningEnd(const char* moduleName) = 0; - virtual void moduleJSRequireBeginningFail(const char* moduleName) = 0; + virtual void moduleJSRequireBeginningStart(const char *moduleName) = 0; + virtual void moduleJSRequireBeginningCacheHit(const char *moduleName) = 0; + virtual void moduleJSRequireBeginningEnd(const char *moduleName) = 0; + virtual void moduleJSRequireBeginningFail(const char *moduleName) = 0; /** * How long does it take to return from the JS require after the platform @@ -74,58 +72,28 @@ class NativeModulePerfLogger { * - moduleJSRequireEndingStart: end creating platform NativeModule * - moduleJSRequireEndingEnd: end of JS require */ - virtual void moduleJSRequireEndingStart(const char* moduleName) = 0; - virtual void moduleJSRequireEndingEnd(const char* moduleName) = 0; - virtual void moduleJSRequireEndingFail(const char* moduleName) = 0; + virtual void moduleJSRequireEndingStart(const char *moduleName) = 0; + virtual void moduleJSRequireEndingEnd(const char *moduleName) = 0; + virtual void moduleJSRequireEndingFail(const char *moduleName) = 0; // Sync method calls - virtual void syncMethodCallStart( - const char* moduleName, - const char* methodName) = 0; - virtual void syncMethodCallArgConversionStart( - const char* moduleName, - const char* methodName) = 0; - virtual void syncMethodCallArgConversionEnd( - const char* moduleName, - const char* methodName) = 0; - virtual void syncMethodCallExecutionStart( - const char* moduleName, - const char* methodName) = 0; - virtual void syncMethodCallExecutionEnd( - const char* moduleName, - const char* methodName) = 0; - virtual void syncMethodCallReturnConversionStart( - const char* moduleName, - const char* methodName) = 0; - virtual void syncMethodCallReturnConversionEnd( - const char* moduleName, - const char* methodName) = 0; - virtual void syncMethodCallEnd( - const char* moduleName, - const char* methodName) = 0; - virtual void syncMethodCallFail( - const char* moduleName, - const char* methodName) = 0; + virtual void syncMethodCallStart(const char *moduleName, const char *methodName) = 0; + virtual void syncMethodCallArgConversionStart(const char *moduleName, const char *methodName) = 0; + virtual void syncMethodCallArgConversionEnd(const char *moduleName, const char *methodName) = 0; + virtual void syncMethodCallExecutionStart(const char *moduleName, const char *methodName) = 0; + virtual void syncMethodCallExecutionEnd(const char *moduleName, const char *methodName) = 0; + virtual void syncMethodCallReturnConversionStart(const char *moduleName, const char *methodName) = 0; + virtual void syncMethodCallReturnConversionEnd(const char *moduleName, const char *methodName) = 0; + virtual void syncMethodCallEnd(const char *moduleName, const char *methodName) = 0; + virtual void syncMethodCallFail(const char *moduleName, const char *methodName) = 0; // Async method calls - virtual void asyncMethodCallStart( - const char* moduleName, - const char* methodName) = 0; - virtual void asyncMethodCallArgConversionStart( - const char* moduleName, - const char* methodName) = 0; - virtual void asyncMethodCallArgConversionEnd( - const char* moduleName, - const char* methodName) = 0; - virtual void asyncMethodCallDispatch( - const char* moduleName, - const char* methodName) = 0; - virtual void asyncMethodCallEnd( - const char* moduleName, - const char* methodName) = 0; - virtual void asyncMethodCallFail( - const char* moduleName, - const char* methodName) = 0; + virtual void asyncMethodCallStart(const char *moduleName, const char *methodName) = 0; + virtual void asyncMethodCallArgConversionStart(const char *moduleName, const char *methodName) = 0; + virtual void asyncMethodCallArgConversionEnd(const char *moduleName, const char *methodName) = 0; + virtual void asyncMethodCallDispatch(const char *moduleName, const char *methodName) = 0; + virtual void asyncMethodCallEnd(const char *moduleName, const char *methodName) = 0; + virtual void asyncMethodCallFail(const char *moduleName, const char *methodName) = 0; /** * In the NativeModule system, we batch async NativeModule method calls. @@ -137,26 +105,12 @@ class NativeModulePerfLogger { virtual void asyncMethodCallBatchPreprocessEnd(int batchSize) = 0; // Async method call execution - virtual void asyncMethodCallExecutionStart( - const char* moduleName, - const char* methodName, - int32_t id) = 0; - virtual void asyncMethodCallExecutionArgConversionStart( - const char* moduleName, - const char* methodName, - int32_t id) = 0; - virtual void asyncMethodCallExecutionArgConversionEnd( - const char* moduleName, - const char* methodName, - int32_t id) = 0; - virtual void asyncMethodCallExecutionEnd( - const char* moduleName, - const char* methodName, - int32_t id) = 0; - virtual void asyncMethodCallExecutionFail( - const char* moduleName, - const char* methodName, - int32_t id) = 0; + virtual void asyncMethodCallExecutionStart(const char *moduleName, const char *methodName, int32_t id) = 0; + virtual void + asyncMethodCallExecutionArgConversionStart(const char *moduleName, const char *methodName, int32_t id) = 0; + virtual void asyncMethodCallExecutionArgConversionEnd(const char *moduleName, const char *methodName, int32_t id) = 0; + virtual void asyncMethodCallExecutionEnd(const char *moduleName, const char *methodName, int32_t id) = 0; + virtual void asyncMethodCallExecutionFail(const char *moduleName, const char *methodName, int32_t id) = 0; }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/reactperflogger/reactperflogger/ReactPerfetto.h b/packages/react-native/ReactCommon/reactperflogger/reactperflogger/ReactPerfetto.h index c46ff051c53..43c08152f97 100644 --- a/packages/react-native/ReactCommon/reactperflogger/reactperflogger/ReactPerfetto.h +++ b/packages/react-native/ReactCommon/reactperflogger/reactperflogger/ReactPerfetto.h @@ -18,8 +18,8 @@ namespace facebook::react { void initializePerfetto(); -perfetto::Track getPerfettoWebPerfTrackSync(const std::string& trackName); -perfetto::Track getPerfettoWebPerfTrackAsync(const std::string& trackName); +perfetto::Track getPerfettoWebPerfTrackSync(const std::string &trackName); +perfetto::Track getPerfettoWebPerfTrackAsync(const std::string &trackName); uint64_t highResTimeStampToPerfettoTraceTime(HighResTimeStamp timestamp); diff --git a/packages/react-native/ReactCommon/reactperflogger/reactperflogger/ReactPerfettoCategories.h b/packages/react-native/ReactCommon/reactperflogger/reactperflogger/ReactPerfettoCategories.h index 133f95a0bc7..06acd9a3ae0 100644 --- a/packages/react-native/ReactCommon/reactperflogger/reactperflogger/ReactPerfettoCategories.h +++ b/packages/react-native/ReactCommon/reactperflogger/reactperflogger/ReactPerfettoCategories.h @@ -13,7 +13,6 @@ PERFETTO_DEFINE_CATEGORIES_IN_NAMESPACE( facebook::react, - perfetto::Category("react-native") - .SetDescription("User timing events from React Native")); + perfetto::Category("react-native").SetDescription("User timing events from React Native")); #endif diff --git a/packages/react-native/ReactCommon/reactperflogger/reactperflogger/ReactPerfettoLogger.h b/packages/react-native/ReactCommon/reactperflogger/reactperflogger/ReactPerfettoLogger.h index 73c7619e770..9acf97f9b3c 100644 --- a/packages/react-native/ReactCommon/reactperflogger/reactperflogger/ReactPerfettoLogger.h +++ b/packages/react-native/ReactCommon/reactperflogger/reactperflogger/ReactPerfettoLogger.h @@ -24,17 +24,17 @@ class ReactPerfettoLogger { static bool isTracing(); static void mark( - const std::string_view& eventName, + const std::string_view &eventName, HighResTimeStamp startTime, - const std::optional& trackName = std::nullopt, - const std::optional& trackGroup = std::nullopt); + const std::optional &trackName = std::nullopt, + const std::optional &trackGroup = std::nullopt); static void measure( - const std::string_view& eventName, + const std::string_view &eventName, HighResTimeStamp startTime, HighResTimeStamp endTime, - const std::optional& trackName = std::nullopt, - const std::optional& trackGroup = std::nullopt); + const std::optional &trackName = std::nullopt, + const std::optional &trackGroup = std::nullopt); }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/runtimeexecutor/ReactCommon/RuntimeExecutor.h b/packages/react-native/ReactCommon/runtimeexecutor/ReactCommon/RuntimeExecutor.h index f8f69b54343..999e38c3134 100644 --- a/packages/react-native/ReactCommon/runtimeexecutor/ReactCommon/RuntimeExecutor.h +++ b/packages/react-native/ReactCommon/runtimeexecutor/ReactCommon/RuntimeExecutor.h @@ -19,7 +19,6 @@ namespace facebook::react { * instead of storing a pointer to the Runtime itself, which makes it more * difficult to ensure that the Runtime is being accessed safely. */ -using RuntimeExecutor = - std::function&& callback)>; +using RuntimeExecutor = std::function &&callback)>; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/runtimeexecutor/platform/cxx/ReactCommon/RuntimeExecutorSyncUIThreadUtils.h b/packages/react-native/ReactCommon/runtimeexecutor/platform/cxx/ReactCommon/RuntimeExecutorSyncUIThreadUtils.h index 0baee4e2841..fd74c21261b 100644 --- a/packages/react-native/ReactCommon/runtimeexecutor/platform/cxx/ReactCommon/RuntimeExecutorSyncUIThreadUtils.h +++ b/packages/react-native/ReactCommon/runtimeexecutor/platform/cxx/ReactCommon/RuntimeExecutorSyncUIThreadUtils.h @@ -18,18 +18,18 @@ namespace facebook::react { * `RuntimeExecutor`, and blocks on its completion. */ void executeSynchronouslyOnSameThread_CAN_DEADLOCK( - const RuntimeExecutor& runtimeExecutor, - std::function&& runtimeWork); + const RuntimeExecutor &runtimeExecutor, + std::function &&runtimeWork); template inline static DataT executeSynchronouslyOnSameThread_CAN_DEADLOCK( - const RuntimeExecutor& runtimeExecutor, - std::function&& runtimeWork) { + const RuntimeExecutor &runtimeExecutor, + std::function &&runtimeWork) +{ DataT data; executeSynchronouslyOnSameThread_CAN_DEADLOCK( - runtimeExecutor, - [&](jsi::Runtime& runtime) { data = runtimeWork(runtime); }); + runtimeExecutor, [&](jsi::Runtime &runtime) { data = runtimeWork(runtime); }); return data; } diff --git a/packages/react-native/ReactCommon/runtimeexecutor/platform/ios/ReactCommon/RuntimeExecutorSyncUIThreadUtils.h b/packages/react-native/ReactCommon/runtimeexecutor/platform/ios/ReactCommon/RuntimeExecutorSyncUIThreadUtils.h index 12ab4d958e7..17d78acf2a8 100644 --- a/packages/react-native/ReactCommon/runtimeexecutor/platform/ios/ReactCommon/RuntimeExecutorSyncUIThreadUtils.h +++ b/packages/react-native/ReactCommon/runtimeexecutor/platform/ios/ReactCommon/RuntimeExecutorSyncUIThreadUtils.h @@ -18,18 +18,18 @@ namespace facebook::react { * `RuntimeExecutor`, and blocks on its completion. */ void executeSynchronouslyOnSameThread_CAN_DEADLOCK( - const RuntimeExecutor& runtimeExecutor, - std::function&& runtimeWork); + const RuntimeExecutor &runtimeExecutor, + std::function &&runtimeWork); template inline static DataT executeSynchronouslyOnSameThread_CAN_DEADLOCK( - const RuntimeExecutor& runtimeExecutor, - std::function&& runtimeWork) { + const RuntimeExecutor &runtimeExecutor, + std::function &&runtimeWork) +{ DataT data; executeSynchronouslyOnSameThread_CAN_DEADLOCK( - runtimeExecutor, - [&](jsi::Runtime& runtime) { data = runtimeWork(runtime); }); + runtimeExecutor, [&](jsi::Runtime &runtime) { data = runtimeWork(runtime); }); return data; } diff --git a/packages/react-native/ReactCommon/yoga/yoga/algorithm/CalculateLayout.cpp b/packages/react-native/ReactCommon/yoga/yoga/algorithm/CalculateLayout.cpp index db7904286d8..fcc05313549 100644 --- a/packages/react-native/ReactCommon/yoga/yoga/algorithm/CalculateLayout.cpp +++ b/packages/react-native/ReactCommon/yoga/yoga/algorithm/CalculateLayout.cpp @@ -110,19 +110,21 @@ static void computeFlexBasisForChild( FloatOptional(paddingAndBorderForAxis( child, FlexDirection::Row, direction, ownerWidth)); - child->setLayoutComputedFlexBasis(yoga::maxOrDefined( - child->getResolvedDimension( - direction, Dimension::Width, ownerWidth, ownerWidth), - paddingAndBorder)); + child->setLayoutComputedFlexBasis( + yoga::maxOrDefined( + child->getResolvedDimension( + direction, Dimension::Width, ownerWidth, ownerWidth), + paddingAndBorder)); } else if (!isMainAxisRow && isColumnStyleDimDefined) { // The height is definite, so use that as the flex basis. const FloatOptional paddingAndBorder = FloatOptional(paddingAndBorderForAxis( child, FlexDirection::Column, direction, ownerWidth)); - child->setLayoutComputedFlexBasis(yoga::maxOrDefined( - child->getResolvedDimension( - direction, Dimension::Height, ownerHeight, ownerWidth), - paddingAndBorder)); + child->setLayoutComputedFlexBasis( + yoga::maxOrDefined( + child->getResolvedDimension( + direction, Dimension::Height, ownerHeight, ownerWidth), + paddingAndBorder)); } else { // Compute the flex basis and hypothetical main size (i.e. the clamped flex // basis). @@ -253,9 +255,10 @@ static void computeFlexBasisForChild( depth, generationCount); - child->setLayoutComputedFlexBasis(FloatOptional(yoga::maxOrDefined( - child->getLayout().measuredDimension(dimension(mainAxis)), - paddingAndBorderForAxis(child, mainAxis, direction, ownerWidth)))); + child->setLayoutComputedFlexBasis(FloatOptional( + yoga::maxOrDefined( + child->getLayout().measuredDimension(dimension(mainAxis)), + paddingAndBorderForAxis(child, mainAxis, direction, ownerWidth)))); } child->setLayoutComputedFlexBasisGeneration(generationCount); } diff --git a/packages/react-native/ReactCxxPlatform/react/coremodules/AppStateModule.h b/packages/react-native/ReactCxxPlatform/react/coremodules/AppStateModule.h index c682ec2439e..089cd19c497 100644 --- a/packages/react-native/ReactCxxPlatform/react/coremodules/AppStateModule.h +++ b/packages/react-native/ReactCxxPlatform/react/coremodules/AppStateModule.h @@ -16,8 +16,7 @@ namespace facebook::react { using AppStateConstants = NativeAppStateAppStateConstants; template <> -struct Bridging - : NativeAppStateAppStateConstantsBridging {}; +struct Bridging : NativeAppStateAppStateConstantsBridging {}; using AppState = NativeAppStateAppState; @@ -26,18 +25,14 @@ struct Bridging : NativeAppStateAppStateBridging {}; class AppStateModule : public NativeAppStateCxxSpec { public: - explicit AppStateModule(std::shared_ptr jsInvoker) - : NativeAppStateCxxSpec(jsInvoker) {} + explicit AppStateModule(std::shared_ptr jsInvoker) : NativeAppStateCxxSpec(jsInvoker) {} - AppStateConstants getConstants(jsi::Runtime& rt); + AppStateConstants getConstants(jsi::Runtime &rt); - void getCurrentAppState( - jsi::Runtime& rt, - const AsyncCallback& success, - jsi::Function error); - void addListener(jsi::Runtime& rt, const std::string& eventName); + void getCurrentAppState(jsi::Runtime &rt, const AsyncCallback &success, jsi::Function error); + void addListener(jsi::Runtime &rt, const std::string &eventName); - void removeListeners(jsi::Runtime& rt, double count); + void removeListeners(jsi::Runtime &rt, double count); }; } // namespace facebook::react diff --git a/packages/react-native/ReactCxxPlatform/react/coremodules/DeviceInfoModule.h b/packages/react-native/ReactCxxPlatform/react/coremodules/DeviceInfoModule.h index 63b50871e9c..c750cf97152 100644 --- a/packages/react-native/ReactCxxPlatform/react/coremodules/DeviceInfoModule.h +++ b/packages/react-native/ReactCxxPlatform/react/coremodules/DeviceInfoModule.h @@ -12,15 +12,9 @@ namespace facebook::react { -using DisplayMetrics = - NativeDeviceInfoDisplayMetrics; +using DisplayMetrics = NativeDeviceInfoDisplayMetrics; -using DisplayMetricsAndroid = NativeDeviceInfoDisplayMetricsAndroid< - double, - double, - double, - double, - double>; +using DisplayMetricsAndroid = NativeDeviceInfoDisplayMetricsAndroid; using DimensionsPayload = NativeDeviceInfoDimensionsPayload< std::optional, @@ -28,33 +22,26 @@ using DimensionsPayload = NativeDeviceInfoDimensionsPayload< std::optional, std::optional>; -using DeviceInfoConstants = NativeDeviceInfoDeviceInfoConstants< - DimensionsPayload, - std::optional, - std::optional>; +using DeviceInfoConstants = + NativeDeviceInfoDeviceInfoConstants, std::optional>; template <> -struct Bridging - : NativeDeviceInfoDisplayMetricsBridging {}; +struct Bridging : NativeDeviceInfoDisplayMetricsBridging {}; template <> -struct Bridging - : NativeDeviceInfoDisplayMetricsAndroidBridging {}; +struct Bridging : NativeDeviceInfoDisplayMetricsAndroidBridging {}; template <> -struct Bridging - : NativeDeviceInfoDimensionsPayloadBridging {}; +struct Bridging : NativeDeviceInfoDimensionsPayloadBridging {}; template <> -struct Bridging - : NativeDeviceInfoDeviceInfoConstantsBridging {}; +struct Bridging : NativeDeviceInfoDeviceInfoConstantsBridging {}; class DeviceInfoModule : public NativeDeviceInfoCxxSpec { public: - explicit DeviceInfoModule(std::shared_ptr jsInvoker) - : NativeDeviceInfoCxxSpec(jsInvoker) {} + explicit DeviceInfoModule(std::shared_ptr jsInvoker) : NativeDeviceInfoCxxSpec(jsInvoker) {} - DeviceInfoConstants getConstants(jsi::Runtime& rt); + DeviceInfoConstants getConstants(jsi::Runtime &rt); }; } // namespace facebook::react diff --git a/packages/react-native/ReactCxxPlatform/react/coremodules/PlatformConstantsModule.h b/packages/react-native/ReactCxxPlatform/react/coremodules/PlatformConstantsModule.h index 04470366940..ea4c9bc27ac 100644 --- a/packages/react-native/ReactCxxPlatform/react/coremodules/PlatformConstantsModule.h +++ b/packages/react-native/ReactCxxPlatform/react/coremodules/PlatformConstantsModule.h @@ -13,49 +13,44 @@ namespace facebook::react { using ReactNativeVersionAndroid = - NativePlatformConstantsAndroidReactNativeVersionAndroid< - int, - int, - int, - std::optional>; + NativePlatformConstantsAndroidReactNativeVersionAndroid>; template <> struct Bridging - : NativePlatformConstantsAndroidReactNativeVersionAndroidBridging< - ReactNativeVersionAndroid> {}; + : NativePlatformConstantsAndroidReactNativeVersionAndroidBridging {}; -using PlatformConstantsAndroid = - NativePlatformConstantsAndroidPlatformConstantsAndroid< - bool, - std::optional, - ReactNativeVersionAndroid, - int, - std::string, - std::string, - std::string, - std::string, - std::optional, - std::string, - std::string, - std::string>; +using PlatformConstantsAndroid = NativePlatformConstantsAndroidPlatformConstantsAndroid< + bool, + std::optional, + ReactNativeVersionAndroid, + int, + std::string, + std::string, + std::string, + std::string, + std::optional, + std::string, + std::string, + std::string>; template <> struct Bridging - : NativePlatformConstantsAndroidPlatformConstantsAndroidBridging< - PlatformConstantsAndroid> {}; + : NativePlatformConstantsAndroidPlatformConstantsAndroidBridging {}; // T159303412: [RN] Metro: Need support for new target platform -class PlatformConstantsModule - : public NativePlatformConstantsAndroidCxxSpec { +class PlatformConstantsModule : public NativePlatformConstantsAndroidCxxSpec { public: explicit PlatformConstantsModule(std::shared_ptr jsInvoker) - : NativePlatformConstantsAndroidCxxSpec(jsInvoker) {} + : NativePlatformConstantsAndroidCxxSpec(jsInvoker) + { + } - std::string getAndroidID(jsi::Runtime& /*rt*/) { + std::string getAndroidID(jsi::Runtime & /*rt*/) + { return ""; } - PlatformConstantsAndroid getConstants(jsi::Runtime& rt); + PlatformConstantsAndroid getConstants(jsi::Runtime &rt); }; } // namespace facebook::react diff --git a/packages/react-native/ReactCxxPlatform/react/devsupport/DevLoadingViewModule.h b/packages/react-native/ReactCxxPlatform/react/devsupport/DevLoadingViewModule.h index 9fa51278f7c..947255f603d 100644 --- a/packages/react-native/ReactCxxPlatform/react/devsupport/DevLoadingViewModule.h +++ b/packages/react-native/ReactCxxPlatform/react/devsupport/DevLoadingViewModule.h @@ -15,22 +15,19 @@ namespace facebook::react { -class DevLoadingViewModule - : public NativeDevLoadingViewCxxSpec { +class DevLoadingViewModule : public NativeDevLoadingViewCxxSpec { public: - DevLoadingViewModule( - std::shared_ptr jsInvoker, - std::weak_ptr devUIDelegate); + DevLoadingViewModule(std::shared_ptr jsInvoker, std::weak_ptr devUIDelegate); ~DevLoadingViewModule() override; void showMessage( - jsi::Runtime& rt, - const std::string& message, + jsi::Runtime &rt, + const std::string &message, std::optional textColor, std::optional backgroundColor); - void hide(jsi::Runtime& rt); + void hide(jsi::Runtime &rt); private: std::weak_ptr devUIDelegate_; diff --git a/packages/react-native/ReactCxxPlatform/react/devsupport/DevServerHelper.h b/packages/react-native/ReactCxxPlatform/react/devsupport/DevServerHelper.h index 68071ba2834..fa0f5844d51 100644 --- a/packages/react-native/ReactCxxPlatform/react/devsupport/DevServerHelper.h +++ b/packages/react-native/ReactCxxPlatform/react/devsupport/DevServerHelper.h @@ -26,13 +26,13 @@ class DevServerHelper { std::string deviceName, std::string devServerHost, uint32_t devServerPort, - const HttpClientFactory& httpClientFactory, + const HttpClientFactory &httpClientFactory, JavaScriptModuleCallback javaScriptModuleCallback) noexcept; ~DevServerHelper() noexcept = default; std::future downloadBundleResourceSync( - const std::string& jsBundleUrl, - DownloadProgressCallback&& downloadProgressCallback = nullptr); + const std::string &jsBundleUrl, + DownloadProgressCallback &&downloadProgressCallback = nullptr); std::string getInspectorUrl() const; @@ -42,7 +42,8 @@ class DevServerHelper { void openDebugger() const; - void setSourcePath(const std::string& sourcePath) { + void setSourcePath(const std::string &sourcePath) + { sourcePath_ = sourcePath; } diff --git a/packages/react-native/ReactCxxPlatform/react/devsupport/DevSettingsModule.h b/packages/react-native/ReactCxxPlatform/react/devsupport/DevSettingsModule.h index ef954b1443b..47a1cdc11ea 100644 --- a/packages/react-native/ReactCxxPlatform/react/devsupport/DevSettingsModule.h +++ b/packages/react-native/ReactCxxPlatform/react/devsupport/DevSettingsModule.h @@ -21,36 +21,36 @@ class DevSettingsModule : public NativeDevSettingsCxxSpec { DevSettingsModule( std::shared_ptr jsInvoker, std::weak_ptr devServerHelper, - LiveReloadCallback&& liveReloadCallback) + LiveReloadCallback &&liveReloadCallback) : NativeDevSettingsCxxSpec(jsInvoker), devServerHelper_(std::move(devServerHelper)), - liveReloadCallback_(std::move(liveReloadCallback)) {} + liveReloadCallback_(std::move(liveReloadCallback)) + { + } - void reload(jsi::Runtime& rt); + void reload(jsi::Runtime &rt); - void reloadWithReason(jsi::Runtime& rt, const std::string& reason); + void reloadWithReason(jsi::Runtime &rt, const std::string &reason); - void onFastRefresh(jsi::Runtime& rt); + void onFastRefresh(jsi::Runtime &rt); - void setHotLoadingEnabled(jsi::Runtime& rt, bool isHotLoadingEnabled); + void setHotLoadingEnabled(jsi::Runtime &rt, bool isHotLoadingEnabled); - void setIsDebuggingRemotely( - jsi::Runtime& rt, - bool isDebuggingRemotelyEnabled); + void setIsDebuggingRemotely(jsi::Runtime &rt, bool isDebuggingRemotelyEnabled); - void setProfilingEnabled(jsi::Runtime& rt, bool isProfilingEnabled); + void setProfilingEnabled(jsi::Runtime &rt, bool isProfilingEnabled); - void toggleElementInspector(jsi::Runtime& rt); + void toggleElementInspector(jsi::Runtime &rt); - void addMenuItem(jsi::Runtime& rt, const std::string& title); + void addMenuItem(jsi::Runtime &rt, const std::string &title); - void setIsShakeToShowDevMenuEnabled(jsi::Runtime& rt, bool enabled); + void setIsShakeToShowDevMenuEnabled(jsi::Runtime &rt, bool enabled); - void openDebugger(jsi::Runtime& rt); + void openDebugger(jsi::Runtime &rt); - void addListener(jsi::Runtime& rt, const std::string& eventName); + void addListener(jsi::Runtime &rt, const std::string &eventName); - void removeListeners(jsi::Runtime& rt, double count); + void removeListeners(jsi::Runtime &rt, double count); private: std::weak_ptr devServerHelper_; diff --git a/packages/react-native/ReactCxxPlatform/react/devsupport/IDevUIDelegate.h b/packages/react-native/ReactCxxPlatform/react/devsupport/IDevUIDelegate.h index daf8ecfc0b1..958cc190199 100644 --- a/packages/react-native/ReactCxxPlatform/react/devsupport/IDevUIDelegate.h +++ b/packages/react-native/ReactCxxPlatform/react/devsupport/IDevUIDelegate.h @@ -20,15 +20,11 @@ struct IDevUIDelegate { virtual void hideDownloadBundleProgress() = 0; - virtual void showLoadingView( - const std::string& message, - SharedColor textColor, - SharedColor backgroundColor) = 0; + virtual void showLoadingView(const std::string &message, SharedColor textColor, SharedColor backgroundColor) = 0; virtual void hideLoadingView() = 0; - virtual void showDebuggerOverlay( - std::function&& resumeDebuggerFn) = 0; + virtual void showDebuggerOverlay(std::function &&resumeDebuggerFn) = 0; virtual void hideDebuggerOverlay() = 0; }; diff --git a/packages/react-native/ReactCxxPlatform/react/devsupport/LogBoxModule.h b/packages/react-native/ReactCxxPlatform/react/devsupport/LogBoxModule.h index 1ace8f9d652..0ee88e327ee 100644 --- a/packages/react-native/ReactCxxPlatform/react/devsupport/LogBoxModule.h +++ b/packages/react-native/ReactCxxPlatform/react/devsupport/LogBoxModule.h @@ -13,14 +13,12 @@ namespace facebook::react { class LogBoxModule : public NativeLogBoxCxxSpec { public: - LogBoxModule( - std::shared_ptr jsInvoker, - std::shared_ptr surfaceDelegate); + LogBoxModule(std::shared_ptr jsInvoker, std::shared_ptr surfaceDelegate); ~LogBoxModule() override; - void show(jsi::Runtime& rt); + void show(jsi::Runtime &rt); - void hide(jsi::Runtime& rt); + void hide(jsi::Runtime &rt); private: std::shared_ptr surfaceDelegate_; diff --git a/packages/react-native/ReactCxxPlatform/react/devsupport/PackagerConnection.h b/packages/react-native/ReactCxxPlatform/react/devsupport/PackagerConnection.h index 8c53f6f6cc3..eee5149fd43 100644 --- a/packages/react-native/ReactCxxPlatform/react/devsupport/PackagerConnection.h +++ b/packages/react-native/ReactCxxPlatform/react/devsupport/PackagerConnection.h @@ -20,15 +20,15 @@ class PackagerConnection { public: PackagerConnection( - const WebSocketClientFactory& webSocketClientFactory, - const std::string& packagerConnectionUrl, - LiveReloadCallback&& liveReloadCallback, - ShowDevMenuCallback&& showDevMenuCallback); + const WebSocketClientFactory &webSocketClientFactory, + const std::string &packagerConnectionUrl, + LiveReloadCallback &&liveReloadCallback, + ShowDevMenuCallback &&showDevMenuCallback); ~PackagerConnection() noexcept; - PackagerConnection(const PackagerConnection& other) = delete; - PackagerConnection& operator=(PackagerConnection& other) = delete; - PackagerConnection(PackagerConnection&& other) = delete; - PackagerConnection& operator=(PackagerConnection&& other) = delete; + PackagerConnection(const PackagerConnection &other) = delete; + PackagerConnection &operator=(PackagerConnection &other) = delete; + PackagerConnection(PackagerConnection &&other) = delete; + PackagerConnection &operator=(PackagerConnection &&other) = delete; private: const LiveReloadCallback liveReloadCallback_; diff --git a/packages/react-native/ReactCxxPlatform/react/devsupport/SourceCodeModule.h b/packages/react-native/ReactCxxPlatform/react/devsupport/SourceCodeModule.h index bbe4931ebe4..9582cba32e0 100644 --- a/packages/react-native/ReactCxxPlatform/react/devsupport/SourceCodeModule.h +++ b/packages/react-native/ReactCxxPlatform/react/devsupport/SourceCodeModule.h @@ -18,17 +18,18 @@ class DevServerHelper; using SourceCodeConstants = NativeSourceCodeSourceCodeConstants; template <> -struct Bridging - : NativeSourceCodeSourceCodeConstantsBridging {}; +struct Bridging : NativeSourceCodeSourceCodeConstantsBridging {}; class SourceCodeModule : public NativeSourceCodeCxxSpec { public: explicit SourceCodeModule( std::shared_ptr jsInvoker, std::shared_ptr devServerHelper = nullptr) - : NativeSourceCodeCxxSpec(jsInvoker), devServerHelper_(devServerHelper) {} + : NativeSourceCodeCxxSpec(jsInvoker), devServerHelper_(devServerHelper) + { + } - SourceCodeConstants getConstants(jsi::Runtime& rt); + SourceCodeConstants getConstants(jsi::Runtime &rt); private: std::weak_ptr devServerHelper_; diff --git a/packages/react-native/ReactCxxPlatform/react/devsupport/inspector/Inspector.cpp b/packages/react-native/ReactCxxPlatform/react/devsupport/inspector/Inspector.cpp index 743aa3ff2c2..88669a77543 100644 --- a/packages/react-native/ReactCxxPlatform/react/devsupport/inspector/Inspector.cpp +++ b/packages/react-native/ReactCxxPlatform/react/devsupport/inspector/Inspector.cpp @@ -41,8 +41,9 @@ class InspectorHostTargetDelegate }; } - void onReload(const jsinspector_modern::HostTargetDelegate::PageReloadRequest& - /*request*/) override { + void onReload( + const jsinspector_modern::HostTargetDelegate::PageReloadRequest& + /*request*/) override { if (liveReloadCallbackFn_ != nullptr) { liveReloadCallbackFn_(); } @@ -69,9 +70,9 @@ class InspectorHostTargetDelegate http::NetworkCallbacks callbacks{ .onResponse = [executor](uint32_t responseCode, const http::Headers& headers) { - executor([responseCode, - headers](jsinspector_modern::NetworkRequestListener& - listener) { + executor([responseCode, headers]( + jsinspector_modern::NetworkRequestListener& + listener) { facebook::react::jsinspector_modern::Headers responseHeaders; for (const auto& [key, value] : headers) { responseHeaders[key] = value; diff --git a/packages/react-native/ReactCxxPlatform/react/devsupport/inspector/Inspector.h b/packages/react-native/ReactCxxPlatform/react/devsupport/inspector/Inspector.h index 22fb9bffe4c..c110ad6aea4 100644 --- a/packages/react-native/ReactCxxPlatform/react/devsupport/inspector/Inspector.h +++ b/packages/react-native/ReactCxxPlatform/react/devsupport/inspector/Inspector.h @@ -20,13 +20,11 @@ namespace facebook::react { -using ToggleDebuggerOverlayFn = - std::function&&)>; +using ToggleDebuggerOverlayFn = std::function &&)>; using LiveReloadCallbackFn = std::function; -class Inspector : public InspectorThread, - public std::enable_shared_from_this { +class Inspector : public InspectorThread, public std::enable_shared_from_this { public: Inspector( std::string appName, @@ -34,24 +32,23 @@ class Inspector : public InspectorThread, WebSocketClientFactory webSocketClientFactory, HttpClientFactory httpClientFactory) noexcept; ~Inspector() noexcept override; - Inspector(const Inspector& other) = delete; - Inspector& operator=(Inspector& other) = delete; - Inspector(Inspector&& other) = delete; - Inspector& operator=(Inspector&& other) = delete; + Inspector(const Inspector &other) = delete; + Inspector &operator=(Inspector &other) = delete; + Inspector(Inspector &&other) = delete; + Inspector &operator=(Inspector &&other) = delete; - void connectDebugger(const std::string& inspectorUrl) noexcept; + void connectDebugger(const std::string &inspectorUrl) noexcept; void ensureHostTarget( - LiveReloadCallbackFn&& liveReloadCallbackFn, - ToggleDebuggerOverlayFn&& toggleDebuggerOverlayFn) noexcept; + LiveReloadCallbackFn &&liveReloadCallbackFn, + ToggleDebuggerOverlayFn &&toggleDebuggerOverlayFn) noexcept; std::shared_ptr inspectorTarget() const; private: void invokeElsePost( - TaskDispatchThread::TaskFn&& callback, - std::chrono::milliseconds delayMs = - std::chrono::milliseconds::zero()) override; + TaskDispatchThread::TaskFn &&callback, + std::chrono::milliseconds delayMs = std::chrono::milliseconds::zero()) override; TaskDispatchThread taskDispatchThread_{"InspectorThread"}; std::string appName_; @@ -61,8 +58,7 @@ class Inspector : public InspectorThread, std::shared_ptr hostDelegate_; std::shared_ptr target_; std::optional pageId_; - std::unique_ptr - packagerConnection_; + std::unique_ptr packagerConnection_; }; } // namespace facebook::react diff --git a/packages/react-native/ReactCxxPlatform/react/devsupport/inspector/InspectorPackagerConnectionDelegate.h b/packages/react-native/ReactCxxPlatform/react/devsupport/inspector/InspectorPackagerConnectionDelegate.h index 871e82eb175..e91d5be9f60 100644 --- a/packages/react-native/ReactCxxPlatform/react/devsupport/inspector/InspectorPackagerConnectionDelegate.h +++ b/packages/react-native/ReactCxxPlatform/react/devsupport/inspector/InspectorPackagerConnectionDelegate.h @@ -19,20 +19,19 @@ namespace facebook::react { class IWebSocketClient; -class InspectorPackagerConnectionDelegate final - : public jsinspector_modern::InspectorPackagerConnectionDelegate { +class InspectorPackagerConnectionDelegate final : public jsinspector_modern::InspectorPackagerConnectionDelegate { class WebSocket : public jsinspector_modern::IWebSocket { public: WebSocket( - const std::string& url, + const std::string &url, std::weak_ptr webSocketDelegate, std::weak_ptr inspectorThread, - const WebSocketClientFactory& webSocketClientFactory); + const WebSocketClientFactory &webSocketClientFactory); ~WebSocket() override; - WebSocket(const WebSocket& other) = delete; - WebSocket& operator=(WebSocket& other) = delete; - WebSocket(WebSocket&& other) = delete; - WebSocket& operator=(WebSocket&& other) = delete; + WebSocket(const WebSocket &other) = delete; + WebSocket &operator=(WebSocket &other) = delete; + WebSocket(WebSocket &&other) = delete; + WebSocket &operator=(WebSocket &&other) = delete; void send(std::string_view message) override; @@ -48,13 +47,12 @@ class InspectorPackagerConnectionDelegate final WebSocketClientFactory webSocketClientFactory) noexcept; std::unique_ptr connectWebSocket( - const std::string& url, + const std::string &url, std::weak_ptr delegate) override; void scheduleCallback( std::function callback, - std::chrono::milliseconds delayMs = - std::chrono::milliseconds::zero()) override; + std::chrono::milliseconds delayMs = std::chrono::milliseconds::zero()) override; private: std::weak_ptr inspectorThread_; diff --git a/packages/react-native/ReactCxxPlatform/react/devsupport/inspector/InspectorThread.h b/packages/react-native/ReactCxxPlatform/react/devsupport/inspector/InspectorThread.h index e6b25fe8fbc..1dbee83051d 100644 --- a/packages/react-native/ReactCxxPlatform/react/devsupport/inspector/InspectorThread.h +++ b/packages/react-native/ReactCxxPlatform/react/devsupport/inspector/InspectorThread.h @@ -16,13 +16,13 @@ class InspectorThread { public: InspectorThread() noexcept = default; virtual ~InspectorThread() = default; - InspectorThread(const InspectorThread& other) = delete; - InspectorThread& operator=(InspectorThread& other) = delete; - InspectorThread(InspectorThread&& other) = delete; - InspectorThread& operator=(InspectorThread&& other) = delete; + InspectorThread(const InspectorThread &other) = delete; + InspectorThread &operator=(InspectorThread &other) = delete; + InspectorThread(InspectorThread &&other) = delete; + InspectorThread &operator=(InspectorThread &&other) = delete; virtual void invokeElsePost( - TaskDispatchThread::TaskFn&& callback, + TaskDispatchThread::TaskFn &&callback, std::chrono::milliseconds delayMs = std::chrono::milliseconds(0)) = 0; }; diff --git a/packages/react-native/ReactCxxPlatform/react/http/IHttpClient.h b/packages/react-native/ReactCxxPlatform/react/http/IHttpClient.h index 5cd56007f88..045e279b08f 100644 --- a/packages/react-native/ReactCxxPlatform/react/http/IHttpClient.h +++ b/packages/react-native/ReactCxxPlatform/react/http/IHttpClient.h @@ -40,13 +40,9 @@ struct Body { using OnUploadProgress = std::function; using OnResponse = std::function; using OnBody = std::function body)>; -using OnBodyIncremental = std::function body)>; +using OnBodyIncremental = std::function body)>; using OnBodyProgress = std::function; -using OnResponseComplete = - std::function; +using OnResponseComplete = std::function; struct NetworkCallbacks { OnUploadProgress onUploadProgress{nullptr}; @@ -71,11 +67,11 @@ struct IHttpClient { virtual ~IHttpClient() = default; virtual std::unique_ptr sendRequest( - http::NetworkCallbacks&& callback, - const std::string& method, - const std::string& url, - const http::Headers& headers = {}, - const http::Body& body = {}, + http::NetworkCallbacks &&callback, + const std::string &method, + const std::string &url, + const http::Headers &headers = {}, + const http::Body &body = {}, uint32_t timeout = 0, std::optional loggingId = std::nullopt) = 0; }; diff --git a/packages/react-native/ReactCxxPlatform/react/http/IWebSocketClient.h b/packages/react-native/ReactCxxPlatform/react/http/IWebSocketClient.h index 9424fb76ab0..86aff58f4d3 100644 --- a/packages/react-native/ReactCxxPlatform/react/http/IWebSocketClient.h +++ b/packages/react-native/ReactCxxPlatform/react/http/IWebSocketClient.h @@ -15,23 +15,21 @@ namespace facebook::react { class IWebSocketClient { public: - using OnConnectCallback = std::function; - using OnClosedCallback = std::function; - using OnMessageCallback = std::function; + using OnConnectCallback = std::function; + using OnClosedCallback = std::function; + using OnMessageCallback = std::function; virtual ~IWebSocketClient() = default; - virtual void setOnClosedCallback(OnClosedCallback&& callback) noexcept = 0; + virtual void setOnClosedCallback(OnClosedCallback &&callback) noexcept = 0; - virtual void setOnMessageCallback(OnMessageCallback&& callback) noexcept = 0; + virtual void setOnMessageCallback(OnMessageCallback &&callback) noexcept = 0; - virtual void connect( - const std::string& url, - OnConnectCallback&& = nullptr) = 0; + virtual void connect(const std::string &url, OnConnectCallback && = nullptr) = 0; - virtual void close(const std::string& reason) = 0; + virtual void close(const std::string &reason) = 0; - virtual void send(const std::string& message) = 0; + virtual void send(const std::string &message) = 0; virtual void ping() = 0; }; @@ -40,8 +38,7 @@ extern const char WebSocketClientFactoryKey[]; extern const char DevToolsWebSocketClientFactoryKey[]; -using WebSocketClientFactory = - std::function()>; +using WebSocketClientFactory = std::function()>; WebSocketClientFactory getWebSocketClientFactory(); diff --git a/packages/react-native/ReactCxxPlatform/react/http/platform/cxx/WebSocketClient.h b/packages/react-native/ReactCxxPlatform/react/http/platform/cxx/WebSocketClient.h index 452f9a8f664..7c12c2acbd2 100644 --- a/packages/react-native/ReactCxxPlatform/react/http/platform/cxx/WebSocketClient.h +++ b/packages/react-native/ReactCxxPlatform/react/http/platform/cxx/WebSocketClient.h @@ -18,22 +18,20 @@ class WebSocketClient : public IWebSocketClient { public: WebSocketClient() noexcept; ~WebSocketClient() override; - WebSocketClient(WebSocketClient& other) = delete; - WebSocketClient& operator=(WebSocketClient& other) = delete; - WebSocketClient(WebSocketClient&& other) = delete; - WebSocketClient& operator=(WebSocketClient&& other) = delete; + WebSocketClient(WebSocketClient &other) = delete; + WebSocketClient &operator=(WebSocketClient &other) = delete; + WebSocketClient(WebSocketClient &&other) = delete; + WebSocketClient &operator=(WebSocketClient &&other) = delete; - void setOnClosedCallback(OnClosedCallback&& callback) noexcept override; + void setOnClosedCallback(OnClosedCallback &&callback) noexcept override; - void setOnMessageCallback(OnMessageCallback&& callback) noexcept override; + void setOnMessageCallback(OnMessageCallback &&callback) noexcept override; - void connect( - const std::string& url, - OnConnectCallback&& onConnectCallback = nullptr) override; + void connect(const std::string &url, OnConnectCallback &&onConnectCallback = nullptr) override; - void close(const std::string& reason) override; + void close(const std::string &reason) override; - void send(const std::string& message) override; + void send(const std::string &message) override; void ping() override; diff --git a/packages/react-native/ReactCxxPlatform/react/io/IImageLoader.h b/packages/react-native/ReactCxxPlatform/react/io/IImageLoader.h index c1a4bcec769..8362646682f 100644 --- a/packages/react-native/ReactCxxPlatform/react/io/IImageLoader.h +++ b/packages/react-native/ReactCxxPlatform/react/io/IImageLoader.h @@ -12,8 +12,7 @@ namespace facebook::react { -using IImageLoaderOnLoadCallback = std::function< - void(double imageWidth, double imageHeight, const char* errorMessage)>; +using IImageLoaderOnLoadCallback = std::function; class IImageLoader { public: @@ -25,11 +24,9 @@ class IImageLoader { virtual ~IImageLoader() = default; - virtual void loadImage( - const std::string& uri, - const IImageLoaderOnLoadCallback&& onLoad) = 0; + virtual void loadImage(const std::string &uri, const IImageLoaderOnLoadCallback &&onLoad) = 0; - virtual CacheStatus getCacheStatus(const std::string& uri) = 0; + virtual CacheStatus getCacheStatus(const std::string &uri) = 0; }; } // namespace facebook::react diff --git a/packages/react-native/ReactCxxPlatform/react/io/ImageLoaderModule.h b/packages/react-native/ReactCxxPlatform/react/io/ImageLoaderModule.h index 209564efc45..0966a70af3b 100644 --- a/packages/react-native/ReactCxxPlatform/react/io/ImageLoaderModule.h +++ b/packages/react-native/ReactCxxPlatform/react/io/ImageLoaderModule.h @@ -21,34 +21,27 @@ class IImageLoader; using ImageSize = NativeImageLoaderAndroidImageSize; template <> -struct Bridging - : NativeImageLoaderAndroidImageSizeBridging {}; +struct Bridging : NativeImageLoaderAndroidImageSizeBridging {}; -class ImageLoaderModule - : public NativeImageLoaderAndroidCxxSpec { +class ImageLoaderModule : public NativeImageLoaderAndroidCxxSpec { public: explicit ImageLoaderModule( std::shared_ptr jsInvoker, std::weak_ptr imageLoader = std::weak_ptr()) - : NativeImageLoaderAndroidCxxSpec(jsInvoker), - imageLoader_(std::move(imageLoader)) {} + : NativeImageLoaderAndroidCxxSpec(jsInvoker), imageLoader_(std::move(imageLoader)) + { + } - jsi::Object getConstants(jsi::Runtime& rt); - void abortRequest(jsi::Runtime& rt, int32_t requestId); + jsi::Object getConstants(jsi::Runtime &rt); + void abortRequest(jsi::Runtime &rt, int32_t requestId); - AsyncPromise getSize(jsi::Runtime& rt, const std::string& uri); + AsyncPromise getSize(jsi::Runtime &rt, const std::string &uri); - AsyncPromise getSizeWithHeaders( - jsi::Runtime& rt, - const std::string& uri, - jsi::Object headers); + AsyncPromise getSizeWithHeaders(jsi::Runtime &rt, const std::string &uri, jsi::Object headers); - AsyncPromise - prefetchImage(jsi::Runtime& rt, const std::string& uri, int32_t requestId); + AsyncPromise prefetchImage(jsi::Runtime &rt, const std::string &uri, int32_t requestId); - jsi::Object queryCache( - jsi::Runtime& rt, - const std::vector& uris); + jsi::Object queryCache(jsi::Runtime &rt, const std::vector &uris); private: std::weak_ptr imageLoader_; diff --git a/packages/react-native/ReactCxxPlatform/react/io/NetworkingModule.h b/packages/react-native/ReactCxxPlatform/react/io/NetworkingModule.h index e2e09005a7b..0d67e3b302d 100644 --- a/packages/react-native/ReactCxxPlatform/react/io/NetworkingModule.h +++ b/packages/react-native/ReactCxxPlatform/react/io/NetworkingModule.h @@ -17,41 +17,26 @@ namespace facebook::react { template <> struct Bridging { - static http::FormDataField fromJs( - jsi::Runtime& rt, - const jsi::Object& value, - const std::shared_ptr& jsInvoker) { - auto fieldName = bridging::fromJs( - rt, value.getProperty(rt, "fieldName"), jsInvoker); - auto headers = bridging::fromJs( - rt, value.getProperty(rt, "headers"), jsInvoker); - auto string = bridging::fromJs>( - rt, value.getProperty(rt, "string"), jsInvoker); - auto uri = bridging::fromJs>( - rt, value.getProperty(rt, "uri"), jsInvoker); - return http::FormDataField{ - .fieldName = fieldName, - .headers = headers, - .string = string, - .uri = uri}; + static http::FormDataField + fromJs(jsi::Runtime &rt, const jsi::Object &value, const std::shared_ptr &jsInvoker) + { + auto fieldName = bridging::fromJs(rt, value.getProperty(rt, "fieldName"), jsInvoker); + auto headers = bridging::fromJs(rt, value.getProperty(rt, "headers"), jsInvoker); + auto string = bridging::fromJs>(rt, value.getProperty(rt, "string"), jsInvoker); + auto uri = bridging::fromJs>(rt, value.getProperty(rt, "uri"), jsInvoker); + return http::FormDataField{.fieldName = fieldName, .headers = headers, .string = string, .uri = uri}; } }; template <> struct Bridging { - static http::Body fromJs( - jsi::Runtime& rt, - const jsi::Object& value, - const std::shared_ptr& jsInvoker) { + static http::Body fromJs(jsi::Runtime &rt, const jsi::Object &value, const std::shared_ptr &jsInvoker) + { return http::Body{ - .string = bridging::fromJs>( - rt, value.getProperty(rt, "string"), jsInvoker), - .blob = bridging::fromJs>( - rt, value.getProperty(rt, "blob"), jsInvoker), - .formData = bridging::fromJs>( - rt, value.getProperty(rt, "formData"), jsInvoker), - .base64 = bridging::fromJs>( - rt, value.getProperty(rt, "base64"), jsInvoker), + .string = bridging::fromJs>(rt, value.getProperty(rt, "string"), jsInvoker), + .blob = bridging::fromJs>(rt, value.getProperty(rt, "blob"), jsInvoker), + .formData = bridging::fromJs>(rt, value.getProperty(rt, "formData"), jsInvoker), + .base64 = bridging::fromJs>(rt, value.getProperty(rt, "base64"), jsInvoker), }; } @@ -61,10 +46,10 @@ class Requests { public: Requests() noexcept = default; ~Requests(); - Requests(Requests& other) = delete; - Requests& operator=(Requests& other) = delete; - Requests(Requests&& other) = delete; - Requests& operator=(Requests&& other) = delete; + Requests(Requests &other) = delete; + Requests &operator=(Requests &other) = delete; + Requests(Requests &&other) = delete; + Requests &operator=(Requests &&other) = delete; bool reserve(uint32_t id); void store(uint32_t id, std::unique_ptr token); @@ -80,35 +65,32 @@ class Requests { }; // Implementation of "Networking" TurboModule -class NetworkingModule - : public NativeNetworkingAndroidCxxSpec, - public std::enable_shared_from_this { +class NetworkingModule : public NativeNetworkingAndroidCxxSpec, + public std::enable_shared_from_this { public: - NetworkingModule( - std::shared_ptr jsInvoker, - const HttpClientFactory& httpClientFactory); + NetworkingModule(std::shared_ptr jsInvoker, const HttpClientFactory &httpClientFactory); ~NetworkingModule() override; void sendRequest( - jsi::Runtime& rt, - const std::string& method, - const std::string& url, + jsi::Runtime &rt, + const std::string &method, + const std::string &url, uint32_t requestId, - const http::Headers& headers, - const http::Body& body, - const std::string& responseType, + const http::Headers &headers, + const http::Body &body, + const std::string &responseType, bool useIncrementalUpdates, uint32_t timeout, bool withCredentials); - void abortRequest(jsi::Runtime& rt, uint32_t requestId); + void abortRequest(jsi::Runtime &rt, uint32_t requestId); - void clearCookies(jsi::Runtime& rt, const AsyncCallback& callback); + void clearCookies(jsi::Runtime &rt, const AsyncCallback &callback); // RCTEventEmitter - void addListener(jsi::Runtime& rt, const std::string& eventName); - void removeListeners(jsi::Runtime& rt, uint32_t count); + void addListener(jsi::Runtime &rt, const std::string &eventName); + void removeListeners(jsi::Runtime &rt, uint32_t count); private: void didSendNetworkData(uint32_t requestId, int64_t progress, int64_t total); @@ -116,13 +98,10 @@ class NetworkingModule void didReceiveNetworkResponse( uint32_t requestId, uint32_t statusCode, - const http::Headers& headers, - const std::string& responseUrl) noexcept; + const http::Headers &headers, + const std::string &responseUrl) noexcept; - void didReceiveNetworkData( - uint32_t requestId, - const std::string& responseType, - std::unique_ptr buf); + void didReceiveNetworkData(uint32_t requestId, const std::string &responseType, std::unique_ptr buf); int64_t didReceiveNetworkIncrementalData( uint32_t requestId, @@ -130,15 +109,9 @@ class NetworkingModule int64_t progress, int64_t total); - void didReceiveNetworkDataProgress( - uint32_t requestId, - int64_t bytesRead, - int64_t total); + void didReceiveNetworkDataProgress(uint32_t requestId, int64_t bytesRead, int64_t total); - void didCompleteNetworkResponse( - uint32_t requestId, - const std::string& error, - bool timeoutError); + void didCompleteNetworkResponse(uint32_t requestId, const std::string &error, bool timeoutError); std::unique_ptr httpClient_; Requests requests_; diff --git a/packages/react-native/ReactCxxPlatform/react/io/ResourceLoader.h b/packages/react-native/ReactCxxPlatform/react/io/ResourceLoader.h index d4aa4f4c560..870213964c9 100644 --- a/packages/react-native/ReactCxxPlatform/react/io/ResourceLoader.h +++ b/packages/react-native/ReactCxxPlatform/react/io/ResourceLoader.h @@ -13,17 +13,16 @@ namespace facebook::react { class ResourceLoader { public: - static bool isDirectory(const std::string& path); - static bool isFile(const std::string& path); - static bool isAbsolutePath(const std::string& path); - static std::string getFileContents(const std::string& path); - static std::filesystem::path getCacheDirectory( - const std::string& path = std::string()); + static bool isDirectory(const std::string &path); + static bool isFile(const std::string &path); + static bool isAbsolutePath(const std::string &path); + static std::string getFileContents(const std::string &path); + static std::filesystem::path getCacheDirectory(const std::string &path = std::string()); protected: - static bool isResourceDirectory(const std::string& path); - static bool isResourceFile(const std::string& path); - static std::string getResourceFileContents(const std::string& path); + static bool isResourceDirectory(const std::string &path); + static bool isResourceFile(const std::string &path); + static std::string getResourceFileContents(const std::string &path); private: static constexpr const auto CACHE_DIR = ".react-native-cxx-cache"; diff --git a/packages/react-native/ReactCxxPlatform/react/io/WebSocketModule.h b/packages/react-native/ReactCxxPlatform/react/io/WebSocketModule.h index f12ca1af328..8ade7372dfc 100644 --- a/packages/react-native/ReactCxxPlatform/react/io/WebSocketModule.h +++ b/packages/react-native/ReactCxxPlatform/react/io/WebSocketModule.h @@ -21,40 +21,31 @@ class IWebSocketClient; class WebSocketModule : public NativeWebSocketModuleCxxSpec, public std::enable_shared_from_this { public: - WebSocketModule( - std::shared_ptr jsInvoker, - WebSocketClientFactory webSocketClientFactory); + WebSocketModule(std::shared_ptr jsInvoker, WebSocketClientFactory webSocketClientFactory); ~WebSocketModule() override; - WebSocketModule(const WebSocketModule& other) = delete; - WebSocketModule& operator=(WebSocketModule& other) = delete; - WebSocketModule(WebSocketModule&& other) = delete; - WebSocketModule& operator=(WebSocketModule&& other) = delete; + WebSocketModule(const WebSocketModule &other) = delete; + WebSocketModule &operator=(WebSocketModule &other) = delete; + WebSocketModule(WebSocketModule &&other) = delete; + WebSocketModule &operator=(WebSocketModule &&other) = delete; void connect( - jsi::Runtime& rt, - const std::string& url, - const std::optional>& protocols, + jsi::Runtime &rt, + const std::string &url, + const std::optional> &protocols, jsi::Object options, int32_t socketID); - void send(jsi::Runtime& rt, const std::string& message, int32_t socketID); + void send(jsi::Runtime &rt, const std::string &message, int32_t socketID); - void sendBinary( - jsi::Runtime& rt, - const std::string& base64String, - int32_t socketID); + void sendBinary(jsi::Runtime &rt, const std::string &base64String, int32_t socketID); - void ping(jsi::Runtime& rt, int32_t socketID); + void ping(jsi::Runtime &rt, int32_t socketID); - void close( - jsi::Runtime& rt, - int32_t code, - const std::string& reason, - int32_t socketID); + void close(jsi::Runtime &rt, int32_t code, const std::string &reason, int32_t socketID); - void addListener(jsi::Runtime& rt, const std::string& eventName); + void addListener(jsi::Runtime &rt, const std::string &eventName); - void removeListeners(jsi::Runtime& rt, int32_t count); + void removeListeners(jsi::Runtime &rt, int32_t count); private: WebSocketClientFactory webSocketClientFactory_; diff --git a/packages/react-native/ReactCxxPlatform/react/io/platform/android/AssetManagerHelpers.h b/packages/react-native/ReactCxxPlatform/react/io/platform/android/AssetManagerHelpers.h index 234cbd43393..8df2d98ca9e 100644 --- a/packages/react-native/ReactCxxPlatform/react/io/platform/android/AssetManagerHelpers.h +++ b/packages/react-native/ReactCxxPlatform/react/io/platform/android/AssetManagerHelpers.h @@ -14,8 +14,8 @@ namespace facebook::react { -AAssetManager* getJavaAssetManager(); +AAssetManager *getJavaAssetManager(); -bool isDirectoryNotEmpty(const std::string& path); +bool isDirectoryNotEmpty(const std::string &path); } // namespace facebook::react diff --git a/packages/react-native/ReactCxxPlatform/react/jni/JniHelper.h b/packages/react-native/ReactCxxPlatform/react/jni/JniHelper.h index 8db809186f3..b449ca25405 100644 --- a/packages/react-native/ReactCxxPlatform/react/jni/JniHelper.h +++ b/packages/react-native/ReactCxxPlatform/react/jni/JniHelper.h @@ -12,7 +12,7 @@ namespace facebook::react { -jobject getApplication(JNIEnv* env); +jobject getApplication(JNIEnv *env); jni::alias_ref getContext(); diff --git a/packages/react-native/ReactCxxPlatform/react/logging/DefaultLogger.h b/packages/react-native/ReactCxxPlatform/react/logging/DefaultLogger.h index 8820d17cd93..d887dd168ba 100644 --- a/packages/react-native/ReactCxxPlatform/react/logging/DefaultLogger.h +++ b/packages/react-native/ReactCxxPlatform/react/logging/DefaultLogger.h @@ -12,8 +12,7 @@ namespace facebook::react { -using Logger = - std::function; +using Logger = std::function; Logger getDefaultLogger(); diff --git a/packages/react-native/ReactCxxPlatform/react/logging/DefaultOnJsErrorHandler.h b/packages/react-native/ReactCxxPlatform/react/logging/DefaultOnJsErrorHandler.h index d2d88fc8cb2..d512d2b006d 100644 --- a/packages/react-native/ReactCxxPlatform/react/logging/DefaultOnJsErrorHandler.h +++ b/packages/react-native/ReactCxxPlatform/react/logging/DefaultOnJsErrorHandler.h @@ -12,9 +12,9 @@ namespace facebook::react { -static inline JsErrorHandler::OnJsError getDefaultOnJsErrorFunc() { - return [](jsi::Runtime& /*runtime*/, - const JsErrorHandler::ProcessedError& error) { +static inline JsErrorHandler::OnJsError getDefaultOnJsErrorFunc() +{ + return [](jsi::Runtime & /*runtime*/, const JsErrorHandler::ProcessedError &error) { LOG(ERROR) << "[onJsError called]: " << error << std::endl; }; } diff --git a/packages/react-native/ReactCxxPlatform/react/logging/NativeExceptionsManager.cpp b/packages/react-native/ReactCxxPlatform/react/logging/NativeExceptionsManager.cpp index 344da5a7c15..ef920df59f5 100644 --- a/packages/react-native/ReactCxxPlatform/react/logging/NativeExceptionsManager.cpp +++ b/packages/react-native/ReactCxxPlatform/react/logging/NativeExceptionsManager.cpp @@ -46,11 +46,12 @@ void NativeExceptionsManager::reportException( std::vector frames; frames.reserve(data.stack.size()); for (const auto& frame : data.stack) { - frames.push_back(JsErrorHandler::ProcessedError::StackFrame{ - .file = frame.file, - .methodName = frame.methodName, - .lineNumber = frame.lineNumber, - .column = frame.column}); + frames.push_back( + JsErrorHandler::ProcessedError::StackFrame{ + .file = frame.file, + .methodName = frame.methodName, + .lineNumber = frame.lineNumber, + .column = frame.column}); } JsErrorHandler::ProcessedError processedError{ .message = data.message, diff --git a/packages/react-native/ReactCxxPlatform/react/logging/NativeExceptionsManager.h b/packages/react-native/ReactCxxPlatform/react/logging/NativeExceptionsManager.h index 685709ec5be..4dba94aa3f0 100644 --- a/packages/react-native/ReactCxxPlatform/react/logging/NativeExceptionsManager.h +++ b/packages/react-native/ReactCxxPlatform/react/logging/NativeExceptionsManager.h @@ -27,8 +27,7 @@ using StackFrame = NativeExceptionsManagerStackFrame< std::optional>; template <> -struct Bridging - : NativeExceptionsManagerStackFrameBridging {}; +struct Bridging : NativeExceptionsManagerStackFrameBridging {}; using ExceptionData = NativeExceptionsManagerExceptionData< std::string, @@ -41,42 +40,29 @@ using ExceptionData = NativeExceptionsManagerExceptionData< std::optional>>; template <> -struct Bridging - : NativeExceptionsManagerExceptionDataBridging {}; +struct Bridging : NativeExceptionsManagerExceptionDataBridging {}; -class NativeExceptionsManager - : public NativeExceptionsManagerCxxSpec { +class NativeExceptionsManager : public NativeExceptionsManagerCxxSpec { public: - NativeExceptionsManager( - JsErrorHandler::OnJsError onJsError, - std::shared_ptr jsInvoker) - : NativeExceptionsManagerCxxSpec(jsInvoker), - onJsError_(std::move(onJsError)) {} + NativeExceptionsManager(JsErrorHandler::OnJsError onJsError, std::shared_ptr jsInvoker) + : NativeExceptionsManagerCxxSpec(jsInvoker), onJsError_(std::move(onJsError)) + { + } - void reportFatalException( - jsi::Runtime& rt, - std::string message, - std::vector stack, - int32_t exceptionId); + void reportFatalException(jsi::Runtime &rt, std::string message, std::vector stack, int32_t exceptionId); - void reportSoftException( - jsi::Runtime& rt, - std::string message, - std::vector stack, - int32_t exceptionId); + void reportSoftException(jsi::Runtime &rt, std::string message, std::vector stack, int32_t exceptionId); - void reportException(jsi::Runtime& runtime, const ExceptionData& data); + void reportException(jsi::Runtime &runtime, const ExceptionData &data); - void updateExceptionMessage( - jsi::Runtime& rt, - jsi::String message, - jsi::Array stack, - double exceptionId) { + void updateExceptionMessage(jsi::Runtime &rt, jsi::String message, jsi::Array stack, double exceptionId) + { // This method is not in modern React Native: // https://github.com/search?q=repo%3Afacebook%2Freact-native+updateExceptionMessage&type=code } - void dismissRedbox(jsi::Runtime& rt) { + void dismissRedbox(jsi::Runtime &rt) + { // Redbox is not supported at this time, LogBox is: // https://reactnative.dev/blog/2020/07/06/version-0.63 } diff --git a/packages/react-native/ReactCxxPlatform/react/nativemodule/JavaScriptModule.h b/packages/react-native/ReactCxxPlatform/react/nativemodule/JavaScriptModule.h index 94e2dfe720a..5b038a00c2c 100644 --- a/packages/react-native/ReactCxxPlatform/react/nativemodule/JavaScriptModule.h +++ b/packages/react-native/ReactCxxPlatform/react/nativemodule/JavaScriptModule.h @@ -13,9 +13,7 @@ namespace facebook::react { -using JavaScriptModuleCallback = std::function; +using JavaScriptModuleCallback = + std::function; } // namespace facebook::react diff --git a/packages/react-native/ReactCxxPlatform/react/nativemodule/TurboModuleManager.h b/packages/react-native/ReactCxxPlatform/react/nativemodule/TurboModuleManager.h index 02a598ef3c9..bd8dce5e105 100644 --- a/packages/react-native/ReactCxxPlatform/react/nativemodule/TurboModuleManager.h +++ b/packages/react-native/ReactCxxPlatform/react/nativemodule/TurboModuleManager.h @@ -15,9 +15,8 @@ namespace facebook::react { -using TurboModuleManagerDelegate = std::function( - const std::string& name, - const std::shared_ptr& jsInvoker)>; +using TurboModuleManagerDelegate = + std::function(const std::string &name, const std::shared_ptr &jsInvoker)>; using TurboModuleManagerDelegates = std::vector; diff --git a/packages/react-native/ReactCxxPlatform/react/profiling/FrameStats.h b/packages/react-native/ReactCxxPlatform/react/profiling/FrameStats.h index 3c527f606bf..ec2d5340c3c 100644 --- a/packages/react-native/ReactCxxPlatform/react/profiling/FrameStats.h +++ b/packages/react-native/ReactCxxPlatform/react/profiling/FrameStats.h @@ -25,7 +25,8 @@ class TimeSeries; void enableFrameStatsPrinting(bool enable = true); void logFrameStats(double timeStampMs, double durationMs); -inline double getTimeStampMs() { +inline double getTimeStampMs() +{ return std::chrono::duration_cast( std::chrono::high_resolution_clock::now().time_since_epoch()) .count() / @@ -36,7 +37,8 @@ class FrameStatsBlock { public: FrameStatsBlock() : startTimeStamp_(getTimeStampMs()) {} - ~FrameStatsBlock() { + ~FrameStatsBlock() + { logFrameStats(startTimeStamp_, getTimeStampMs() - startTimeStamp_); } diff --git a/packages/react-native/ReactCxxPlatform/react/profiling/RuntimeHeapInfoCollector.cpp b/packages/react-native/ReactCxxPlatform/react/profiling/RuntimeHeapInfoCollector.cpp index 0bada4167aa..c838515c88a 100644 --- a/packages/react-native/ReactCxxPlatform/react/profiling/RuntimeHeapInfoCollector.cpp +++ b/packages/react-native/ReactCxxPlatform/react/profiling/RuntimeHeapInfoCollector.cpp @@ -17,8 +17,9 @@ RuntimeHeapInfoCollector::RuntimeHeapInfoCollector( std::chrono::milliseconds intervalMs) : intervalMs_(intervalMs) { if (intervalMs_ <= std::chrono::milliseconds::zero()) { - throw std::runtime_error(fmt::format( - "Invalid interval, must be > 0ms, got {} ms", intervalMs_.count())); + throw std::runtime_error( + fmt::format( + "Invalid interval, must be > 0ms, got {} ms", intervalMs_.count())); } lastCollectionTime_ = std::chrono::steady_clock::now(); diff --git a/packages/react-native/ReactCxxPlatform/react/profiling/RuntimeHeapInfoCollector.h b/packages/react-native/ReactCxxPlatform/react/profiling/RuntimeHeapInfoCollector.h index a941b55eff0..120c394fa77 100644 --- a/packages/react-native/ReactCxxPlatform/react/profiling/RuntimeHeapInfoCollector.h +++ b/packages/react-native/ReactCxxPlatform/react/profiling/RuntimeHeapInfoCollector.h @@ -20,9 +20,9 @@ struct HeapInfo { int64_t numCollections{0}; }; -inline std::ostream& operator<<(std::ostream& os, HeapInfo& heapInfo) { - os << "[heapInfo: allocatedBytes: " << heapInfo.allocatedBytes - << ", heapSize: " << heapInfo.heapSize +inline std::ostream &operator<<(std::ostream &os, HeapInfo &heapInfo) +{ + os << "[heapInfo: allocatedBytes: " << heapInfo.allocatedBytes << ", heapSize: " << heapInfo.heapSize << ", numCollections: " << heapInfo.numCollections << "]"; return os; } @@ -31,12 +31,12 @@ class RuntimeHeapInfoCollector { public: RuntimeHeapInfoCollector(std::chrono::milliseconds intervalMs); - static std::unique_ptr create( - std::chrono::milliseconds intervalMs); + static std::unique_ptr create(std::chrono::milliseconds intervalMs); - void collectHeapInfo(jsi::Runtime& runtime); + void collectHeapInfo(jsi::Runtime &runtime); - HeapInfo getHeapInfo() { + HeapInfo getHeapInfo() + { return heapInfo_; } diff --git a/packages/react-native/ReactCxxPlatform/react/profiling/TimeSeries.h b/packages/react-native/ReactCxxPlatform/react/profiling/TimeSeries.h index ac2878a1c3b..1e2ba3669df 100644 --- a/packages/react-native/ReactCxxPlatform/react/profiling/TimeSeries.h +++ b/packages/react-native/ReactCxxPlatform/react/profiling/TimeSeries.h @@ -20,15 +20,18 @@ class TimeSeries { int idxFrom2{0}; int idxTo2{0}; - int size() const { + int size() const + { return (idxTo1 - idxFrom1) + (idxTo2 - idxFrom2); } - bool isEmpty() const { + bool isEmpty() const + { return size() == 0; } - bool isContinuous() const { + bool isContinuous() const + { return idxTo2 - idxFrom2 == 0; } }; @@ -39,9 +42,10 @@ class TimeSeries { TimeSeries(int capacity = DEFAULT_CAPACITY); - bool operator==(const TimeSeries& rhs) const; + bool operator==(const TimeSeries &rhs) const; - int getCapacity() const { + int getCapacity() const + { return static_cast(times_.capacity()); } void setCapacity(int capacity); @@ -50,26 +54,31 @@ class TimeSeries { int findHistoryPointIndex(double t, Bound bound = Bound::Lower) const; - int getNumPoints() const { + int getNumPoints() const + { return static_cast(times_.size()); } - double& valueAtIndex(int idx) { + double &valueAtIndex(int idx) + { const int numPoints = getNumPoints(); return values_[(idx + position_) % numPoints]; } - double& timeAtIndex(int idx) { + double &timeAtIndex(int idx) + { const int numPoints = getNumPoints(); return times_[(idx + position_) % numPoints]; } - double valueAtIndex(int idx) const { + double valueAtIndex(int idx) const + { const int numPoints = getNumPoints(); return values_[(idx + position_) % numPoints]; } - double timeAtIndex(int idx) const { + double timeAtIndex(int idx) const + { const int numPoints = getNumPoints(); return times_[(idx + position_) % numPoints]; } @@ -81,8 +90,7 @@ class TimeSeries { double getValue(double time) const; double getPercentile(unsigned int percentile) const; - double getPercentile(unsigned int percentile, double timeFrom, double timeTo) - const; + double getPercentile(unsigned int percentile, double timeFrom, double timeTo) const; double getAverage() const; double getAverage(double timeFrom, double timeTo) const; @@ -101,10 +109,8 @@ class TimeSeries { double getMaxTime() const; double getMinTime() const; - friend std::ostream& operator<<(std::ostream& os, const TimeSeries& ts); - friend std::ostream& operator<<( - std::ostream& os, - const TimeSeries::Range& range); + friend std::ostream &operator<<(std::ostream &os, const TimeSeries &ts); + friend std::ostream &operator<<(std::ostream &os, const TimeSeries::Range &range); private: std::vector times_; @@ -115,11 +121,11 @@ class TimeSeries { Range findHistoryPointRange(double timeFrom, double timeTo) const; Range wholeRange() const; - double getPercentile(unsigned int percentile, const Range& range) const; - double getAverage(const Range& range) const; - double getMax(const Range& range) const; - double getMin(const Range& range) const; - double getSum(const Range& range) const; + double getPercentile(unsigned int percentile, const Range &range) const; + double getAverage(const Range &range) const; + double getMax(const Range &range) const; + double getMin(const Range &range) const; + double getSum(const Range &range) const; }; } // namespace facebook::react diff --git a/packages/react-native/ReactCxxPlatform/react/profiling/perfetto.h b/packages/react-native/ReactCxxPlatform/react/profiling/perfetto.h index f1b1ca9aa14..ea7fe39a956 100644 --- a/packages/react-native/ReactCxxPlatform/react/profiling/perfetto.h +++ b/packages/react-native/ReactCxxPlatform/react/profiling/perfetto.h @@ -24,7 +24,8 @@ PERFETTO_DEFINE_CATEGORIES_IN_NAMESPACE( void initializePerfetto(); -inline uint64_t getCurrentPerfettoTimestamp() { +inline uint64_t getCurrentPerfettoTimestamp() +{ return std::chrono::duration_cast( std::chrono::high_resolution_clock::now().time_since_epoch()) .count(); diff --git a/packages/react-native/ReactCxxPlatform/react/profiling/tracy_noop.h b/packages/react-native/ReactCxxPlatform/react/profiling/tracy_noop.h index 22f84d65442..40ec4d9e99d 100644 --- a/packages/react-native/ReactCxxPlatform/react/profiling/tracy_noop.h +++ b/packages/react-native/ReactCxxPlatform/react/profiling/tracy_noop.h @@ -26,16 +26,11 @@ static inline constexpr char kTraceCategory[] = "react_native"; HZT_DEFINE_TRACING_CATEGORIES( facebook::react, - horizon::tracing::Category( - kTraceCategory, - "react_native", - horizon::tracing::StrippingLevel::Important)); + horizon::tracing::Category(kTraceCategory, "react_native", horizon::tracing::StrippingLevel::Important)); -#define SCOPED_TRACE_CPU_AUTO() \ - HZT_TRACE_SCOPE_NS(::facebook::react, kTraceCategory, TRACE_FUNCTION); +#define SCOPED_TRACE_CPU_AUTO() HZT_TRACE_SCOPE_NS(::facebook::react, kTraceCategory, TRACE_FUNCTION); -#define SCOPED_TRACE_CPU(name) \ - HZT_TRACE_SCOPE_NS(::facebook::react, kTraceCategory, name); +#define SCOPED_TRACE_CPU(name) HZT_TRACE_SCOPE_NS(::facebook::react, kTraceCategory, name); #else #ifndef SCOPED_TRACE_CPU_AUTO diff --git a/packages/react-native/ReactCxxPlatform/react/renderer/scheduler/SchedulerDelegateImpl.h b/packages/react-native/ReactCxxPlatform/react/renderer/scheduler/SchedulerDelegateImpl.h index b9c4296be2d..2167e5fe143 100644 --- a/packages/react-native/ReactCxxPlatform/react/renderer/scheduler/SchedulerDelegateImpl.h +++ b/packages/react-native/ReactCxxPlatform/react/renderer/scheduler/SchedulerDelegateImpl.h @@ -16,48 +16,36 @@ class IMountingManager; class SchedulerDelegateImpl : public SchedulerDelegate { public: - SchedulerDelegateImpl( - std::shared_ptr mountingManager) noexcept; + SchedulerDelegateImpl(std::shared_ptr mountingManager) noexcept; ~SchedulerDelegateImpl() noexcept override = default; - SchedulerDelegateImpl(SchedulerDelegateImpl&&) noexcept = default; - SchedulerDelegateImpl& operator=(SchedulerDelegateImpl&&) noexcept = default; - SchedulerDelegateImpl(const SchedulerDelegateImpl&) = delete; - SchedulerDelegateImpl& operator=(const SchedulerDelegateImpl&) = delete; + SchedulerDelegateImpl(SchedulerDelegateImpl &&) noexcept = default; + SchedulerDelegateImpl &operator=(SchedulerDelegateImpl &&) noexcept = default; + SchedulerDelegateImpl(const SchedulerDelegateImpl &) = delete; + SchedulerDelegateImpl &operator=(const SchedulerDelegateImpl &) = delete; private: - void schedulerDidFinishTransaction( - const std::shared_ptr& mountingCoordinator) - override; + void schedulerDidFinishTransaction(const std::shared_ptr &mountingCoordinator) override; void schedulerShouldRenderTransactions( - const std::shared_ptr& mountingCoordinator) - override; + const std::shared_ptr &mountingCoordinator) override; - void schedulerDidRequestPreliminaryViewAllocation( - const ShadowNode& shadowNode) override; + void schedulerDidRequestPreliminaryViewAllocation(const ShadowNode &shadowNode) override; void schedulerDidDispatchCommand( - const ShadowView& shadowView, - const std::string& commandName, - const folly::dynamic& args) override; + const ShadowView &shadowView, + const std::string &commandName, + const folly::dynamic &args) override; - void schedulerDidSetIsJSResponder( - const ShadowView& shadowView, - bool isJSResponder, - bool blockNativeResponder) override; + void schedulerDidSetIsJSResponder(const ShadowView &shadowView, bool isJSResponder, bool blockNativeResponder) + override; - void schedulerDidSendAccessibilityEvent( - const ShadowView& shadowView, - const std::string& eventType) override; + void schedulerDidSendAccessibilityEvent(const ShadowView &shadowView, const std::string &eventType) override; - void schedulerShouldSynchronouslyUpdateViewOnUIThread( - Tag tag, - const folly::dynamic& props) override; + void schedulerShouldSynchronouslyUpdateViewOnUIThread(Tag tag, const folly::dynamic &props) override; - void schedulerDidUpdateShadowTree( - const std::unordered_map& tagToProps) override; + void schedulerDidUpdateShadowTree(const std::unordered_map &tagToProps) override; std::shared_ptr mountingManager_; }; diff --git a/packages/react-native/ReactCxxPlatform/react/renderer/uimanager/IMountingManager.h b/packages/react-native/ReactCxxPlatform/react/renderer/uimanager/IMountingManager.h index 1ffc7bc1d0e..6c8e9aebbfe 100644 --- a/packages/react-native/ReactCxxPlatform/react/renderer/uimanager/IMountingManager.h +++ b/packages/react-native/ReactCxxPlatform/react/renderer/uimanager/IMountingManager.h @@ -18,13 +18,11 @@ class Scheduler; class UIManager; class IImageLoader; -using SchedulerTask = std::function; -using SchedulerTaskExecutor = std::function; +using SchedulerTask = std::function; +using SchedulerTaskExecutor = std::function; -using EventEmitterListener = std::function; +using EventEmitterListener = + std::function; class IMountingManager { public: @@ -32,31 +30,21 @@ class IMountingManager { virtual ~IMountingManager() noexcept = default; - IMountingManager(IMountingManager&&) noexcept = default; - IMountingManager& operator=(IMountingManager&&) noexcept = default; - IMountingManager(const IMountingManager&) = delete; - IMountingManager& operator=(const IMountingManager&) = delete; + IMountingManager(IMountingManager &&) noexcept = default; + IMountingManager &operator=(IMountingManager &&) noexcept = default; + IMountingManager(const IMountingManager &) = delete; + IMountingManager &operator=(const IMountingManager &) = delete; - virtual void executeMount( - SurfaceId surfaceId, - MountingTransaction&& mountingTransaction) = 0; + virtual void executeMount(SurfaceId surfaceId, MountingTransaction &&mountingTransaction) = 0; - virtual void dispatchCommand( - const ShadowView& shadowView, - const std::string& commandName, - const folly::dynamic& args) = 0; + virtual void + dispatchCommand(const ShadowView &shadowView, const std::string &commandName, const folly::dynamic &args) = 0; - virtual void setIsJSResponder( - const ShadowView& shadowView, - bool isJSResponder, - bool blockNativeResponder) {}; + virtual void setIsJSResponder(const ShadowView &shadowView, bool isJSResponder, bool blockNativeResponder) {}; - virtual void synchronouslyUpdateViewOnUIThread( - Tag reactTag, - const folly::dynamic& changedProps) {}; + virtual void synchronouslyUpdateViewOnUIThread(Tag reactTag, const folly::dynamic &changedProps) {}; - virtual void onUpdateShadowTree( - const std::unordered_map& tagToProps) {}; + virtual void onUpdateShadowTree(const std::unordered_map &tagToProps) {}; virtual void initializeAccessibilityManager() {}; @@ -70,30 +58,30 @@ class IMountingManager { virtual void accessibleScrollInDirection(Tag viewTag, int direction) {}; - virtual void accessibleSetText(Tag viewTag, const std::string& text) {}; + virtual void accessibleSetText(Tag viewTag, const std::string &text) {}; virtual void clearFocusedView(Tag viewTag) {}; - virtual void setAfterMountCallback( - std::function&& onAfterMount) {}; + virtual void setAfterMountCallback(std::function &&onAfterMount) {}; - virtual ComponentRegistryFactory getComponentRegistryFactory() { + virtual ComponentRegistryFactory getComponentRegistryFactory() + { return nullptr; } - virtual bool hasComponent(const std::string& /*name*/) { + virtual bool hasComponent(const std::string & /*name*/) + { return false; } - virtual void setSchedulerTaskExecutor( - SchedulerTaskExecutor&& schedulerTaskExecutor) noexcept {}; + virtual void setSchedulerTaskExecutor(SchedulerTaskExecutor &&schedulerTaskExecutor) noexcept {}; - virtual void setEventEmitterListener( - std::shared_ptr listener) noexcept {}; + virtual void setEventEmitterListener(std::shared_ptr listener) noexcept {}; virtual void setUIManager(std::weak_ptr uiManager) noexcept {}; - virtual std::shared_ptr getImageLoader() noexcept { + virtual std::shared_ptr getImageLoader() noexcept + { return nullptr; } }; diff --git a/packages/react-native/ReactCxxPlatform/react/runtime/ReactHost.h b/packages/react-native/ReactCxxPlatform/react/runtime/ReactHost.h index ba5571aed09..9a02cddb9a7 100644 --- a/packages/react-native/ReactCxxPlatform/react/runtime/ReactHost.h +++ b/packages/react-native/ReactCxxPlatform/react/runtime/ReactHost.h @@ -50,32 +50,29 @@ class ReactHost { std::shared_ptr devUIDelegate = nullptr, TurboModuleManagerDelegates turboModuleManagerDelegates = {}, std::shared_ptr logBoxSurfaceDelegate = nullptr, - std::shared_ptr - animatedNodesManagerProvider = nullptr, + std::shared_ptr animatedNodesManagerProvider = nullptr, ReactInstance::BindingsInstallFunc bindingsInstallFunc = nullptr); - ReactHost(const ReactHost&) = delete; - ReactHost& operator=(const ReactHost&) = delete; - ReactHost(ReactHost&&) noexcept = delete; - ReactHost& operator=(ReactHost&&) noexcept = delete; + ReactHost(const ReactHost &) = delete; + ReactHost &operator=(const ReactHost &) = delete; + ReactHost(ReactHost &&) noexcept = delete; + ReactHost &operator=(ReactHost &&) noexcept = delete; ~ReactHost() noexcept; - bool loadScript( - const std::string& bundlePath, - const std::string& sourcePath) noexcept; + bool loadScript(const std::string &bundlePath, const std::string &sourcePath) noexcept; void openDebugger(); void startSurface( SurfaceId surfaceId, - const std::string& moduleName /* can be empty */, - const folly::dynamic& initialProps, - const LayoutConstraints& layoutConstraints, - const LayoutContext& layoutContext = {}) noexcept; + const std::string &moduleName /* can be empty */, + const folly::dynamic &initialProps, + const LayoutConstraints &layoutConstraints, + const LayoutContext &layoutContext = {}) noexcept; void setSurfaceConstraints( SurfaceId surfaceId, - const LayoutConstraints& layoutConstraints, - const LayoutContext& layoutContext) noexcept; + const LayoutConstraints &layoutConstraints, + const LayoutContext &layoutContext) noexcept; void stopSurface(SurfaceId surfaceId) noexcept; @@ -85,14 +82,13 @@ class ReactHost { std::unordered_set getRunningSurfaces() const noexcept; - void runOnScheduler(std::function&& task) const; + void runOnScheduler(std::function &&task) const; void runOnRuntimeScheduler( - std::function&& task, - SchedulerPriority priority = - SchedulerPriority::NormalPriority) const noexcept; + std::function &&task, + SchedulerPriority priority = SchedulerPriority::NormalPriority) const noexcept; - void emitDeviceEvent(folly::dynamic&& args); + void emitDeviceEvent(folly::dynamic &&args); private: void createReactInstance(); @@ -100,7 +96,7 @@ class ReactHost { void reloadReactInstance(); bool loadScriptFromDevServer(); - bool loadScriptFromBundlePath(const std::string& bundlePath); + bool loadScriptFromBundlePath(const std::string &bundlePath); const ReactInstanceConfig reactInstanceConfig_; std::unique_ptr reactInstanceData_; @@ -115,8 +111,7 @@ class ReactHost { std::shared_ptr inspector_; std::unique_ptr packagerConnection_; - std::shared_ptr - animatedMountingOverrideDelegate_; + std::shared_ptr animatedMountingOverrideDelegate_; }; } // namespace facebook::react diff --git a/packages/react-native/ReactCxxPlatform/react/runtime/platform/cxx/react/runtime/PlatformTimerRegistryImpl.h b/packages/react-native/ReactCxxPlatform/react/runtime/platform/cxx/react/runtime/PlatformTimerRegistryImpl.h index ea55f34e161..d1ae13a518f 100644 --- a/packages/react-native/ReactCxxPlatform/react/runtime/platform/cxx/react/runtime/PlatformTimerRegistryImpl.h +++ b/packages/react-native/ReactCxxPlatform/react/runtime/platform/cxx/react/runtime/PlatformTimerRegistryImpl.h @@ -19,12 +19,10 @@ namespace facebook::react { class PlatformTimerRegistryImpl : public PlatformTimerRegistry { public: PlatformTimerRegistryImpl() noexcept = default; - PlatformTimerRegistryImpl(const PlatformTimerRegistryImpl&) = delete; - PlatformTimerRegistryImpl& operator=(const PlatformTimerRegistryImpl&) = - delete; - PlatformTimerRegistryImpl(PlatformTimerRegistryImpl&&) noexcept = delete; - PlatformTimerRegistryImpl& operator=(PlatformTimerRegistryImpl&&) noexcept = - delete; + PlatformTimerRegistryImpl(const PlatformTimerRegistryImpl &) = delete; + PlatformTimerRegistryImpl &operator=(const PlatformTimerRegistryImpl &) = delete; + PlatformTimerRegistryImpl(PlatformTimerRegistryImpl &&) noexcept = delete; + PlatformTimerRegistryImpl &operator=(PlatformTimerRegistryImpl &&) noexcept = delete; ~PlatformTimerRegistryImpl() noexcept override; void createTimer(uint32_t timerId, double delayMs) override; @@ -47,10 +45,7 @@ class PlatformTimerRegistryImpl : public PlatformTimerRegistry { std::unordered_map timers_; std::mutex timersMutex_; - void createTimerInternal( - uint32_t timerID, - double delayMs, - bool isRecurring = false); + void createTimerInternal(uint32_t timerID, double delayMs, bool isRecurring = false); void startTimer(uint32_t timerId, double delayMs); }; diff --git a/packages/react-native/ReactCxxPlatform/react/threading/MessageQueueThreadImpl.h b/packages/react-native/ReactCxxPlatform/react/threading/MessageQueueThreadImpl.h index 2e95efdbd09..68b9dff74b7 100644 --- a/packages/react-native/ReactCxxPlatform/react/threading/MessageQueueThreadImpl.h +++ b/packages/react-native/ReactCxxPlatform/react/threading/MessageQueueThreadImpl.h @@ -13,8 +13,7 @@ namespace facebook::react { -using MessageQueueThreadFactory = - std::function()>; +using MessageQueueThreadFactory = std::function()>; constexpr char MessageQueueThreadFactoryKey[] = "MessageQueueThreadFactoryKey"; @@ -25,20 +24,19 @@ constexpr char MessageQueueThreadFactoryKey[] = "MessageQueueThreadFactoryKey"; class MessageQueueThreadImpl : public MessageQueueThread { public: MessageQueueThreadImpl() noexcept = default; - explicit MessageQueueThreadImpl(int priorityOffset) noexcept - : taskDispatchThread_("MessageQueue", priorityOffset) {} + explicit MessageQueueThreadImpl(int priorityOffset) noexcept : taskDispatchThread_("MessageQueue", priorityOffset) {} ~MessageQueueThreadImpl() noexcept override = default; /** Add a job to the queue asynchronously */ - void runOnQueue(std::function&& runnable) override; + void runOnQueue(std::function &&runnable) override; /** * Add a job to the queue synchronously - call won't return until runnable * has completed. Will run immediately if called from the looper thread. * Should only be used for initialization. */ - void runOnQueueSync(std::function&& runnable) override; + void runOnQueueSync(std::function &&runnable) override; /** * Stop the message queue thread. Should only be used for cleanup - once it diff --git a/packages/react-native/ReactCxxPlatform/react/threading/TaskDispatchThread.h b/packages/react-native/ReactCxxPlatform/react/threading/TaskDispatchThread.h index 6e377032372..6c637237bf2 100644 --- a/packages/react-native/ReactCxxPlatform/react/threading/TaskDispatchThread.h +++ b/packages/react-native/ReactCxxPlatform/react/threading/TaskDispatchThread.h @@ -26,9 +26,7 @@ class TaskDispatchThread { using TaskFn = std::function; using TimePoint = std::chrono::time_point; - TaskDispatchThread( - std::string threadName = "", - int priorityOffset = 0) noexcept; + TaskDispatchThread(std::string threadName = "", int priorityOffset = 0) noexcept; ~TaskDispatchThread() noexcept; @@ -39,13 +37,10 @@ class TaskDispatchThread { bool isRunning() noexcept; /** Add task to the queue and return immediately. */ - void runAsync( - TaskFn&& task, - std::chrono::milliseconds delayMs = - std::chrono::milliseconds::zero()) noexcept; + void runAsync(TaskFn &&task, std::chrono::milliseconds delayMs = std::chrono::milliseconds::zero()) noexcept; /** Add task to the queue and wait until it has completed. */ - void runSync(TaskFn&& task) noexcept; + void runSync(TaskFn &&task) noexcept; /** Shut down and clean up the thread. */ void quit() noexcept; @@ -55,10 +50,10 @@ class TaskDispatchThread { TimePoint dispatchTime; TaskFn fn; - Task(TimePoint dispatchTime, TaskFn&& fn) - : dispatchTime(dispatchTime), fn(std::move(fn)) {} + Task(TimePoint dispatchTime, TaskFn &&fn) : dispatchTime(dispatchTime), fn(std::move(fn)) {} - bool operator<(const Task& other) const { + bool operator<(const Task &other) const + { // Have the earliest tasks be at the front of the queue. return dispatchTime > other.dispatchTime; } diff --git a/packages/react-native/ReactCxxPlatform/react/utils/PlatformRunLoopObserver.h b/packages/react-native/ReactCxxPlatform/react/utils/PlatformRunLoopObserver.h index b50ac8170fd..69cafe56323 100644 --- a/packages/react-native/ReactCxxPlatform/react/utils/PlatformRunLoopObserver.h +++ b/packages/react-native/ReactCxxPlatform/react/utils/PlatformRunLoopObserver.h @@ -17,22 +17,24 @@ class PlatformRunLoopObserver; class PlatformRunLoopObserver : public RunLoopObserver { public: - PlatformRunLoopObserver( - RunLoopObserver::Activity activities, - const RunLoopObserver::WeakOwner& owner) - : RunLoopObserver(activities, owner) {} + PlatformRunLoopObserver(RunLoopObserver::Activity activities, const RunLoopObserver::WeakOwner &owner) + : RunLoopObserver(activities, owner) + { + } ~PlatformRunLoopObserver() override = default; - PlatformRunLoopObserver(PlatformRunLoopObserver& other) = delete; - PlatformRunLoopObserver& operator=(PlatformRunLoopObserver& other) = delete; - PlatformRunLoopObserver(PlatformRunLoopObserver&& other) = delete; - PlatformRunLoopObserver& operator=(PlatformRunLoopObserver&& other) = delete; + PlatformRunLoopObserver(PlatformRunLoopObserver &other) = delete; + PlatformRunLoopObserver &operator=(PlatformRunLoopObserver &other) = delete; + PlatformRunLoopObserver(PlatformRunLoopObserver &&other) = delete; + PlatformRunLoopObserver &operator=(PlatformRunLoopObserver &&other) = delete; - bool isOnRunLoopThread() const noexcept override { + bool isOnRunLoopThread() const noexcept override + { return false; } - void onRender() const noexcept { + void onRender() const noexcept + { if (auto owner = owner_.lock()) { activityDidChange(activities_); } diff --git a/packages/react-native/ReactCxxPlatform/react/utils/RunLoopObserverManager.h b/packages/react-native/ReactCxxPlatform/react/utils/RunLoopObserverManager.h index 1f565b1ccb4..f7b0f241e99 100644 --- a/packages/react-native/ReactCxxPlatform/react/utils/RunLoopObserverManager.h +++ b/packages/react-native/ReactCxxPlatform/react/utils/RunLoopObserverManager.h @@ -15,12 +15,11 @@ namespace facebook::react { -class RunLoopObserverManager - : std::enable_shared_from_this { +class RunLoopObserverManager : std::enable_shared_from_this { public: std::unique_ptr createEventBeat( std::shared_ptr ownerBox, - RuntimeScheduler& runtimeScheduler); + RuntimeScheduler &runtimeScheduler); void onRender() const noexcept; diff --git a/packages/rn-tester/NativeCxxModuleExample/NativeCxxModuleExample.cpp b/packages/rn-tester/NativeCxxModuleExample/NativeCxxModuleExample.cpp index 1a5c836259f..492c29a33b6 100644 --- a/packages/rn-tester/NativeCxxModuleExample/NativeCxxModuleExample.cpp +++ b/packages/rn-tester/NativeCxxModuleExample/NativeCxxModuleExample.cpp @@ -186,10 +186,11 @@ void NativeCxxModuleExample::voidFunc(jsi::Runtime& /*rt*/) { emitOnPress(); emitOnClick("value from callback on click!"); emitOnChange(ObjectStruct{1, "two", std::nullopt}); - emitOnSubmit(std::vector{ - ObjectStruct{1, "two", std::nullopt}, - ObjectStruct{3, "four", std::nullopt}, - ObjectStruct{5, "six", std::nullopt}}); + emitOnSubmit( + std::vector{ + ObjectStruct{1, "two", std::nullopt}, + ObjectStruct{3, "four", std::nullopt}, + ObjectStruct{5, "six", std::nullopt}}); emitOnEvent(NativeCxxModuleExampleEnumNone::NA); } @@ -217,13 +218,14 @@ void NativeCxxModuleExample::emitCustomDeviceEvent( eventName, [jsInvoker = jsInvoker_]( jsi::Runtime& rt, std::vector& args) { - args.emplace_back(jsi::Array::createWithElements( - rt, - jsi::Value(true), - jsi::Value(42), - jsi::String::createFromAscii(rt, "stringArg"), - bridging::toJs( - rt, CustomDeviceEvent{"one", 2, std::nullopt}, jsInvoker))); + args.emplace_back( + jsi::Array::createWithElements( + rt, + jsi::Value(true), + jsi::Value(42), + jsi::String::createFromAscii(rt, "stringArg"), + bridging::toJs( + rt, CustomDeviceEvent{"one", 2, std::nullopt}, jsInvoker))); }); } diff --git a/packages/rn-tester/NativeCxxModuleExample/NativeCxxModuleExample.h b/packages/rn-tester/NativeCxxModuleExample/NativeCxxModuleExample.h index b250f125341..9c2ce01677b 100644 --- a/packages/rn-tester/NativeCxxModuleExample/NativeCxxModuleExample.h +++ b/packages/rn-tester/NativeCxxModuleExample/NativeCxxModuleExample.h @@ -23,35 +23,28 @@ namespace facebook::react { #pragma mark - Structs -using ConstantsStruct = - NativeCxxModuleExampleConstantsStruct; +using ConstantsStruct = NativeCxxModuleExampleConstantsStruct; template <> -struct Bridging - : NativeCxxModuleExampleConstantsStructBridging {}; +struct Bridging : NativeCxxModuleExampleConstantsStructBridging {}; -using ObjectStruct = NativeCxxModuleExampleObjectStruct< - int32_t, - std::string, - std::optional>; +using ObjectStruct = NativeCxxModuleExampleObjectStruct>; template <> -struct Bridging - : NativeCxxModuleExampleObjectStructBridging {}; +struct Bridging : NativeCxxModuleExampleObjectStructBridging {}; -using ValueStruct = - NativeCxxModuleExampleValueStruct; +using ValueStruct = NativeCxxModuleExampleValueStruct; template <> -struct Bridging - : NativeCxxModuleExampleValueStructBridging {}; +struct Bridging : NativeCxxModuleExampleValueStructBridging {}; #pragma mark - enums enum class CustomEnumInt : int32_t { A = 23, B = 42 }; template <> struct Bridging { - static CustomEnumInt fromJs(jsi::Runtime& rt, jsi::Value rawValue) { + static CustomEnumInt fromJs(jsi::Runtime &rt, jsi::Value rawValue) + { auto value = static_cast(rawValue.asNumber()); if (value == 23) { return CustomEnumInt::A; @@ -62,7 +55,8 @@ struct Bridging { } } - static int32_t toJs(jsi::Runtime& rt, CustomEnumInt value) { + static int32_t toJs(jsi::Runtime &rt, CustomEnumInt value) + { return bridging::toJs(rt, static_cast(value)); } }; @@ -73,7 +67,8 @@ class HostObjectWrapper : public jsi::HostObject { public: HostObjectWrapper(std::shared_ptr value) : value_(std::move(value)) {} - std::shared_ptr getValue() const { + std::shared_ptr getValue() const + { return value_; } @@ -96,121 +91,96 @@ using CustomHostObject = HostObjectWrapper; using BinaryTreeNode = NativeCxxModuleExampleBinaryTreeNode; template <> -struct Bridging - : NativeCxxModuleExampleBinaryTreeNodeBridging {}; +struct Bridging : NativeCxxModuleExampleBinaryTreeNodeBridging {}; using GraphNode = NativeCxxModuleExampleGraphNode; template <> -struct Bridging - : NativeCxxModuleExampleGraphNodeBridging {}; +struct Bridging : NativeCxxModuleExampleGraphNodeBridging {}; #pragma mark - functional object properties -using MenuItem = NativeCxxModuleExampleMenuItem< - std::string, - AsyncCallback, - std::optional>; +using MenuItem = + NativeCxxModuleExampleMenuItem, std::optional>; template <> struct Bridging : NativeCxxModuleExampleMenuItemBridging {}; #pragma mark - RCTDeviceEventEmitter events -using CustomDeviceEvent = NativeCxxModuleExampleCustomDeviceEvent< - std::string, - int32_t, - std::optional>; +using CustomDeviceEvent = NativeCxxModuleExampleCustomDeviceEvent>; template <> -struct Bridging - : NativeCxxModuleExampleCustomDeviceEventBridging {}; +struct Bridging : NativeCxxModuleExampleCustomDeviceEventBridging {}; #pragma mark - implementation -class NativeCxxModuleExample - : public NativeCxxModuleExampleCxxSpec { +class NativeCxxModuleExample : public NativeCxxModuleExampleCxxSpec { public: NativeCxxModuleExample(std::shared_ptr jsInvoker); - void getValueWithCallback( - jsi::Runtime& rt, - const AsyncCallback& callback); + void getValueWithCallback(jsi::Runtime &rt, const AsyncCallback &callback); - std::function setValueCallbackWithSubscription( - jsi::Runtime& rt, - AsyncCallback callback); + std::function setValueCallbackWithSubscription(jsi::Runtime &rt, AsyncCallback callback); - std::vector> getArray( - jsi::Runtime& rt, - std::vector> arg); + std::vector> getArray(jsi::Runtime &rt, std::vector> arg); - bool getBool(jsi::Runtime& rt, bool arg); + bool getBool(jsi::Runtime &rt, bool arg); - ConstantsStruct getConstants(jsi::Runtime& rt); + ConstantsStruct getConstants(jsi::Runtime &rt); - CustomEnumInt getCustomEnum(jsi::Runtime& rt, CustomEnumInt arg); + CustomEnumInt getCustomEnum(jsi::Runtime &rt, CustomEnumInt arg); - std::shared_ptr getCustomHostObject(jsi::Runtime& rt); + std::shared_ptr getCustomHostObject(jsi::Runtime &rt); - std::string consumeCustomHostObject( - jsi::Runtime& rt, - std::shared_ptr arg); + std::string consumeCustomHostObject(jsi::Runtime &rt, std::shared_ptr arg); - BinaryTreeNode getBinaryTreeNode(jsi::Runtime& rt, BinaryTreeNode arg); + BinaryTreeNode getBinaryTreeNode(jsi::Runtime &rt, BinaryTreeNode arg); - GraphNode getGraphNode(jsi::Runtime& rt, GraphNode arg); + GraphNode getGraphNode(jsi::Runtime &rt, GraphNode arg); - NativeCxxModuleExampleEnumInt getNumEnum( - jsi::Runtime& rt, - NativeCxxModuleExampleEnumInt arg); + NativeCxxModuleExampleEnumInt getNumEnum(jsi::Runtime &rt, NativeCxxModuleExampleEnumInt arg); - NativeCxxModuleExampleEnumStr getStrEnum( - jsi::Runtime& rt, - NativeCxxModuleExampleEnumNone arg); + NativeCxxModuleExampleEnumStr getStrEnum(jsi::Runtime &rt, NativeCxxModuleExampleEnumNone arg); std::map> getMap( - jsi::Runtime& rt, + jsi::Runtime &rt, std::map> arg); - double getNumber(jsi::Runtime& rt, double arg); + double getNumber(jsi::Runtime &rt, double arg); - ObjectStruct getObject(jsi::Runtime& rt, ObjectStruct arg); + ObjectStruct getObject(jsi::Runtime &rt, ObjectStruct arg); - std::set getSet(jsi::Runtime& rt, std::set arg); + std::set getSet(jsi::Runtime &rt, std::set arg); - std::string getString(jsi::Runtime& rt, std::string arg); + std::string getString(jsi::Runtime &rt, std::string arg); - std::string - getUnion(jsi::Runtime& rt, float x, const std::string& y, jsi::Object z); + std::string getUnion(jsi::Runtime &rt, float x, const std::string &y, jsi::Object z); - ValueStruct - getValue(jsi::Runtime& rt, double x, std::string y, ObjectStruct z); + ValueStruct getValue(jsi::Runtime &rt, double x, std::string y, ObjectStruct z); - AsyncPromise getValueWithPromise(jsi::Runtime& rt, bool error); + AsyncPromise getValueWithPromise(jsi::Runtime &rt, bool error); - std::optional getWithWithOptionalArgs( - jsi::Runtime& rt, - std::optional optionalArg); + std::optional getWithWithOptionalArgs(jsi::Runtime &rt, std::optional optionalArg); - void voidFunc(jsi::Runtime& rt); + void voidFunc(jsi::Runtime &rt); - AsyncPromise<> voidPromise(jsi::Runtime& rt); + AsyncPromise<> voidPromise(jsi::Runtime &rt); - void setMenu(jsi::Runtime& rt, MenuItem menuItem); + void setMenu(jsi::Runtime &rt, MenuItem menuItem); - void emitCustomDeviceEvent(jsi::Runtime& rt, const std::string& eventName); + void emitCustomDeviceEvent(jsi::Runtime &rt, const std::string &eventName); - void voidFuncThrows(jsi::Runtime& rt); + void voidFuncThrows(jsi::Runtime &rt); - ObjectStruct getObjectThrows(jsi::Runtime& rt, const ObjectStruct& arg); + ObjectStruct getObjectThrows(jsi::Runtime &rt, const ObjectStruct &arg); - AsyncPromise<> promiseThrows(jsi::Runtime& rt); + AsyncPromise<> promiseThrows(jsi::Runtime &rt); - void voidFuncAssert(jsi::Runtime& rt); + void voidFuncAssert(jsi::Runtime &rt); - ObjectStruct getObjectAssert(jsi::Runtime& rt, const ObjectStruct& arg); + ObjectStruct getObjectAssert(jsi::Runtime &rt, const ObjectStruct &arg); - AsyncPromise<> promiseAssert(jsi::Runtime& rt); + AsyncPromise<> promiseAssert(jsi::Runtime &rt); private: std::optional> valueCallback_; diff --git a/packages/rn-tester/NativeModuleExample/Screenshot.mm b/packages/rn-tester/NativeModuleExample/Screenshot.mm index ceb28ac6d06..0ccb229d557 100644 --- a/packages/rn-tester/NativeModuleExample/Screenshot.mm +++ b/packages/rn-tester/NativeModuleExample/Screenshot.mm @@ -13,11 +13,9 @@ RCT_EXPORT_MODULE(); -RCT_EXPORT_METHOD(takeScreenshot - : (id /* NSString or NSNumber */)target withOptions - : (NSDictionary *)options resolve - : (RCTPromiseResolveBlock)resolve reject - : (RCTPromiseRejectBlock)reject) +RCT_EXPORT_METHOD( + takeScreenshot : (id /* NSString or NSNumber */)target withOptions : (NSDictionary *) + options resolve : (RCTPromiseResolveBlock)resolve reject : (RCTPromiseRejectBlock)reject) { [self.bridge.uiManager addUIBlock:^( __unused RCTUIManager *uiManager, NSDictionary *viewRegistry) { diff --git a/packages/rn-tester/RCTTest/RCTTestModule.mm b/packages/rn-tester/RCTTest/RCTTestModule.mm index ab797d55f89..cc2149a4582 100644 --- a/packages/rn-tester/RCTTest/RCTTestModule.mm +++ b/packages/rn-tester/RCTTest/RCTTestModule.mm @@ -137,16 +137,16 @@ RCT_EXPORT_METHOD(sendAppEvent : (NSString *)name body : (nullable id)body) #pragma clang diagnostic pop } -RCT_REMAP_METHOD(shouldResolve, shouldResolve_resolve - : (RCTPromiseResolveBlock)resolve reject - : (RCTPromiseRejectBlock)reject) +RCT_REMAP_METHOD( + shouldResolve, + shouldResolve_resolve : (RCTPromiseResolveBlock)resolve reject : (RCTPromiseRejectBlock)reject) { resolve(@1); } -RCT_REMAP_METHOD(shouldReject, shouldReject_resolve - : (RCTPromiseResolveBlock)resolve reject - : (RCTPromiseRejectBlock)reject) +RCT_REMAP_METHOD( + shouldReject, + shouldReject_resolve : (RCTPromiseResolveBlock)resolve reject : (RCTPromiseRejectBlock)reject) { reject(nil, nil, nil); } diff --git a/packages/rn-tester/RNTesterIntegrationTests/RNTesterTestModule.m b/packages/rn-tester/RNTesterIntegrationTests/RNTesterTestModule.m index cc444d4d181..119a34458c1 100644 --- a/packages/rn-tester/RNTesterIntegrationTests/RNTesterTestModule.m +++ b/packages/rn-tester/RNTesterIntegrationTests/RNTesterTestModule.m @@ -27,9 +27,8 @@ RCT_EXPORT_BLOCKING_SYNCHRONOUS_METHOD(methodThatReturnsNil) return nil; } -RCT_EXPORT_BLOCKING_SYNCHRONOUS_METHOD(methodThatCallsCallbackWithString - : (NSString *)input callback - : (RCTResponseSenderBlock)callback) +RCT_EXPORT_BLOCKING_SYNCHRONOUS_METHOD( + methodThatCallsCallbackWithString : (NSString *)input callback : (RCTResponseSenderBlock)callback) { callback(@[ input ]); return nil; diff --git a/packages/rn-tester/RNTesterUnitTests/RCTAllocationTests.m b/packages/rn-tester/RNTesterUnitTests/RCTAllocationTests.m index ed1f3a7e5da..a8d13468415 100644 --- a/packages/rn-tester/RNTesterUnitTests/RCTAllocationTests.m +++ b/packages/rn-tester/RNTesterUnitTests/RCTAllocationTests.m @@ -37,11 +37,9 @@ RCT_EXPORT_MODULE(); self.valid = NO; } -RCT_EXPORT_METHOD(test - : (__unused NSString *)a - : (__unused NSNumber *)b - : (__unused RCTResponseSenderBlock)c - : (__unused RCTResponseErrorBlock)d) +RCT_EXPORT_METHOD( + test : (__unused NSString *)a : (__unused NSNumber *)b : (__unused RCTResponseSenderBlock) + c : (__unused RCTResponseErrorBlock)d) { } diff --git a/private/react-native-fantom/tester/src/AppSettings.h b/private/react-native-fantom/tester/src/AppSettings.h index e1fb381998e..ea2279ae8b4 100644 --- a/private/react-native-fantom/tester/src/AppSettings.h +++ b/private/react-native-fantom/tester/src/AppSettings.h @@ -25,7 +25,7 @@ class AppSettings { static std::optional dynamicFeatureFlags; - static void init(int argc, char* argv[]); + static void init(int argc, char *argv[]); private: static void initInternal(); diff --git a/private/react-native-fantom/tester/src/FantomImageLoader.h b/private/react-native-fantom/tester/src/FantomImageLoader.h index 5dd09a2fbd3..695e8041efb 100644 --- a/private/react-native-fantom/tester/src/FantomImageLoader.h +++ b/private/react-native-fantom/tester/src/FantomImageLoader.h @@ -22,16 +22,14 @@ class FantomImageLoader : public IImageLoader { std::optional errorMessage; }; - void setImageResponse(const std::string& uri, ImageResponse imageResponse); - void clearImage(const std::string& uri); + void setImageResponse(const std::string &uri, ImageResponse imageResponse); + void clearImage(const std::string &uri); void clearAllImages(); // IImageLoader implementation - void loadImage( - const std::string& uri, - const IImageLoaderOnLoadCallback&& onLoad) override; + void loadImage(const std::string &uri, const IImageLoaderOnLoadCallback &&onLoad) override; - IImageLoader::CacheStatus getCacheStatus(const std::string& uri) override; + IImageLoader::CacheStatus getCacheStatus(const std::string &uri) override; private: std::unordered_map images_; diff --git a/private/react-native-fantom/tester/src/NativeFantom.h b/private/react-native-fantom/tester/src/NativeFantom.h index 5870a89751a..2c0a19a20fb 100644 --- a/private/react-native-fantom/tester/src/NativeFantom.h +++ b/private/react-native-fantom/tester/src/NativeFantom.h @@ -21,21 +21,20 @@ namespace facebook::react { class TesterAppDelegate; -using NativeFantomGetRenderedOutputRenderFormatOptions = - NativeFantomRenderFormatOptions< - // includeRoot - bool, - // includeLayoutMetrics - bool>; +using NativeFantomGetRenderedOutputRenderFormatOptions = NativeFantomRenderFormatOptions< + // includeRoot + bool, + // includeLayoutMetrics + bool>; template <> struct Bridging - : NativeFantomRenderFormatOptionsBridging< - NativeFantomGetRenderedOutputRenderFormatOptions> {}; + : NativeFantomRenderFormatOptionsBridging {}; template <> struct Bridging { - static RawEvent::Category fromJs(jsi::Runtime& rt, jsi::Value rawValue) { + static RawEvent::Category fromJs(jsi::Runtime &rt, jsi::Value rawValue) + { auto value = static_cast(rawValue.asNumber()); if (value == 0) { return RawEvent::Category::ContinuousStart; @@ -54,17 +53,16 @@ struct Bridging { } } - static jsi::Value toJs(jsi::Runtime& rt, RawEvent::Category value) { + static jsi::Value toJs(jsi::Runtime &rt, RawEvent::Category value) + { return bridging::toJs(rt, static_cast(value)); } }; -using ScrollOptions = - NativeFantomScrollOptions>; +using ScrollOptions = NativeFantomScrollOptions>; template <> -struct Bridging - : NativeFantomScrollOptionsBridging {}; +struct Bridging : NativeFantomScrollOptionsBridging {}; using NativeFantomSetImageResponseImageResponse = NativeFantomImageResponse< Float, // width @@ -73,102 +71,78 @@ using NativeFantomSetImageResponseImageResponse = NativeFantomImageResponse< std::optional>; // errorMessage template <> struct Bridging - : NativeFantomImageResponseBridging< - NativeFantomSetImageResponseImageResponse> {}; + : NativeFantomImageResponseBridging {}; class NativeFantom : public NativeFantomCxxSpec { public: - NativeFantom( - TesterAppDelegate& appDelegate, - std::shared_ptr jsInvoker); + NativeFantom(TesterAppDelegate &appDelegate, std::shared_ptr jsInvoker); SurfaceId startSurface( - jsi::Runtime& runtime, + jsi::Runtime &runtime, double viewportWidth, double viewportHeight, double devicePixelRatio, double viewportOffsetX, double viewportOffsetY); - void stopSurface(jsi::Runtime& runtime, SurfaceId surfaceId); + void stopSurface(jsi::Runtime &runtime, SurfaceId surfaceId); - void produceFramesForDuration(jsi::Runtime& runtime, double milliseconds); + void produceFramesForDuration(jsi::Runtime &runtime, double milliseconds); - void flushMessageQueue(jsi::Runtime& runtime); - void flushEventQueue(jsi::Runtime& runtime); - void validateEmptyMessageQueue(jsi::Runtime& runtime); + void flushMessageQueue(jsi::Runtime &runtime); + void flushEventQueue(jsi::Runtime &runtime); + void validateEmptyMessageQueue(jsi::Runtime &runtime); - std::vector takeMountingManagerLogs( - jsi::Runtime& runtime, - SurfaceId surfaceId); + std::vector takeMountingManagerLogs(jsi::Runtime &runtime, SurfaceId surfaceId); std::string getRenderedOutput( - jsi::Runtime& runtime, + jsi::Runtime &runtime, SurfaceId surfaceId, NativeFantomGetRenderedOutputRenderFormatOptions options); - void reportTestSuiteResultsJSON( - jsi::Runtime& runtime, - const std::string& testSuiteResultsJSON); + void reportTestSuiteResultsJSON(jsi::Runtime &runtime, const std::string &testSuiteResultsJSON); void enqueueNativeEvent( - jsi::Runtime& runtime, + jsi::Runtime &runtime, std::shared_ptr shadowNode, - const std::string& type, - const std::optional& payload, + const std::string &type, + const std::optional &payload, std::optional category, std::optional isUnique); - void enqueueScrollEvent( - jsi::Runtime& runtime, - std::shared_ptr shadowNode, - ScrollOptions options); + void enqueueScrollEvent(jsi::Runtime &runtime, std::shared_ptr shadowNode, ScrollOptions options); - jsi::Object getDirectManipulationProps( - jsi::Runtime& runtime, - const std::shared_ptr& shadowNode); + jsi::Object getDirectManipulationProps(jsi::Runtime &runtime, const std::shared_ptr &shadowNode); - jsi::Object getFabricUpdateProps( - jsi::Runtime& runtime, - const std::shared_ptr& shadowNode); + jsi::Object getFabricUpdateProps(jsi::Runtime &runtime, const std::shared_ptr &shadowNode); void enqueueModalSizeUpdate( - jsi::Runtime& runtime, + jsi::Runtime &runtime, std::shared_ptr shadowNode, double width, double height); - jsi::Function createShadowNodeReferenceCounter( - jsi::Runtime& runtime, - std::shared_ptr shadowNode); + jsi::Function createShadowNodeReferenceCounter(jsi::Runtime &runtime, std::shared_ptr shadowNode); - jsi::Function createShadowNodeRevisionGetter( - jsi::Runtime& runtime, - std::shared_ptr shadowNode); + jsi::Function createShadowNodeRevisionGetter(jsi::Runtime &runtime, std::shared_ptr shadowNode); - void saveJSMemoryHeapSnapshot( - jsi::Runtime& runtime, - const std::string& filePath); + void saveJSMemoryHeapSnapshot(jsi::Runtime &runtime, const std::string &filePath); - void forceHighResTimeStamp( - jsi::Runtime& runtime, - std::optional now); + void forceHighResTimeStamp(jsi::Runtime &runtime, std::optional now); - void startJSSamplingProfiler(jsi::Runtime& runtime); + void startJSSamplingProfiler(jsi::Runtime &runtime); - void stopJSSamplingProfilerAndSaveToFile( - jsi::Runtime& runtime, - const std::string& filePath); + void stopJSSamplingProfilerAndSaveToFile(jsi::Runtime &runtime, const std::string &filePath); void setImageResponse( - jsi::Runtime& rt, - const std::string& uri, - const NativeFantomSetImageResponseImageResponse& imageResponse); - void clearImage(jsi::Runtime& rt, const std::string& uri); - void clearAllImages(jsi::Runtime& rt); + jsi::Runtime &rt, + const std::string &uri, + const NativeFantomSetImageResponseImageResponse &imageResponse); + void clearImage(jsi::Runtime &rt, const std::string &uri); + void clearAllImages(jsi::Runtime &rt); private: - TesterAppDelegate& appDelegate_; + TesterAppDelegate &appDelegate_; SurfaceId nextSurfaceId_ = 1; }; diff --git a/private/react-native-fantom/tester/src/TesterAppDelegate.h b/private/react-native-fantom/tester/src/TesterAppDelegate.h index a07fb043855..b8dc581348d 100644 --- a/private/react-native-fantom/tester/src/TesterAppDelegate.h +++ b/private/react-native-fantom/tester/src/TesterAppDelegate.h @@ -27,21 +27,21 @@ class RunLoopObserverManager; class TesterAppDelegate { public: - TesterAppDelegate(const ReactInstanceConfig& reactInstanceConfig); + TesterAppDelegate(const ReactInstanceConfig &reactInstanceConfig); ~TesterAppDelegate(); // TesterAppDelegate is not copyable or movable. - TesterAppDelegate(const TesterAppDelegate&) = delete; - TesterAppDelegate& operator=(const TesterAppDelegate&) = delete; - TesterAppDelegate(TesterAppDelegate&&) = delete; - TesterAppDelegate& operator=(TesterAppDelegate&&) = delete; + TesterAppDelegate(const TesterAppDelegate &) = delete; + TesterAppDelegate &operator=(const TesterAppDelegate &) = delete; + TesterAppDelegate(TesterAppDelegate &&) = delete; + TesterAppDelegate &operator=(TesterAppDelegate &&) = delete; - void loadScript(const std::string& bundlePath, const std::string& sourcePath); + void loadScript(const std::string &bundlePath, const std::string &sourcePath); void openDebugger() const; void startSurface( - jsi::Runtime& runtime, + jsi::Runtime &runtime, float widthDp, float heightDp, SurfaceId surfaceId, @@ -49,11 +49,7 @@ class TesterAppDelegate { float viewportOffsetX = 0.0f, float viewportOffsetY = 0.0f); - void updateSurfaceConstraints( - SurfaceId surfaceId, - float widthDp, - float heightDp, - float pointScaleFactor); + void updateSurfaceConstraints(SurfaceId surfaceId, float widthDp, float heightDp, float pointScaleFactor); void stopSurface(SurfaceId surfaceId); diff --git a/private/react-native-fantom/tester/src/TesterMountingManager.h b/private/react-native-fantom/tester/src/TesterMountingManager.h index 2d8f908e5d9..cdfdf96d584 100644 --- a/private/react-native-fantom/tester/src/TesterMountingManager.h +++ b/private/react-native-fantom/tester/src/TesterMountingManager.h @@ -21,23 +21,16 @@ class IImageLoader; class TesterMountingManager : public IMountingManager { public: - TesterMountingManager(std::function&& onAfterMount); + TesterMountingManager(std::function &&onAfterMount); - void executeMount( - SurfaceId surfaceId, - MountingTransaction&& mountingTransaction) override; + void executeMount(SurfaceId surfaceId, MountingTransaction &&mountingTransaction) override; - void dispatchCommand( - const ShadowView& shadowView, - const std::string& commandName, - const folly::dynamic& args) override; + void dispatchCommand(const ShadowView &shadowView, const std::string &commandName, const folly::dynamic &args) + override; - void synchronouslyUpdateViewOnUIThread( - Tag reactTag, - const folly::dynamic& changedProps) override; + void synchronouslyUpdateViewOnUIThread(Tag reactTag, const folly::dynamic &changedProps) override; - void onUpdateShadowTree( - const std::unordered_map& tagToProps) override; + void onUpdateShadowTree(const std::unordered_map &tagToProps) override; ComponentRegistryFactory getComponentRegistryFactory() override; @@ -48,17 +41,20 @@ class TesterMountingManager : public IMountingManager { folly::dynamic getViewFabricUpdateProps(Tag tag) const; StubViewTree getViewTree(SurfaceId surfaceId); - void initViewTree(SurfaceId surfaceId, const StubViewTree& viewTree) { + void initViewTree(SurfaceId surfaceId, const StubViewTree &viewTree) + { viewTrees_[surfaceId] = viewTree; } std::shared_ptr imageLoader_; - std::shared_ptr getImageLoader() noexcept override { + std::shared_ptr getImageLoader() noexcept override + { return imageLoader_; } - std::unique_ptr& renderer() { + std::unique_ptr &renderer() + { return renderer_; } diff --git a/private/react-native-fantom/tester/src/render/RenderOutput.h b/private/react-native-fantom/tester/src/render/RenderOutput.h index d4d9e8775c3..81d3da93604 100644 --- a/private/react-native-fantom/tester/src/render/RenderOutput.h +++ b/private/react-native-fantom/tester/src/render/RenderOutput.h @@ -15,26 +15,21 @@ namespace facebook::react { class RenderOutput { public: - std::string render( - const StubViewTree& tree, - const RenderFormatOptions& options); + std::string render(const StubViewTree &tree, const RenderFormatOptions &options); - void markMutated(SurfaceId surfaceId) { + void markMutated(SurfaceId surfaceId) + { treesMutated_.insert(surfaceId); } private: - folly::dynamic renderView( - const StubView& view, - const RenderFormatOptions& options); + folly::dynamic renderView(const StubView &view, const RenderFormatOptions &options); #if RN_DEBUG_STRING_CONVERTIBLE - folly::dynamic renderProps(const SharedDebugStringConvertibleList& propsList); + folly::dynamic renderProps(const SharedDebugStringConvertibleList &propsList); #endif - folly::dynamic renderAttributedString( - const Tag& selfTag, - const AttributedString& string); + folly::dynamic renderAttributedString(const Tag &selfTag, const AttributedString &string); std::unordered_map renderedViews_{}; diff --git a/private/react-native-fantom/tester/src/stubs/StubClock.h b/private/react-native-fantom/tester/src/stubs/StubClock.h index a3c2ff43e33..b766700e70a 100644 --- a/private/react-native-fantom/tester/src/stubs/StubClock.h +++ b/private/react-native-fantom/tester/src/stubs/StubClock.h @@ -13,11 +13,13 @@ namespace facebook::react { class StubClock { public: - static std::chrono::steady_clock::time_point now() { + static std::chrono::steady_clock::time_point now() + { return timePoint_; } - static void advanceTimeBy(std::chrono::steady_clock::duration duration) { + static void advanceTimeBy(std::chrono::steady_clock::duration duration) + { timePoint_ += duration; } @@ -25,7 +27,6 @@ class StubClock { static std::chrono::steady_clock::time_point timePoint_; }; -std::chrono::steady_clock::time_point facebook::react::StubClock::timePoint_ = - std::chrono::steady_clock::now(); +std::chrono::steady_clock::time_point facebook::react::StubClock::timePoint_ = std::chrono::steady_clock::now(); } // namespace facebook::react diff --git a/private/react-native-fantom/tester/src/stubs/StubComponentRegistryFactory.h b/private/react-native-fantom/tester/src/stubs/StubComponentRegistryFactory.h index 7ea4a1647ee..f7b4a5861e7 100644 --- a/private/react-native-fantom/tester/src/stubs/StubComponentRegistryFactory.h +++ b/private/react-native-fantom/tester/src/stubs/StubComponentRegistryFactory.h @@ -19,30 +19,22 @@ namespace facebook::react { -inline ComponentRegistryFactory getDefaultComponentRegistryFactory() { - return [](const EventDispatcher::Weak& eventDispatcher, - const std::shared_ptr& contextContainer) { +inline ComponentRegistryFactory getDefaultComponentRegistryFactory() +{ + return [](const EventDispatcher::Weak &eventDispatcher, + const std::shared_ptr &contextContainer) { static auto providerRegistry = []() { - auto providerRegistry = - std::make_shared(); - providerRegistry->add( - concreteComponentDescriptorProvider()); - providerRegistry->add( - concreteComponentDescriptorProvider()); - providerRegistry->add( - concreteComponentDescriptorProvider()); - providerRegistry->add( - concreteComponentDescriptorProvider()); - providerRegistry->add( - concreteComponentDescriptorProvider()); - providerRegistry->add( - concreteComponentDescriptorProvider()); - providerRegistry->add(concreteComponentDescriptorProvider< - ModalHostViewComponentDescriptor>()); + auto providerRegistry = std::make_shared(); + providerRegistry->add(concreteComponentDescriptorProvider()); + providerRegistry->add(concreteComponentDescriptorProvider()); + providerRegistry->add(concreteComponentDescriptorProvider()); + providerRegistry->add(concreteComponentDescriptorProvider()); + providerRegistry->add(concreteComponentDescriptorProvider()); + providerRegistry->add(concreteComponentDescriptorProvider()); + providerRegistry->add(concreteComponentDescriptorProvider()); return providerRegistry; }(); - return providerRegistry->createComponentDescriptorRegistry( - {eventDispatcher, contextContainer, nullptr}); + return providerRegistry->createComponentDescriptorRegistry({eventDispatcher, contextContainer, nullptr}); }; } diff --git a/private/react-native-fantom/tester/src/stubs/StubHttpClient.h b/private/react-native-fantom/tester/src/stubs/StubHttpClient.h index 2750bde819c..ef6dbfe1c61 100644 --- a/private/react-native-fantom/tester/src/stubs/StubHttpClient.h +++ b/private/react-native-fantom/tester/src/stubs/StubHttpClient.h @@ -15,10 +15,10 @@ class StubRequestToken : public http::IRequestToken { public: StubRequestToken() = default; ~StubRequestToken() override = default; - StubRequestToken(StubRequestToken& other) = delete; - StubRequestToken& operator=(StubRequestToken& other) = delete; - StubRequestToken(StubRequestToken&& other) = delete; - StubRequestToken& operator=(StubRequestToken&& other) = delete; + StubRequestToken(StubRequestToken &other) = delete; + StubRequestToken &operator=(StubRequestToken &other) = delete; + StubRequestToken(StubRequestToken &&other) = delete; + StubRequestToken &operator=(StubRequestToken &&other) = delete; void cancel() noexcept override {} }; @@ -27,19 +27,20 @@ class StubHttpClient : public IHttpClient { public: StubHttpClient() = default; ~StubHttpClient() override = default; - StubHttpClient(StubHttpClient& other) = delete; - StubHttpClient& operator=(StubHttpClient& other) = delete; - StubHttpClient(StubHttpClient&& other) = delete; - StubHttpClient& operator=(StubHttpClient&& other) = delete; + StubHttpClient(StubHttpClient &other) = delete; + StubHttpClient &operator=(StubHttpClient &other) = delete; + StubHttpClient(StubHttpClient &&other) = delete; + StubHttpClient &operator=(StubHttpClient &&other) = delete; std::unique_ptr sendRequest( - http::NetworkCallbacks&& /*callback*/, - const std::string& /*method*/, - const std::string& /*url*/, - const http::Headers& /*headers*/ = {}, - const http::Body& /*body*/ = {}, + http::NetworkCallbacks && /*callback*/, + const std::string & /*method*/, + const std::string & /*url*/, + const http::Headers & /*headers*/ = {}, + const http::Body & /*body*/ = {}, uint32_t /*timeout*/ = 0, - std::optional /*loggingId*/ = std::nullopt) override { + std::optional /*loggingId*/ = std::nullopt) override + { return std::make_unique(); } }; diff --git a/private/react-native-fantom/tester/src/stubs/StubQueue.h b/private/react-native-fantom/tester/src/stubs/StubQueue.h index 175eaa309f5..83da413309d 100644 --- a/private/react-native-fantom/tester/src/stubs/StubQueue.h +++ b/private/react-native-fantom/tester/src/stubs/StubQueue.h @@ -16,9 +16,9 @@ namespace facebook::react { class StubQueue : public MessageQueueThread { public: - void runOnQueue(std::function&& func) override; + void runOnQueue(std::function &&func) override; - void runOnQueueSync(std::function&& runnable) override; + void runOnQueueSync(std::function &&runnable) override; void quitSynchronous() override; diff --git a/private/react-native-fantom/tester/src/stubs/StubWebSocketClient.h b/private/react-native-fantom/tester/src/stubs/StubWebSocketClient.h index 8dcaf802cb9..0cdf5189da1 100644 --- a/private/react-native-fantom/tester/src/stubs/StubWebSocketClient.h +++ b/private/react-native-fantom/tester/src/stubs/StubWebSocketClient.h @@ -15,22 +15,20 @@ class StubWebSocketClient : public IWebSocketClient { public: StubWebSocketClient() noexcept = default; ~StubWebSocketClient() override = default; - StubWebSocketClient(StubWebSocketClient& other) = delete; - StubWebSocketClient& operator=(StubWebSocketClient& other) = delete; - StubWebSocketClient(StubWebSocketClient&& other) = delete; - StubWebSocketClient& operator=(StubWebSocketClient&& other) = delete; + StubWebSocketClient(StubWebSocketClient &other) = delete; + StubWebSocketClient &operator=(StubWebSocketClient &other) = delete; + StubWebSocketClient(StubWebSocketClient &&other) = delete; + StubWebSocketClient &operator=(StubWebSocketClient &&other) = delete; - void setOnClosedCallback(OnClosedCallback&& callback) noexcept override {} + void setOnClosedCallback(OnClosedCallback &&callback) noexcept override {} - void setOnMessageCallback(OnMessageCallback&& callback) noexcept override {} + void setOnMessageCallback(OnMessageCallback &&callback) noexcept override {} - void connect( - const std::string& url, - OnConnectCallback&& onConnectCallback = nullptr) override {} + void connect(const std::string &url, OnConnectCallback &&onConnectCallback = nullptr) override {} - void close(const std::string& reason) override {} + void close(const std::string &reason) override {} - void send(const std::string& message) override {} + void send(const std::string &message) override {} void ping() override {} };