diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs new file mode 100644 index 000000000000..3455530b383e --- /dev/null +++ b/.git-blame-ignore-revs @@ -0,0 +1 @@ +# add clang-format commit SHA after merging diff --git a/packages/react-native-popup-menu-android/android/src/main/jni/ReactPopupMenuAndroidSpecs.h b/packages/react-native-popup-menu-android/android/src/main/jni/ReactPopupMenuAndroidSpecs.h index 251fb6983bfe..c890663ed1fe 100644 --- a/packages/react-native-popup-menu-android/android/src/main/jni/ReactPopupMenuAndroidSpecs.h +++ b/packages/react-native-popup-menu-android/android/src/main/jni/ReactPopupMenuAndroidSpecs.h @@ -1,9 +1,10 @@ /** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). + * This code was generated by + * [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. + * Do not edit this file as changes may cause incorrect behavior and will be + * lost once the code is regenerated. * * @generated by codegen project: GenerateModuleJniH.js */ @@ -16,9 +17,9 @@ namespace facebook::react { - - JSI_EXPORT -std::shared_ptr ReactPopupMenuAndroidSpecs_ModuleProvider(const std::string &moduleName, const JavaTurboModule::InitParams ¶ms); +std::shared_ptr ReactPopupMenuAndroidSpecs_ModuleProvider( + const std::string& moduleName, + const JavaTurboModule::InitParams& params); } // namespace facebook::react diff --git a/packages/react-native-popup-menu-android/android/src/main/jni/react/renderer/components/ReactPopupMenuAndroidSpecs/ComponentDescriptors.h b/packages/react-native-popup-menu-android/android/src/main/jni/react/renderer/components/ReactPopupMenuAndroidSpecs/ComponentDescriptors.h index 48fbdfabc578..ef83f91306c9 100644 --- a/packages/react-native-popup-menu-android/android/src/main/jni/react/renderer/components/ReactPopupMenuAndroidSpecs/ComponentDescriptors.h +++ b/packages/react-native-popup-menu-android/android/src/main/jni/react/renderer/components/ReactPopupMenuAndroidSpecs/ComponentDescriptors.h @@ -1,24 +1,26 @@ /** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). + * This code was generated by + * [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. + * Do not edit this file as changes may cause incorrect behavior and will be + * lost once the code is regenerated. * * @generated by codegen project: GenerateComponentDescriptorH.js */ #pragma once -#include "ShadowNodes.h" -#include #include +#include +#include "ShadowNodes.h" namespace facebook::react { -using AndroidPopupMenuComponentDescriptor = ConcreteComponentDescriptor; +using AndroidPopupMenuComponentDescriptor = + ConcreteComponentDescriptor; void rncore_registerComponentDescriptorsFromCodegen( - std::shared_ptr registry); + std::shared_ptr registry); } // namespace facebook::react diff --git a/packages/react-native-popup-menu-android/android/src/main/jni/react/renderer/components/ReactPopupMenuAndroidSpecs/EventEmitters.h b/packages/react-native-popup-menu-android/android/src/main/jni/react/renderer/components/ReactPopupMenuAndroidSpecs/EventEmitters.h index 94a01949d676..c3d161a79983 100644 --- a/packages/react-native-popup-menu-android/android/src/main/jni/react/renderer/components/ReactPopupMenuAndroidSpecs/EventEmitters.h +++ b/packages/react-native-popup-menu-android/android/src/main/jni/react/renderer/components/ReactPopupMenuAndroidSpecs/EventEmitters.h @@ -1,9 +1,10 @@ /** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). + * This code was generated by + * [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. + * Do not edit this file as changes may cause incorrect behavior and will be + * lost once the code is regenerated. * * @generated by codegen project: GenerateEventEmitterH.js */ @@ -11,19 +12,16 @@ #include - namespace facebook::react { class AndroidPopupMenuEventEmitter : public ViewEventEmitter { public: using ViewEventEmitter::ViewEventEmitter; struct OnPopupMenuSelectionChange { - int item; - }; + int item; + }; - struct OnPopupMenuDismiss { - - }; + struct OnPopupMenuDismiss {}; void onPopupMenuSelectionChange(OnPopupMenuSelectionChange value) const; void onPopupMenuDismiss(OnPopupMenuDismiss value) const; diff --git a/packages/react-native-popup-menu-android/android/src/main/jni/react/renderer/components/ReactPopupMenuAndroidSpecs/Props.h b/packages/react-native-popup-menu-android/android/src/main/jni/react/renderer/components/ReactPopupMenuAndroidSpecs/Props.h index 191f0b15776b..1ab76cb90146 100644 --- a/packages/react-native-popup-menu-android/android/src/main/jni/react/renderer/components/ReactPopupMenuAndroidSpecs/Props.h +++ b/packages/react-native-popup-menu-android/android/src/main/jni/react/renderer/components/ReactPopupMenuAndroidSpecs/Props.h @@ -1,9 +1,10 @@ /** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). + * This code was generated by + * [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. + * Do not edit this file as changes may cause incorrect behavior and will be + * lost once the code is regenerated. * * @generated by codegen project: GeneratePropsH.js */ @@ -18,7 +19,10 @@ namespace facebook::react { class AndroidPopupMenuProps final : public ViewProps { public: AndroidPopupMenuProps() = default; - AndroidPopupMenuProps(const PropsParserContext& context, const AndroidPopupMenuProps &sourceProps, const RawProps &rawProps); + AndroidPopupMenuProps( + const PropsParserContext& context, + const AndroidPopupMenuProps& sourceProps, + const RawProps& rawProps); #pragma mark - Props diff --git a/packages/react-native-popup-menu-android/android/src/main/jni/react/renderer/components/ReactPopupMenuAndroidSpecs/ShadowNodes.h b/packages/react-native-popup-menu-android/android/src/main/jni/react/renderer/components/ReactPopupMenuAndroidSpecs/ShadowNodes.h index 0fd9852b1bca..1e99cd3d508e 100644 --- a/packages/react-native-popup-menu-android/android/src/main/jni/react/renderer/components/ReactPopupMenuAndroidSpecs/ShadowNodes.h +++ b/packages/react-native-popup-menu-android/android/src/main/jni/react/renderer/components/ReactPopupMenuAndroidSpecs/ShadowNodes.h @@ -1,20 +1,21 @@ /** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). + * This code was generated by + * [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. + * Do not edit this file as changes may cause incorrect behavior and will be + * lost once the code is regenerated. * * @generated by codegen project: GenerateShadowNodeH.js */ #pragma once +#include +#include #include "EventEmitters.h" #include "Props.h" #include "States.h" -#include -#include namespace facebook::react { diff --git a/packages/react-native-popup-menu-android/android/src/main/jni/react/renderer/components/ReactPopupMenuAndroidSpecs/States.h b/packages/react-native-popup-menu-android/android/src/main/jni/react/renderer/components/ReactPopupMenuAndroidSpecs/States.h index de97a8fb38e4..60b690fcc67e 100644 --- a/packages/react-native-popup-menu-android/android/src/main/jni/react/renderer/components/ReactPopupMenuAndroidSpecs/States.h +++ b/packages/react-native-popup-menu-android/android/src/main/jni/react/renderer/components/ReactPopupMenuAndroidSpecs/States.h @@ -1,8 +1,9 @@ /** - * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). + * This code was generated by + * [react-native-codegen](https://www.npmjs.com/package/react-native-codegen). * - * Do not edit this file as changes may cause incorrect behavior and will be lost - * once the code is regenerated. + * Do not edit this file as changes may cause incorrect behavior and will be + * lost once the code is regenerated. * * @generated by codegen project: GenerateStateH.js */ @@ -17,11 +18,13 @@ namespace facebook::react { class AndroidPopupMenuState { -public: + public: AndroidPopupMenuState() = default; #ifdef RN_SERIALIZABLE_STATE - AndroidPopupMenuState(AndroidPopupMenuState const &previousState, folly::dynamic data){}; + AndroidPopupMenuState( + const AndroidPopupMenuState& previousState, + folly::dynamic data){}; folly::dynamic getDynamic() const { return {}; }; diff --git a/packages/react-native/Libraries/Blob/RCTBlobPlugins.h b/packages/react-native/Libraries/Blob/RCTBlobPlugins.h index 84e3e322d526..696d91ae2f6e 100644 --- a/packages/react-native/Libraries/Blob/RCTBlobPlugins.h +++ b/packages/react-native/Libraries/Blob/RCTBlobPlugins.h @@ -26,7 +26,7 @@ extern "C" { #endif // RCTTurboModuleManagerDelegate should call this to resolve module classes. -Class RCTBlobClassProvider(const char *name); +Class RCTBlobClassProvider(const char* name); // Lookup functions Class RCTBlobManagerCls(void) __attribute__((used)); diff --git a/packages/react-native/Libraries/FBLazyVector/FBLazyVector/FBLazyIterator.h b/packages/react-native/Libraries/FBLazyVector/FBLazyVector/FBLazyIterator.h index 50387bad32c0..dec884adc8cb 100644 --- a/packages/react-native/Libraries/FBLazyVector/FBLazyVector/FBLazyIterator.h +++ b/packages/react-native/Libraries/FBLazyVector/FBLazyVector/FBLazyIterator.h @@ -26,81 +26,68 @@ 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]); } @@ -111,26 +98,24 @@ 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 || 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 4d7090562061..46c2782bf9bd 100644 --- a/packages/react-native/Libraries/FBLazyVector/FBLazyVector/FBLazyVector.h +++ b/packages/react-native/Libraries/FBLazyVector/FBLazyVector/FBLazyVector.h @@ -31,28 +31,24 @@ 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"); @@ -63,47 +59,41 @@ 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/RCTImagePlugins.h b/packages/react-native/Libraries/Image/RCTImagePlugins.h index 03e18e23f799..ccb72e3d3f49 100644 --- a/packages/react-native/Libraries/Image/RCTImagePlugins.h +++ b/packages/react-native/Libraries/Image/RCTImagePlugins.h @@ -26,7 +26,7 @@ extern "C" { #endif // RCTTurboModuleManagerDelegate should call this to resolve module classes. -Class RCTImageClassProvider(const char *name); +Class RCTImageClassProvider(const char* name); // Lookup functions Class RCTBundleAssetImageLoaderCls(void) __attribute__((used)); diff --git a/packages/react-native/Libraries/LinkingIOS/RCTLinkingPlugins.h b/packages/react-native/Libraries/LinkingIOS/RCTLinkingPlugins.h index 4cf0a9b4ec48..231e5268b7ac 100644 --- a/packages/react-native/Libraries/LinkingIOS/RCTLinkingPlugins.h +++ b/packages/react-native/Libraries/LinkingIOS/RCTLinkingPlugins.h @@ -26,7 +26,7 @@ extern "C" { #endif // RCTTurboModuleManagerDelegate should call this to resolve module classes. -Class RCTLinkingClassProvider(const char *name); +Class RCTLinkingClassProvider(const char* name); // Lookup functions Class RCTLinkingManagerCls(void) __attribute__((used)); diff --git a/packages/react-native/Libraries/NativeAnimation/RCTAnimationPlugins.h b/packages/react-native/Libraries/NativeAnimation/RCTAnimationPlugins.h index 37e3cc8643c7..8cd0e3f2532c 100644 --- a/packages/react-native/Libraries/NativeAnimation/RCTAnimationPlugins.h +++ b/packages/react-native/Libraries/NativeAnimation/RCTAnimationPlugins.h @@ -26,7 +26,7 @@ extern "C" { #endif // RCTTurboModuleManagerDelegate should call this to resolve module classes. -Class RCTAnimationClassProvider(const char *name); +Class RCTAnimationClassProvider(const char* name); // Lookup functions Class RCTNativeAnimatedModuleCls(void) __attribute__((used)); diff --git a/packages/react-native/Libraries/Network/RCTNetworkPlugins.h b/packages/react-native/Libraries/Network/RCTNetworkPlugins.h index 7fcf4722f258..ddc19de9270b 100644 --- a/packages/react-native/Libraries/Network/RCTNetworkPlugins.h +++ b/packages/react-native/Libraries/Network/RCTNetworkPlugins.h @@ -26,7 +26,7 @@ extern "C" { #endif // RCTTurboModuleManagerDelegate should call this to resolve module classes. -Class RCTNetworkClassProvider(const char *name); +Class RCTNetworkClassProvider(const char* name); // Lookup functions Class RCTDataRequestHandlerCls(void) __attribute__((used)); diff --git a/packages/react-native/Libraries/PushNotificationIOS/RCTPushNotificationPlugins.h b/packages/react-native/Libraries/PushNotificationIOS/RCTPushNotificationPlugins.h index d25e019c14b3..4414a0624f38 100644 --- a/packages/react-native/Libraries/PushNotificationIOS/RCTPushNotificationPlugins.h +++ b/packages/react-native/Libraries/PushNotificationIOS/RCTPushNotificationPlugins.h @@ -9,7 +9,8 @@ #ifdef RN_DISABLE_OSS_PLUGIN_HEADER -// FB Internal: FBRCTPushNotificationPlugins.h is autogenerated by the build system. +// FB Internal: FBRCTPushNotificationPlugins.h is autogenerated by the build +// system. #import #else @@ -26,7 +27,7 @@ extern "C" { #endif // RCTTurboModuleManagerDelegate should call this to resolve module classes. -Class RCTPushNotificationClassProvider(const char *name); +Class RCTPushNotificationClassProvider(const char* name); // Lookup functions Class RCTPushNotificationManagerCls(void) __attribute__((used)); diff --git a/packages/react-native/Libraries/Required/RCTRequired.h b/packages/react-native/Libraries/Required/RCTRequired.h index 331b82a725a0..169cf00fb2dd 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,25 +67,21 @@ 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/Settings/RCTSettingsPlugins.h b/packages/react-native/Libraries/Settings/RCTSettingsPlugins.h index b6a5158a56ca..c780363f6c98 100644 --- a/packages/react-native/Libraries/Settings/RCTSettingsPlugins.h +++ b/packages/react-native/Libraries/Settings/RCTSettingsPlugins.h @@ -26,7 +26,7 @@ extern "C" { #endif // RCTTurboModuleManagerDelegate should call this to resolve module classes. -Class RCTSettingsClassProvider(const char *name); +Class RCTSettingsClassProvider(const char* name); // Lookup functions Class RCTSettingsManagerCls(void) __attribute__((used)); diff --git a/packages/react-native/Libraries/Vibration/RCTVibrationPlugins.h b/packages/react-native/Libraries/Vibration/RCTVibrationPlugins.h index 098c03afc615..40c0f1deab24 100644 --- a/packages/react-native/Libraries/Vibration/RCTVibrationPlugins.h +++ b/packages/react-native/Libraries/Vibration/RCTVibrationPlugins.h @@ -26,7 +26,7 @@ extern "C" { #endif // RCTTurboModuleManagerDelegate should call this to resolve module classes. -Class RCTVibrationClassProvider(const char *name); +Class RCTVibrationClassProvider(const char* name); // Lookup functions Class RCTVibrationCls(void) __attribute__((used)); diff --git a/packages/react-native/React/Base/RCTMockDef.h b/packages/react-native/React/Base/RCTMockDef.h index 65e6d2d913b3..38ee254ef7d2 100644 --- a/packages/react-native/React/Base/RCTMockDef.h +++ b/packages/react-native/React/Base/RCTMockDef.h @@ -44,9 +44,12 @@ */ #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/RCTRootView.h b/packages/react-native/React/Base/RCTRootView.h index 1501d30fadda..e0a37bc8a93f 100644 --- a/packages/react-native/React/Base/RCTRootView.h +++ b/packages/react-native/React/Base/RCTRootView.h @@ -40,7 +40,7 @@ extern NS_ASSUME_NONNULL_BEGIN - NSString *const RCTContentDidAppearNotification; + NSString *const RCTContentDidAppearNotification; /** * Native view used to host React-managed views within the app. Can be used just diff --git a/packages/react-native/React/Base/RCTUtils.h b/packages/react-native/React/Base/RCTUtils.h index abc8a851a5d8..b995f0d9a638 100644 --- a/packages/react-native/React/Base/RCTUtils.h +++ b/packages/react-native/React/Base/RCTUtils.h @@ -69,13 +69,13 @@ RCT_EXTERN BOOL RCTClassOverridesClassMethod(Class cls, SEL selector); RCT_EXTERN BOOL RCTClassOverridesInstanceMethod(Class cls, SEL selector); // Creates a standardized error object to return in callbacks -RCT_EXTERN NSDictionary * -RCTMakeError(NSString *message, id __nullable toStringify, NSDictionary *__nullable extraData); +RCT_EXTERN NSDictionary + *RCTMakeError(NSString *message, id __nullable toStringify, NSDictionary *__nullable extraData); RCT_EXTERN NSDictionary * RCTMakeAndLogError(NSString *message, id __nullable toStringify, NSDictionary *__nullable extraData); RCT_EXTERN NSDictionary *RCTJSErrorFromNSError(NSError *error); -RCT_EXTERN NSDictionary * -RCTJSErrorFromCodeMessageAndNSError(NSString *code, NSString *message, NSError *__nullable error); +RCT_EXTERN NSDictionary + *RCTJSErrorFromCodeMessageAndNSError(NSString *code, NSString *message, NSError *__nullable error); // The default error code to use as the `code` property for callback error objects RCT_EXTERN NSString *const RCTErrorUnspecified; diff --git a/packages/react-native/React/CoreModules/CoreModulesPlugins.h b/packages/react-native/React/CoreModules/CoreModulesPlugins.h index 618c5535d4c9..feca0fa5b6d5 100644 --- a/packages/react-native/React/CoreModules/CoreModulesPlugins.h +++ b/packages/react-native/React/CoreModules/CoreModulesPlugins.h @@ -26,7 +26,7 @@ extern "C" { #endif // RCTTurboModuleManagerDelegate should call this to resolve module classes. -Class RCTCoreModulesClassProvider(const char *name); +Class RCTCoreModulesClassProvider(const char* name); // Lookup functions Class RCTAccessibilityManagerCls(void) __attribute__((used)); diff --git a/packages/react-native/React/CoreModules/RCTAccessibilityManager+Internal.h b/packages/react-native/React/CoreModules/RCTAccessibilityManager+Internal.h index 6e180007fdca..e1b8a597f6d0 100644 --- a/packages/react-native/React/CoreModules/RCTAccessibilityManager+Internal.h +++ b/packages/react-native/React/CoreModules/RCTAccessibilityManager+Internal.h @@ -16,7 +16,7 @@ RCT_EXTERN_C_BEGIN // Only to be used for testing and internal tooling. Do not use this in // production. void RCTAccessibilityManagerSetIsVoiceOverEnabled( - RCTAccessibilityManager *accessibilityManager, + RCTAccessibilityManager* accessibilityManager, BOOL isVoiceOverEnabled); RCT_EXTERN_C_END diff --git a/packages/react-native/React/CxxBridge/RCTMessageThread.h b/packages/react-native/React/CxxBridge/RCTMessageThread.h index 73d7605ca9df..0306a1fea3c1 100644 --- a/packages/react-native/React/CxxBridge/RCTMessageThread.h +++ b/packages/react-native/React/CxxBridge/RCTMessageThread.h @@ -16,17 +16,18 @@ 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/Fabric/AppleEventBeat.h b/packages/react-native/React/Fabric/AppleEventBeat.h index 256e0f0983ad..f2f9ef4316a3 100644 --- a/packages/react-native/React/Fabric/AppleEventBeat.h +++ b/packages/react-native/React/Fabric/AppleEventBeat.h @@ -25,12 +25,13 @@ 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/ComponentViews/RCTFabricComponentsPlugins.h b/packages/react-native/React/Fabric/Mounting/ComponentViews/RCTFabricComponentsPlugins.h index 6b8a6ff6d6dc..d0411c8e4ffd 100644 --- a/packages/react-native/React/Fabric/Mounting/ComponentViews/RCTFabricComponentsPlugins.h +++ b/packages/react-native/React/Fabric/Mounting/ComponentViews/RCTFabricComponentsPlugins.h @@ -9,7 +9,8 @@ #ifdef RN_DISABLE_OSS_PLUGIN_HEADER -// FB Internal: FBRCTFabricComponentsPlugins.h is autogenerated by the build system. +// FB Internal: FBRCTFabricComponentsPlugins.h is autogenerated by the build +// system. #import #else @@ -26,19 +27,24 @@ extern "C" { #endif -Class RCTFabricComponentsProvider(const char *name); +Class RCTFabricComponentsProvider(const char* name); // Lookup functions -Class RCTActivityIndicatorViewCls(void) __attribute__((used)); -Class RCTDebuggingOverlayCls(void) __attribute__((used)); -Class RCTInputAccessoryCls(void) __attribute__((used)); +Class RCTActivityIndicatorViewCls(void) + __attribute__((used)); +Class RCTDebuggingOverlayCls(void) + __attribute__((used)); +Class RCTInputAccessoryCls(void) + __attribute__((used)); Class RCTParagraphCls(void) __attribute__((used)); -Class RCTPullToRefreshViewCls(void) __attribute__((used)); +Class RCTPullToRefreshViewCls(void) + __attribute__((used)); Class RCTSafeAreaViewCls(void) __attribute__((used)); Class RCTScrollViewCls(void) __attribute__((used)); Class RCTSwitchCls(void) __attribute__((used)); Class RCTTextInputCls(void) __attribute__((used)); -Class RCTUnimplementedNativeViewCls(void) __attribute__((used)); +Class RCTUnimplementedNativeViewCls(void) + __attribute__((used)); Class RCTViewCls(void) __attribute__((used)); Class VirtualViewCls(void) __attribute__((used)); Class RCTImageCls(void) __attribute__((used)); diff --git a/packages/react-native/React/Fabric/Mounting/RCTMountingTransactionObserverCoordinator.h b/packages/react-native/React/Fabric/Mounting/RCTMountingTransactionObserverCoordinator.h index 6f11b31c28a3..40ba1fd82146 100644 --- a/packages/react-native/React/Fabric/Mounting/RCTMountingTransactionObserverCoordinator.h +++ b/packages/react-native/React/Fabric/Mounting/RCTMountingTransactionObserverCoordinator.h @@ -21,22 +21,25 @@ 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> registry_; + std::unordered_map< + facebook::react::SurfaceId, + std::unordered_set> + registry_; }; diff --git a/packages/react-native/React/Fabric/RCTImageResponseObserverProxy.h b/packages/react-native/React/Fabric/RCTImageResponseObserverProxy.h index f131431ea6ac..93dca1a4ef98 100644 --- a/packages/react-native/React/Fabric/RCTImageResponseObserverProxy.h +++ b/packages/react-native/React/Fabric/RCTImageResponseObserverProxy.h @@ -19,9 +19,10 @@ class RCTImageResponseObserverProxy final : public ImageResponseObserver { public: RCTImageResponseObserverProxy(id delegate = nil); - void didReceiveImage(const ImageResponse &imageResponse) const override; - void didReceiveProgress(float progress, int64_t loaded, int64_t total) const override; - void didReceiveFailure(const ImageLoadError &error) const override; + void didReceiveImage(const ImageResponse& imageResponse) const override; + void didReceiveProgress(float progress, int64_t loaded, int64_t total) + const override; + void didReceiveFailure(const ImageLoadError& error) const override; private: __weak id delegate_; diff --git a/packages/react-native/React/Fabric/Utils/PlatformRunLoopObserver.h b/packages/react-native/React/Fabric/Utils/PlatformRunLoopObserver.h index 3faf9ec093f2..4f097aaac506 100644 --- a/packages/react-native/React/Fabric/Utils/PlatformRunLoopObserver.h +++ b/packages/react-native/React/Fabric/Utils/PlatformRunLoopObserver.h @@ -20,7 +20,10 @@ 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(); @@ -40,10 +43,13 @@ 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 ec5e849c8127..89c984e90d9d 100644 --- a/packages/react-native/React/Fabric/Utils/RCTIdentifierPool.h +++ b/packages/react-native/React/Fabric/Utils/RCTIdentifierPool.h @@ -14,13 +14,11 @@ 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; @@ -30,8 +28,7 @@ class RCTIdentifierPool { } } - void reset() - { + void reset() { for (int i = 0; i < size; i++) { usage[i] = false; } diff --git a/packages/react-native/React/I18n/FBXXHashUtils.h b/packages/react-native/React/I18n/FBXXHashUtils.h index 3609705f6bc9..85d11c23ee55 100644 --- a/packages/react-native/React/I18n/FBXXHashUtils.h +++ b/packages/react-native/React/I18n/FBXXHashUtils.h @@ -21,8 +21,10 @@ * THE SOFTWARE. */ -// Based on implementation: https://github.com/ekpyron/xxhashct/blob/master/xxh64.hpp -// To generate string hash at compile time, the original file has been slightly modified by i18n team. +// Based on implementation: +// https://github.com/ekpyron/xxhashct/blob/master/xxh64.hpp To generate string +// hash at compile time, the original file has been slightly modified by i18n +// team. #import @@ -35,88 +37,125 @@ static const uint64_t METAXXHASHUTILS_PRIME_3 = 1609587929392839161ULL; static const uint64_t METAXXHASHUTILS_PRIME_4 = 9650029242287828579ULL; static const uint64_t METAXXHASHUTILS_PRIME_5 = 2870177450012600261ULL; -#define METAXXHASHUTILS_INLINE_ATTRS \ - NS_SWIFT_UNAVAILABLE("You'll need to bridge to C/ObjC to use this API.") \ - NS_INLINE +#define METAXXHASHUTILS_INLINE_ATTRS \ + NS_SWIFT_UNAVAILABLE("You'll need to bridge to C/ObjC to use this API.") \ + NS_INLINE METAXXHASHUTILS_INLINE_ATTRS -uint64_t rotl(uint64_t x, int r) -{ +uint64_t rotl(uint64_t x, int r) { return ((x << r) | (x >> (64 - r))); } METAXXHASHUTILS_INLINE_ATTRS -uint64_t mix1(const uint64_t h, const uint64_t prime, int rshift) -{ +uint64_t mix1(const uint64_t h, const uint64_t prime, int rshift) { return (h ^ (h >> rshift)) * prime; } METAXXHASHUTILS_INLINE_ATTRS -uint64_t mix2(const uint64_t p, const uint64_t v) -{ +uint64_t mix2(const uint64_t p, const uint64_t v) { return rotl(v + p * METAXXHASHUTILS_PRIME_2, 31) * METAXXHASHUTILS_PRIME_1; } METAXXHASHUTILS_INLINE_ATTRS -uint64_t mix3(const uint64_t h, const uint64_t v) -{ +uint64_t mix3(const uint64_t h, const uint64_t v) { return (h ^ mix2(v, 0)) * METAXXHASHUTILS_PRIME_1 + METAXXHASHUTILS_PRIME_4; } METAXXHASHUTILS_INLINE_ATTRS -uint32_t endian32(const char *v) -{ - return (uint32_t)((uint8_t)(v[0])) | ((uint32_t)((uint8_t)(v[1])) << 8) - | ((uint32_t)((uint8_t)(v[2])) << 16) | ((uint32_t)((uint8_t)(v[3])) << 24); +uint32_t endian32(const char* v) { + return (uint32_t)((uint8_t)(v[0])) | ((uint32_t)((uint8_t)(v[1])) << 8) | + ((uint32_t)((uint8_t)(v[2])) << 16) | ((uint32_t)((uint8_t)(v[3])) << 24); } METAXXHASHUTILS_INLINE_ATTRS -uint64_t endian64(const char *v) -{ - return (uint64_t)((uint8_t)(v[0])) | ((uint64_t)((uint8_t)(v[1])) << 8) - | ((uint64_t)((uint8_t)(v[2])) << 16) | ((uint64_t)((uint8_t)(v[3])) << 24) - | ((uint64_t)((uint8_t)(v[4])) << 32) | ((uint64_t)((uint8_t)(v[5])) << 40) - | ((uint64_t)((uint8_t)(v[6])) << 48) | ((uint64_t)((uint8_t)(v[7])) << 56); +uint64_t endian64(const char* v) { + return (uint64_t)((uint8_t)(v[0])) | ((uint64_t)((uint8_t)(v[1])) << 8) | + ((uint64_t)((uint8_t)(v[2])) << 16) | + ((uint64_t)((uint8_t)(v[3])) << 24) | + ((uint64_t)((uint8_t)(v[4])) << 32) | + ((uint64_t)((uint8_t)(v[5])) << 40) | + ((uint64_t)((uint8_t)(v[6])) << 48) | ((uint64_t)((uint8_t)(v[7])) << 56); } METAXXHASHUTILS_INLINE_ATTRS -uint64_t fetch64(const char *p, const uint64_t v) -{ +uint64_t fetch64(const char* p, const uint64_t v) { return mix2(endian64(p), v); } METAXXHASHUTILS_INLINE_ATTRS -uint64_t fetch32(const char *p) -{ +uint64_t fetch32(const char* p) { return (uint64_t)(endian32(p)) * METAXXHASHUTILS_PRIME_1; } METAXXHASHUTILS_INLINE_ATTRS -uint64_t fetch8(const char *p) -{ +uint64_t fetch8(const char* p) { return (uint8_t)(*p) * METAXXHASHUTILS_PRIME_5; } METAXXHASHUTILS_INLINE_ATTRS -uint64_t finalize(const uint64_t h, const char *p, uint64_t len) -{ - return (len >= 8) ? (finalize(rotl(h ^ fetch64(p, 0), 27) * METAXXHASHUTILS_PRIME_1 + METAXXHASHUTILS_PRIME_4, p + 8, len - 8)) - : ((len >= 4) ? (finalize(rotl(h ^ fetch32(p), 23) * METAXXHASHUTILS_PRIME_2 + METAXXHASHUTILS_PRIME_3, p + 4, len - 4)) - : ((len > 0) ? (finalize(rotl(h ^ fetch8(p), 11) * METAXXHASHUTILS_PRIME_1, p + 1, len - 1)) - : (mix1(mix1(mix1(h, METAXXHASHUTILS_PRIME_2, 33), METAXXHASHUTILS_PRIME_3, 29), 1, 32)))); +uint64_t finalize(const uint64_t h, const char* p, uint64_t len) { + return (len >= 8) + ? (finalize( + rotl(h ^ fetch64(p, 0), 27) * METAXXHASHUTILS_PRIME_1 + + METAXXHASHUTILS_PRIME_4, + p + 8, + len - 8)) + : ((len >= 4) + ? (finalize( + rotl(h ^ fetch32(p), 23) * METAXXHASHUTILS_PRIME_2 + + METAXXHASHUTILS_PRIME_3, + p + 4, + len - 4)) + : ((len > 0) + ? (finalize( + rotl(h ^ fetch8(p), 11) * METAXXHASHUTILS_PRIME_1, + p + 1, + len - 1)) + : (mix1( + mix1( + mix1(h, METAXXHASHUTILS_PRIME_2, 33), + METAXXHASHUTILS_PRIME_3, + 29), + 1, + 32)))); } METAXXHASHUTILS_INLINE_ATTRS -uint64_t h32bytes_compute(const char *p, uint64_t len, const uint64_t v1, const uint64_t v2, const uint64_t v3, const uint64_t v4) -{ - return (len >= 32) ? h32bytes_compute(p + 32, len - 32, fetch64(p, v1), fetch64(p + 8, v2), fetch64(p + 16, v3), fetch64(p + 24, v4)) - : mix3(mix3(mix3(mix3(rotl(v1, 1) + rotl(v2, 7) + rotl(v3, 12) + rotl(v4, 18), v1), v2), v3), v4); +uint64_t h32bytes_compute( + const char* p, + uint64_t len, + const uint64_t v1, + const uint64_t v2, + const uint64_t v3, + const uint64_t v4) { + return (len >= 32) + ? h32bytes_compute( + p + 32, + len - 32, + fetch64(p, v1), + fetch64(p + 8, v2), + fetch64(p + 16, v3), + fetch64(p + 24, v4)) + : mix3( + mix3( + mix3( + mix3( + rotl(v1, 1) + rotl(v2, 7) + rotl(v3, 12) + rotl(v4, 18), + v1), + v2), + v3), + v4); } METAXXHASHUTILS_INLINE_ATTRS -uint64_t h32bytes(const char *p, uint64_t len, const uint64_t seed) -{ - return h32bytes_compute(p, len, seed + METAXXHASHUTILS_PRIME_1 + METAXXHASHUTILS_PRIME_2, seed + METAXXHASHUTILS_PRIME_2, seed, seed - METAXXHASHUTILS_PRIME_1); +uint64_t h32bytes(const char* p, uint64_t len, const uint64_t seed) { + return h32bytes_compute( + p, + len, + seed + METAXXHASHUTILS_PRIME_1 + METAXXHASHUTILS_PRIME_2, + seed + METAXXHASHUTILS_PRIME_2, + seed, + seed - METAXXHASHUTILS_PRIME_1); } /* @@ -124,14 +163,16 @@ uint64_t h32bytes(const char *p, uint64_t len, const uint64_t seed) */ METAXXHASHUTILS_INLINE_ATTRS -uint64_t meta_xxhash64(const char *p, uint64_t len, uint64_t seed) -{ - return finalize((len >= 32 ? h32bytes(p, len, seed) : seed + METAXXHASHUTILS_PRIME_5) + len, p + (len & ~0x1FULL), len & 0x1FULL); +uint64_t meta_xxhash64(const char* p, uint64_t len, uint64_t seed) { + return finalize( + (len >= 32 ? h32bytes(p, len, seed) : seed + METAXXHASHUTILS_PRIME_5) + + len, + p + (len & ~0x1FULL), + len & 0x1FULL); } METAXXHASHUTILS_INLINE_ATTRS -uint64_t FBxxHash64(const char *p, uint64_t len, uint64_t seed) -{ +uint64_t FBxxHash64(const char* p, uint64_t len, uint64_t seed) { return meta_xxhash64(p, len, seed); } diff --git a/packages/react-native/React/Inspector/RCTCxxInspectorPackagerConnectionDelegate.h b/packages/react-native/React/Inspector/RCTCxxInspectorPackagerConnectionDelegate.h index 2a680c349492..56e5f51c161d 100644 --- a/packages/react-native/React/Inspector/RCTCxxInspectorPackagerConnectionDelegate.h +++ b/packages/react-native/React/Inspector/RCTCxxInspectorPackagerConnectionDelegate.h @@ -21,23 +21,26 @@ 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/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 4461e2aadb75..f8258552ccbe 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 0d68ffb84dac..1eb30b6fedf9 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,300 +126,376 @@ 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); - - 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); - - 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 (*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 *); - - 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 *); - - 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); - - 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 *); - - 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 *); - - 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); - - 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); + 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 (*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 (*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*); + + 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 ( + *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*); + + 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); + + 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*); + + 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); + + 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); /* 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); - - 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 *); - - 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 *); + 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); + + 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 ( + *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 *); - - 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 *(*GetPrimitiveArrayCritical)(JNIEnv *, jarray, jboolean *); - void (*ReleasePrimitiveArrayCritical)(JNIEnv *, jarray, void *, jint); - - const jchar *(*GetStringCritical)(JNIEnv *, jstring, jboolean *); - void (*ReleaseStringCritical)(JNIEnv *, jstring, const jchar *); - - jweak (*NewWeakGlobalRef)(JNIEnv *, jobject); - void (*DeleteWeakGlobalRef)(JNIEnv *, jweak); - - jboolean (*ExceptionCheck)(JNIEnv *); - - jobject (*NewDirectByteBuffer)(JNIEnv *, void *, jlong); - void *(*GetDirectBufferAddress)(JNIEnv *, jobject); - jlong (*GetDirectBufferCapacity)(JNIEnv *, jobject); + 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**); + + 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); + + const jchar* (*GetStringCritical)(JNIEnv*, jstring, jboolean*); + void (*ReleaseStringCritical)(JNIEnv*, jstring, const jchar*); + + jweak (*NewWeakGlobalRef)(JNIEnv*, jobject); + void (*DeleteWeakGlobalRef)(JNIEnv*, jweak); + + jboolean (*ExceptionCheck)(JNIEnv*); + + 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); }; /* @@ -430,132 +506,111 @@ 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); @@ -563,34 +618,28 @@ 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); \ @@ -598,15 +647,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) \ @@ -624,41 +673,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) \ @@ -676,125 +725,113 @@ 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) \ @@ -812,414 +849,369 @@ 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*/ @@ -1229,42 +1221,37 @@ struct _JNIEnv { * JNI invocation interface. */ struct JNIInvokeInterface { - 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 *); + 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*); }; /* * 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*/ @@ -1272,7 +1259,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; @@ -1282,15 +1269,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; @@ -1302,9 +1289,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"))) @@ -1314,8 +1301,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 6adb0d390bf0..0b8122d7c19a 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,7 +13,8 @@ #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__); @@ -37,69 +38,70 @@ #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/react/devsupport/JCxxInspectorPackagerConnection.h b/packages/react-native/ReactAndroid/src/main/jni/react/devsupport/JCxxInspectorPackagerConnection.h index 26d29aac4a03..79793b751148 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,9 +20,11 @@ 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(); @@ -30,7 +32,7 @@ class JCxxInspectorPackagerConnection : public jni::HybridClass 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 7ce5c5899d62..087c5ecb579d 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,31 +28,39 @@ 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 6d75450f88ae..d73b360fb8a5 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,9 +22,11 @@ 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 3fc7c0caa683..0335f7a2de96 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,14 +20,17 @@ namespace facebook::react::jsinspector_modern { * IWebSocketDelegate to Java. */ class JCxxInspectorPackagerConnectionWebSocketDelegate - : public jni::HybridClass { + : public jni::HybridClass< + JCxxInspectorPackagerConnectionWebSocketDelegate> { 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(); @@ -35,7 +38,8 @@ 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 1056132c7c68..55132da45bd0 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,7 +16,8 @@ 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 getScreenshotCaptureEnabled(jni::alias_ref /*unused*/); static bool getFuseboxEnabled(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 f751dda40117..075d34d2f9c6 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,9 +11,11 @@ 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*/); @@ -39,14 +41,20 @@ class JInspectorNetworkReporter : public jni::HybridClass> 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*/, @@ -87,7 +95,9 @@ class JInspectorNetworkReporter : public jni::HybridClass payloadData, jboolean isBinary); - static void reportWebSocketClosed(jni::alias_ref /*unused*/, jni::alias_ref requestId); + static void reportWebSocketClosed( + jni::alias_ref /*unused*/, + jni::alias_ref requestId); static void registerNatives(); diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/fabric/AndroidAnimationChoreographer.h b/packages/react-native/ReactAndroid/src/main/jni/react/fabric/AndroidAnimationChoreographer.h index 17124e4ecea4..f5b76007ab43 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/fabric/AndroidAnimationChoreographer.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/fabric/AndroidAnimationChoreographer.h @@ -14,18 +14,15 @@ namespace facebook::react { class AndroidAnimationChoreographer : public AnimationChoreographer { public: - void resume() override - { + void resume() override { active_.store(true); } - void pause() override - { + void pause() override { active_.store(false); } - void onAnimationFrameIfActive(AnimationTimestamp timestamp) const - { + void onAnimationFrameIfActive(AnimationTimestamp timestamp) const { if (active_.load()) { onAnimationFrame(timestamp); } 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 8f5a2ce92d04..b093a7cf841c 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,12 +13,13 @@ 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; @@ -28,7 +29,7 @@ class AndroidEventBeat final : public EventBeat, public EventBeatManagerObserver 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 e6b72a28173e..c87780f3f96a 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,14 +17,16 @@ 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.h b/packages/react-native/ReactAndroid/src/main/jni/react/fabric/CoreComponentsRegistry.h index 36eec9bbae7b..da6653c86bc9 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,8 +11,10 @@ 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 d056cc9feca8..78059248060b 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,7 +27,8 @@ 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(); @@ -36,8 +37,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: /* @@ -45,7 +46,8 @@ 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 50143ad8f6c9..301b970cb4cc 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,17 +17,29 @@ 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, jlong eventTimestamp); - void dispatchEventSynchronously(std::string eventName, NativeMap *params, jlong eventTimestamp); - void dispatchUniqueEvent(std::string eventName, NativeMap *payload, jlong eventTimestamp); + void dispatchEvent( + std::string eventName, + NativeMap* payload, + int category, + jlong eventTimestamp); + void dispatchEventSynchronously( + std::string eventName, + NativeMap* params, + jlong eventTimestamp); + void dispatchUniqueEvent( + std::string eventName, + NativeMap* payload, + jlong eventTimestamp); }; } // namespace facebook::react 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 3d31c58db7eb..b256c5337d87 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,17 +22,18 @@ 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 @@ -45,7 +46,7 @@ class FabricMountingManager final { * allocatedViewRegistry_ so that executeMount skips the redundant Create * mount item for this tag. */ - void preallocateShadowView(const ShadowView &shadowView); + void preallocateShadowView(const ShadowView& shadowView); /* * Returns true if the given tag is registered in allocatedViewRegistry_ @@ -64,7 +65,9 @@ class FabricMountingManager final { * In the pull model (`synchronous` = true) the batch is * applied immediately on the calling (UI) thread. */ - void executeMount(const MountingTransaction &transaction, bool synchronous = false); + void executeMount( + const MountingTransaction& transaction, + bool synchronous = false); /* * Pull model: notify Java that a transaction is available for `surfaceId` so @@ -72,17 +75,27 @@ class FabricMountingManager final { */ void onTransactionAvailable(SurfaceId surfaceId); - 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); void captureViewSnapshot(Tag tag, SurfaceId surfaceId); @@ -109,7 +122,8 @@ class FabricMountingManager final { */ std::vector preallocatedViewsQueue_{}; - std::unordered_map> allocatedViewRegistry_{}; + std::unordered_map> + allocatedViewRegistry_{}; std::recursive_mutex allocatedViewsMutex_; }; 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 ea4b928357ec..5b0b6f355684 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 @@ -38,7 +38,8 @@ 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,15 +66,18 @@ 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, @@ -87,39 +91,55 @@ 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 schedulerShouldMergeReactRevision(SurfaceId surfaceId) override; void mergeReactRevision(SurfaceId surfaceId); - 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 schedulerDidCaptureViewSnapshot(Tag tag, SurfaceId surfaceId) override; - void schedulerDidSetViewSnapshot(Tag sourceTag, Tag targetTag, SurfaceId surfaceId) override; + void schedulerDidSetViewSnapshot( + Tag sourceTag, + Tag targetTag, + SurfaceId surfaceId) override; void schedulerDidClearPendingSnapshots() override; @@ -135,7 +155,8 @@ class FabricUIManagerBinding : public jni::HybridClass, void pullAndExecuteTransaction(SurfaceId surfaceId); - jint findNextFocusableElement(jint parentTag, jint focusedTag, jint direction); + jint + findNextFocusableElement(jint parentTag, jint focusedTag, jint direction); jintArray getRelativeAncestorList(jint rootTag, jint childTag); @@ -146,7 +167,8 @@ 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; @@ -157,9 +179,14 @@ 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>> + std::unordered_map< + SurfaceId, + std::variant< + SurfaceHandler, + jni::weak_ref>> 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 802ba1699785..cd15298685c4 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 16e3bf8fb20c..c19701fe871f 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,9 +15,10 @@ 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 3384e4df3b4c..ad115be9161f 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,31 +13,39 @@ 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 6e107180b555..0ae065f0e98e 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 @@ -17,17 +17,20 @@ namespace facebook::react { class Instance; -class StateWrapperImpl : public jni::HybridClass { +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 fe687d148abc..3e6f9f61d6cc 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,11 +17,12 @@ 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); @@ -42,14 +43,17 @@ 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/fabric/test_helper/FabricMountingManagerTestHelper.h b/packages/react-native/ReactAndroid/src/main/jni/react/fabric/test_helper/FabricMountingManagerTestHelper.h index a5a53ffbb518..a5254e0ab38c 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/fabric/test_helper/FabricMountingManagerTestHelper.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/fabric/test_helper/FabricMountingManagerTestHelper.h @@ -17,9 +17,11 @@ namespace facebook::react { /** * JNI test helper that wraps a real FabricMountingManager */ -class FabricMountingManagerTestHelper : public jni::HybridClass { +class FabricMountingManagerTestHelper + : public jni::HybridClass { public: - static constexpr auto kJavaDescriptor = "Lcom/facebook/react/fabric/FabricMountingManagerTestHelper;"; + static constexpr auto kJavaDescriptor = + "Lcom/facebook/react/fabric/FabricMountingManagerTestHelper;"; void startSurface(jint surfaceId); void stopSurface(jint surfaceId); @@ -32,7 +34,8 @@ class FabricMountingManagerTestHelper : public jni::HybridClass jFabricUIManager); + explicit FabricMountingManagerTestHelper( + jni::alias_ref jFabricUIManager); static void initHybrid( jni::alias_ref jobj, diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/featureflags/JReactNativeFeatureFlagsCxxInterop.h b/packages/react-native/ReactAndroid/src/main/jni/react/featureflags/JReactNativeFeatureFlagsCxxInterop.h index a787b50e7c9c..9b7e9a053bac 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/featureflags/JReactNativeFeatureFlagsCxxInterop.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/featureflags/JReactNativeFeatureFlagsCxxInterop.h @@ -31,265 +31,265 @@ class JReactNativeFeatureFlagsCxxInterop "Lcom/facebook/react/internal/featureflags/ReactNativeFeatureFlagsCxxInterop;"; static bool commonTestFlag( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool cdpInteractionMetricsEnabled( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool cxxNativeAnimatedEnabled( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool defaultTextToOverflowHidden( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool disableEarlyViewCommandExecution( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool disableImageViewPreallocationAndroid( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool disableMountItemReorderingAndroid( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool disableSubviewClippingAndroid( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool disableTextLayoutManagerCacheAndroid( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool disableViewPreallocationAndroid( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool enableAccessibilityOrder( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool enableAccumulatedUpdatesInRawPropsAndroid( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool enableAndroidFontWeightAdjustment( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool enableAndroidTextMeasurementOptimizations( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool enableBridgelessArchitecture( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool enableCppPropsIteratorSetter( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool enableCustomFocusSearchOnClippedElementsAndroid( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool enableDestroyShadowTreeRevisionAsync( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool enableDoubleMeasurementFixAndroid( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool enableEagerRootViewAttachment( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool enableExclusivePropsUpdateAndroid( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool enableFabricCommitBranching( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool enableFabricLogs( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool enableFlexboxAutoMinSizeInStrictMode( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool enableFontScaleChangesUpdatingLayout( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool enableIOSCompressedTextFrameAdjustment( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool enableIOSTextBaselineOffsetPerLine( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool enableIOSViewClipToPaddingBox( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool enableImagePrefetchingAndroid( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool enableImageTransparentTintColor( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool enableImmediateUpdateModeForContentOffsetChanges( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool enableImperativeFocus( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool enableInteropViewManagerClassLookUpOptimizationIOS( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool enableIntersectionObserverByDefault( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool enableKeyEvents( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool enableLayoutAnimationsOnAndroid( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool enableLayoutAnimationsOnIOS( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool enableModuleArgumentNSNullConversionIOS( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool enableMountingCoordinatorPullModelAndroid( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool enableMutationObserverByDefault( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool enableNativeCSSParsing( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool enablePreparedTextLayout( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool enablePropsUpdateReconciliationAndroid( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool enableRuntimeSchedulerQueueClearingOnError( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool enableSchedulerDelegateInvalidation( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool enableSwiftUIBasedFilters( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool enableViewCulling( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool enableViewRecycling( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool enableViewRecyclingForImage( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool enableViewRecyclingForScrollView( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool enableViewRecyclingForText( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool enableViewRecyclingForView( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool enableVirtualViewContainerStateExperimental( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool fixDifferentiatorParentTagForUnflattenCase( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool fixMappingOfEventPrioritiesBetweenFabricAndReact( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool fixYogaFlexBasisFitContentInMainAxis( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool fuseboxAssertSingleHostState( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool fuseboxEnabledRelease( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool fuseboxFrameRecordingEnabled( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool fuseboxScreenshotCaptureEnabled( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool fuseboxWebSocketEventsEnabled( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool optimizedAnimatedPropUpdates( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool overrideBySynchronousMountPropsAtMountingAndroid( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool perfIssuesEnabled( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool perfMonitorV2Enabled( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static double preparedTextCacheSize( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool preventShadowTreeCommitExhaustion( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool redBoxV2Android( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool redBoxV2IOS( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool shouldPressibilityUseW3CPointerEventsForHover( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool shouldTriggerResponderTransferOnScrollAndroid( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool skipActivityIdentityAssertionOnHostPause( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool syncAndroidClipBoundsWithOverflow( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool traceTurboModulePromiseRejectionsOnAndroid( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool updateRuntimeShadowNodeReferencesOnCommit( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool updateRuntimeShadowNodeReferencesOnCommitThread( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool useAlwaysAvailableJSErrorHandling( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool useFabricInterop( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool useNativeViewConfigsInBridgelessMode( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool useNestedScrollViewAndroid( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool useSharedAnimatedBackend( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool useTraitHiddenOnAndroid( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool useTurboModuleInterop( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static double viewCullingOutsetRatio( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool viewTransitionEnabled( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static bool viewTransitionUseHardwareBitmapAndroid( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static double virtualViewPrerenderRatio( - facebook::jni::alias_ref); + facebook::jni::alias_ref); static void override( facebook::jni::alias_ref, 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 16a7f7b034c1..b1bd30874b59 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,29 +16,30 @@ 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 3b06dcf26ddc..4cfb0e8fc346 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,10 +17,13 @@ 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/jni/CxxModuleWrapperBase.h b/packages/react-native/ReactAndroid/src/main/jni/react/jni/CxxModuleWrapperBase.h index bf9f11fc3cb4..cc425837c9f5 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 @@ -12,7 +12,8 @@ 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;"; }; } // namespace facebook::react 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 8bf97abce2a0..48745a0dba5f 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,13 +15,17 @@ 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(); @@ -30,9 +34,11 @@ class InspectorNetworkRequestListener : public jni::HybridClass executor); + jsinspector_modern::ScopedExecutor< + jsinspector_modern::NetworkRequestListener> executor); - jsinspector_modern::ScopedExecutor executor_; + jsinspector_modern::ScopedExecutor + executor_; }; } // namespace facebook::react diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/jni/JByteBufferMutableBuffer.h b/packages/react-native/ReactAndroid/src/main/jni/react/jni/JByteBufferMutableBuffer.h index 56b82bbd3edd..506e3689d846 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/jni/JByteBufferMutableBuffer.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/jni/JByteBufferMutableBuffer.h @@ -24,27 +24,22 @@ namespace facebook::react { class JByteBufferMutableBuffer final : public jsi::MutableBuffer { public: explicit JByteBufferMutableBuffer(jni::alias_ref byteBuffer) - : byteBuffer_(jni::make_global(byteBuffer)) - { - } + : byteBuffer_(jni::make_global(byteBuffer)) {} - ~JByteBufferMutableBuffer() override - { + ~JByteBufferMutableBuffer() override { jni::ThreadScope threadScope; byteBuffer_.reset(); } - JByteBufferMutableBuffer(const JByteBufferMutableBuffer &) = delete; - JByteBufferMutableBuffer &operator=(const JByteBufferMutableBuffer &) = delete; - JByteBufferMutableBuffer(JByteBufferMutableBuffer &&) = delete; - JByteBufferMutableBuffer &operator=(JByteBufferMutableBuffer &&) = delete; + JByteBufferMutableBuffer(const JByteBufferMutableBuffer&) = delete; + JByteBufferMutableBuffer& operator=(const JByteBufferMutableBuffer&) = delete; + JByteBufferMutableBuffer(JByteBufferMutableBuffer&&) = delete; + JByteBufferMutableBuffer& operator=(JByteBufferMutableBuffer&&) = delete; - size_t size() const override - { + size_t size() const override { return byteBuffer_->getDirectSize(); } - uint8_t *data() override - { + uint8_t* data() override { return byteBuffer_->getDirectBytes(); } 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 bde467d4a7e8..f052c2cd83d4 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,15 +19,16 @@ 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), }); @@ -39,8 +40,7 @@ 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.h b/packages/react-native/ReactAndroid/src/main/jni/react/jni/JDynamicNative.h index 1ba0d485c0b1..8b05243fc227 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 cd5068103513..716e58b0a7b6 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,7 +16,8 @@ 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 { @@ -26,14 +27,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/JReactMarker.h b/packages/react-native/ReactAndroid/src/main/jni/react/jni/JReactMarker.h index 22011d682e7a..4a5036d9a55b 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,16 +16,23 @@ 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 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 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 29342660799c..c8ea6e1d4427 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,11 +12,15 @@ 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 9caffec9c434..b614ad1a1fec 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,7 +14,8 @@ 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 69537d43f01d..6220ccedda34 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,7 +14,8 @@ 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.h b/packages/react-native/ReactAndroid/src/main/jni/react/jni/JSLoader.h index e41806bf68cd..ed71c5b3505d 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 @@ -23,8 +23,11 @@ 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 2217203f141d..423e5896b64b 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 66db613fb2b1..6674afb9cfb1 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 2239ee579808..05e7609e0917 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,9 +20,11 @@ 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; @@ -30,33 +32,39 @@ struct [[deprecated("This API will be removed along with the legacy architecture 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::javaobject()>("getMethodDescriptors"); + getClass() + ->getMethod< + jni::JList::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( @@ -65,16 +73,16 @@ class [[deprecated("This API will be removed along with the legacy architecture. 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 &¶ms, int callId) override; - MethodCallResult callSerializableNativeHook(unsigned int reactMethodId, folly::dynamic &¶ms) override; + void invoke(unsigned int reactMethodId, folly::dynamic&& params, int callId) + override; + MethodCallResult callSerializableNativeHook( + unsigned int reactMethodId, folly::dynamic&& params) 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 d144398244f5..5849b42cf5ce 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,18 +14,20 @@ 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 3c246e47d5eb..052155f697f4 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,24 +16,28 @@ 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 bdefb6a068f6..5fd7e0deb824 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,24 +19,27 @@ 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, @@ -46,14 +49,13 @@ class [[deprecated("This API will be removed along with the legacy architecture. bool isSync); MethodCallResult invoke( - std::weak_ptr &instance, + std::weak_ptr & instance, jni::alias_ref module, - const folly::dynamic ¶ms); + const folly::dynamic& params); 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.h b/packages/react-native/ReactAndroid/src/main/jni/react/jni/ModuleRegistryBuilder.h index f277fc334976..de62612cc7d3 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,20 +20,27 @@ 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, - std::shared_ptr moduleMessageQueue); +[[deprecated( + "This API will be removed along with the legacy architecture.")]] std:: + vector> + buildNativeModuleList( + std::weak_ptr winstance, + jni::alias_ref< + jni::JCollection::javaobject> + javaModules, + std::shared_ptr moduleMessageQueue); } // namespace facebook::react #endif 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 792dee8b21d5..738738437b01 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 8f79c5db6795..b3b7bc0f45af 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,20 +17,21 @@ 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 2a4e513029db..a451c41aa164 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,7 +16,8 @@ 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(); @@ -34,14 +35,13 @@ 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/ReadableNativeArray.h b/packages/react-native/ReactAndroid/src/main/jni/react/jni/ReadableNativeArray.h index 0129c066165d..1ab3243ad12b 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,20 +15,22 @@ 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 b2818cb48ab4..16ff720b4c00 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,19 +21,24 @@ 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 635725a2e3b2..af1eb84fa3c6 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,51 +37,43 @@ 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 cbb7e639bb10..342a8ee11004 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,7 +13,8 @@ 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 0554e1ea1341..b40eb5916fb7 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,14 +18,17 @@ 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); @@ -35,8 +38,8 @@ struct WritableNativeArray : public jni::HybridClass { - 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); @@ -34,9 +37,9 @@ struct WritableNativeMap : jni::HybridClass 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 aed8d355ad13..0ccc90d6aa65 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,11 +17,13 @@ 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 4cd0df3ef32e..e076b28385bf 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,7 +14,8 @@ 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 b432b1a53714..a5a77b4e61a7 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,20 +15,26 @@ 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 c8f87d39ce91..0a8af0d35d23 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,27 +17,36 @@ namespace facebook::react { -class DefaultTurboModuleManagerDelegate - : public jni::HybridClass { +class DefaultTurboModuleManagerDelegate : public jni::HybridClass< + DefaultTurboModuleManagerDelegate, + TurboModuleManagerDelegate> { 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 ¶ms) - 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& params) override; private: friend HybridBase; @@ -46,7 +55,8 @@ class DefaultTurboModuleManagerDelegate 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 63d07b975c6f..a7246248406e 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 @@ -27,13 +27,14 @@ class BlobCollector : public jsi::HostObject { class BlobModuleJSIBindings : public jni::JavaClass { public: - static constexpr const char *kJavaDescriptor = "Lcom/facebook/react/modules/blob/BlobModule;"; + static constexpr const char* kJavaDescriptor = + "Lcom/facebook/react/modules/blob/BlobModule;"; static void registerNatives(); private: - 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/ReactAndroid/src/main/jni/react/reactperflogger/reactperflogger/JNativeModulePerfLogger.h b/packages/react-native/ReactAndroid/src/main/jni/react/reactperflogger/reactperflogger/JNativeModulePerfLogger.h index c530ce57b5c1..3081409afd83 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,9 +13,11 @@ 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 30adda5ed131..cdf1a86a7f42 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,11 +17,12 @@ 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 53b0b36c7c3a..eb732d881bea 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,17 +19,23 @@ 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 f6af0cebfb3f..b0d8d1f581a2 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,9 +15,11 @@ 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 5c8e4603ccc9..03c312cd378d 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,9 +13,11 @@ 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 b34b7fec8832..a3b89ebb6f64 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,7 +17,8 @@ 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(); @@ -25,7 +26,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 29f2c8cd7a25..e576a1f892a5 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,7 +15,8 @@ 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 c86547a3240c..8ab06a236bf5 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,11 +13,15 @@ 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 933b7d896c01..da7b7fa1b06c 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 @@ -22,7 +22,8 @@ namespace facebook::react { struct JTracingState : public jni::JavaClass { - static constexpr auto kJavaDescriptor = "Lcom/facebook/react/devsupport/inspector/TracingState;"; + static constexpr auto kJavaDescriptor = + "Lcom/facebook/react/devsupport/inspector/TracingState;"; }; namespace { @@ -33,81 +34,95 @@ enum class TracingState { EnabledInCDPMode, }; -jni::local_ref convertCPPTracingStateToJava(TracingState tracingState) -{ - auto tracingStateClass = jni::findClassLocal("com/facebook/react/devsupport/inspector/TracingState"); - auto valueOfMethod = tracingStateClass->getStaticMethod("valueOf"); +jni::local_ref convertCPPTracingStateToJava( + TracingState tracingState) { + auto tracingStateClass = jni::findClassLocal( + "com/facebook/react/devsupport/inspector/TracingState"); + auto valueOfMethod = + tracingStateClass->getStaticMethod("valueOf"); switch (tracingState) { case TracingState::Disabled: - return valueOfMethod(tracingStateClass, jni::make_jstring("DISABLED").get()); + return valueOfMethod( + tracingStateClass, jni::make_jstring("DISABLED").get()); case TracingState::EnabledInBackgroundMode: - return valueOfMethod(tracingStateClass, jni::make_jstring("ENABLED_IN_BACKGROUND_MODE").get()); + return valueOfMethod( + tracingStateClass, + jni::make_jstring("ENABLED_IN_BACKGROUND_MODE").get()); case TracingState::EnabledInCDPMode: - return valueOfMethod(tracingStateClass, jni::make_jstring("ENABLED_IN_CDP_MODE").get()); + return valueOfMethod( + tracingStateClass, jni::make_jstring("ENABLED_IN_CDP_MODE").get()); default: - jni::throwNewJavaException("java/lang/IllegalStateException", "Unexpected new TracingState."); + jni::throwNewJavaException( + "java/lang/IllegalStateException", "Unexpected new TracingState."); } } } // namespace struct JTaskInterface : public jni::JavaClass { - static constexpr auto kJavaDescriptor = "Lcom/facebook/react/interfaces/TaskInterface;"; + static constexpr auto kJavaDescriptor = + "Lcom/facebook/react/interfaces/TaskInterface;"; }; struct JTracingStateListener : public jni::JavaClass { - static constexpr auto kJavaDescriptor = "Lcom/facebook/react/devsupport/inspector/TracingStateListener;"; + static constexpr auto kJavaDescriptor = + "Lcom/facebook/react/devsupport/inspector/TracingStateListener;"; - void onStateChanged(TracingState tracingState, bool screenshotsEnabled) const - { + void onStateChanged(TracingState tracingState, bool screenshotsEnabled) + const { static auto method = - javaClassStatic()->getMethod, jboolean)>("onStateChanged"); - return method(self(), convertCPPTracingStateToJava(tracingState), static_cast(screenshotsEnabled)); + javaClassStatic() + ->getMethod, jboolean)>( + "onStateChanged"); + return method( + self(), + convertCPPTracingStateToJava(tracingState), + static_cast(screenshotsEnabled)); } }; struct JFrameTimingSequence : public jni::JavaClass { - static constexpr auto kJavaDescriptor = "Lcom/facebook/react/devsupport/inspector/FrameTimingSequence;"; + static constexpr auto kJavaDescriptor = + "Lcom/facebook/react/devsupport/inspector/FrameTimingSequence;"; - uint64_t getId() const - { + uint64_t getId() const { auto field = javaClassStatic()->getField("id"); return static_cast(getFieldValue(field)); } - uint64_t getThreadId() const - { + uint64_t getThreadId() const { auto field = javaClassStatic()->getField("threadId"); return static_cast(getFieldValue(field)); } - HighResTimeStamp getBeginTimestamp() const - { + HighResTimeStamp getBeginTimestamp() const { auto field = javaClassStatic()->getField("beginTimestamp"); return HighResTimeStamp::fromChronoSteadyClockTimePoint( - std::chrono::steady_clock::time_point(std::chrono::nanoseconds(getFieldValue(field)))); + std::chrono::steady_clock::time_point( + std::chrono::nanoseconds(getFieldValue(field)))); } - HighResTimeStamp getEndTimestamp() const - { + HighResTimeStamp getEndTimestamp() const { auto field = javaClassStatic()->getField("endTimestamp"); return HighResTimeStamp::fromChronoSteadyClockTimePoint( - std::chrono::steady_clock::time_point(std::chrono::nanoseconds(getFieldValue(field)))); + std::chrono::steady_clock::time_point( + std::chrono::nanoseconds(getFieldValue(field)))); } - std::optional> getScreenshot() const - { + std::optional> getScreenshot() const { auto field = javaClassStatic()->getField("screenshot"); auto javaScreenshot = getFieldValue(field); if (javaScreenshot) { auto size = static_cast(javaScreenshot->size()); if (size > 0) { std::vector result(size); - javaScreenshot->getRegion(0, javaScreenshot->size(), reinterpret_cast(result.data())); + javaScreenshot->getRegion( + 0, javaScreenshot->size(), reinterpret_cast(result.data())); return result; } } @@ -116,46 +131,59 @@ struct JFrameTimingSequence : public jni::JavaClass { }; 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); } - jni::local_ref captureScreenshot(const std::string &format, int quality) const - { - auto method = javaClassStatic()->getMethod(jni::local_ref, jint)>( - "captureScreenshot"); - return method(self(), jni::make_jstring(format), static_cast(quality)); + jni::local_ref captureScreenshot( + const std::string& format, + int quality) const { + auto method = + javaClassStatic() + ->getMethod( + jni::local_ref, jint)>("captureScreenshot"); + return method( + self(), jni::make_jstring(format), static_cast(quality)); } - void setEmulatedMedia(const std::string &colorScheme) - { - static auto method = javaClassStatic()->getMethod)>("setEmulatedMedia"); + void setEmulatedMedia(const std::string& colorScheme) { + static auto method = + javaClassStatic()->getMethod)>( + "setEmulatedMedia"); method(self(), jni::make_jstring(colorScheme)); } }; @@ -163,11 +191,14 @@ struct JReactHostImpl : public jni::JavaClass { /** * A callback that will be invoked when tracing state has changed. */ -using TracingStateListener = std::function; +using TracingStateListener = + std::function; class TracingDelegate : public jsinspector_modern::HostTargetTracingDelegate { public: - void onTracingStarted(jsinspector_modern::tracing::Mode tracingMode, bool screenshotsCategoryEnabled) override; + void onTracingStarted( + jsinspector_modern::tracing::Mode tracingMode, + bool screenshotsCategoryEnabled) override; void onTracingStopped() override; /** @@ -192,9 +223,9 @@ class TracingDelegate : public jsinspector_modern::HostTargetTracingDelegate { */ std::mutex mutex_; /** - * Since HostInspectorTarget creates HostTarget, the default value is Disabled. - * However, the TracingDelegate is subscribed at the construction of HostTarget, so it will be notified as early as - * possible. + * Since HostInspectorTarget creates HostTarget, the default value is + * Disabled. However, the TracingDelegate is subscribed at the construction of + * HostTarget, so it will be notified as early as possible. */ TracingState tracingState_ = TracingState::Disabled; /** @@ -206,23 +237,25 @@ class TracingDelegate : public jsinspector_modern::HostTargetTracingDelegate { */ uint64_t nextSubscriptionId_ = 0; /** - * Returns a collection of listeners that are subscribed at the time of the call. - * Expected to be only called with mutex_ locked. + * Returns a collection of listeners that are subscribed at the time of the + * call. Expected to be only called with mutex_ locked. */ std::vector copySubscribedListeners(); /** * Notifies specified listeners about the state change. */ void notifyListeners( - const std::vector &listeners, + const std::vector& listeners, TracingState state, bool screenshotsCategoryEnabled); }; -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; @@ -253,7 +286,7 @@ class JReactHostInspectorTarget : public jni::HybridClass listener); + jlong registerTracingStateListener( + jni::alias_ref listener); /** * Unregister a previously registered tracing state listener. * - * \param subscriptionId The subscription ID returned from JReactHostInspectorTarget::registerTracingStateListener. + * \param subscriptionId The subscription ID returned from + * JReactHostInspectorTarget::registerTracingStateListener. */ void unregisterTracingStateListener(jlong subscriptionId); /** * Propagate frame timings information to the Inspector's Tracing subsystem. */ - void recordFrameTimings(jni::alias_ref frameTimingSequence); + void recordFrameTimings( + jni::alias_ref frameTimingSequence); // HostTargetDelegate methods jsinspector_modern::HostTargetMetadata getMetadata() override; - void onReload(const PageReloadRequest &request) override; - void onSetPausedInDebuggerMessage(const OverlaySetPausedInDebuggerMessageRequest &request) override; - void unstable_onPerfIssueAdded(const jsinspector_modern::PerfIssuePayload &issue) override; + void onReload(const PageReloadRequest& request) override; + void onSetPausedInDebuggerMessage( + const OverlaySetPausedInDebuggerMessageRequest& request) override; + void unstable_onPerfIssueAdded( + const jsinspector_modern::PerfIssuePayload& issue) override; void loadNetworkResource( - const jsinspector_modern::LoadNetworkResourceRequest ¶ms, - jsinspector_modern::ScopedExecutor executor) override; + const jsinspector_modern::LoadNetworkResourceRequest& params, + jsinspector_modern::ScopedExecutor< + jsinspector_modern::NetworkRequestListener> executor) override; std::optional captureScreenshot( - const jsinspector_modern::HostTargetDelegate::PageCaptureScreenshotRequest &request) override; - bool onSetEmulatedMedia(const jsinspector_modern::HostTargetDelegate::SetEmulatedMediaRequest &request) override; - jsinspector_modern::HostTargetTracingDelegate *getTracingDelegate() override; + const jsinspector_modern::HostTargetDelegate:: + PageCaptureScreenshotRequest& request) override; + bool onSetEmulatedMedia( + const jsinspector_modern::HostTargetDelegate::SetEmulatedMediaRequest& + request) override; + jsinspector_modern::HostTargetTracingDelegate* getTracingDelegate() override; private: JReactHostInspectorTarget( @@ -300,10 +342,11 @@ class JReactHostInspectorTarget : public jni::HybridClass javaExecutor); /** - * Returns a reference to the HostTarget, throwing a Java IllegalStateException - * if the Fusebox backend is not enabled (i.e., inspectorTarget_ is null). + * Returns a reference to the HostTarget, throwing a Java + * IllegalStateException if the Fusebox backend is not enabled (i.e., + * inspectorTarget_ is null). */ - jsinspector_modern::HostTarget &inspectorTarget(); + jsinspector_modern::HostTarget& inspectorTarget(); jni::global_ref jobj_; // This weak reference breaks the cycle between the C++ HostTarget and the 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 d58e52722b71..1274cad4f2be 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,33 +33,45 @@ 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); @@ -71,23 +83,27 @@ 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 e87a8fc873ae..06670e141b4c 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,7 +22,8 @@ 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/tracing/PerformanceTracerCxxInterop.h b/packages/react-native/ReactAndroid/src/main/jni/react/tracing/PerformanceTracerCxxInterop.h index d4592d96367c..985d515f7663 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/tracing/PerformanceTracerCxxInterop.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/tracing/PerformanceTracerCxxInterop.h @@ -13,7 +13,8 @@ namespace facebook::react { -class TracingStateCallback : public facebook::jni::JavaClass { +class TracingStateCallback + : public facebook::jni::JavaClass { public: static constexpr auto kJavaDescriptor = "Lcom/facebook/react/internal/tracing/PerformanceTracer$TracingStateCallback;"; @@ -21,9 +22,11 @@ class TracingStateCallback : public facebook::jni::JavaClass { +class PerformanceTracerCxxInterop + : public facebook::jni::JavaClass { public: - static constexpr auto kJavaDescriptor = "Lcom/facebook/react/internal/tracing/PerformanceTracer;"; + static constexpr auto kJavaDescriptor = + "Lcom/facebook/react/internal/tracing/PerformanceTracer;"; static void reportMark( facebook::jni::alias_ref jthis, @@ -47,7 +50,8 @@ class PerformanceTracerCxxInterop : public facebook::jni::JavaClass trackGroup, facebook::jni::alias_ref color); - static jboolean isTracing(facebook::jni::alias_ref jthis); + static jboolean isTracing( + facebook::jni::alias_ref jthis); static jint subscribeToTracingStateChanges( facebook::jni::alias_ref jthis, 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 1ca58bba4399..3f972192cc7a 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,18 +13,23 @@ 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 ca1fd0ff3e39..6561f9cc5dd0 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 b6f9b1aed4c4..cc5a2e3637ff 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,18 +13,20 @@ 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 0cc6a096436e..90b43e1bb176 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,11 +24,13 @@ 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 jsCallInvokerHolder, - jni::alias_ref nativeMethodCallInvokerHolder, + jni::alias_ref + nativeMethodCallInvokerHolder, jni::alias_ref delegate); static void registerNatives(); @@ -39,7 +41,8 @@ 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): @@ -57,18 +60,26 @@ class TurboModuleManager : public jni::HybridClass { std::shared_ptr nativeMethodCallInvoker, jni::alias_ref delegate); - static void installJSBindings(jsi::Runtime &runtime, jni::alias_ref javaPart); + static void installJSBindings( + jsi::Runtime& runtime, + jni::alias_ref javaPart); static void dispatchJSBindingInstall( jni::alias_ref javaPart, jni::alias_ref runtimeExecutor); - static TurboModuleProviderFunctionTypeWithRuntime createTurboModuleProvider(jni::alias_ref javaPart); - std::shared_ptr - getTurboModule(jni::alias_ref javaPart, const std::string &name, jsi::Runtime &runtime); + static TurboModuleProviderFunctionTypeWithRuntime createTurboModuleProvider( + jni::alias_ref javaPart); + std::shared_ptr getTurboModule( + jni::alias_ref javaPart, + const std::string& name, + jsi::Runtime& runtime); #ifndef RCT_REMOVE_LEGACY_MODULE_INTEROP - static TurboModuleProviderFunctionTypeWithRuntime createLegacyModuleProvider(jni::alias_ref javaPart); - std::shared_ptr getLegacyModule(jni::alias_ref javaPart, const std::string &name); + static TurboModuleProviderFunctionTypeWithRuntime createLegacyModuleProvider( + jni::alias_ref javaPart); + std::shared_ptr getLegacyModule( + jni::alias_ref javaPart, + const std::string& name); #endif // RCT_REMOVE_LEGACY_MODULE_INTEROP }; 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 ce7ac58fa364..0c387004da3b 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,16 +15,18 @@ 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 ¶ms) = 0; + const std::string& name, + const JavaTurboModule::InitParams& params) = 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 71599f269b97..fb0b9f7cb38f 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,9 +12,11 @@ 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/StateWrapper.h b/packages/react-native/ReactAndroid/src/main/jni/react/uimanager/StateWrapper.h index aae4a394bf35..d2bcd7b8155a 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/uimanager/StateWrapper.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/uimanager/StateWrapper.h @@ -13,7 +13,8 @@ namespace facebook::react { class StateWrapper : public jni::HybridClass { public: - constexpr static const char *const kJavaDescriptor = "Lcom/facebook/react/uimanager/StateWrapper;"; + constexpr static const char* const kJavaDescriptor = + "Lcom/facebook/react/uimanager/StateWrapper;"; }; } // namespace facebook::react 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 27222d4f48c3..aa01a342ec0c 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,28 +13,33 @@ 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; @@ -45,25 +50,31 @@ class ConstantsForViewManagerProvider : 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/ReactAndroid/src/main/jni/third-party/glog/config.h b/packages/react-native/ReactAndroid/src/main/jni/third-party/glog/config.h index ab05c5a7e192..294a18f240bc 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/third-party/glog/config.h +++ b/packages/react-native/ReactAndroid/src/main/jni/third-party/glog/config.h @@ -122,7 +122,7 @@ #define HAVE___SYNC_VAL_COMPARE_AND_SWAP 1 /* Define to the sub-directory in which libtool stores uninstalled libraries. - */ + */ #define LT_OBJDIR ".libs/" /* Name of package */ @@ -173,9 +173,8 @@ /* Puts following code inside the Google namespace */ #define _START_GOOGLE_NAMESPACE_ namespace google { - - -/* TODO(vjn/dreiss): revisit these when use the android-21 (or newer) NDK platform. */ +/* TODO(vjn/dreiss): revisit these when use the android-21 (or newer) NDK + * platform. */ #undef HAVE_SYSCALL_H #undef HAVE_SYS_SYSCALL_H #undef OS_LINUX diff --git a/packages/react-native/ReactCommon/callinvoker/ReactCommon/CallInvoker.h b/packages/react-native/ReactCommon/callinvoker/ReactCommon/CallInvoker.h index 452493c27e3e..91a8b4ee5919 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,24 +26,23 @@ 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; @@ -53,8 +52,12 @@ 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 17ef56e51644..98807df7cc9c 100644 --- a/packages/react-native/ReactCommon/callinvoker/ReactCommon/tests/TestCallInvoker.h +++ b/packages/react-native/ReactCommon/callinvoker/ReactCommon/tests/TestCallInvoker.h @@ -15,20 +15,18 @@ 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(); @@ -36,13 +34,12 @@ 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 6582fd40dd84..59c7d637a95f 100644 --- a/packages/react-native/ReactCommon/cxxreact/CxxModule.h +++ b/packages/react-native/ReactCommon/cxxreact/CxxModule.h @@ -69,85 +69,110 @@ 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) - : 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))) {} - 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), std::placeholders::_1)) - { - } + 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)) - { - } - - Method(std::string aname, std::function &&afunc) - : name(std::move(aname)), callbacks(2), isPromise(true), func(std::move(afunc)) - { - } + 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, 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 @@ -155,18 +180,25 @@ 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(); }) - { - } - - Method(std::string aname, std::function &&afunc, SyncTagType /*unused*/) - : name(std::move(aname)), callbacks(0), isPromise(false), syncFunc(std::move(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)) {} }; /** @@ -185,8 +217,7 @@ 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 {}; }; @@ -198,8 +229,7 @@ class CxxModule { /** * Called during the construction of CxxNativeModule. */ - void setInstance(std::weak_ptr instance) - { + void setInstance(std::weak_ptr instance) { instance_ = instance; } @@ -209,8 +239,7 @@ 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 7b42f6d9f892..92517e38e030 100644 --- a/packages/react-native/ReactCommon/cxxreact/CxxNativeModule.h +++ b/packages/react-native/ReactCommon/cxxreact/CxxNativeModule.h @@ -23,10 +23,15 @@ 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); - -class RN_EXPORT [[deprecated("This API will be removed along with the legacy architecture.")]] CxxNativeModule +[[deprecated( + "This API will be removed along with the legacy architecture.")]] 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 : public NativeModule { public: CxxNativeModule( @@ -34,16 +39,19 @@ class RN_EXPORT [[deprecated("This API will be removed along with the legacy arc 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 &¶ms, int callId) override; - MethodCallResult callSerializableNativeHook(unsigned int hookId, folly::dynamic &&args) override; + void invoke(unsigned int reactMethodId, folly::dynamic&& params, int callId) + override; + MethodCallResult callSerializableNativeHook( + unsigned int hookId, folly::dynamic&& args) override; static void setShouldWarnOnUse(bool value); @@ -56,7 +64,8 @@ class RN_EXPORT [[deprecated("This API will be removed along with the legacy arc 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/Instance.h b/packages/react-native/ReactCommon/cxxreact/Instance.h index a8026d0aaec7..f6e78ce1b982 100644 --- a/packages/react-native/ReactCommon/cxxreact/Instance.h +++ b/packages/react-native/ReactCommon/cxxreact/Instance.h @@ -34,14 +34,16 @@ 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; @@ -50,31 +52,36 @@ class RN_EXPORT [[deprecated("This API will be removed along with the legacy arc 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 loadScriptFromString( + std::unique_ptr string, + 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 &¶ms); - void callJSCallback(uint64_t callbackId, folly::dynamic &¶ms); + void callJSFunction( + std::string && module, std::string && method, folly::dynamic && params); + void callJSCallback(uint64_t callbackId, folly::dynamic && params); // 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); @@ -129,7 +136,7 @@ class RN_EXPORT [[deprecated("This API will be removed along with the legacy arc 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, @@ -154,19 +161,21 @@ class RN_EXPORT [[deprecated("This API will be removed along with the legacy arc 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.h b/packages/react-native/ReactCommon/cxxreact/JSBigString.h index a2365dee8962..85ed4e6da368 100644 --- a/packages/react-native/ReactCommon/cxxreact/JSBigString.h +++ b/packages/react-native/ReactCommon/cxxreact/JSBigString.h @@ -34,24 +34,23 @@ class JSBigString : public facebook::jsi::Buffer { JSBigString() = default; // Not copyable or movable - JSBigString(const JSBigString &) = delete; - JSBigString &operator=(const JSBigString &) = delete; - JSBigString(JSBigString &&) = delete; - JSBigString &operator=(JSBigString &&) = delete; + JSBigString(const JSBigString&) = delete; + JSBigString& operator=(const JSBigString&) = delete; + JSBigString(JSBigString&&) = delete; + JSBigString& operator=(JSBigString&&) = delete; ~JSBigString() override = 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. size_t size() const override = 0; - const uint8_t *data() const final - { - return reinterpret_cast(c_str()); + const uint8_t* data() const final { + return reinterpret_cast(c_str()); } }; @@ -59,20 +58,18 @@ class JSBigString : public facebook::jsi::Buffer { // 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(); } @@ -87,40 +84,34 @@ 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 *mutableData() - { + char* mutableData() { return m_data; } private: - char *m_data; + char* m_data; size_t m_size; }; @@ -130,12 +121,11 @@ 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; @@ -145,14 +135,15 @@ class RN_EXPORT JSBigFileString : public JSBigString { // be gone at load time (such as an OS-purgeable / LRU-evictable cache) must // catch this and degrade gracefully rather than let it surface as an // unhandled exception. - 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 08cb4d4974fe..c88add2cb0c1 100644 --- a/packages/react-native/ReactCommon/cxxreact/JSBundleType.h +++ b/packages/react-native/ReactCommon/cxxreact/JSBundleType.h @@ -41,8 +41,7 @@ struct FOLLY_PACK_ATTR Magic32 { }; struct FOLLY_PACK_ATTR BundleHeader { - BundleHeader() - { + BundleHeader() { std::memset(this, 0, sizeof(BundleHeader)); } @@ -58,17 +57,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 e69594168347..6412d3aa47d2 100644 --- a/packages/react-native/ReactCommon/cxxreact/JSExecutor.h +++ b/packages/react-native/ReactCommon/cxxreact/JSExecutor.h @@ -31,21 +31,24 @@ 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, @@ -53,7 +56,8 @@ class [[deprecated("This API will be removed along with the legacy architecture. 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. @@ -63,19 +67,22 @@ class RN_EXPORT [[deprecated("This API will be removed along with the legacy arc /** * 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, @@ -83,8 +90,10 @@ class RN_EXPORT [[deprecated("This API will be removed along with the legacy arc * 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, @@ -92,12 +101,13 @@ class RN_EXPORT [[deprecated("This API will be removed along with the legacy arc * 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; } @@ -106,8 +116,7 @@ class RN_EXPORT [[deprecated("This API will be removed along with the legacy arc * Chrome remote debugging protocol. If true, the executor should also * override the \c createAgentDelegate method. */ - virtual bool isInspectable() - { + virtual bool isInspectable() { return false; } @@ -125,21 +134,23 @@ class RN_EXPORT [[deprecated("This API will be removed along with the legacy arc 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/JSModulesUnbundle.h b/packages/react-native/ReactCommon/cxxreact/JSModulesUnbundle.h index 7abea636d56c..69aebe6cafa8 100644 --- a/packages/react-native/ReactCommon/cxxreact/JSModulesUnbundle.h +++ b/packages/react-native/ReactCommon/cxxreact/JSModulesUnbundle.h @@ -15,7 +15,8 @@ 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. @@ -28,9 +29,8 @@ class [[deprecated("This API will be removed along with the legacy architecture. 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("This API will be removed along with the legacy architecture. 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 6795c3335d85..3814e3df320b 100644 --- a/packages/react-native/ReactCommon/cxxreact/JsArgumentHelpers-inl.h +++ b/packages/react-native/ReactCommon/cxxreact/JsArgumentHelpers-inl.h @@ -14,72 +14,79 @@ 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) { - throw JsArgumentException("Error converting JavaScript arg " + toStringHelper(desc...) + " to C++: " + ex.what()); - } catch (const std::range_error &ex) { + } catch (const folly::TypeError& ex) { throw JsArgumentException( - "Could not convert argument " + toStringHelper(desc...) + " to required type: " + ex.what()); + "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()); } } } // 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); } @@ -88,30 +95,31 @@ 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 9f6c1963de42..cf5343cb3e73 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,9 +34,15 @@ 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 @@ -44,9 +50,15 @@ R jsArg(const folly::dynamic &arg, R (folly::dynamic::*asFoo)() const &, const T // 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 { @@ -56,7 +68,8 @@ 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 @@ -66,45 +79,41 @@ 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 724f7f7516de..4c31f881a7dd 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 bf2aa8eb5561..df45019ad6dc 100644 --- a/packages/react-native/ReactCommon/cxxreact/MethodCall.h +++ b/packages/react-native/ReactCommon/cxxreact/MethodCall.h @@ -17,21 +17,25 @@ 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); +[[deprecated( + "This API will be removed along with the legacy architecture.")]] 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 831a69e62bb2..cc59e3fdb566 100644 --- a/packages/react-native/ReactCommon/cxxreact/ModuleRegistry.h +++ b/packages/react-native/ReactCommon/cxxreact/ModuleRegistry.h @@ -25,12 +25,14 @@ 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 @@ -39,20 +41,28 @@ class RN_EXPORT [[deprecated("This API will be removed along with the legacy arc // 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 &¶ms, int callId); - MethodCallResult callSerializableNativeHook(unsigned int moduleId, unsigned int methodId, folly::dynamic &¶ms); + void callNativeMethod( + unsigned int moduleId, + unsigned int methodId, + folly::dynamic&& params, + int callId); + MethodCallResult callSerializableNativeHook( + unsigned int moduleId, unsigned int methodId, folly::dynamic&& params); 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/NativeModule.h b/packages/react-native/ReactCommon/cxxreact/NativeModule.h index d8f49eabd0c3..200d07726259 100644 --- a/packages/react-native/ReactCommon/cxxreact/NativeModule.h +++ b/packages/react-native/ReactCommon/cxxreact/NativeModule.h @@ -16,27 +16,32 @@ 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 &¶ms, int callId) = 0; - virtual MethodCallResult callSerializableNativeHook(unsigned int reactMethodId, folly::dynamic &&args) = 0; + virtual void invoke( + unsigned int reactMethodId, folly::dynamic&& params, 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.h b/packages/react-native/ReactCommon/cxxreact/NativeToJsBridge.h index ac0d3a0c05bf..12cdc9aac8ea 100644 --- a/packages/react-native/ReactCommon/cxxreact/NativeToJsBridge.h +++ b/packages/react-native/ReactCommon/cxxreact/NativeToJsBridge.h @@ -38,7 +38,8 @@ 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; @@ -46,7 +47,7 @@ class [[deprecated("This API will be removed along with the legacy architecture. * 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); @@ -56,12 +57,15 @@ class [[deprecated("This API will be removed along with the legacy architecture. * 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. @@ -82,9 +86,10 @@ class [[deprecated("This API will be removed along with the legacy architecture. 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(); @@ -95,7 +100,7 @@ class [[deprecated("This API will be removed along with the legacy architecture. */ void destroy(); - void runOnExecutorQueue(std::function &&task) noexcept; + void runOnExecutorQueue(std::function && task) noexcept; /** * NativeMethodCallInvoker is used by TurboModules to schedule work on the @@ -104,7 +109,7 @@ class [[deprecated("This API will be removed along with the legacy architecture. 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 16ce66943ed8..c74857f68b84 100644 --- a/packages/react-native/ReactCommon/cxxreact/RAMBundleRegistry.h +++ b/packages/react-native/ReactCommon/cxxreact/RAMBundleRegistry.h @@ -23,23 +23,25 @@ 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; 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& 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 94af5f9ddf42..f9d75dc013e1 100644 --- a/packages/react-native/ReactCommon/cxxreact/ReactMarker.h +++ b/packages/react-native/ReactCommon/cxxreact/ReactMarker.h @@ -34,7 +34,7 @@ enum ReactMarkerId { REACT_INSTANCE_INIT_STOP }; -using LogTaggedMarker = std::function; +using LogTaggedMarker = std::function; using LogTaggedMarkerBridgeless = LogTaggedMarker; #ifndef RN_EXPORT @@ -44,21 +44,18 @@ using LogTaggedMarkerBridgeless = LogTaggedMarker; /// Thread-safe holder for a LogTaggedMarker callback. Reads and writes are /// internally synchronized, so callers do not need external locking. struct RN_EXPORT AtomicLogTaggedMarker { - AtomicLogTaggedMarker &operator=(LogTaggedMarker marker) - { + AtomicLogTaggedMarker& operator=(LogTaggedMarker marker) { std::unique_lock lock(mutex_); impl_ = std::move(marker); return *this; } - explicit operator bool() const noexcept - { + explicit operator bool() const noexcept { std::shared_lock lock(mutex_); return static_cast(impl_); } - void operator()(ReactMarkerId markerId, const char *tag) const - { + void operator()(ReactMarkerId markerId, const char* tag) const { std::shared_lock lock(mutex_); if (impl_) { impl_(markerId, tag); @@ -73,21 +70,21 @@ struct RN_EXPORT AtomicLogTaggedMarker { extern RN_EXPORT AtomicLogTaggedMarker logTaggedMarkerImpl; extern RN_EXPORT void logMarker(ReactMarkerId markerId); -extern RN_EXPORT void logTaggedMarker(ReactMarkerId markerId, const char *tag); -[[deprecated("Use logMarker instead")]] -extern RN_EXPORT void logMarkerBridgeless(ReactMarkerId markerId); -[[deprecated("Use logTaggedMarker instead")]] -extern RN_EXPORT void logTaggedMarkerBridgeless(ReactMarkerId markerId, const char *tag); +extern RN_EXPORT void logTaggedMarker(ReactMarkerId markerId, const char* tag); +[[deprecated("Use logMarker instead")]] extern RN_EXPORT void +logMarkerBridgeless(ReactMarkerId markerId); +[[deprecated("Use logTaggedMarker instead")]] 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(); @@ -98,8 +95,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 980f6ce76f00..bf3907b9e522 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,11 +33,10 @@ 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 b32518823b67..922dab062fbc 100644 --- a/packages/react-native/ReactCommon/cxxreact/SystraceSection.h +++ b/packages/react-native/ReactCommon/cxxreact/SystraceSection.h @@ -17,11 +17,10 @@ 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 c18442d1b943..5b8f1a79805f 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) && !defined(WITH_PERFETTO) +#if defined(__APPLE__) && OS_LOG_TARGET_HAS_10_15_FEATURES && \ + !defined(WITH_LOOM_TRACE) && !defined(WITH_PERFETTO) 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,14 +168,24 @@ 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 d491f150d055..aa6ae8dd7508 100644 --- a/packages/react-native/ReactCommon/devtoolsruntimesettings/DevToolsRuntimeSettings.h +++ b/packages/react-native/ReactCommon/devtoolsruntimesettings/DevToolsRuntimeSettings.h @@ -12,24 +12,27 @@ namespace facebook::react { using NativePartialReloadAndProfileConfig = - NativeReactDevToolsRuntimeSettingsModulePartialReloadAndProfileConfig, std::optional>; + NativeReactDevToolsRuntimeSettingsModulePartialReloadAndProfileConfig< + std::optional, + std::optional>; template <> struct Bridging : NativeReactDevToolsRuntimeSettingsModulePartialReloadAndProfileConfigBridging< NativePartialReloadAndProfileConfig> {}; -using NativeReloadAndProfileConfig = NativeReactDevToolsRuntimeSettingsModuleReloadAndProfileConfig; +using NativeReloadAndProfileConfig = + NativeReactDevToolsRuntimeSettingsModuleReloadAndProfileConfig; template <> struct Bridging - : NativeReactDevToolsRuntimeSettingsModuleReloadAndProfileConfigBridging {}; + : NativeReactDevToolsRuntimeSettingsModuleReloadAndProfileConfigBridging< + NativeReloadAndProfileConfig> {}; class DevToolsRuntimeSettings { public: // static to persist across Turbo Module reloads - static DevToolsRuntimeSettings &getInstance() - { + static DevToolsRuntimeSettings& getInstance() { static DevToolsRuntimeSettings instance; return instance; } @@ -41,10 +44,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 ae50fd8577bf..84d9891c484c 100644 --- a/packages/react-native/ReactCommon/hermes/executor/HermesExecutorFactory.h +++ b/packages/react-native/ReactCommon/hermes/executor/HermesExecutorFactory.h @@ -13,21 +13,24 @@ 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, @@ -43,18 +46,20 @@ class [[deprecated("This API will be removed along with the legacy architecture. 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/HermesRuntimeAgentDelegate.h b/packages/react-native/ReactCommon/hermes/inspector-modern/chrome/HermesRuntimeAgentDelegate.h index 2dbc170461aa..d38e86358ca2 100644 --- a/packages/react-native/ReactCommon/hermes/inspector-modern/chrome/HermesRuntimeAgentDelegate.h +++ b/packages/react-native/ReactCommon/hermes/inspector-modern/chrome/HermesRuntimeAgentDelegate.h @@ -48,11 +48,12 @@ 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); /** @@ -63,9 +64,10 @@ 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; @@ -76,5 +78,6 @@ 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 a81b3c70e53a..7bc3396be2a1 100644 --- a/packages/react-native/ReactCommon/hermes/inspector-modern/chrome/HermesRuntimeSamplingProfileSerializer.h +++ b/packages/react-native/ReactCommon/hermes/inspector-modern/chrome/HermesRuntimeSamplingProfileSerializer.h @@ -15,10 +15,9 @@ 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 7edb1bd14272..9d0592c855ba 100644 --- a/packages/react-native/ReactCommon/hermes/inspector-modern/chrome/HermesRuntimeTargetDelegate.h +++ b/packages/react-native/ReactCommon/hermes/inspector-modern/chrome/HermesRuntimeTargetDelegate.h @@ -29,7 +29,9 @@ class HermesRuntimeTargetDelegate : public RuntimeTargetDelegate { /** * Creates a HermesRuntimeTargetDelegate for the given runtime. */ - explicit HermesRuntimeTargetDelegate(std::shared_ptr runtime, hermes::HermesRuntime &hermesRuntime); + explicit HermesRuntimeTargetDelegate( + std::shared_ptr runtime, + hermes::HermesRuntime& hermesRuntime); ~HermesRuntimeTargetDelegate() override; @@ -37,22 +39,28 @@ 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 @@ -66,7 +74,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/jserrorhandler/ErrorUtils.h b/packages/react-native/ReactCommon/jserrorhandler/ErrorUtils.h index f71377e3a9a6..9a458370eb39 100644 --- a/packages/react-native/ReactCommon/jserrorhandler/ErrorUtils.h +++ b/packages/react-native/ReactCommon/jserrorhandler/ErrorUtils.h @@ -11,6 +11,9 @@ namespace facebook::react { -void handleJSError(jsi::Runtime &runtime, const jsi::JSError &error, bool isFatal); +void handleJSError( + jsi::Runtime& runtime, + const jsi::JSError& error, + bool isFatal); } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/jserrorhandler/JsErrorHandler.h b/packages/react-native/ReactCommon/jserrorhandler/JsErrorHandler.h index 40d61f442f2a..377d3ff3737f 100644 --- a/packages/react-native/ReactCommon/jserrorhandler/JsErrorHandler.h +++ b/packages/react-native/ReactCommon/jserrorhandler/JsErrorHandler.h @@ -21,7 +21,9 @@ 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; @@ -32,17 +34,25 @@ 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(); @@ -60,9 +70,13 @@ 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 92436c4c60c0..e69787ca0ab0 100644 --- a/packages/react-native/ReactCommon/jserrorhandler/StackTraceParser.h +++ b/packages/react-native/ReactCommon/jserrorhandler/StackTraceParser.h @@ -15,7 +15,9 @@ 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/jsiexecutor/jsireact/JSIExecutor.h b/packages/react-native/ReactCommon/jsiexecutor/jsireact/JSIExecutor.h index b1a09bd61414..54ea5b3ebeb5 100644 --- a/packages/react-native/ReactCommon/jsiexecutor/jsireact/JSIExecutor.h +++ b/packages/react-native/ReactCommon/jsiexecutor/jsireact/JSIExecutor.h @@ -47,20 +47,22 @@ 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 [[deprecated("JSBigString implements jsi::Buffer directly")]] BigStringBuffer : public jsi::Buffer { +class [[deprecated( + "JSBigString implements jsi::Buffer directly")]] 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 - { + const uint8_t* data() const override { return script_->data(); } @@ -68,35 +70,45 @@ class [[deprecated("JSBigString implements jsi::Buffer directly")]] BigStringBuf 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(); } @@ -108,10 +120,10 @@ class [[deprecated("This API will be removed along with the legacy architecture. 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_; diff --git a/packages/react-native/ReactCommon/jsiexecutor/jsireact/JSINativeModules.h b/packages/react-native/ReactCommon/jsiexecutor/jsireact/JSINativeModules.h index c23f183a1463..94fc4f2b3684 100644 --- a/packages/react-native/ReactCommon/jsiexecutor/jsireact/JSINativeModules.h +++ b/packages/react-native/ReactCommon/jsiexecutor/jsireact/JSINativeModules.h @@ -21,10 +21,11 @@ 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: @@ -32,7 +33,8 @@ class [[deprecated("This API will be removed along with the legacy architecture. 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/ConsoleMessage.h b/packages/react-native/ReactCommon/jsinspector-modern/ConsoleMessage.h index c22a969b3871..6130ca572d7e 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/ConsoleMessage.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/ConsoleMessage.h @@ -43,14 +43,18 @@ 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; }; @@ -68,16 +72,17 @@ 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/ConsoleTask.h b/packages/react-native/ReactCommon/jsinspector-modern/ConsoleTask.h index 599396ca614f..5c98245f7635 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/ConsoleTask.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/ConsoleTask.h @@ -24,15 +24,15 @@ class ConsoleTask { explicit ConsoleTask(std::shared_ptr taskContext); ~ConsoleTask(); - ConsoleTask(const ConsoleTask &) = default; - ConsoleTask &operator=(const ConsoleTask &) = delete; + ConsoleTask(const ConsoleTask&) = default; + ConsoleTask& operator=(const ConsoleTask&) = delete; - ConsoleTask(ConsoleTask &&) = default; - ConsoleTask &operator=(ConsoleTask &&) = delete; + ConsoleTask(ConsoleTask&&) = default; + ConsoleTask& operator=(ConsoleTask&&) = delete; private: std::shared_ptr taskContext_; - ConsoleTaskOrchestrator &orchestrator_; + ConsoleTaskOrchestrator& orchestrator_; }; } // namespace facebook::react::jsinspector_modern diff --git a/packages/react-native/ReactCommon/jsinspector-modern/ConsoleTaskContext.h b/packages/react-native/ReactCommon/jsinspector-modern/ConsoleTaskContext.h index 86fa68a571ba..dcb4001f4494 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/ConsoleTaskContext.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/ConsoleTaskContext.h @@ -27,46 +27,47 @@ class ConsoleTaskId { ConsoleTaskId() = default; ~ConsoleTaskId() = default; - ConsoleTaskId(const ConsoleTaskId &) = default; - ConsoleTaskId &operator=(const ConsoleTaskId &) = default; + ConsoleTaskId(const ConsoleTaskId&) = default; + ConsoleTaskId& operator=(const ConsoleTaskId&) = default; - ConsoleTaskId(ConsoleTaskId &&) = default; - ConsoleTaskId &operator=(ConsoleTaskId &&) = default; + ConsoleTaskId(ConsoleTaskId&&) = default; + ConsoleTaskId& operator=(ConsoleTaskId&&) = default; - bool operator==(const ConsoleTaskId &) const = default; - inline operator bool() const - { + bool operator==(const ConsoleTaskId&) const = default; + inline operator bool() const { return (bool)id_; } - explicit inline operator void *() const - { + explicit inline operator void*() const { return id_; } private: - explicit inline ConsoleTaskId(void *id) : id_(id) - { + explicit inline ConsoleTaskId(void* id) : id_(id) { assert(id_ != nullptr); } - void *id_{nullptr}; + void* id_{nullptr}; friend class ConsoleTaskContext; }; -class ConsoleTaskContext : public std::enable_shared_from_this { +class ConsoleTaskContext + : public std::enable_shared_from_this { public: - ConsoleTaskContext(jsi::Runtime &runtime, RuntimeTargetDelegate &runtimeTargetDelegate, std::string name); + ConsoleTaskContext( + jsi::Runtime& runtime, + RuntimeTargetDelegate& runtimeTargetDelegate, + std::string name); ~ConsoleTaskContext(); // Can't be moved or copied: the address of `ConsoleTaskContext` is used to // identify this task and all corresponding invocations. - ConsoleTaskContext(const ConsoleTaskContext &) = delete; - ConsoleTaskContext &operator=(const ConsoleTaskContext &) = delete; + ConsoleTaskContext(const ConsoleTaskContext&) = delete; + ConsoleTaskContext& operator=(const ConsoleTaskContext&) = delete; - ConsoleTaskContext(ConsoleTaskContext &&) = delete; - ConsoleTaskContext &operator=(ConsoleTaskContext &&) = delete; + ConsoleTaskContext(ConsoleTaskContext&&) = delete; + ConsoleTaskContext& operator=(ConsoleTaskContext&&) = delete; /** * Unique identifier that is calculated based on the address of @@ -83,9 +84,9 @@ class ConsoleTaskContext : public std::enable_shared_from_this stackTrace_; }; @@ -94,9 +95,9 @@ class ConsoleTaskContext : public std::enable_shared_from_this struct hash { - size_t operator()(const facebook::react::jsinspector_modern::ConsoleTaskId &id) const - { - return std::hash{}(static_cast(id)); + size_t operator()( + const facebook::react::jsinspector_modern::ConsoleTaskId& id) const { + return std::hash{}(static_cast(id)); } }; } // namespace std diff --git a/packages/react-native/ReactCommon/jsinspector-modern/ConsoleTaskOrchestrator.h b/packages/react-native/ReactCommon/jsinspector-modern/ConsoleTaskOrchestrator.h index 79d645baeda9..8217d054d8e9 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/ConsoleTaskOrchestrator.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/ConsoleTaskOrchestrator.h @@ -17,17 +17,19 @@ namespace facebook::react::jsinspector_modern { class ConsoleTaskOrchestrator { public: - static ConsoleTaskOrchestrator &getInstance(); + static ConsoleTaskOrchestrator& getInstance(); ~ConsoleTaskOrchestrator() = default; - ConsoleTaskOrchestrator(const ConsoleTaskOrchestrator &) = delete; - ConsoleTaskOrchestrator &operator=(const ConsoleTaskOrchestrator &) = delete; + ConsoleTaskOrchestrator(const ConsoleTaskOrchestrator&) = delete; + ConsoleTaskOrchestrator& operator=(const ConsoleTaskOrchestrator&) = delete; - ConsoleTaskOrchestrator(ConsoleTaskOrchestrator &&) = delete; - ConsoleTaskOrchestrator &operator=(ConsoleTaskOrchestrator &&) = delete; + ConsoleTaskOrchestrator(ConsoleTaskOrchestrator&&) = delete; + ConsoleTaskOrchestrator& operator=(ConsoleTaskOrchestrator&&) = delete; - void scheduleTask(ConsoleTaskId taskId, std::weak_ptr taskContext); + void scheduleTask( + ConsoleTaskId taskId, + std::weak_ptr taskContext); void cancelTask(ConsoleTaskId taskId); void startTask(ConsoleTaskId taskId); diff --git a/packages/react-native/ReactCommon/jsinspector-modern/EmulationAgent.h b/packages/react-native/ReactCommon/jsinspector-modern/EmulationAgent.h index 161b8ac82119..ce991f14ec0d 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/EmulationAgent.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/EmulationAgent.h @@ -27,7 +27,9 @@ class EmulationAgent { * is attached to. The caller is responsible for ensuring that the * HostTargetDelegate and underlying HostTarget both outlive the agent. */ - EmulationAgent(FrontendChannel frontendChannel, HostTargetController &hostTargetController); + EmulationAgent( + FrontendChannel frontendChannel, + HostTargetController& hostTargetController); /** * Handle a CDP request. The response will be sent over the provided @@ -35,13 +37,13 @@ class EmulationAgent { * \param req The parsed request. * \returns true if the request was handled. */ - bool handleRequest(const cdp::PreparsedRequest &req); + bool handleRequest(const cdp::PreparsedRequest& req); private: - void handleSetEmulatedMedia(const cdp::PreparsedRequest &req); + void handleSetEmulatedMedia(const cdp::PreparsedRequest& req); FrontendChannel frontendChannel_; - HostTargetController &hostTargetController_; + HostTargetController& hostTargetController_; }; } // namespace facebook::react::jsinspector_modern diff --git a/packages/react-native/ReactCommon/jsinspector-modern/EnumArray.h b/packages/react-native/ReactCommon/jsinspector-modern/EnumArray.h index ae25023c4cfb..0abef955c28c 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/EnumArray.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/EnumArray.h @@ -18,23 +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< + std::underlying_type_t, + int>&& requires { IndexType::kMaxValue; } && + (static_cast(IndexType::kMaxValue) < std::numeric_limits::max()) -class EnumArray { + 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 c47bfc9ba26f..b8c099a9c3c9 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,14 +49,15 @@ 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_; } @@ -74,16 +75,20 @@ 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; + friend struct std::hash< + facebook::react::jsinspector_modern::ExecutionContextSelector>; }; -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 @@ -91,9 +96,12 @@ 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.h b/packages/react-native/ReactCommon/jsinspector-modern/FallbackRuntimeAgentDelegate.h index 17eeaf666f14..1c9934f02e4a 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 0af607370a59..9507eb2379d4 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/FallbackRuntimeTargetDelegate.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/FallbackRuntimeTargetDelegate.h @@ -25,16 +25,20 @@ 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; @@ -42,7 +46,8 @@ 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.h b/packages/react-native/ReactCommon/jsinspector-modern/HostAgent.h index 083632667f14..4b088634604e 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 @@ -98,12 +98,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.h b/packages/react-native/ReactCommon/jsinspector-modern/HostTarget.h index 6abf9bb64f26..9eaf63ad4e09 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/HostTarget.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/HostTarget.h @@ -60,7 +60,8 @@ struct HostTargetMetadata { }; /** - * Receives any performance-related events from a HostTarget: could be Tracing, Performance Monitor, etc. + * Receives any performance-related events from a HostTarget: could be Tracing, + * Performance Monitor, etc. */ class HostTargetTracingDelegate { public: @@ -68,25 +69,28 @@ class HostTargetTracingDelegate { virtual ~HostTargetTracingDelegate() = default; /** - * Fired when the corresponding HostTarget started recording a tracing session. - * The tracing state is expected to be initialized at this point and the delegate should be able to record events - * through HostTarget. + * Fired when the corresponding HostTarget started recording a tracing + * session. The tracing state is expected to be initialized at this point and + * the delegate should be able to record events through HostTarget. */ - virtual void onTracingStarted(tracing::Mode /* tracingMode */, bool /* screenshotsCategoryEnabled */) {} + virtual void onTracingStarted( + tracing::Mode /* tracingMode */, + bool /* screenshotsCategoryEnabled */) {} /** - * Fired when the corresponding HostTarget is about to end recording a tracing session. - * The tracing state is expected to be still initialized during the call and the delegate should be able to record - * events through HostTarget. + * Fired when the corresponding HostTarget is about to end recording a tracing + * session. The tracing state is expected to be still initialized during the + * call and the delegate should be able to record events through HostTarget. * * Any attempts to record events after this callback is finished will fail. */ virtual void onTracingStopped() {} - HostTargetTracingDelegate(const HostTargetTracingDelegate &) = delete; - HostTargetTracingDelegate(HostTargetTracingDelegate &&) = delete; - HostTargetTracingDelegate &operator=(const HostTargetTracingDelegate &) = delete; - HostTargetTracingDelegate &operator=(HostTargetTracingDelegate &&) = delete; + HostTargetTracingDelegate(const HostTargetTracingDelegate&) = delete; + HostTargetTracingDelegate(HostTargetTracingDelegate&&) = delete; + HostTargetTracingDelegate& operator=(const HostTargetTracingDelegate&) = + delete; + HostTargetTracingDelegate& operator=(HostTargetTracingDelegate&&) = delete; }; /** @@ -97,10 +101,10 @@ class HostTargetTracingDelegate { 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. @@ -115,9 +119,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; } }; @@ -130,8 +134,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; } }; @@ -156,8 +160,7 @@ class HostTargetDelegate : public LoadNetworkResourceDelegate { */ std::string colorScheme; - inline bool operator==(const SetEmulatedMediaRequest &rhs) const - { + inline bool operator==(const SetEmulatedMediaRequest& rhs) const { return colorScheme == rhs.colorScheme; } }; @@ -175,7 +178,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 @@ -187,13 +190,14 @@ 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; /** * [Experimental] Called when the runtime has new data for the V2 Perf * Monitor overlay. This is called on the inspector thread. */ - virtual void unstable_onPerfIssueAdded(const PerfIssuePayload & /*issue*/) {} + virtual void unstable_onPerfIssueAdded(const PerfIssuePayload& /*issue*/) {} /** * Called by NetworkIOAgent on handling a `Network.loadNetworkResource` CDP @@ -202,9 +206,8 @@ 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."); } @@ -215,8 +218,8 @@ class HostTargetDelegate : public LoadNetworkResourceDelegate { * view, encode it to the requested format, and return base64-encoded * image data. Return std::nullopt on failure. */ - virtual std::optional captureScreenshot(const PageCaptureScreenshotRequest & /*request*/) - { + virtual std::optional captureScreenshot( + const PageCaptureScreenshotRequest& /*request*/) { return std::nullopt; } @@ -227,16 +230,15 @@ class HostTargetDelegate : public LoadNetworkResourceDelegate { * * \returns true if the override was applied successfully. */ - virtual bool onSetEmulatedMedia(const SetEmulatedMediaRequest & /*request*/) - { + virtual bool onSetEmulatedMedia(const SetEmulatedMediaRequest& /*request*/) { return false; } /** - * An optional delegate that will be used by HostTarget to notify about tracing-related events. + * An optional delegate that will be used by HostTarget to notify about + * tracing-related events. */ - virtual HostTargetTracingDelegate *getTracingDelegate() - { + virtual HostTargetTracingDelegate* getTracingDelegate() { return nullptr; } }; @@ -247,9 +249,9 @@ class HostTargetDelegate : public LoadNetworkResourceDelegate { */ class HostTargetController final { public: - explicit HostTargetController(HostTarget &target); + explicit HostTargetController(HostTarget& target); - HostTargetDelegate &getDelegate(); + HostTargetDelegate& getDelegate(); bool hasInstance() const; @@ -280,7 +282,9 @@ class HostTargetController final { * * \return false if already tracing, true otherwise. */ - bool startTracing(tracing::Mode mode, std::set enabledCategories); + bool startTracing( + tracing::Mode mode, + std::set enabledCategories); /** * Stops previously started trace recording. @@ -289,12 +293,13 @@ class HostTargetController final { /** * If there is a stashed background trace, emit it to all eligible sessions. - * \return true if an eligible session is found (even if there was no stashed background trace). + * \return true if an eligible session is found (even if there was no stashed + * background trace). */ bool maybeEmitStashedBackgroundTrace(); private: - HostTarget &target_; + HostTarget& target_; size_t pauseOverlayCounter_{0}; }; @@ -303,7 +308,8 @@ 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. @@ -321,12 +327,14 @@ class JSINSPECTOR_EXPORT HostTarget : public EnableExecutorFromThis * 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); - - HostTarget(const HostTarget &) = delete; - HostTarget(HostTarget &&) = delete; - HostTarget &operator=(const HostTarget &) = delete; - HostTarget &operator=(HostTarget &&) = delete; + 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(); /** @@ -336,7 +344,8 @@ class JSINSPECTOR_EXPORT HostTarget : public EnableExecutorFromThis * 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. @@ -348,14 +357,14 @@ class JSINSPECTOR_EXPORT HostTarget : public EnableExecutorFromThis * (or the HostTarget is destroyed). \pre There isn't currently an instance * registered with this HostTarget. */ - InstanceTarget ®isterInstance(InstanceTargetDelegate &delegate); + InstanceTarget& registerInstance(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 @@ -371,7 +380,8 @@ class JSINSPECTOR_EXPORT HostTarget : 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); /** * Starts trace recording for this HostTarget. @@ -381,7 +391,9 @@ class JSINSPECTOR_EXPORT HostTarget : public EnableExecutorFromThis * * \return false if already tracing, true otherwise. */ - bool startTracing(tracing::Mode mode, std::set enabledCategories); + bool startTracing( + tracing::Mode mode, + std::set enabledCategories); /** * Stops previously started trace recording. @@ -398,8 +410,8 @@ class JSINSPECTOR_EXPORT HostTarget : public EnableExecutorFromThis bool stopAndMaybeEmitBackgroundTrace(); /** - * An endpoint for the Host to report frame timings that will be recorded if and only if there is currently an active - * tracing session. + * An endpoint for the Host to report frame timings that will be recorded if + * and only if there is currently an active tracing session. */ void recordFrameTimings(tracing::FrameTimingSequence frameTimingSequence); #pragma endregion @@ -413,9 +425,9 @@ class JSINSPECTOR_EXPORT HostTarget : public EnableExecutorFromThis * 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 @@ -436,26 +448,26 @@ class JSINSPECTOR_EXPORT HostTarget : public EnableExecutorFromThis */ std::unique_ptr traceRecording_{nullptr}; /** - * Previously recorded HostTracingProfile that will be emitted when CDP session is created - * and enables ReactNativeApplication. Once emitted, the value will be cleared. + * Previously recorded HostTracingProfile that will be emitted when CDP + * session is created and enables ReactNativeApplication. Once emitted, the + * value will be cleared. */ std::optional stashedTracingProfile_; /** * Protects the state inside traceRecording_. * - * Calls to tracing subsystem could happen from different threads, depending on the mode (Background or CDP) and - * the method: the Host could report frame timings from any arbitrary thread. + * Calls to tracing subsystem could happen from different threads, depending + * on the mode (Background or CDP) and the method: the Host could report frame + * timings from any arbitrary thread. */ std::mutex tracingMutex_; #pragma endregion - inline HostTargetDelegate &getDelegate() - { + inline HostTargetDelegate& getDelegate() { return delegate_; } - inline bool hasInstance() const - { + inline bool hasInstance() const { return currentInstance_ != nullptr; } @@ -467,8 +479,9 @@ class JSINSPECTOR_EXPORT HostTarget : public EnableExecutorFromThis void installPerfIssuesBinding(); /** - * If there is a stashed background trace, emit it to the first eligible session. - * \return true if an eligible session is found (even if there was no stashed background trace). + * If there is a stashed background trace, emit it to the first eligible + * session. \return true if an eligible session is found (even if there was no + * stashed background trace). */ bool maybeEmitStashedBackgroundTrace(); @@ -478,6 +491,6 @@ class JSINSPECTOR_EXPORT HostTarget : public EnableExecutorFromThis 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 193d9e2aa970..8a82c2a50019 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/HostTargetTraceRecording.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/HostTargetTraceRecording.h @@ -35,25 +35,23 @@ namespace facebook::react::jsinspector_modern { class HostTargetTraceRecording { public: HostTargetTraceRecording( - HostTarget &hostTarget, + HostTarget& hostTarget, tracing::Mode tracingMode, std::set enabledCategories, std::optional windowSize = std::nullopt); - 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. @@ -70,9 +68,11 @@ class HostTargetTraceRecording { tracing::HostTracingProfile stop(); /** - * Adds the frame timing sequence to the current state of this trace recording. + * Adds the frame timing sequence to the current state of this trace + * recording. * - * The caller guarantees the protection from data races. This is protected by the tracing mutex in HostTarget. + * The caller guarantees the protection from data races. This is protected by + * the tracing mutex in HostTarget. */ void recordFrameTimings(tracing::FrameTimingSequence frameTimingSequence); @@ -80,7 +80,7 @@ class HostTargetTraceRecording { /** * The Host for which this Trace Recording is going to happen. */ - HostTarget &hostTarget_; + HostTarget& hostTarget_; /** * The mode in which this trace recording was initialized. diff --git a/packages/react-native/ReactCommon/jsinspector-modern/HostTargetTracing.h b/packages/react-native/ReactCommon/jsinspector-modern/HostTargetTracing.h index c007212445d4..cbaaea572e07 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/HostTargetTracing.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/HostTargetTracing.h @@ -22,23 +22,26 @@ namespace facebook::react::jsinspector_modern { /** * Emits a captured HostTracingProfile in a series of - * Tracing.dataCollected events, followed by a Tracing.tracingComplete event, to zero or more - * FrontendChannels. If \p isBackgroundTrace is true, a ReactNativeApplication.traceRequested - * notification is sent to each FrontendChannel before the trace events are emitted. + * Tracing.dataCollected events, followed by a Tracing.tracingComplete event, to + * zero or more FrontendChannels. If \p isBackgroundTrace is true, a + * ReactNativeApplication.traceRequested notification is sent to each + * FrontendChannel before the trace events are emitted. */ template void emitNotificationsForTracingProfile( - tracing::HostTracingProfile &&hostTracingProfile, - const ChannelsRange &channels, + tracing::HostTracingProfile&& hostTracingProfile, + const ChannelsRange& channels, bool isBackgroundTrace) requires std::ranges::range && - std::convertible_to, FrontendChannel> -{ + std::convertible_to< + std::ranges::range_value_t, + FrontendChannel> { /** * Maximum serialized byte size of a Trace Event chunk before it is flushed * with a Tracing.dataCollected event. */ - static constexpr size_t TRACE_EVENT_CHUNK_MAX_BYTES = 10 * 1024 * 1024; // 10 MiB + static constexpr size_t TRACE_EVENT_CHUNK_MAX_BYTES = + 10 * 1024 * 1024; // 10 MiB /** * The maximum number of ProfileChunk trace events @@ -51,39 +54,43 @@ void emitNotificationsForTracingProfile( } if (isBackgroundTrace) { - for (auto &frontendChannel : channels) { - frontendChannel(cdp::jsonNotification("ReactNativeApplication.traceRequested")); + for (auto& frontendChannel : channels) { + frontendChannel( + cdp::jsonNotification("ReactNativeApplication.traceRequested")); } } // Serialize each chunk once and send it to all eligible sessions. tracing::HostTracingProfileSerializer::emitAsDataCollectedChunks( std::move(hostTracingProfile), - [&](folly::dynamic &&serializedChunk) { - for (auto &frontendChannel : channels) { - frontendChannel( - cdp::jsonNotification("Tracing.dataCollected", folly::dynamic::object("value", serializedChunk))); + [&](folly::dynamic&& serializedChunk) { + for (auto& frontendChannel : channels) { + frontendChannel(cdp::jsonNotification( + "Tracing.dataCollected", + folly::dynamic::object("value", serializedChunk))); } }, TRACE_EVENT_CHUNK_MAX_BYTES, PROFILE_TRACE_EVENT_CHUNK_SIZE); - for (auto &frontendChannel : channels) { - frontendChannel( - cdp::jsonNotification("Tracing.tracingComplete", folly::dynamic::object("dataLossOccurred", false))); + for (auto& frontendChannel : channels) { + frontendChannel(cdp::jsonNotification( + "Tracing.tracingComplete", + folly::dynamic::object("dataLossOccurred", false))); } } /** - * Convenience overload of emitNotificationsForTracingProfile() for a single FrontendChannel. + * Convenience overload of emitNotificationsForTracingProfile() for a single + * FrontendChannel. */ inline void emitNotificationsForTracingProfile( - tracing::HostTracingProfile &&hostTracingProfile, - const FrontendChannel &channel, - bool isBackgroundTrace) -{ + tracing::HostTracingProfile&& hostTracingProfile, + const FrontendChannel& channel, + bool isBackgroundTrace) { std::array channels{channel}; - emitNotificationsForTracingProfile(std::move(hostTracingProfile), channels, isBackgroundTrace); + emitNotificationsForTracingProfile( + std::move(hostTracingProfile), channels, isBackgroundTrace); } } // namespace facebook::react::jsinspector_modern diff --git a/packages/react-native/ReactCommon/jsinspector-modern/InspectorFlags.h b/packages/react-native/ReactCommon/jsinspector-modern/InspectorFlags.h index 5cbe81978b9b..f116daf0846f 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/InspectorFlags.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/InspectorFlags.h @@ -18,10 +18,10 @@ namespace facebook::react::jsinspector_modern { */ class InspectorFlags { public: - static InspectorFlags &getInstance(); + static InspectorFlags& getInstance(); - InspectorFlags(const InspectorFlags &) = delete; - InspectorFlags &operator=(const InspectorFlags &) = delete; + InspectorFlags(const InspectorFlags&) = delete; + InspectorFlags& operator=(const InspectorFlags&) = delete; /** * Flag determining if the inspector backend should strictly assert that only @@ -75,7 +75,7 @@ class InspectorFlags { bool fuseboxEnabled; bool isProfilingBuild; bool perfIssuesEnabled; - bool operator==(const Values &) const = default; + bool operator==(const Values&) const = default; }; InspectorFlags() = default; @@ -86,7 +86,7 @@ class InspectorFlags { 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 97e80c6426dc..1668019be912 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/InspectorInterfaces.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/InspectorInterfaces.h @@ -38,7 +38,8 @@ struct InspectorTargetCapabilities { bool nativeSourceCodeFetching = false; }; -folly::dynamic targetCapabilitiesToDynamic(const InspectorTargetCapabilities &capabilities); +folly::dynamic targetCapabilitiesToDynamic( + const InspectorTargetCapabilities& capabilities); struct InspectorPageDescription { const int id; @@ -89,7 +90,8 @@ 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; @@ -103,8 +105,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; @@ -125,13 +127,16 @@ 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; /** * Get the current \c InspectorSystemState object. @@ -141,10 +146,10 @@ class JSINSPECTOR_EXPORT IInspector : public IDestructible { 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(); } @@ -154,7 +159,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.h b/packages/react-native/ReactCommon/jsinspector-modern/InspectorPackagerConnection.h index b55df312eab0..a6d2bca845ac 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,7 +78,9 @@ 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 d669bfd5ac6a..a30298ad8e28 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/InspectorPackagerConnectionImpl.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/InspectorPackagerConnectionImpl.h @@ -18,10 +18,11 @@ 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; @@ -38,7 +39,7 @@ class InspectorPackagerConnection::Impl : public IWebSocketDelegate, bool isConnected() const; void connect(); void closeQuietly(); - void sendEventToAllConnections(const std::string &event); + void sendEventToAllConnections(const std::string& event); /** * Send a message to the packager as soon as possible. This method is safe @@ -49,8 +50,8 @@ class InspectorPackagerConnection::Impl : public IWebSocketDelegate, void scheduleSendToPackager( folly::dynamic message, SessionId sourceSessionId, - const std::string &sourcePageId, - const std::string &sourceProxySessionId); + const std::string& sourcePageId, + const std::string& sourceProxySessionId); private: struct Session { @@ -59,56 +60,67 @@ class InspectorPackagerConnection::Impl : public IWebSocketDelegate, std::string proxySessionId; // Session ID assigned by the proxy }; class RemoteConnection; - using PageSessions = std::unordered_map; - using InspectorSessionsByPage = std::unordered_map; + using PageSessions = + std::unordered_map; + using InspectorSessionsByPage = + std::unordered_map; Impl( std::string url, 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); /** * Finds the page and session and referenced by the given message payload. - * Returns a pair of valid (dereferenceable) iterators if found, or nullopt otherwise. - * Supports both legacy single-session mode (proxySessionId == missing or empty) and multi-session mode - * (proxySessionId == some unique identifier assigned by the proxy). + * Returns a pair of valid (dereferenceable) iterators if found, or nullopt + * otherwise. Supports both legacy single-session mode (proxySessionId == + * missing or empty) and multi-session mode (proxySessionId == some unique + * identifier assigned by the proxy). */ - std::optional> findPageAndSession( - const folly::const_dynamic_view &payload, + std::optional< + std::pair> + findPageAndSession( + const folly::const_dynamic_view& payload, std::string_view caller); /** - * Given a pair of (dereferenceable) iterators as returned by findPageAndSession, disconnects the - * given session. Invalidates the session iterator and may invalidate the page iterator. Returns - * the page iterator if still valid, or the corresponding end() iterator otherwise - this is - * useful when disconnecting multiple sessions in a loop. + * Given a pair of (dereferenceable) iterators as returned by + * findPageAndSession, disconnects the given session. Invalidates the session + * iterator and may invalidate the page iterator. Returns the page iterator if + * still valid, or the corresponding end() iterator otherwise - this is useful + * when disconnecting multiple sessions in a loop. */ InspectorSessionsByPage::iterator disconnectSession( - std::pair sessionIterators); + std::pair + sessionIterators); /** * Switch to legacy single-session mode. */ - void disconnectNonLegacySessions(const std::string &pageId); + void disconnectNonLegacySessions(const std::string& pageId); 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; @@ -138,7 +150,8 @@ class InspectorPackagerConnection::Impl : public IWebSocketDelegate, SessionId nextSessionId_{1}; }; -class InspectorPackagerConnection::Impl::RemoteConnection : public IRemoteConnection { +class InspectorPackagerConnection::Impl::RemoteConnection + : public IRemoteConnection { public: RemoteConnection( std::weak_ptr owningPackagerConnection, @@ -151,7 +164,8 @@ class InspectorPackagerConnection::Impl::RemoteConnection : public IRemoteConnec void onDisconnect() override; private: - const std::weak_ptr owningPackagerConnection_; + const std::weak_ptr + owningPackagerConnection_; const std::string pageId_; const SessionId sessionId_; const std::string proxySessionId_; diff --git a/packages/react-native/ReactCommon/jsinspector-modern/InstanceAgent.h b/packages/react-native/ReactCommon/jsinspector-modern/InstanceAgent.h index e073067c14e9..d465601254db 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/InstanceAgent.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/InstanceAgent.h @@ -35,14 +35,17 @@ 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 @@ -50,7 +53,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. @@ -63,9 +66,9 @@ class InstanceAgent final { void maybeSendPendingConsoleMessages(); FrontendChannel frontendChannel_; - InstanceTarget &target_; + InstanceTarget& target_; std::shared_ptr runtimeAgent_; - SessionState &sessionState_; + SessionState& sessionState_; }; #pragma mark - Tracing @@ -78,14 +81,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 1bcc09f34403..4ccd7df6dd24 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 &&) = delete; - InstanceTargetDelegate &operator=(const InstanceTargetDelegate &) = delete; - InstanceTargetDelegate &operator=(InstanceTargetDelegate &&) = delete; + InstanceTargetDelegate(const InstanceTargetDelegate&) = delete; + InstanceTargetDelegate(InstanceTargetDelegate&&) = delete; + InstanceTargetDelegate& operator=(const InstanceTargetDelegate&) = delete; + InstanceTargetDelegate& operator=(InstanceTargetDelegate&&) = delete; virtual ~InstanceTargetDelegate(); }; @@ -58,16 +58,18 @@ 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. @@ -78,14 +80,17 @@ 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 ®isterRuntime(RuntimeTargetDelegate &delegate, RuntimeExecutor executor); + RuntimeTarget& registerRuntime( + RuntimeTargetDelegate& delegate, + RuntimeExecutor executor); /** * Unregisters a JS runtime from this InstanceTarget. This destroys the \c @@ -94,7 +99,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: /** @@ -105,9 +110,11 @@ 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.h b/packages/react-native/ReactCommon/jsinspector-modern/NetworkIOAgent.h index c0561f5e4af3..816719534205 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/NetworkIOAgent.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/NetworkIOAgent.h @@ -44,8 +44,7 @@ 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 @@ -66,7 +65,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)); @@ -81,8 +80,7 @@ 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); @@ -93,8 +91,7 @@ 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; @@ -109,10 +106,11 @@ 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; /** @@ -122,7 +120,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. @@ -139,7 +137,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. @@ -165,10 +163,12 @@ 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 ¶ms, + [[maybe_unused]] const LoadNetworkResourceRequest& params, [[maybe_unused]] ScopedExecutor executor) = 0; }; @@ -207,23 +207,25 @@ 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()) {} ~NetworkIOAgent(); - NetworkIOAgent(const NetworkIOAgent &) = delete; - NetworkIOAgent &operator=(const NetworkIOAgent &) = delete; - NetworkIOAgent(NetworkIOAgent &&) = delete; - NetworkIOAgent &operator=(NetworkIOAgent &&) = delete; + NetworkIOAgent(const NetworkIOAgent&) = delete; + NetworkIOAgent& operator=(const NetworkIOAgent&) = delete; + NetworkIOAgent(NetworkIOAgent&&) = delete; + NetworkIOAgent& operator=(NetworkIOAgent&&) = delete; /** * 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: /** @@ -266,24 +268,26 @@ 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/PerfMonitorV2.h b/packages/react-native/ReactCommon/jsinspector-modern/PerfMonitorV2.h index e8336f4755ab..e7a7a2e13acd 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/PerfMonitorV2.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/PerfMonitorV2.h @@ -27,15 +27,16 @@ struct PerfIssuePayload { */ class PerfMonitorUpdateHandler { public: - explicit PerfMonitorUpdateHandler(HostTargetDelegate &delegate) : delegate_(delegate) {} + explicit PerfMonitorUpdateHandler(HostTargetDelegate& delegate) + : delegate_(delegate) {} /** * Handle a new "__react_native_perf_issues_reporter" message. */ - void handlePerfIssueAdded(const std::string &message); + void handlePerfIssueAdded(const std::string& message); private: - HostTargetDelegate &delegate_; + HostTargetDelegate& delegate_; }; } // namespace facebook::react::jsinspector_modern diff --git a/packages/react-native/ReactCommon/jsinspector-modern/RuntimeAgent.h b/packages/react-native/ReactCommon/jsinspector-modern/RuntimeAgent.h index d6a584ede942..ced62d247f0f 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,14 +63,16 @@ 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); /** * Called by RuntimeTarget when JS calls __notifyFastRefreshComplete(). @@ -92,8 +94,8 @@ class RuntimeAgent final { private: FrontendChannel frontendChannel_; - RuntimeTargetController &targetController_; - SessionState &sessionState_; + RuntimeTargetController& targetController_; + SessionState& sessionState_; const std::unique_ptr delegate_; const ExecutionContextDescription executionContextDescription_; }; @@ -108,12 +110,14 @@ class RuntimeAgent final { */ class RuntimeTracingAgent : public 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 886fa54c7aad..911cacb6883c 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,8 +43,7 @@ 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 0136ba376eed..e7d018563ffb 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/RuntimeTarget.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/RuntimeTarget.h @@ -54,9 +54,10 @@ 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; /** @@ -70,7 +71,9 @@ 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. @@ -90,7 +93,9 @@ 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. @@ -110,7 +115,8 @@ 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; }; /** @@ -120,14 +126,14 @@ class RuntimeTargetController { public: enum class Domain { Log, Network, Runtime, 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); /** * Evaluates the given JavaScript source on the runtime's thread before any @@ -135,13 +141,16 @@ class RuntimeTargetController { * Page.addScriptToEvaluateOnNewDocument scripts onto a freshly created * runtime. */ - void installScriptToEvaluateOnNewDocument(const std::string &source); + void installScriptToEvaluateOnNewDocument(const std::string& source); /** * 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 ¬ifyingAgent); + void notifyDomainStateChanged( + Domain domain, + bool enabled, + const RuntimeAgent& notifyingAgent); /** * Start sampling profiler for the corresponding RuntimeTarget. @@ -162,13 +171,14 @@ class RuntimeTargetController { void emitTracingStateChange(bool isTracing); 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 @@ -189,15 +199,15 @@ class JSINSPECTOR_EXPORT RuntimeTarget : public EnableExecutorFromThis 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(); /** @@ -209,7 +219,9 @@ class JSINSPECTOR_EXPORT RuntimeTarget : public EnableExecutorFromThis createAgent(const FrontendChannel &channel, SessionState &sessionState); + std::shared_ptr createAgent( + const FrontendChannel& channel, + SessionState& sessionState); /** * Creates a new RuntimeTracingAgent. @@ -219,7 +231,8 @@ class JSINSPECTOR_EXPORT RuntimeTarget : public EnableExecutorFromThis createTracingAgent(tracing::TraceRecordingState &state); + std::shared_ptr createTracingAgent( + tracing::TraceRecordingState& state); private: using Domain = RuntimeTargetController::Domain; @@ -243,11 +256,11 @@ class JSINSPECTOR_EXPORT RuntimeTarget : public EnableExecutorFromThis agents_; RuntimeTargetController controller_{*this}; @@ -255,7 +268,8 @@ class JSINSPECTOR_EXPORT RuntimeTarget : public EnableExecutorFromThis> agentsByEnabledDomain_; + EnumArray> + agentsByEnabledDomain_; /** * For each Domain, contains true if the domain has been enabled by any @@ -295,7 +309,7 @@ class JSINSPECTOR_EXPORT RuntimeTarget : public EnableExecutorFromThis processDomainChange(Domain domain, bool enabled, const RuntimeAgent ¬ifyingAgent); + std::pair processDomainChange( + Domain domain, + bool enabled, + const RuntimeAgent& notifyingAgent); /** * Checks whether the given domain is enabled in at least one session diff --git a/packages/react-native/ReactCommon/jsinspector-modern/RuntimeTargetGlobalStateObserver.h b/packages/react-native/ReactCommon/jsinspector-modern/RuntimeTargetGlobalStateObserver.h index af76002d6ecd..40e6757d447f 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/RuntimeTargetGlobalStateObserver.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/RuntimeTargetGlobalStateObserver.h @@ -24,10 +24,10 @@ namespace facebook::react::jsinspector_modern { * "onSessionStatusChange"). */ void installGlobalStateObserver( - jsi::Runtime &runtime, - const char *globalName, - const char *statusProperty, - const char *callbackName); + jsi::Runtime& runtime, + const char* globalName, + const char* statusProperty, + const char* callbackName); /** * Emits a state change to an installed global state observer by calling its @@ -37,6 +37,10 @@ void installGlobalStateObserver( * @param callbackName The name of the state change callback. * @param value The new boolean state value. */ -void emitGlobalStateObserverChange(jsi::Runtime &runtime, const char *globalName, const char *callbackName, bool value); +void emitGlobalStateObserverChange( + jsi::Runtime& runtime, + const char* globalName, + const char* callbackName, + bool value); } // namespace facebook::react::jsinspector_modern diff --git a/packages/react-native/ReactCommon/jsinspector-modern/RuntimeTargetTracingStateObserver.h b/packages/react-native/ReactCommon/jsinspector-modern/RuntimeTargetTracingStateObserver.h index 95f1595e8834..c45d1085add5 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/RuntimeTargetTracingStateObserver.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/RuntimeTargetTracingStateObserver.h @@ -16,12 +16,12 @@ namespace facebook::react::jsinspector_modern { * object, which can be referenced from JavaScript side for determining the * status of performance tracing. */ -void installTracingStateObserver(jsi::Runtime &runtime); +void installTracingStateObserver(jsi::Runtime& runtime); /** * Emits the tracing state change to JavaScript by calling onTracingStateChange * on __TRACING_STATE_OBSERVER__. */ -void emitTracingStateObserverChange(jsi::Runtime &runtime, bool isTracing); +void emitTracingStateObserverChange(jsi::Runtime& runtime, bool isTracing); } // namespace facebook::react::jsinspector_modern diff --git a/packages/react-native/ReactCommon/jsinspector-modern/ScopedExecutor.h b/packages/react-native/ReactCommon/jsinspector-modern/ScopedExecutor.h index 5ad157dd51ad..3b683cd2b13c 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/ScopedExecutor.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/ScopedExecutor.h @@ -20,9 +20,10 @@ 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 @@ -30,8 +31,9 @@ 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)); } @@ -41,9 +43,10 @@ ScopedExecutor makeScopedExecutor(std::shared_ptr self, ScopedExecut * 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) { @@ -59,9 +62,10 @@ ScopedExecutor makeScopedExecutor(std::shared_ptr self, VoidExecutor * 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 @@ -71,20 +75,17 @@ 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); @@ -104,15 +105,18 @@ class EnableExecutorFromThis : public std::enable_shared_from_this { * on the object). */ template - requires std::derived_from> -static void tryExecuteSync(std::weak_ptr selfWeak, std::invocable auto func) -{ + requires std::derived_from< + ExecutorEnabledType, + EnableExecutorFromThis> +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 6d304a1466fa..ddf95eea0f00 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/SessionState.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/SessionState.h @@ -42,7 +42,8 @@ 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; /** * A single script registered during this session using @cdp diff --git a/packages/react-native/ReactCommon/jsinspector-modern/StackTrace.h b/packages/react-native/ReactCommon/jsinspector-modern/StackTrace.h index 94973df749cf..81aef58f8d6f 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/StackTrace.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/StackTrace.h @@ -19,8 +19,7 @@ class StackTrace { /** * Constructs an empty stack trace. */ - static inline std::unique_ptr empty() - { + static inline std::unique_ptr empty() { return std::make_unique(); } @@ -29,10 +28,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.h b/packages/react-native/ReactCommon/jsinspector-modern/TracingAgent.h index 2fe4c8ad6669..158f5e677327 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/TracingAgent.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/TracingAgent.h @@ -30,7 +30,10 @@ 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(); @@ -39,7 +42,7 @@ class TracingAgent { * \c FrontendChannel synchronously or asynchronously. * \param req The parsed request. */ - bool handleRequest(const cdp::PreparsedRequest &req); + bool handleRequest(const cdp::PreparsedRequest& req); private: /** @@ -47,9 +50,9 @@ class TracingAgent { */ FrontendChannel frontendChannel_; - SessionState &sessionState_; + SessionState& sessionState_; - HostTargetController &hostTargetController_; + HostTargetController& hostTargetController_; }; } // namespace facebook::react::jsinspector_modern diff --git a/packages/react-native/ReactCommon/jsinspector-modern/UniqueMonostate.h b/packages/react-native/ReactCommon/jsinspector-modern/UniqueMonostate.h index 215008cbaac0..613f6d378a51 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/UniqueMonostate.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/UniqueMonostate.h @@ -18,24 +18,24 @@ 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 true; } - constexpr bool operator>=(const UniqueMonostate & /*unused*/) const noexcept - { + constexpr bool operator>=( + const UniqueMonostate& /*unused*/) const noexcept { return true; } }; @@ -46,8 +46,9 @@ namespace std { template struct hash<::facebook::react::jsinspector_modern::UniqueMonostate> { - size_t operator()(const ::facebook::react::jsinspector_modern::UniqueMonostate & /*unused*/) const noexcept - { + size_t operator()( + const ::facebook::react::jsinspector_modern::UniqueMonostate< + key>& /*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 4e82e3df0bd7..aa87c131a64d 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/Utf8.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/Utf8.h @@ -19,8 +19,7 @@ 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. @@ -32,7 +31,8 @@ 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,7 +46,8 @@ 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 8b299742449e..7ea9cfc5e31d 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/WeakList.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/WeakList.h @@ -30,8 +30,7 @@ class WeakList { * to destroyed elements) will be removed during iteration. */ template - void forEach(Fn &&fn) - { + void forEach(Fn&& fn) { for (auto it = ptrs_.begin(); it != ptrs_.end();) { if (auto ptr = it->lock()) { fn(*ptr); @@ -51,8 +50,7 @@ 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_.cbegin(); it != ptrs_.cend();) { if (auto ptr = it->lock()) { fn(*ptr); @@ -71,10 +69,9 @@ class WeakList { * to destroyed elements) will be removed during iteration. */ template - bool anyOf(Fn &&fn) - { + bool anyOf(Fn&& fn) { bool found = false; - forEach([&](auto &element) { + forEach([&](auto& element) { if (!found && fn(element)) { found = true; } @@ -90,10 +87,9 @@ class WeakList { * to destroyed elements) will be removed during iteration. */ template - bool anyOf(Fn &&fn) const - { + bool anyOf(Fn&& fn) const { bool found = false; - forEach([&](const auto &element) { + forEach([&](const auto& element) { if (!found && fn(element)) { found = true; } @@ -109,10 +105,9 @@ 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; } @@ -122,16 +117,14 @@ 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 28cd9797b878..09798fbed315 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/WebSocketInterfaces.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/WebSocketInterfaces.h @@ -43,7 +43,9 @@ 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 89576d96295b..12e536366e07 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/cdp/CdpJson.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/cdp/CdpJson.h @@ -52,8 +52,7 @@ 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; } @@ -93,7 +92,10 @@ 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. @@ -103,7 +105,9 @@ std::string jsonError(std::optional id, ErrorCode code, std::optional * \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. @@ -113,7 +117,9 @@ std::string jsonResult(RequestId id, const folly::dynamic &result = folly::dynam * \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. @@ -124,6 +130,9 @@ std::string jsonNotification(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 a84c728aa1c4..7ec1d3f9bbde 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/network/BoundedRequestBuffer.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/network/BoundedRequestBuffer.h @@ -40,14 +40,17 @@ 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. @@ -55,7 +58,8 @@ 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 e017d3a10d6f..090f530acb9b 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/network/CdpNetwork.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/network/CdpNetwork.h @@ -45,8 +45,11 @@ 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; }; @@ -150,7 +153,9 @@ struct WebSocketResponse { * Convenience function to construct a `WebSocketResponse` from generic * input params, deriving the status text. */ - static WebSocketResponse fromInputParams(uint16_t status, const Headers &headers); + static WebSocketResponse fromInputParams( + uint16_t status, + const Headers& headers); folly::dynamic toDynamic() const; }; @@ -234,6 +239,6 @@ struct WebSocketClosedParams { * * 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 78cee7663c95..3cabf2438a33 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.h b/packages/react-native/ReactCommon/jsinspector-modern/network/NetworkHandler.h index b71890f495fc..e93cb436f242 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/network/NetworkHandler.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/network/NetworkHandler.h @@ -34,7 +34,7 @@ using Headers = std::map; */ class NetworkHandler { public: - static NetworkHandler &getInstance(); + static NetworkHandler& getInstance(); /** * Register a frontend channel for receiving Network domain events. @@ -52,8 +52,7 @@ class NetworkHandler { /** * Returns whether network debugging is currently enabled. */ - inline bool isEnabled() const - { + inline bool isEnabled() const { return enabled_.load(std::memory_order_acquire); } @@ -61,49 +60,61 @@ 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); /** * @cdp Network.webSocketCreated */ - void onWebSocketCreated(const std::string &requestId, const std::string &url); + void onWebSocketCreated(const std::string& requestId, const std::string& url); /** * @cdp Network.webSocketWillSendHandshakeRequest */ - void onWebSocketWillSendHandshakeRequest(const std::string &requestId, const Headers &headers); + void onWebSocketWillSendHandshakeRequest( + const std::string& requestId, + const Headers& headers); /** * @cdp Network.webSocketHandshakeResponseReceived */ - void onWebSocketHandshakeResponseReceived(const std::string &requestId, uint16_t status, const Headers &headers); + void onWebSocketHandshakeResponseReceived( + const std::string& requestId, + uint16_t status, + const Headers& headers); /** * @cdp Network.webSocketFrameSent @@ -112,7 +123,10 @@ class NetworkHandler { * or a base64-encoded string for binary messages. * \param isBinary Whether this is a binary message. */ - void onWebSocketFrameSent(const std::string &requestId, const std::string &payloadData, bool isBinary); + void onWebSocketFrameSent( + const std::string& requestId, + const std::string& payloadData, + bool isBinary); /** * @cdp Network.webSocketFrameReceived @@ -121,12 +135,15 @@ class NetworkHandler { * or a base64-encoded string for binary messages. * \param isBinary Whether this is a binary message. */ - void onWebSocketFrameReceived(const std::string &requestId, const std::string &payloadData, bool isBinary); + void onWebSocketFrameReceived( + const std::string& requestId, + const std::string& payloadData, + bool isBinary); /** * @cdp Network.webSocketClosed */ - void onWebSocketClosed(const std::string &requestId); + void onWebSocketClosed(const std::string& requestId); /** * Store the fetched response body for a text or image network response. @@ -136,7 +153,10 @@ 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. @@ -144,27 +164,30 @@ 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); /** * Send a message to all registered frontend channels. diff --git a/packages/react-native/ReactCommon/jsinspector-modern/tests/FollyDynamicMatchers.h b/packages/react-native/ReactCommon/jsinspector-modern/tests/FollyDynamicMatchers.h index 2877d7e97664..f1f42f625d65 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/tests/FollyDynamicMatchers.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/tests/FollyDynamicMatchers.h @@ -17,8 +17,9 @@ 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 @@ -31,11 +32,11 @@ std::string explain_error(folly::dynamic::json_pointer_resolution_error(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); } @@ -44,10 +45,14 @@ 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); } /** @@ -58,15 +63,17 @@ 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; } @@ -77,8 +84,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()) { @@ -93,8 +100,7 @@ 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 070989ab9f68..0308b0acb2e0 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/tests/GmockHelpers.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/tests/GmockHelpers.h @@ -13,8 +13,10 @@ * 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::WithoutMatchers::Get(), nullptr) \ +#define GMOCK_ON_CALL_WITH_SOURCE_LOCATION_IMPL_( \ + location, mock_expr, Setter, call) \ + ((mock_expr).gmock_##call)( \ + ::testing::internal::WithoutMatchers::Get(), nullptr) \ .Setter((location).file_name(), (location).line(), #mock_expr, #call) /** @@ -22,4 +24,5 @@ * 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/InspectorMocks.h b/packages/react-native/ReactCommon/jsinspector-modern/tests/InspectorMocks.h index b50582b771f9..b3e549fa70c9 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/tests/InspectorMocks.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/tests/InspectorMocks.h @@ -25,9 +25,12 @@ 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; @@ -37,8 +40,7 @@ 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; @@ -59,18 +61,15 @@ 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_); } @@ -82,18 +81,22 @@ 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([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([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()); } @@ -101,7 +104,7 @@ class MockInspectorPackagerConnectionDelegate : public InspectorPackagerConnecti 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, @@ -110,42 +113,48 @@ class MockInspectorPackagerConnectionDelegate : public InspectorPackagerConnecti (override)); private: - folly::Executor &executor_; + folly::Executor& executor_; }; class MockHostTargetTracingDelegate : public HostTargetTracingDelegate { public: - MOCK_METHOD(void, onTracingStarted, (tracing::Mode tracingMode, bool screenshotsCategoryEnabled), (override)); + MOCK_METHOD( + void, + onTracingStarted, + (tracing::Mode tracingMode, bool screenshotsCategoryEnabled), + (override)); MOCK_METHOD(void, onTracingStopped, (), (override)); }; 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 ¶ms, ScopedExecutor executor), + (const LoadNetworkResourceRequest& params, + ScopedExecutor executor), + (override)); + MOCK_METHOD( + std::optional, + captureScreenshot, + (const PageCaptureScreenshotRequest& request), (override)); - MOCK_METHOD(std::optional, captureScreenshot, (const PageCaptureScreenshotRequest &request), (override)); - HostTargetTracingDelegate *getTracingDelegate() override - { + HostTargetTracingDelegate* getTracingDelegate() override { return mockTracingDelegate_.get(); } - MockHostTargetTracingDelegate &getTracingDelegateMock() - { + MockHostTargetTracingDelegate& getTracingDelegateMock() { return *mockTracingDelegate_; } @@ -163,12 +172,17 @@ 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, @@ -177,11 +191,18 @@ 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 @@ -195,21 +216,23 @@ 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.h b/packages/react-native/ReactCommon/jsinspector-modern/tests/InspectorPackagerConnectionTest.h index 53365f30168f..10b501228d4d 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/tests/InspectorPackagerConnectionTest.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/tests/InspectorPackagerConnectionTest.h @@ -36,25 +36,27 @@ template class InspectorPackagerConnectionTestBase : public testing::Test { protected: InspectorPackagerConnectionTestBase() - : packagerConnection_( - InspectorPackagerConnection{ - "ws://mock-host:12345", - "my-device", - "my-app", - packagerConnectionDelegates_.make_unique(asyncExecutor_)}) - { - auto makeSocket = webSockets_.lazily_make_unique>(); - ON_CALL(*packagerConnectionDelegate(), connectWebSocket(testing::_, testing::_)) - .WillByDefault([makeSocket](auto &&...args) { + : 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>(); + ON_CALL( + *packagerConnectionDelegate(), connectWebSocket(testing::_, testing::_)) + .WillByDefault([makeSocket](auto&&... args) { auto socket = makeSocket(std::forward(args)...); socket->getDelegate().didOpen(); return std::move(socket); }); - EXPECT_CALL(*packagerConnectionDelegate(), connectWebSocket(testing::_, testing::_)).Times(testing::AnyNumber()); + EXPECT_CALL( + *packagerConnectionDelegate(), connectWebSocket(testing::_, testing::_)) + .Times(testing::AnyNumber()); } - void TearDown() override - { + void TearDown() override { // Forcibly clean up all pages currently registered with the inspector in // order to isolate state between tests. NOTE: Using TearDown instead of a // destructor so that we can use FAIL() etc. @@ -69,20 +71,21 @@ class InspectorPackagerConnectionTestBase : public testing::Test { EXPECT_CALL(*localConnections_[i], disconnect()); } } - for (auto &page : pages) { + for (auto& page : pages) { getInspectorInstance().removePage(page.id); } if (!pages.empty() && (liveConnectionCount != 0)) { if (!::testing::Test::HasFailure()) { - FAIL() << "Test case ended with " << liveConnectionCount << " open connection(s) and " << pages.size() - << " registered page(s). You must manually call removePage for each page."; + FAIL() + << "Test case ended with " << liveConnectionCount + << " open connection(s) and " << pages.size() + << " registered page(s). You must manually call removePage for each page."; } } ::testing::Test::TearDown(); } - MockInspectorPackagerConnectionDelegate *packagerConnectionDelegate() - { + MockInspectorPackagerConnectionDelegate* packagerConnectionDelegate() { // We only create one PackagerConnectionDelegate per test. EXPECT_EQ(packagerConnectionDelegates_.objectsVended(), 1); return packagerConnectionDelegates_[0]; @@ -90,7 +93,8 @@ class InspectorPackagerConnectionTestBase : public testing::Test { Executor asyncExecutor_; - UniquePtrFactory packagerConnectionDelegates_; + UniquePtrFactory + packagerConnectionDelegates_; /** * webSockets_ will hold the WebSocket instance(s) owned by * packagerConnection_ while also allowing us to access them during @@ -118,17 +122,18 @@ class InspectorPackagerConnectionTestBase : public testing::Test { * Standard test fixture that uses QueuedImmediateExecutor. * Work scheduled on the executor is run immediately inline. */ -using InspectorPackagerConnectionTest = InspectorPackagerConnectionTestBase; +using InspectorPackagerConnectionTest = + InspectorPackagerConnectionTestBase; /** * Test fixture that uses ManualExecutor. * Work scheduled on the executor is *not* run automatically; it must be * manually advanced in the body of the test. */ -class InspectorPackagerConnectionTestAsync : public InspectorPackagerConnectionTestBase { +class InspectorPackagerConnectionTestAsync + : public InspectorPackagerConnectionTestBase { public: - void TearDown() override - { + void TearDown() override { // Assert there are no pending tasks on the ManualExecutor. auto tasksCleared = asyncExecutor_.clear(); EXPECT_EQ(tasksCleared, 0) diff --git a/packages/react-native/ReactCommon/jsinspector-modern/tests/JsiIntegrationTest.h b/packages/react-native/ReactCommon/jsinspector-modern/tests/JsiIntegrationTest.h index 8f0b6e22665c..d6a34b24f569 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/tests/JsiIntegrationTest.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/tests/JsiIntegrationTest.h @@ -44,29 +44,27 @@ 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_); @@ -90,10 +88,10 @@ class JsiIntegrationPortableTestBase : public ::testing::Test, private HostTarge * 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()); @@ -103,16 +101,17 @@ class JsiIntegrationPortableTestBase : public ::testing::Test, private HostTarge 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_); @@ -126,21 +125,22 @@ class JsiIntegrationPortableTestBase : public ::testing::Test, private HostTarge 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,25 +151,24 @@ class JsiIntegrationPortableTestBase : public ::testing::Test, private HostTarge */ 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(); } @@ -177,33 +176,32 @@ class JsiIntegrationPortableTestBase : public ::testing::Test, private HostTarge 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. @@ -211,26 +209,29 @@ class JsiIntegrationPortableTestBase : public ::testing::Test, private HostTarge 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_. @@ -239,18 +240,17 @@ class JsiIntegrationPortableTestBase : public ::testing::Test, private HostTarge 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/ReactInstanceIntegrationTest.h b/packages/react-native/ReactCommon/jsinspector-modern/tests/ReactInstanceIntegrationTest.h index fdd8226224d8..3d53e5e5143c 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/tests/ReactInstanceIntegrationTest.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/tests/ReactInstanceIntegrationTest.h @@ -27,27 +27,29 @@ 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 ¶ms = folly::dynamic::object()); - void sendJSONString(const std::string &message); + void send( + const std::string& method, + const folly::dynamic& params = 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 2798a71a4ff6..362a4d991e26 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,10 +48,9 @@ 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/TracingTest.h b/packages/react-native/ReactCommon/jsinspector-modern/tests/TracingTest.h index bc8e271d316a..26f4a6b75a9f 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/tests/TracingTest.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/tests/TracingTest.h @@ -24,35 +24,35 @@ namespace facebook::react::jsinspector_modern { * Base test class providing tracing-related test utilities for tests. */ template -class TracingTestBase : public JsiIntegrationPortableTestBase { +class TracingTestBase + : public JsiIntegrationPortableTestBase { protected: - using JsiIntegrationPortableTestBase::JsiIntegrationPortableTestBase; + using JsiIntegrationPortableTestBase:: + JsiIntegrationPortableTestBase; /** * Helper method to start tracing via Tracing.start CDP command. */ void startTracing( - const std::set &enabledCategories = { + const std::set& enabledCategories = { tracing::Category::HiddenTimeline, tracing::Category::JavaScriptSampling, tracing::Category::RuntimeExecution, tracing::Category::Timeline, tracing::Category::UserTiming, - }) - { + }) { this->expectMessageFromPage(JsonEq(R"({ "id": 1, "result": {} })")); - this->toPage_->sendMessage( - fmt::format( - R"({{ + this->toPage_->sendMessage(fmt::format( + R"({{ "id": 1, "method": "Tracing.start", "params": {{ "categories": "{0}" }} }})", - tracing::serializeTracingCategories(enabledCategories))); + tracing::serializeTracingCategories(enabledCategories))); } /** @@ -60,8 +60,7 @@ class TracingTestBase : public JsiIntegrationPortableTestBase endTracingAndCollectEvents() - { + std::vector endTracingAndCollectEvents() { testing::InSequence s; this->expectMessageFromPage(JsonEq(R"({ @@ -71,17 +70,23 @@ class TracingTestBase : public JsiIntegrationPortableTestBase allTraceEvents; - EXPECT_CALL(this->fromPage(), onMessage(JsonParsed(AtJsonPtr("/method", "Tracing.dataCollected")))) + EXPECT_CALL( + this->fromPage(), + onMessage(JsonParsed(AtJsonPtr("/method", "Tracing.dataCollected")))) .Times(testing::AtLeast(1)) - .WillRepeatedly(testing::Invoke([&allTraceEvents](const std::string &message) { - auto parsedMessage = folly::parseJson(message); - auto &events = parsedMessage.at("params").at("value"); - allTraceEvents.insert( - allTraceEvents.end(), std::make_move_iterator(events.begin()), std::make_move_iterator(events.end())); - })); - - this->expectMessageFromPage(JsonParsed( - testing::AllOf(AtJsonPtr("/method", "Tracing.tracingComplete"), AtJsonPtr("/params/dataLossOccurred", false)))); + .WillRepeatedly( + testing::Invoke([&allTraceEvents](const std::string& message) { + auto parsedMessage = folly::parseJson(message); + auto& events = parsedMessage.at("params").at("value"); + allTraceEvents.insert( + allTraceEvents.end(), + std::make_move_iterator(events.begin()), + std::make_move_iterator(events.end())); + })); + + this->expectMessageFromPage(JsonParsed(testing::AllOf( + AtJsonPtr("/method", "Tracing.tracingComplete"), + AtJsonPtr("/params/dataLossOccurred", false)))); this->toPage_->sendMessage(R"({ "id": 1, diff --git a/packages/react-native/ReactCommon/jsinspector-modern/tests/UniquePtrFactory.h b/packages/react-native/ReactCommon/jsinspector-modern/tests/UniquePtrFactory.h index d89c8f4295f3..62edd59d3566 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/tests/UniquePtrFactory.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/tests/UniquePtrFactory.h @@ -30,17 +30,19 @@ 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; } @@ -50,17 +52,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]; } @@ -68,8 +70,7 @@ 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]; } @@ -77,8 +78,7 @@ 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,20 +92,19 @@ 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 0783eae801a2..836d09530bff 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 a1b1eeb49235..8bf3b2dcb86a 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/prelude.js.h b/packages/react-native/ReactCommon/jsinspector-modern/tests/prelude.js.h index 33b06d9950bb..0f546e1e3bff 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/tests/prelude.js.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/tests/prelude.js.h @@ -9,7 +9,8 @@ * @format */ -/* eslint-disable no-shadow, eqeqeq, curly, no-unused-vars, no-void, no-control-regex */ +/* eslint-disable no-shadow, eqeqeq, curly, no-unused-vars, no-void, + * no-control-regex */ #pragma once 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 9648e7c4345b..787571472ab7 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/tests/utils/InspectorFlagOverridesGuard.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/tests/utils/InspectorFlagOverridesGuard.h @@ -30,11 +30,13 @@ 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 d73702fa7fda..875cc10d121f 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/tracing/ConsoleTimeStamp.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/tracing/ConsoleTimeStamp.h @@ -39,8 +39,7 @@ enum class ConsoleTimeStampColor { Error, }; -inline std::string consoleTimeStampColorToString(ConsoleTimeStampColor color) -{ +inline std::string consoleTimeStampColorToString(ConsoleTimeStampColor color) { switch (color) { case ConsoleTimeStampColor::Primary: return "primary"; @@ -69,8 +68,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") { @@ -98,6 +97,8 @@ inline std::optional getConsoleTimeStampColorFromString(c } }; -std::optional getConsoleTimeStampDetailFromObject(jsi::Runtime &runtime, const jsi::Value &detailValue); +std::optional getConsoleTimeStampDetailFromObject( + jsi::Runtime& runtime, + const jsi::Value& detailValue); }; // namespace facebook::react::jsinspector_modern::tracing diff --git a/packages/react-native/ReactCommon/jsinspector-modern/tracing/EventLoopReporter.h b/packages/react-native/ReactCommon/jsinspector-modern/tracing/EventLoopReporter.h index 62932fc0cc93..211fe139cba7 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/FrameTimingSequence.h b/packages/react-native/ReactCommon/jsinspector-modern/tracing/FrameTimingSequence.h index 6aa0db5d1744..e38291046cdc 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/tracing/FrameTimingSequence.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/tracing/FrameTimingSequence.h @@ -20,7 +20,8 @@ namespace facebook::react::jsinspector_modern::tracing { using FrameSequenceId = uint64_t; /** - * A struct representing a sequence of frame timings that happened on the Host side. + * A struct representing a sequence of frame timings that happened on the Host + * side. */ struct FrameTimingSequence { FrameTimingSequence() = delete; @@ -35,12 +36,11 @@ struct FrameTimingSequence { threadId(threadId), beginTimestamp(beginTimestamp), endTimestamp(endTimestamp), - screenshot(std::move(screenshot)) - { - } + screenshot(std::move(screenshot)) {} /** - * Unique ID of the sequence, used by Chrome DevTools Frontend to identify the events that form one sequence. + * Unique ID of the sequence, used by Chrome DevTools Frontend to identify the + * events that form one sequence. */ FrameSequenceId id; diff --git a/packages/react-native/ReactCommon/jsinspector-modern/tracing/HostTracingProfile.h b/packages/react-native/ReactCommon/jsinspector-modern/tracing/HostTracingProfile.h index aa37579fc696..d1bbc9487a14 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/tracing/HostTracingProfile.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/tracing/HostTracingProfile.h @@ -19,8 +19,8 @@ namespace facebook::react::jsinspector_modern::tracing { /** * The final tracing profile for the given HostTarget. - * Contains all necessary information that is required to be be emitted as a series of Tracing.dataCollected CDP - * messages. + * Contains all necessary information that is required to be be emitted as a + * series of Tracing.dataCollected CDP messages. */ struct HostTracingProfile { HostTracingProfile() = default; @@ -30,10 +30,10 @@ struct HostTracingProfile { // is instantiated. Plain C++ never instantiates it, but Swift's C++ interop // does when these headers are reached from an imported module, turning it // into a hard compile error (Xcode 26.3). - HostTracingProfile(const HostTracingProfile &) = delete; - HostTracingProfile &operator=(const HostTracingProfile &) = delete; - HostTracingProfile(HostTracingProfile &&) = default; - HostTracingProfile &operator=(HostTracingProfile &&) = default; + HostTracingProfile(const HostTracingProfile&) = delete; + HostTracingProfile& operator=(const HostTracingProfile&) = delete; + HostTracingProfile(HostTracingProfile&&) = default; + HostTracingProfile& operator=(HostTracingProfile&&) = default; ~HostTracingProfile() = default; // The ID of the OS-level process that this Trace Recording is associated diff --git a/packages/react-native/ReactCommon/jsinspector-modern/tracing/HostTracingProfileSerializer.h b/packages/react-native/ReactCommon/jsinspector-modern/tracing/HostTracingProfileSerializer.h index ceb8ac4c072c..93f93585c5eb 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/tracing/HostTracingProfileSerializer.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/tracing/HostTracingProfileSerializer.h @@ -29,21 +29,21 @@ class HostTracingProfileSerializer { * \p chunkCallback. */ static void emitAsDataCollectedChunks( - HostTracingProfile &&hostTracingProfile, - const std::function &chunkCallback, + HostTracingProfile&& hostTracingProfile, + const std::function& chunkCallback, size_t maxChunkBytes, uint16_t profileTraceEventsChunkSize); static void emitPerformanceTraceEvents( - std::vector &&events, - const std::function &chunkCallback, + std::vector&& events, + const std::function& chunkCallback, size_t maxChunkBytes); static void emitFrameTimings( - std::vector &&frameTimings, + std::vector&& frameTimings, ProcessId processId, HighResTimeStamp recordingStartTimestamp, - const std::function &chunkCallback, + const std::function& chunkCallback, size_t maxChunkBytes); }; diff --git a/packages/react-native/ReactCommon/jsinspector-modern/tracing/PerformanceTracer.h b/packages/react-native/ReactCommon/jsinspector-modern/tracing/PerformanceTracer.h index 5c1da0656437..9dab1b5bad32 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/tracing/PerformanceTracer.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/tracing/PerformanceTracer.h @@ -34,7 +34,7 @@ using Headers = std::map; */ class PerformanceTracer { public: - static PerformanceTracer &getInstance(); + static PerformanceTracer& getInstance(); /** * Starts a tracing session. Returns `false` if already tracing. @@ -58,8 +58,7 @@ class PerformanceTracer { * avoid doing expensive work (like formatting strings) if tracing is not * enabled. */ - inline bool isTracing() const - { + inline bool isTracing() const { return tracingAtomic_; } @@ -69,7 +68,10 @@ 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 @@ -78,10 +80,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, std::optional stackTrace = nullptr); /** @@ -92,7 +94,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, @@ -120,7 +122,9 @@ 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,17 +134,20 @@ 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 "ResourceReceivedData" event. * If not currently tracing, this is a no-op. */ - void reportResourceReceivedData(const std::string &devtoolsRequestId, HighResTimeStamp start, int encodedDataLength); + void reportResourceReceivedData( + const std::string& devtoolsRequestId, + HighResTimeStamp start, + int encodedDataLength); /** * Record a "ResourceReceiveResponse" event. Paired with other "Resource*" @@ -150,10 +157,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); @@ -164,7 +171,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); @@ -190,7 +197,7 @@ class PerformanceTracer { ProcessId processId, ProcessId threadId, HighResTimeStamp chunkTimestamp, - TraceEventProfileChunk &&traceEventProfileChunk); + TraceEventProfileChunk&& traceEventProfileChunk); /** * Callback function type for tracing state changes. @@ -205,20 +212,22 @@ class PerformanceTracer { * Tracing stop state is reported before tracing has stopped, so callbacks * can report final events. * @param callback Function to call when tracing starts or stops - * @return A unique identifier for the subscription that can be used to unsubscribe + * @return A unique identifier for the subscription that can be used to + * unsubscribe */ uint32_t subscribeToTracingStateChanges(TracingStateCallback callback); /** * Unsubscribe from tracing state changes. - * @param subscriptionId The identifier returned from subscribeToTracingStateChanges + * @param subscriptionId The identifier returned from + * subscribeToTracingStateChanges */ void unsubscribeFromTracingStateChanges(uint32_t subscriptionId); 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 @@ -347,8 +356,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 @@ -365,19 +374,25 @@ class PerformanceTracer { std::map tracingStateCallbacks_; uint32_t nextCallbackId_{0}; - 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/PerformanceTracerSection.h b/packages/react-native/ReactCommon/jsinspector-modern/tracing/PerformanceTracerSection.h index 59545a2b6237..8c770250d003 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/tracing/PerformanceTracerSection.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/tracing/PerformanceTracerSection.h @@ -29,29 +29,31 @@ template class PerformanceTracerSection { public: explicit PerformanceTracerSection( - const char *name, - const char *track = nullptr, - const char *trackGroup = nullptr, - const char *color = nullptr, + const char* name, + const char* track = nullptr, + const char* trackGroup = nullptr, + const char* color = nullptr, Args... args) noexcept - : name_(name), track_(track), trackGroup_(trackGroup), color_(color), args_(std::move(args)...) - { + : name_(name), + track_(track), + trackGroup_(trackGroup), + color_(color), + args_(std::move(args)...) { static_assert( sizeof...(Args) % 2 == 0, "PerformanceTracerSection expects an even number of variadic args representing [name, value] pairs."); } // Non-movable - PerformanceTracerSection(const PerformanceTracerSection &) = delete; - PerformanceTracerSection(PerformanceTracerSection &&) = delete; + PerformanceTracerSection(const PerformanceTracerSection&) = delete; + PerformanceTracerSection(PerformanceTracerSection&&) = delete; // Non-copyable - PerformanceTracerSection &operator=(const PerformanceTracerSection &) = delete; - PerformanceTracerSection &operator=(PerformanceTracerSection &&) = delete; + PerformanceTracerSection& operator=(const PerformanceTracerSection&) = delete; + PerformanceTracerSection& operator=(PerformanceTracerSection&&) = delete; - ~PerformanceTracerSection() noexcept - { - auto &tracer = PerformanceTracer::getInstance(); + ~PerformanceTracerSection() noexcept { + auto& tracer = PerformanceTracer::getInstance(); if (!tracer.isTracing()) { return; } @@ -62,10 +64,11 @@ class PerformanceTracerSection { if constexpr (sizeof...(Args) > 0) { auto properties = folly::dynamic::array(); std::apply( - [&](const auto &...elems) { + [&](const auto&... elems) { size_t idx = 0; - (((idx % 2 == 0) ? properties.push_back(folly::dynamic::array(elems)) - : properties[properties.size() - 1].push_back(elems), + (((idx % 2 == 0) + ? properties.push_back(folly::dynamic::array(elems)) + : properties[properties.size() - 1].push_back(elems), ++idx), ...); }, @@ -89,7 +92,11 @@ class PerformanceTracerSection { folly::dynamic detail = folly::dynamic::object(); detail["devtools"] = std::move(devtools); - tracer.reportMeasure(std::string(name_), startTime_, endTime - startTime_, std::move(detail)); + tracer.reportMeasure( + std::string(name_), + startTime_, + endTime - startTime_, + std::move(detail)); } else { tracer.reportTimeStamp( std::string(name_), @@ -97,16 +104,17 @@ class PerformanceTracerSection { endTime, track_ != nullptr ? std::optional{track_} : std::nullopt, trackGroup_ != nullptr ? std::optional{trackGroup_} : std::nullopt, - color_ != nullptr ? getConsoleTimeStampColorFromString(color_) : std::nullopt); + color_ != nullptr ? getConsoleTimeStampColorFromString(color_) + : std::nullopt); } } private: HighResTimeStamp startTime_{HighResTimeStamp::now()}; std::string_view name_; - const char *track_; - const char *trackGroup_; - const char *color_; + const char* track_; + const char* trackGroup_; + const char* color_; std::tuple args_; }; diff --git a/packages/react-native/ReactCommon/jsinspector-modern/tracing/ProfileTreeNode.h b/packages/react-native/ReactCommon/jsinspector-modern/tracing/ProfileTreeNode.h index 78736b065a3e..e529a658418b 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/tracing/ProfileTreeNode.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/tracing/ProfileTreeNode.h @@ -34,35 +34,31 @@ 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_; } @@ -70,12 +66,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; } } @@ -87,10 +83,12 @@ 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 f5c06f50857a..3016aa3eda53 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/tracing/RuntimeSamplingProfile.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/tracing/RuntimeSamplingProfile.h @@ -41,7 +41,8 @@ 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; @@ -67,18 +68,21 @@ 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; @@ -99,17 +103,15 @@ 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 5ce2bf655183..0453e1cd2896 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/tracing/RuntimeSamplingProfileTraceEventSerializer.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/tracing/RuntimeSamplingProfileTraceEventSerializer.h @@ -29,8 +29,7 @@ constexpr uint16_t MAX_UNIQUE_NODES_PER_CHUNK = 50; struct IdGenerator { public: - uint32_t getNext() - { + uint32_t getNext() { return ++counter_; } @@ -58,19 +57,21 @@ 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 a1a1260c6494..0061891405d0 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/tracing/TargetTracingAgent.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/tracing/TargetTracingAgent.h @@ -22,18 +22,16 @@ namespace facebook::react::jsinspector_modern::tracing { */ class TargetTracingAgent { public: - explicit TargetTracingAgent(TraceRecordingState &state) : state_(state) - { + explicit TargetTracingAgent(TraceRecordingState& state) : state_(state) { (void)state_; } - bool isRunningInBackgroundMode() - { + bool isRunningInBackgroundMode() { return state_.mode == tracing::Mode::Background; } protected: - TraceRecordingState &state_; + TraceRecordingState& state_; }; } // namespace facebook::react::jsinspector_modern::tracing diff --git a/packages/react-native/ReactCommon/jsinspector-modern/tracing/TimeWindowedBuffer.h b/packages/react-native/ReactCommon/jsinspector-modern/tracing/TimeWindowedBuffer.h index 6951c815f48e..c9069a9fde43 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/tracing/TimeWindowedBuffer.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/tracing/TimeWindowedBuffer.h @@ -19,22 +19,24 @@ namespace facebook::react::jsinspector_modern::tracing { /** * The currentBufferStartTime_ is initialized once first element is pushed. */ -constexpr HighResTimeStamp kCurrentBufferStartTimeUninitialized = HighResTimeStamp::min(); +constexpr HighResTimeStamp kCurrentBufferStartTimeUninitialized = + HighResTimeStamp::min(); template class TimeWindowedBuffer { public: - using TimestampAccessor = std::function; + using TimestampAccessor = std::function; - TimeWindowedBuffer() : timestampAccessor_(std::nullopt), windowSize_(std::nullopt) {} + TimeWindowedBuffer() + : timestampAccessor_(std::nullopt), windowSize_(std::nullopt) {} - TimeWindowedBuffer(TimestampAccessor timestampAccessor, HighResDuration windowSize) - : timestampAccessor_(std::move(timestampAccessor)), windowSize_(windowSize) - { - } + TimeWindowedBuffer( + TimestampAccessor timestampAccessor, + HighResDuration windowSize) + : timestampAccessor_(std::move(timestampAccessor)), + windowSize_(windowSize) {} - void push(const T &element) - { + void push(const T& element) { if (timestampAccessor_) { auto timestamp = (*timestampAccessor_)(element); enqueueElement(element, timestamp); @@ -43,8 +45,7 @@ class TimeWindowedBuffer { } } - void push(T &&element) - { + void push(T&& element) { if (timestampAccessor_) { auto timestamp = (*timestampAccessor_)(element); enqueueElement(std::move(element), timestamp); @@ -53,8 +54,7 @@ class TimeWindowedBuffer { } } - void clear() - { + void clear() { primaryBuffer_.clear(); alternativeBuffer_.clear(); currentBufferIndex_ = BufferIndex::Primary; @@ -63,19 +63,20 @@ class TimeWindowedBuffer { /** * Forces immediate removal of elements that are outside the time window. - * The right boundary of the window is the reference timestamp passed as an argument. + * The right boundary of the window is the reference timestamp passed as an + * argument. */ - std::vector pruneExpiredAndExtract(HighResTimeStamp windowRightBoundary = HighResTimeStamp::now()) - { + std::vector pruneExpiredAndExtract( + HighResTimeStamp windowRightBoundary = HighResTimeStamp::now()) { std::vector result; - for (auto &wrappedElement : getPreviousBuffer()) { + for (auto& wrappedElement : getPreviousBuffer()) { if (isInsideTimeWindow(wrappedElement, windowRightBoundary)) { result.push_back(std::move(wrappedElement.element)); } } - for (auto &wrappedElement : getCurrentBuffer()) { + for (auto& wrappedElement : getCurrentBuffer()) { if (isInsideTimeWindow(wrappedElement, windowRightBoundary)) { result.push_back(std::move(wrappedElement.element)); } @@ -93,25 +94,26 @@ class TimeWindowedBuffer { HighResTimeStamp timestamp; }; - std::vector &getCurrentBuffer() - { - return currentBufferIndex_ == BufferIndex::Primary ? primaryBuffer_ : alternativeBuffer_; + std::vector& getCurrentBuffer() { + return currentBufferIndex_ == BufferIndex::Primary ? primaryBuffer_ + : alternativeBuffer_; } - std::vector &getPreviousBuffer() - { - return currentBufferIndex_ == BufferIndex::Primary ? alternativeBuffer_ : primaryBuffer_; + std::vector& getPreviousBuffer() { + return currentBufferIndex_ == BufferIndex::Primary ? alternativeBuffer_ + : primaryBuffer_; } - void enqueueElement(const T &element, HighResTimeStamp timestamp) - { + void enqueueElement(const T& element, HighResTimeStamp timestamp) { if (windowSize_) { if (currentBufferStartTime_ == kCurrentBufferStartTimeUninitialized) { currentBufferStartTime_ = timestamp; } else if (timestamp > currentBufferStartTime_ + *windowSize_) { - // We moved past the current buffer. We need to switch the other buffer as current. - currentBufferIndex_ = - currentBufferIndex_ == BufferIndex::Primary ? BufferIndex::Alternative : BufferIndex::Primary; + // We moved past the current buffer. We need to switch the other buffer + // as current. + currentBufferIndex_ = currentBufferIndex_ == BufferIndex::Primary + ? BufferIndex::Alternative + : BufferIndex::Primary; getCurrentBuffer().clear(); currentBufferStartTime_ = timestamp; } @@ -120,15 +122,16 @@ class TimeWindowedBuffer { getCurrentBuffer().push_back({element, timestamp}); } - void enqueueElement(T &&element, HighResTimeStamp timestamp) - { + void enqueueElement(T&& element, HighResTimeStamp timestamp) { if (windowSize_) { if (currentBufferStartTime_ == kCurrentBufferStartTimeUninitialized) { currentBufferStartTime_ = timestamp; } else if (timestamp > currentBufferStartTime_ + *windowSize_) { - // We moved past the current buffer. We need to switch the other buffer as current. - currentBufferIndex_ = - currentBufferIndex_ == BufferIndex::Primary ? BufferIndex::Alternative : BufferIndex::Primary; + // We moved past the current buffer. We need to switch the other buffer + // as current. + currentBufferIndex_ = currentBufferIndex_ == BufferIndex::Primary + ? BufferIndex::Alternative + : BufferIndex::Primary; getCurrentBuffer().clear(); currentBufferStartTime_ = timestamp; } @@ -137,13 +140,15 @@ class TimeWindowedBuffer { getCurrentBuffer().push_back({std::move(element), timestamp}); } - bool isInsideTimeWindow(const TimestampedElement &element, HighResTimeStamp windowRightBoundary) const - { + bool isInsideTimeWindow( + const TimestampedElement& element, + HighResTimeStamp windowRightBoundary) const { if (!windowSize_) { return true; } - return element.timestamp >= windowRightBoundary - *windowSize_ && element.timestamp <= windowRightBoundary; + return element.timestamp >= windowRightBoundary - *windowSize_ && + element.timestamp <= windowRightBoundary; } std::optional timestampAccessor_; @@ -152,7 +157,8 @@ class TimeWindowedBuffer { std::vector primaryBuffer_; std::vector alternativeBuffer_; BufferIndex currentBufferIndex_ = BufferIndex::Primary; - HighResTimeStamp currentBufferStartTime_{kCurrentBufferStartTimeUninitialized}; + HighResTimeStamp currentBufferStartTime_{ + kCurrentBufferStartTimeUninitialized}; }; } // 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 d82bd717ff30..bda8f65df22d 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/tracing/Timing.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/tracing/Timing.h @@ -19,20 +19,24 @@ 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/TraceEventGenerator.h b/packages/react-native/ReactCommon/jsinspector-modern/tracing/TraceEventGenerator.h index 898fba6ef729..e199d0e6c5c9 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/tracing/TraceEventGenerator.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/tracing/TraceEventGenerator.h @@ -19,8 +19,8 @@ namespace facebook::react::jsinspector_modern::tracing { /** - * This class encapsulates the logic for generating canonical trace events that will be serialized and sent as part of - * Tracing.dataCollected CDP message. + * This class encapsulates the logic for generating canonical trace events that + * will be serialized and sent as part of Tracing.dataCollected CDP message. */ class TraceEventGenerator { public: @@ -51,7 +51,7 @@ class TraceEventGenerator { static TraceEvent createScreenshotEvent( FrameSequenceId frameSequenceId, int sourceId, - std::vector &&snapshot, + std::vector&& snapshot, HighResTimeStamp expectedDisplayTime, ProcessId processId, ThreadId threadId); diff --git a/packages/react-native/ReactCommon/jsinspector-modern/tracing/TraceEventSerializer.h b/packages/react-native/ReactCommon/jsinspector-modern/tracing/TraceEventSerializer.h index 0240e2c5d2c2..80b72bd0ba33 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,7 +37,8 @@ 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 @@ -48,7 +49,8 @@ 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 @@ -59,7 +61,8 @@ 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 @@ -70,7 +73,8 @@ 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 @@ -83,14 +87,14 @@ class TraceEventSerializer { * CDP. */ static folly::dynamic serializeProfileChunkCPUProfileNodeCallFrame( - TraceEventProfileChunk::CPUProfile::Node::CallFrame &&callFrame); + TraceEventProfileChunk::CPUProfile::Node::CallFrame&& callFrame); /** * Estimates the JSON-serialized byte size of a folly::dynamic value. * This is a rough but conservative estimate to avoid the cost of * double-serialization (once to measure, once to emit). */ - static size_t estimateJsonSize(const folly::dynamic &value); + static size_t estimateJsonSize(const folly::dynamic& value); }; } // namespace facebook::react::jsinspector_modern::tracing diff --git a/packages/react-native/ReactCommon/jsinspector-modern/tracing/TraceRecordingState.h b/packages/react-native/ReactCommon/jsinspector-modern/tracing/TraceRecordingState.h index 2a3187c7610a..2716c88abf9d 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/tracing/TraceRecordingState.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/tracing/TraceRecordingState.h @@ -20,26 +20,27 @@ namespace facebook::react::jsinspector_modern::tracing { /** * The global state for the given Trace Recording. - * Shared with Tracing Agents, which could use it to stash the corresponding target profiles during reloads. + * Shared with Tracing Agents, which could use it to stash the corresponding + * target profiles during reloads. */ struct TraceRecordingState { TraceRecordingState( tracing::Mode tracingMode, std::set enabledCategories, std::optional windowSize = std::nullopt) - : mode(tracingMode), enabledCategories(std::move(enabledCategories)), windowSize(windowSize) - { - } + : mode(tracingMode), + enabledCategories(std::move(enabledCategories)), + windowSize(windowSize) {} // Explicitly move-only: RuntimeSamplingProfile is not copyable, so the // implicit copy constructor is ill-formed the moment it is instantiated. // Plain C++ never instantiates it, but Swift's C++ interop (ClangImporter) // does when a consumer imports these headers as part of a module, turning // it into a hard compile error (Xcode 26.3). - TraceRecordingState(const TraceRecordingState &) = delete; - TraceRecordingState &operator=(const TraceRecordingState &) = delete; - TraceRecordingState(TraceRecordingState &&) = default; - TraceRecordingState &operator=(TraceRecordingState &&) = default; + TraceRecordingState(const TraceRecordingState&) = delete; + TraceRecordingState& operator=(const TraceRecordingState&) = delete; + TraceRecordingState(TraceRecordingState&&) = default; + TraceRecordingState& operator=(TraceRecordingState&&) = default; ~TraceRecordingState() = default; // The mode of this Trace Recording. diff --git a/packages/react-native/ReactCommon/jsinspector-modern/tracing/TracingCategory.h b/packages/react-native/ReactCommon/jsinspector-modern/tracing/TracingCategory.h index 24c1880b9dfe..0d8ffef0e5cf 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/tracing/TracingCategory.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/tracing/TracingCategory.h @@ -25,8 +25,7 @@ enum class Category { Screenshot, /* disabled-by-default-devtools.screenshot */ }; -inline std::string tracingCategoryToString(const Category &category) -{ +inline std::string tracingCategoryToString(const Category& category) { switch (category) { case Category::Timeline: return "devtools.timeline"; @@ -47,8 +46,8 @@ inline std::string tracingCategoryToString(const Category &category) } } -inline std::optional getTracingCategoryFromString(const std::string &str) -{ +inline std::optional getTracingCategoryFromString( + const std::string& str) { if (str == "blink.user_timing") { return Category::UserTiming; } else if (str == "devtools.timeline") { @@ -69,13 +68,13 @@ inline std::optional getTracingCategoryFromString(const std::string &s } /** - * The Trace Event could have multiple categories, but this is extremely rare case. + * The Trace Event could have multiple categories, but this is extremely rare + * case. */ using Categories = folly::small_vector; // { Timeline, UserTiming } => "devtools.timeline,blink.user_timing" -inline std::string serializeTracingCategories(const Categories &categories) -{ +inline std::string serializeTracingCategories(const Categories& categories) { if (categories.size() == 1) { return tracingCategoryToString(categories.front()); } @@ -91,8 +90,8 @@ inline std::string serializeTracingCategories(const Categories &categories) } // { Timeline, UserTiming } => "devtools.timeline,blink.user_timing" -inline std::string serializeTracingCategories(const std::set &categories) -{ +inline std::string serializeTracingCategories( + const std::set& categories) { std::string serializedValue; auto current = categories.begin(); @@ -109,8 +108,8 @@ inline std::string serializeTracingCategories(const std::set &categori } // "devtools.timeline,blink.user_timing" => { Timeline, UserTiming } -inline std::set parseSerializedTracingCategories(const std::string &serializedCategories) -{ +inline std::set parseSerializedTracingCategories( + const std::string& serializedCategories) { std::set categories; if (serializedCategories.empty()) { return categories; diff --git a/packages/react-native/ReactCommon/jsitooling/react/runtime/JSRuntimeBindings.h b/packages/react-native/ReactCommon/jsitooling/react/runtime/JSRuntimeBindings.h index 720ef82ed853..280f06e3d447 100644 --- a/packages/react-native/ReactCommon/jsitooling/react/runtime/JSRuntimeBindings.h +++ b/packages/react-native/ReactCommon/jsitooling/react/runtime/JSRuntimeBindings.h @@ -12,9 +12,10 @@ namespace facebook::react { -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); } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/jsitooling/react/runtime/JSRuntimeFactory.h b/packages/react-native/ReactCommon/jsitooling/react/runtime/JSRuntimeFactory.h index 22759cb33bb3..29f7ec932aa6 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,7 +45,8 @@ class JSRuntime { * Initialized by \c getRuntimeTargetDelegate if not overridden, and then * never changes. */ - std::optional runtimeTargetDelegate_; + std::optional + runtimeTargetDelegate_; }; /** @@ -53,7 +54,8 @@ 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; }; @@ -63,7 +65,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 41d8204bd041..8ae96fc7d7c6 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 7b7b4f6a713e..3d26ea6b77f4 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 b5d48354ef20..0592955320dd 100644 --- a/packages/react-native/ReactCommon/react/bridging/AString.h +++ b/packages/react-native/ReactCommon/react/bridging/AString.h @@ -16,27 +16,25 @@ 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 03ee6e464df4..b59ca8929e29 100644 --- a/packages/react-native/ReactCommon/react/bridging/Array.h +++ b/packages/react-native/ReactCommon/react/bridging/Array.h @@ -24,31 +24,35 @@ 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)); } @@ -59,15 +63,18 @@ 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; @@ -75,10 +82,12 @@ struct Bridging> : array_detail::BridgingStatic -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)); @@ -86,29 +95,35 @@ struct Bridging> : array_detail::BridgingStatic -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; @@ -117,14 +132,16 @@ struct Bridging> : array_detail::BridgingDynamic> 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/ArrayBuffer.h b/packages/react-native/ReactCommon/react/bridging/ArrayBuffer.h index 93592f2779ab..b956f82b9633 100644 --- a/packages/react-native/ReactCommon/react/bridging/ArrayBuffer.h +++ b/packages/react-native/ReactCommon/react/bridging/ArrayBuffer.h @@ -24,15 +24,14 @@ namespace detail { */ class OwnedBytesBuffer final : public jsi::MutableBuffer { public: - explicit OwnedBytesBuffer(std::vector bytes) noexcept : bytes_(std::move(bytes)) {} + explicit OwnedBytesBuffer(std::vector bytes) noexcept + : bytes_(std::move(bytes)) {} - size_t size() const override - { + size_t size() const override { return bytes_.size(); } - uint8_t *data() override - { + uint8_t* data() override { return bytes_.data(); } @@ -44,21 +43,20 @@ class OwnedBytesBuffer final : public jsi::MutableBuffer { template <> struct Bridging { - static jsi::ArrayBuffer fromJs(jsi::Runtime &rt, const jsi::Object &obj) - { + static jsi::ArrayBuffer fromJs(jsi::Runtime& rt, const jsi::Object& obj) { if (!obj.isArrayBuffer(rt)) { throw jsi::JSError(rt, "Expected ArrayBuffer"); } return obj.getArrayBuffer(rt); } - static jsi::Value toJs(jsi::Runtime &rt, jsi::ArrayBuffer buf) - { + static jsi::Value toJs(jsi::Runtime& rt, jsi::ArrayBuffer buf) { return {rt, buf}; } }; -/* AsyncArrayBuffer holds ArrayBuffer bytes for use off the JS thread. Move-only. +/* AsyncArrayBuffer holds ArrayBuffer bytes for use off the JS thread. + * Move-only. * * Always backed by a shared_ptr: either one borrowed from * a native-backed jsi::ArrayBuffer or an internal adapter wrapping owned @@ -68,15 +66,16 @@ struct Bridging { */ class AsyncArrayBuffer { public: - AsyncArrayBuffer(const AsyncArrayBuffer &) = delete; - AsyncArrayBuffer &operator=(const AsyncArrayBuffer &) = delete; - AsyncArrayBuffer(AsyncArrayBuffer &&) noexcept = default; - AsyncArrayBuffer &operator=(AsyncArrayBuffer &&) noexcept = default; + AsyncArrayBuffer(const AsyncArrayBuffer&) = delete; + AsyncArrayBuffer& operator=(const AsyncArrayBuffer&) = delete; + AsyncArrayBuffer(AsyncArrayBuffer&&) noexcept = default; + AsyncArrayBuffer& operator=(AsyncArrayBuffer&&) noexcept = default; ~AsyncArrayBuffer() = default; // Zero-copy if the input has a native MutableBuffer; copies otherwise. - static AsyncArrayBuffer acquire(jsi::Runtime &rt, const jsi::ArrayBuffer &buffer) - { + static AsyncArrayBuffer acquire( + jsi::Runtime& rt, + const jsi::ArrayBuffer& buffer) { throwIfDetached(rt, buffer, "AsyncArrayBuffer::acquire"); if (auto mutableBuf = buffer.tryGetMutableBuffer(rt)) { return AsyncArrayBuffer{std::move(mutableBuf)}; @@ -85,8 +84,9 @@ class AsyncArrayBuffer { } // Zero-copy. Throws if the input has no native MutableBuffer. - static AsyncArrayBuffer borrow(jsi::Runtime &rt, const jsi::ArrayBuffer &buffer) - { + static AsyncArrayBuffer borrow( + jsi::Runtime& rt, + const jsi::ArrayBuffer& buffer) { throwIfDetached(rt, buffer, "AsyncArrayBuffer::borrow"); auto mutableBuf = buffer.tryGetMutableBuffer(rt); if (!mutableBuf) { @@ -99,70 +99,72 @@ class AsyncArrayBuffer { } // Always copies. - static AsyncArrayBuffer copy(jsi::Runtime &rt, const jsi::ArrayBuffer &buffer) - { + static AsyncArrayBuffer copy( + jsi::Runtime& rt, + const jsi::ArrayBuffer& buffer) { throwIfDetached(rt, buffer, "AsyncArrayBuffer::copy"); return copyBytes(rt, buffer); } // Wraps an existing MutableBuffer. Safe to call from any thread. - static AsyncArrayBuffer wrap(std::shared_ptr buffer) noexcept - { + static AsyncArrayBuffer wrap( + std::shared_ptr buffer) noexcept { return AsyncArrayBuffer{std::move(buffer)}; } // Takes ownership of a byte vector. Safe to call from any thread. - static AsyncArrayBuffer wrap(std::vector bytes) - { - return AsyncArrayBuffer{std::make_shared(std::move(bytes))}; + static AsyncArrayBuffer wrap(std::vector bytes) { + return AsyncArrayBuffer{ + std::make_shared(std::move(bytes))}; } - uint8_t *data() noexcept - { + uint8_t* data() noexcept { return buffer_->data(); } - const uint8_t *data() const noexcept - { + const uint8_t* data() const noexcept { return buffer_->data(); } - size_t size() const noexcept - { + size_t size() const noexcept { return buffer_->size(); } // Returns the underlying MutableBuffer. Used by // Bridging::toJs to hand the buffer back to JS without a // copy. Always non-null. - std::shared_ptr getMutableBuffer() const noexcept - { + std::shared_ptr getMutableBuffer() const noexcept { return buffer_; } private: - explicit AsyncArrayBuffer(std::shared_ptr buffer) noexcept : buffer_{std::move(buffer)} {} + explicit AsyncArrayBuffer(std::shared_ptr buffer) noexcept + : buffer_{std::move(buffer)} {} - static AsyncArrayBuffer copyBytes(jsi::Runtime &rt, const jsi::ArrayBuffer &buffer) - { + static AsyncArrayBuffer copyBytes( + jsi::Runtime& rt, + const jsi::ArrayBuffer& buffer) { auto bytes = std::span(buffer.data(rt), buffer.size(rt)); return wrap(std::vector(bytes.begin(), bytes.end())); } - // Best-effort detached check. jsi::ArrayBuffer::detached relies on the JS-level - // `detached` property, which some runtimes (e.g. Hermes) don't implement and - // signal by throwing. In that case we silently skip the check rather than - // surfacing a confusing error from an unrelated method. - static void throwIfDetached(jsi::Runtime &rt, const jsi::ArrayBuffer &buffer, const char *callerName) - { + // Best-effort detached check. jsi::ArrayBuffer::detached relies on the + // JS-level `detached` property, which some runtimes (e.g. Hermes) don't + // implement and signal by throwing. In that case we silently skip the check + // rather than surfacing a confusing error from an unrelated method. + static void throwIfDetached( + jsi::Runtime& rt, + const jsi::ArrayBuffer& buffer, + const char* callerName) { bool detached = false; try { detached = buffer.detached(rt); - } catch (const jsi::JSINativeException &) { + } catch (const jsi::JSINativeException&) { return; } if (detached) { - throw jsi::JSError(rt, std::string(callerName) + ": ArrayBuffer is detached"); + throw jsi::JSError( + rt, std::string(callerName) + ": ArrayBuffer is detached"); } } @@ -171,8 +173,7 @@ class AsyncArrayBuffer { template <> struct Bridging { - static jsi::Value toJs(jsi::Runtime &rt, AsyncArrayBuffer buffer) - { + static jsi::Value toJs(jsi::Runtime& rt, AsyncArrayBuffer buffer) { return {rt, rt.createArrayBuffer(buffer.getMutableBuffer())}; } }; diff --git a/packages/react-native/ReactCommon/react/bridging/Base.h b/packages/react-native/ReactCommon/react/bridging/Base.h index fcae10f42de0..8265c47338af 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,7 +51,9 @@ 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::operator())>> +struct bridging_wrapper< + T, + std::void_t::operator())>> : function_wrapper::operator())> {}; } // namespace detail @@ -61,45 +63,71 @@ 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); } @@ -110,13 +138,19 @@ 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; @@ -125,15 +159,31 @@ template inline constexpr bool supportsToJs< JSReturnT, ReturnT, - std::void_t(), std::declval(), nullptr))>> = - std::is_convertible_v(), std::declval(), nullptr)), ReturnT>; + std::void_t(), + std::declval(), + nullptr))>> = + std::is_convertible_v< + decltype(toJs( + std::declval(), + std::declval(), + nullptr)), + ReturnT>; template inline constexpr bool supportsToJs< ReturnT, jsi::Value, - std::void_t(), std::declval(), nullptr))>> = - std::is_convertible_v(), std::declval(), nullptr)), jsi::Value>; + std::void_t(), + std::declval(), + nullptr))>> = + std::is_convertible_v< + decltype(toJs( + std::declval(), + 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 10bb7500abd4..1a3912ac1fbf 100644 --- a/packages/react-native/ReactCommon/react/bridging/Bool.h +++ b/packages/react-native/ReactCommon/react/bridging/Bool.h @@ -13,13 +13,11 @@ 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 a6c5083ef267..3f0d4c8129a1 100644 --- a/packages/react-native/ReactCommon/react/bridging/CallbackWrapper.h +++ b/packages/react-native/ReactCommon/react/bridging/CallbackWrapper.h @@ -20,47 +20,46 @@ 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 16bc0cf0abaa..083bd6f09877 100644 --- a/packages/react-native/ReactCommon/react/bridging/Class.h +++ b/packages/react-native/ReactCommon/react/bridging/Class.h @@ -11,41 +11,64 @@ namespace facebook::react::bridging { -template +template < + typename JSReturnT, + typename ClassT, + typename ReturnT, + typename... ArgsT, + typename... JSArgsT> 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 - : supportsToJs, + is_optional_v + ? supportsToJs< + typename ReturnT::value_type, + typename JSReturnT::value_type> + : 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()) { @@ -55,20 +78,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 a34a22ea9ac6..ca92fa9aea59 100644 --- a/packages/react-native/ReactCommon/react/bridging/Convert.h +++ b/packages/react-native/ReactCommon/react/bridging/Convert.h @@ -19,8 +19,10 @@ 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 {}; @@ -35,8 +37,9 @@ 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; @@ -45,10 +48,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_); @@ -78,16 +81,17 @@ 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 && std::is_same_v, int> = 0> + template < + typename U, + std::enable_if_t && std::is_same_v, int> = 0> operator U() && = delete; // Prevent unwanted upcasting of JSI values. protected: - jsi::Runtime &rt_; + jsi::Runtime& rt_; T value_; }; @@ -100,28 +104,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_); } - operator jsi::ArrayBuffer() && - { + operator jsi::ArrayBuffer() && { return std::move(value_).asObject(rt_).getArrayBuffer(rt_); } }; @@ -130,31 +129,25 @@ 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_); } - operator jsi::ArrayBuffer() && - { + operator jsi::ArrayBuffer() && { return std::move(value_).getArrayBuffer(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 {}; } @@ -163,26 +156,24 @@ 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 || std::is_scalar_v, int> = 0> -auto convert(jsi::Runtime &rt, std::optional value) -{ +template < + typename T, + std::enable_if_t || 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 b06266325921..90d1954386f6 100644 --- a/packages/react-native/ReactCommon/react/bridging/Dynamic.h +++ b/packages/react-native/ReactCommon/react/bridging/Dynamic.h @@ -14,13 +14,11 @@ 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 621fd0bfb083..e8b45973a33d 100644 --- a/packages/react-native/ReactCommon/react/bridging/Error.h +++ b/packages/react-native/ReactCommon/react/bridging/Error.h @@ -16,10 +16,9 @@ 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_; } @@ -29,26 +28,22 @@ 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 3a76abcc36cd..a635ce1bae13 100644 --- a/packages/react-native/ReactCommon/react/bridging/EventEmitter.h +++ b/packages/react-native/ReactCommon/react/bridging/EventEmitter.h @@ -13,21 +13,22 @@ #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_(); } @@ -38,18 +39,23 @@ 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; } }; @@ -58,21 +64,24 @@ 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; - - virtual jsi::Object get(jsi::Runtime &rt, const std::shared_ptr &jsInvoker) const = 0; + 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; }; 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++; @@ -84,29 +93,30 @@ 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); } @@ -126,9 +136,10 @@ 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 eb5d08749b5b..01ac6af94208 100644 --- a/packages/react-native/ReactCommon/react/bridging/Function.h +++ b/packages/react-native/ReactCommon/react/bridging/Function.h @@ -21,34 +21,37 @@ 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))) - { - } - - void operator()(Args... args) const noexcept - { + 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 { 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)); } @@ -57,14 +60,15 @@ 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 { @@ -75,19 +79,20 @@ 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 { @@ -103,39 +108,40 @@ 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 @@ -148,15 +154,19 @@ 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); } } @@ -164,14 +174,13 @@ 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))...); } @@ -181,28 +190,32 @@ 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); } }; @@ -214,14 +227,19 @@ 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"); } @@ -230,7 +248,10 @@ 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); } }); } @@ -238,12 +259,11 @@ 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)...); } }; @@ -251,7 +271,8 @@ struct Bridging> { template struct Bridging< std::function, - std::enable_if_t, std::function>>> + std::enable_if_t< + !std::is_same_v, 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 83807d54e87c..ea3aa83bc62b 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 1e3ff3f97bcc..d043a0a9a919 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 2fb0c8a9b0d4..68b4c2594404 100644 --- a/packages/react-native/ReactCommon/react/bridging/Number.h +++ b/packages/react-native/ReactCommon/react/bridging/Number.h @@ -13,52 +13,44 @@ 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 0ccd3a24e1e2..89e5714b798f 100644 --- a/packages/react-native/ReactCommon/react/bridging/Object.h +++ b/packages/react-native/ReactCommon/react/bridging/Object.h @@ -17,26 +17,24 @@ 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::enable_if_t>> { - static std::shared_ptr fromJs(jsi::Runtime &rt, const jsi::Object &value) - { +struct Bridging< + std::shared_ptr, + 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)); } }; @@ -45,8 +43,10 @@ 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,18 +56,24 @@ 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; @@ -77,7 +83,8 @@ 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 a1f17f813adf..6dfb0d9b0671 100644 --- a/packages/react-native/ReactCommon/react/bridging/Promise.h +++ b/packages/react-native/ReactCommon/react/bridging/Promise.h @@ -18,12 +18,13 @@ 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( @@ -31,21 +32,23 @@ 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) { @@ -55,8 +58,7 @@ class AsyncPromise { } } - void reject(Error error) - { + void reject(Error error) { std::lock_guard lock(state_->mutex); if (state_->reject) { @@ -66,8 +68,7 @@ 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 { @@ -77,14 +78,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(); } @@ -101,8 +102,7 @@ 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 deb99ad5d394..dfd832c8a2f5 100644 --- a/packages/react-native/ReactCommon/react/bridging/Value.h +++ b/packages/react-native/ReactCommon/react/bridging/Value.h @@ -16,8 +16,7 @@ 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 { @@ -25,17 +24,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 {}; } @@ -43,17 +42,20 @@ 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); } @@ -62,9 +64,13 @@ struct Bridging> { }; template -struct Bridging, std::enable_if_t>> { - static jsi::Value toJs(jsi::Runtime &rt, const std::shared_ptr &ptr, const std::shared_ptr &jsInvoker) - { +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) { if (ptr) { return bridging::toJs(rt, *ptr, jsInvoker); } @@ -74,8 +80,10 @@ struct Bridging, std::enable_if_t 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); } @@ -85,9 +93,10 @@ 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.h b/packages/react-native/ReactCommon/react/bridging/tests/BridgingTest.h index 71a072acd3c1..533feeceaca9 100644 --- a/packages/react-native/ReactCommon/react/bridging/tests/BridgingTest.h +++ b/packages/react-native/ReactCommon/react/bridging/tests/BridgingTest.h @@ -18,54 +18,46 @@ 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/cxxstableapi/FrameworksGuard.h b/packages/react-native/ReactCommon/react/cxxstableapi/FrameworksGuard.h index 3f73494371c3..4ee6e8a7e887 100644 --- a/packages/react-native/ReactCommon/react/cxxstableapi/FrameworksGuard.h +++ b/packages/react-native/ReactCommon/react/cxxstableapi/FrameworksGuard.h @@ -22,14 +22,15 @@ // RN_STRICT_API Consumer opt-in master switch; the guard is inert // without it. // RN_ALLOW_FRAMEWORKS Consumer opt-out acknowledging framework-tier usage. -// RN_UMBRELLA_CONTEXT Internal marker set by an umbrella around its includes. -// RN_BUILDING Set by React Native's own build. +// RN_UMBRELLA_CONTEXT Internal marker set by an umbrella around its +// includes. RN_BUILDING Set by React Native's own build. // // This header is intentionally NOT `#pragma once`-guarded: it must be // re-evaluated on every inclusion so each direct include is checked. // ============================================================================= -#if defined(RN_STRICT_API) && !defined(RN_ALLOW_FRAMEWORKS) && !defined(RN_UMBRELLA_CONTEXT) && !defined(RN_BUILDING) +#if defined(RN_STRICT_API) && !defined(RN_ALLOW_FRAMEWORKS) && \ + !defined(RN_UMBRELLA_CONTEXT) && !defined(RN_BUILDING) #warning \ "This is a 'for frameworks' React Native API, intended for framework authors rather than app code. Include it via the module umbrella .h>, or define RN_ALLOW_FRAMEWORKS to acknowledge framework-tier usage and silence this warning." #endif diff --git a/packages/react-native/ReactCommon/react/cxxstableapi/PrivateGuard.h b/packages/react-native/ReactCommon/react/cxxstableapi/PrivateGuard.h index 723eca8bc7de..5d75620e8f10 100644 --- a/packages/react-native/ReactCommon/react/cxxstableapi/PrivateGuard.h +++ b/packages/react-native/ReactCommon/react/cxxstableapi/PrivateGuard.h @@ -21,8 +21,8 @@ // // See for the full `RN_*` macro contract. // In short: -// RN_STRICT_API Consumer opt-in master switch; the guard is inert without it. -// RN_BUILDING Set by React Native's own build. +// RN_STRICT_API Consumer opt-in master switch; the guard is inert without +// it. RN_BUILDING Set by React Native's own build. // // This header is intentionally NOT `#pragma once`-guarded: it must be // re-evaluated on every inclusion so each direct include is checked. diff --git a/packages/react-native/ReactCommon/react/cxxstableapi/UmbrellaGuard.h b/packages/react-native/ReactCommon/react/cxxstableapi/UmbrellaGuard.h index fa925805f1e2..8808cf505148 100644 --- a/packages/react-native/ReactCommon/react/cxxstableapi/UmbrellaGuard.h +++ b/packages/react-native/ReactCommon/react/cxxstableapi/UmbrellaGuard.h @@ -28,18 +28,20 @@ // when a consumer opts into the strict public API by // defining RN_STRICT_API. // -// RN_UMBRELLA_CONTEXT Internal marker (implementation detail; consumers never +// RN_UMBRELLA_CONTEXT Internal marker (implementation detail; consumers +// never // set it). A module umbrella defines it around its own // `#include`s to signal the blessed inclusion path: // #define RN_UMBRELLA_CONTEXT // #include // #include // #undef RN_UMBRELLA_CONTEXT -// The `#undef` matters: it keeps the marker scoped to the -// umbrella's includes so later *direct* includes in the -// same translation unit are still caught. +// The `#undef` matters: it keeps the marker scoped to +// the umbrella's includes so later *direct* includes in +// the same translation unit are still caught. // -// RN_BUILDING Defined by React Native's own build targets so internal +// RN_BUILDING Defined by React Native's own build targets so +// internal // sources may keep including the fine-grained headers // directly. // @@ -47,7 +49,8 @@ // re-evaluated on every inclusion so each direct include is checked. // ============================================================================= -#if defined(RN_STRICT_API) && !defined(RN_UMBRELLA_CONTEXT) && !defined(RN_BUILDING) +#if defined(RN_STRICT_API) && !defined(RN_UMBRELLA_CONTEXT) && \ + !defined(RN_BUILDING) #error \ "Do not include this React Native header directly. Include the module's umbrella header .h> instead." #endif 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 d209e0041bb8..1d399d454217 100644 --- a/packages/react-native/ReactCommon/react/debug/react_native_assert.h +++ b/packages/react-native/ReactCommon/react/debug/react_native_assert.h @@ -37,12 +37,17 @@ #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/debug/redbox/AnsiParser.h b/packages/react-native/ReactCommon/react/debug/redbox/AnsiParser.h index 89f2aa8eda26..24abce09d888 100644 --- a/packages/react-native/ReactCommon/react/debug/redbox/AnsiParser.h +++ b/packages/react-native/ReactCommon/react/debug/redbox/AnsiParser.h @@ -27,9 +27,9 @@ struct AnsiSpan { * Parse ANSI escape sequences in text and produce a list of styled spans. * Uses the Afterglow color theme (matching LogBox's AnsiHighlight.js). */ -std::vector parseAnsi(const std::string &text); +std::vector parseAnsi(const std::string& text); /** Strip all ANSI escape sequences from text. */ -std::string stripAnsi(const std::string &text); +std::string stripAnsi(const std::string& text); } // namespace facebook::react::unstable_redbox diff --git a/packages/react-native/ReactCommon/react/debug/redbox/JscSafeUrl.h b/packages/react-native/ReactCommon/react/debug/redbox/JscSafeUrl.h index 39417d1b06b2..5cd1b35b85c1 100644 --- a/packages/react-native/ReactCommon/react/debug/redbox/JscSafeUrl.h +++ b/packages/react-native/ReactCommon/react/debug/redbox/JscSafeUrl.h @@ -15,7 +15,8 @@ namespace facebook::react::unstable_redbox { /** * These functions are for handling of query-string free URLs, necessitated * by query string stripping of URLs in JavaScriptCore stack traces - * introduced in iOS 16.4. This is a direct port of https://www.npmjs.com/package/jsc-safe-url. + * introduced in iOS 16.4. This is a direct port of + * https://www.npmjs.com/package/jsc-safe-url. * * See https://github.com/facebook/react-native/issues/36794 for context. */ diff --git a/packages/react-native/ReactCommon/react/debug/redbox/RedBoxErrorParser.h b/packages/react-native/ReactCommon/react/debug/redbox/RedBoxErrorParser.h index b8aaf6d85b3b..91a2db574cc8 100644 --- a/packages/react-native/ReactCommon/react/debug/redbox/RedBoxErrorParser.h +++ b/packages/react-native/ReactCommon/react/debug/redbox/RedBoxErrorParser.h @@ -32,9 +32,9 @@ struct ParsedError { * C++ port of parseLogBoxException from parseLogBoxLog.js. */ ParsedError parseErrorMessage( - const std::string &message, - const std::string &name = "", - const std::string &componentStack = "", + const std::string& message, + const std::string& name = "", + const std::string& componentStack = "", bool isFatal = true); } // namespace facebook::react::unstable_redbox diff --git a/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlags.h b/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlags.h index 648d7bf4a0c3..865a3ca9010f 100644 --- a/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlags.h +++ b/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlags.h @@ -45,17 +45,20 @@ class ReactNativeFeatureFlags { RN_EXPORT static bool commonTestFlag(); /** - * Enable emitting of InteractionEntry live metrics to the debugger. Requires `enableBridgelessArchitecture`. + * Enable emitting of InteractionEntry live metrics to the debugger. Requires + * `enableBridgelessArchitecture`. */ RN_EXPORT static bool cdpInteractionMetricsEnabled(); /** - * Use a C++ implementation of Native Animated instead of the platform implementation. + * Use a C++ implementation of Native Animated instead of the platform + * implementation. */ RN_EXPORT static bool cxxNativeAnimatedEnabled(); /** - * When enabled, sets the default overflow style for Text components to hidden instead of visible. + * When enabled, sets the default overflow style for Text components to hidden + * instead of visible. */ RN_EXPORT static bool defaultTextToOverflowHidden(); @@ -65,12 +68,14 @@ class ReactNativeFeatureFlags { RN_EXPORT static bool disableEarlyViewCommandExecution(); /** - * Force disable view preallocation for images triggered from createNode off the main thread on Android + * Force disable view preallocation for images triggered from createNode off + * the main thread on Android */ RN_EXPORT static bool disableImageViewPreallocationAndroid(); /** - * Prevent FabricMountingManager from reordering mountItems, which may lead to invalid state on the UI thread + * Prevent FabricMountingManager from reordering mountItems, which may lead to + * invalid state on the UI thread */ RN_EXPORT static bool disableMountItemReorderingAndroid(); @@ -80,32 +85,38 @@ class ReactNativeFeatureFlags { RN_EXPORT static bool disableSubviewClippingAndroid(); /** - * Turns off the global measurement cache used by TextLayoutManager on Android. + * Turns off the global measurement cache used by TextLayoutManager on + * Android. */ RN_EXPORT static bool disableTextLayoutManagerCacheAndroid(); /** - * Force disable view preallocation triggered from createNode off the main thread on Android + * Force disable view preallocation triggered from createNode off the main + * thread on Android */ RN_EXPORT static bool disableViewPreallocationAndroid(); /** - * When enabled, the accessibilityOrder prop will propagate to native platforms and define the accessibility order. + * When enabled, the accessibilityOrder prop will propagate to native + * platforms and define the accessibility order. */ RN_EXPORT static bool enableAccessibilityOrder(); /** - * When enabled, Android will accumulate updates in rawProps to reduce the number of mounting instructions for cascading re-renders. + * When enabled, Android will accumulate updates in rawProps to reduce the + * number of mounting instructions for cascading re-renders. */ RN_EXPORT static bool enableAccumulatedUpdatesInRawPropsAndroid(); /** - * When enabled, Android Text measurement and rendering respects the system Bold text accessibility setting via `Configuration.fontWeightAdjustment`. + * When enabled, Android Text measurement and rendering respects the system + * Bold text accessibility setting via `Configuration.fontWeightAdjustment`. */ RN_EXPORT static bool enableAndroidFontWeightAdjustment(); /** - * Enables various optimizations throughout the path of measuring text on Android. + * Enables various optimizations throughout the path of measuring text on + * Android. */ RN_EXPORT static bool enableAndroidTextMeasurementOptimizations(); @@ -115,37 +126,44 @@ class ReactNativeFeatureFlags { RN_EXPORT static bool enableBridgelessArchitecture(); /** - * Enable prop iterator setter-style construction of Props in C++ (this flag is not used in Java). + * Enable prop iterator setter-style construction of Props in C++ (this flag + * is not used in Java). */ RN_EXPORT static bool enableCppPropsIteratorSetter(); /** - * This enables the fabric implementation of focus search so that we can focus clipped elements + * This enables the fabric implementation of focus search so that we can focus + * clipped elements */ RN_EXPORT static bool enableCustomFocusSearchOnClippedElementsAndroid(); /** - * Enables destructor calls for ShadowTreeRevision in the background to reduce UI thread work. + * Enables destructor calls for ShadowTreeRevision in the background to reduce + * UI thread work. */ RN_EXPORT static bool enableDestroyShadowTreeRevisionAsync(); /** - * When enabled a subset of components will avoid double measurement on Android. + * When enabled a subset of components will avoid double measurement on + * Android. */ RN_EXPORT static bool enableDoubleMeasurementFixAndroid(); /** - * Feature flag to configure eager attachment of the root view/initialisation of the JS code. + * Feature flag to configure eager attachment of the root view/initialisation + * of the JS code. */ RN_EXPORT static bool enableEagerRootViewAttachment(); /** - * When enabled, Android will disable Props 1.5 raw value merging when Props 2.0 is available. + * When enabled, Android will disable Props 1.5 raw value merging when + * Props 2.0 is available. */ RN_EXPORT static bool enableExclusivePropsUpdateAndroid(); /** - * Enables Fabric commit branching to fix starvation problems and atomic JS updates. + * Enables Fabric commit branching to fix starvation problems and atomic JS + * updates. */ RN_EXPORT static bool enableFabricCommitBranching(); @@ -155,7 +173,12 @@ class ReactNativeFeatureFlags { RN_EXPORT static bool enableFabricLogs(); /** - * Enables CSS Flexbox §4.5 automatic minimum sizing under strict layout conformance. When enabled, a flex item with an undefined main-axis `min-width`/`min-height` under strict conformance receives a content-derived minimum size (per spec) instead of an undefined (0) minimum. Defaults off so the behaviour can be ramped independently of strict conformance. + * Enables CSS Flexbox §4.5 automatic minimum sizing under strict layout + * conformance. When enabled, a flex item with an undefined main-axis + * `min-width`/`min-height` under strict conformance receives a + * content-derived minimum size (per spec) instead of an undefined (0) + * minimum. Defaults off so the behaviour can be ramped independently of + * strict conformance. */ RN_EXPORT static bool enableFlexboxAutoMinSizeInStrictMode(); @@ -180,17 +203,24 @@ class ReactNativeFeatureFlags { RN_EXPORT static bool enableIOSViewClipToPaddingBox(); /** - * When enabled, Android will build and initiate image prefetch requests on ImageShadowNode::layout + * When enabled, Android will build and initiate image prefetch requests on + * ImageShadowNode::layout */ RN_EXPORT static bool enableImagePrefetchingAndroid(); /** - * When enabled, Image `tintColor` is handled as a true optional: any defined color is applied as a tint — including `transparent` (alpha 0), which renders the image invisible — and an unset value clears a previously applied tint. When disabled, the prior behavior is preserved, where a transparent `tintColor` is treated as unassigned and the image renders untinted. + * When enabled, Image `tintColor` is handled as a true optional: any defined + * color is applied as a tint — including `transparent` (alpha 0), which + * renders the image invisible — and an unset value clears a previously + * applied tint. When disabled, the prior behavior is preserved, where a + * transparent `tintColor` is treated as unassigned and the image renders + * untinted. */ RN_EXPORT static bool enableImageTransparentTintColor(); /** - * Dispatches state updates for content offset changes synchronously on the main thread. + * Dispatches state updates for content offset changes synchronously on the + * main thread. */ RN_EXPORT static bool enableImmediateUpdateModeForContentOffsetChanges(); @@ -200,7 +230,8 @@ class ReactNativeFeatureFlags { RN_EXPORT static bool enableImperativeFocus(); /** - * This is to fix the issue with interop view manager where component descriptor lookup is causing ViewManager to preload. + * This is to fix the issue with interop view manager where component + * descriptor lookup is causing ViewManager to preload. */ RN_EXPORT static bool enableInteropViewManagerClassLookUpOptimizationIOS(); @@ -230,7 +261,16 @@ class ReactNativeFeatureFlags { RN_EXPORT static bool enableModuleArgumentNSNullConversionIOS(); /** - * When enabled, Android mounts transactions with the pull model (like iOS): the commit thread no longer pulls and builds the mount batch in schedulerShouldRenderTransactions. Instead the UI thread pulls the transaction itself via a PullTransactionMountItem enqueued in the MountItemDispatcher, builds the IntBufferBatchMountItem, and applies it synchronously. Requires `enableAccumulatedUpdatesInRawPropsAndroid` to be enabled as well, since a single pull may collapse several commits into one diff and therefore needs complete accumulated rawProps; when used together with Props 2.0, also enable `enableExclusivePropsUpdateAndroid` and `enablePropsUpdateReconciliationAndroid`. + * When enabled, Android mounts transactions with the pull model (like iOS): + * the commit thread no longer pulls and builds the mount batch in + * schedulerShouldRenderTransactions. Instead the UI thread pulls the + * transaction itself via a PullTransactionMountItem enqueued in the + * MountItemDispatcher, builds the IntBufferBatchMountItem, and applies it + * synchronously. Requires `enableAccumulatedUpdatesInRawPropsAndroid` to be + * enabled as well, since a single pull may collapse several commits into one + * diff and therefore needs complete accumulated rawProps; when used together + * with Props 2.0, also enable `enableExclusivePropsUpdateAndroid` and + * `enablePropsUpdateReconciliationAndroid`. */ RN_EXPORT static bool enableMountingCoordinatorPullModelAndroid(); @@ -240,7 +280,8 @@ class ReactNativeFeatureFlags { RN_EXPORT static bool enableMutationObserverByDefault(); /** - * Parse CSS strings using the Fabric CSS parser instead of ViewConfig processing + * Parse CSS strings using the Fabric CSS parser instead of ViewConfig + * processing */ RN_EXPORT static bool enableNativeCSSParsing(); @@ -250,17 +291,22 @@ class ReactNativeFeatureFlags { RN_EXPORT static bool enablePreparedTextLayout(); /** - * When enabled, Android will receive prop updates based on the differences between the last rendered shadow node and the last committed shadow node. + * When enabled, Android will receive prop updates based on the differences + * between the last rendered shadow node and the last committed shadow node. */ RN_EXPORT static bool enablePropsUpdateReconciliationAndroid(); /** - * When enabled, RuntimeScheduler_Modern clears pending tasks and rendering updates before handling an error. + * When enabled, RuntimeScheduler_Modern clears pending tasks and rendering + * updates before handling an error. */ RN_EXPORT static bool enableRuntimeSchedulerQueueClearingOnError(); /** - * Gates a defensive guard around Scheduler::uiManagerDidDispatchCommand and uiManagerDidFinishTransaction that prevents queued rendering-update lambdas from dereferencing the SchedulerDelegate after it has been destroyed (use-after-free). + * Gates a defensive guard around Scheduler::uiManagerDidDispatchCommand and + * uiManagerDidFinishTransaction that prevents queued rendering-update lambdas + * from dereferencing the SchedulerDelegate after it has been destroyed + * (use-after-free). */ RN_EXPORT static bool enableSchedulerDelegateInvalidation(); @@ -270,12 +316,15 @@ class ReactNativeFeatureFlags { RN_EXPORT static bool enableSwiftUIBasedFilters(); /** - * Enables View Culling: as soon as a view goes off screen, it can be reused anywhere in the UI and pieced together with other items to create new UI elements. + * Enables View Culling: as soon as a view goes off screen, it can be reused + * anywhere in the UI and pieced together with other items to create new UI + * elements. */ RN_EXPORT static bool enableViewCulling(); /** - * Enables View Recycling. When enabled, individual ViewManagers must still opt-in. + * Enables View Recycling. When enabled, individual ViewManagers must still + * opt-in. */ RN_EXPORT static bool enableViewRecycling(); @@ -285,7 +334,8 @@ class ReactNativeFeatureFlags { RN_EXPORT static bool enableViewRecyclingForImage(); /** - * Enables View Recycling for via ReactViewGroup/ReactViewManager. + * Enables View Recycling for via + * ReactViewGroup/ReactViewManager. */ RN_EXPORT static bool enableViewRecyclingForScrollView(); @@ -305,62 +355,87 @@ class ReactNativeFeatureFlags { RN_EXPORT static bool enableVirtualViewContainerStateExperimental(); /** - * Fix incorrect parentTag passed as parentTagForUpdate in the unflatten-unflatten branch of calculateShadowViewMutationsFlattener, which causes UPDATE mutations to reference a parent being created in the same batch. + * Fix incorrect parentTag passed as parentTagForUpdate in the + * unflatten-unflatten branch of calculateShadowViewMutationsFlattener, which + * causes UPDATE mutations to reference a parent being created in the same + * batch. */ RN_EXPORT static bool fixDifferentiatorParentTagForUnflattenCase(); /** - * Uses the default event priority instead of the discreet event priority by default when dispatching events from Fabric to React. + * Uses the default event priority instead of the discreet event priority by + * default when dispatching events from Fabric to React. */ RN_EXPORT static bool fixMappingOfEventPrioritiesBetweenFabricAndReact(); /** - * Fix flex basis computation to not apply FitContent constraint in the main axis for non-measure container nodes, preventing unnecessary re-measurement in scroll containers. + * Fix flex basis computation to not apply FitContent constraint in the main + * axis for non-measure container nodes, preventing unnecessary re-measurement + * in scroll containers. */ RN_EXPORT static bool fixYogaFlexBasisFitContentInMainAxis(); /** - * Enable system assertion validating that Fusebox is configured with a single host. When set, the CDP backend will dynamically disable features (Perf and Network) in the event that multiple hosts are registered (undefined behaviour), and broadcast this over `ReactNativeApplication.systemStateChanged`. + * Enable system assertion validating that Fusebox is configured with a single + * host. When set, the CDP backend will dynamically disable features (Perf and + * Network) in the event that multiple hosts are registered (undefined + * behaviour), and broadcast this over + * `ReactNativeApplication.systemStateChanged`. */ RN_EXPORT static bool fuseboxAssertSingleHostState(); /** - * Flag determining if the React Native DevTools (Fusebox) CDP backend should be enabled in release builds. This flag is global and should not be changed across React Host lifetimes. + * Flag determining if the React Native DevTools (Fusebox) CDP backend should + * be enabled in release builds. This flag is global and should not be changed + * across React Host lifetimes. */ RN_EXPORT static bool fuseboxEnabledRelease(); /** - * Enable frame timings and screenshots support in the React Native DevTools CDP backend. This flag is global and should not be changed across React Host lifetimes. + * Enable frame timings and screenshots support in the React Native DevTools + * CDP backend. This flag is global and should not be changed across React + * Host lifetimes. */ RN_EXPORT static bool fuseboxFrameRecordingEnabled(); /** - * Enable Page.captureScreenshot CDP method support in the React Native DevTools CDP backend. This flag is global and should not be changed across React Host lifetimes. + * Enable Page.captureScreenshot CDP method support in the React Native + * DevTools CDP backend. This flag is global and should not be changed across + * React Host lifetimes. */ RN_EXPORT static bool fuseboxScreenshotCaptureEnabled(); /** - * Enable reporting of WebSocket network events (`Network.webSocket*` CDP events) to the React Native DevTools CDP backend. + * Enable reporting of WebSocket network events (`Network.webSocket*` CDP + * events) to the React Native DevTools CDP backend. */ RN_EXPORT static bool fuseboxWebSocketEventsEnabled(); /** - * When enabled, uses optimized platform-specific paths to apply animated props synchronously. On Android, this uses a batched int/double buffer protocol with a single JNI call. On iOS, this passes AnimatedProps directly through the delegate chain and applies them via cloneProps, avoiding the folly::dynamic round-trip. + * When enabled, uses optimized platform-specific paths to apply animated + * props synchronously. On Android, this uses a batched int/double buffer + * protocol with a single JNI call. On iOS, this passes AnimatedProps directly + * through the delegate chain and applies them via cloneProps, avoiding the + * folly::dynamic round-trip. */ RN_EXPORT static bool optimizedAnimatedPropUpdates(); /** - * Override props at mounting with synchronously mounted (i.e. direct manipulation) props from Native Animated. + * Override props at mounting with synchronously mounted (i.e. direct + * manipulation) props from Native Animated. */ RN_EXPORT static bool overrideBySynchronousMountPropsAtMountingAndroid(); /** - * Enable reporting Performance Issues (`detail.devtools.performanceIssue`). Displayed in the V2 Performance Monitor and the "Performance Issues" sub-panel in DevTools. + * Enable reporting Performance Issues (`detail.devtools.performanceIssue`). + * Displayed in the V2 Performance Monitor and the "Performance Issues" + * sub-panel in DevTools. */ RN_EXPORT static bool perfIssuesEnabled(); /** - * Enable the V2 in-app Performance Monitor. This flag is global and should not be changed across React Host lifetimes. + * Enable the V2 in-app Performance Monitor. This flag is global and should + * not be changed across React Host lifetimes. */ RN_EXPORT static bool perfMonitorV2Enabled(); @@ -370,27 +445,33 @@ class ReactNativeFeatureFlags { RN_EXPORT static double preparedTextCacheSize(); /** - * Enables a new mechanism in ShadowTree to prevent problems caused by multiple threads trying to commit concurrently. If a thread tries to commit a few times unsuccessfully, it will acquire a lock and try again. + * Enables a new mechanism in ShadowTree to prevent problems caused by + * multiple threads trying to commit concurrently. If a thread tries to commit + * a few times unsuccessfully, it will acquire a lock and try again. */ RN_EXPORT static bool preventShadowTreeCommitExhaustion(); /** - * Use the redesigned RedBox error overlay on Android, styled to match the LogBox visual language. + * Use the redesigned RedBox error overlay on Android, styled to match the + * LogBox visual language. */ RN_EXPORT static bool redBoxV2Android(); /** - * Use the redesigned RedBox error overlay on iOS, styled to match the LogBox visual language. + * Use the redesigned RedBox error overlay on iOS, styled to match the LogBox + * visual language. */ RN_EXPORT static bool redBoxV2IOS(); /** - * Function used to enable / disable Pressibility from using W3C Pointer Events for its hover callbacks + * Function used to enable / disable Pressibility from using W3C Pointer + * Events for its hover callbacks */ RN_EXPORT static bool shouldPressibilityUseW3CPointerEventsForHover(); /** - * Do not emit touchcancel from Android ScrollView, instead native topScroll event will trigger responder transfer and terminate in RN renderer. + * Do not emit touchcancel from Android ScrollView, instead native topScroll + * event will trigger responder transfer and terminate in RN renderer. */ RN_EXPORT static bool shouldTriggerResponderTransferOnScrollAndroid(); @@ -400,32 +481,42 @@ class ReactNativeFeatureFlags { RN_EXPORT static bool skipActivityIdentityAssertionOnHostPause(); /** - * Override getClipBounds on Android views to return the padding box when overflow is hidden + * Override getClipBounds on Android views to return the padding box when + * overflow is hidden */ RN_EXPORT static bool syncAndroidClipBoundsWithOverflow(); /** - * Enables storing js caller stack when creating promise in native module. This is useful in case of Promise rejection and tracing the cause. + * Enables storing js caller stack when creating promise in native module. + * This is useful in case of Promise rejection and tracing the cause. */ RN_EXPORT static bool traceTurboModulePromiseRejectionsOnAndroid(); /** - * When enabled, runtime shadow node references will be updated during the commit. This allows running RSNRU from any thread without corrupting the renderer state. + * When enabled, runtime shadow node references will be updated during the + * commit. This allows running RSNRU from any thread without corrupting the + * renderer state. */ RN_EXPORT static bool updateRuntimeShadowNodeReferencesOnCommit(); /** - * When enabled, runtime shadow node references will be updated during the commit only on the allowed thread. + * When enabled, runtime shadow node references will be updated during the + * commit only on the allowed thread. */ RN_EXPORT static bool updateRuntimeShadowNodeReferencesOnCommitThread(); /** - * In Bridgeless mode, use the always available javascript error reporting pipeline. + * In Bridgeless mode, use the always available javascript error reporting + * pipeline. */ RN_EXPORT static bool useAlwaysAvailableJSErrorHandling(); /** - * Should this application enable the Fabric Interop Layer for Android? If yes, the application will behave so that it can accept non-Fabric components and render them on Fabric. This toggle is controlling extra logic such as custom event dispatching that are needed for the Fabric Interop Layer to work correctly. + * Should this application enable the Fabric Interop Layer for Android? If + * yes, the application will behave so that it can accept non-Fabric + * components and render them on Fabric. This toggle is controlling extra + * logic such as custom event dispatching that are needed for the Fabric + * Interop Layer to work correctly. */ RN_EXPORT static bool useFabricInterop(); @@ -435,7 +526,8 @@ class ReactNativeFeatureFlags { RN_EXPORT static bool useNativeViewConfigsInBridgelessMode(); /** - * When enabled, ReactScrollView will extend NestedScrollView instead of ScrollView on Android for improved nested scrolling support. + * When enabled, ReactScrollView will extend NestedScrollView instead of + * ScrollView on Android for improved nested scrolling support. */ RN_EXPORT static bool useNestedScrollViewAndroid(); @@ -455,7 +547,9 @@ class ReactNativeFeatureFlags { RN_EXPORT static bool useTurboModuleInterop(); /** - * Outset the culling context frame with the provided ratio. The culling context frame size will be outset by width * ratio on the left and right, and height * ratio on the top and bottom. + * Outset the culling context frame with the provided ratio. The culling + * context frame size will be outset by width * ratio on the left and right, + * and height * ratio on the top and bottom. */ RN_EXPORT static double viewCullingOutsetRatio(); diff --git a/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlagsAccessor.h b/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlagsAccessor.h index 76686e57e2aa..a7e2c646f83b 100644 --- a/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlagsAccessor.h +++ b/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlagsAccessor.h @@ -148,7 +148,8 @@ class ReactNativeFeatureFlagsAccessor { std::atomic> enableAndroidTextMeasurementOptimizations_; std::atomic> enableBridgelessArchitecture_; std::atomic> enableCppPropsIteratorSetter_; - std::atomic> enableCustomFocusSearchOnClippedElementsAndroid_; + std::atomic> + enableCustomFocusSearchOnClippedElementsAndroid_; std::atomic> enableDestroyShadowTreeRevisionAsync_; std::atomic> enableDoubleMeasurementFixAndroid_; std::atomic> enableEagerRootViewAttachment_; @@ -162,9 +163,11 @@ class ReactNativeFeatureFlagsAccessor { std::atomic> enableIOSViewClipToPaddingBox_; std::atomic> enableImagePrefetchingAndroid_; std::atomic> enableImageTransparentTintColor_; - std::atomic> enableImmediateUpdateModeForContentOffsetChanges_; + std::atomic> + enableImmediateUpdateModeForContentOffsetChanges_; std::atomic> enableImperativeFocus_; - std::atomic> enableInteropViewManagerClassLookUpOptimizationIOS_; + std::atomic> + enableInteropViewManagerClassLookUpOptimizationIOS_; std::atomic> enableIntersectionObserverByDefault_; std::atomic> enableKeyEvents_; std::atomic> enableLayoutAnimationsOnAndroid_; @@ -186,7 +189,8 @@ class ReactNativeFeatureFlagsAccessor { std::atomic> enableViewRecyclingForView_; std::atomic> enableVirtualViewContainerStateExperimental_; std::atomic> fixDifferentiatorParentTagForUnflattenCase_; - std::atomic> fixMappingOfEventPrioritiesBetweenFabricAndReact_; + std::atomic> + fixMappingOfEventPrioritiesBetweenFabricAndReact_; std::atomic> fixYogaFlexBasisFitContentInMainAxis_; std::atomic> fuseboxAssertSingleHostState_; std::atomic> fuseboxEnabledRelease_; @@ -194,20 +198,24 @@ class ReactNativeFeatureFlagsAccessor { std::atomic> fuseboxScreenshotCaptureEnabled_; std::atomic> fuseboxWebSocketEventsEnabled_; std::atomic> optimizedAnimatedPropUpdates_; - std::atomic> overrideBySynchronousMountPropsAtMountingAndroid_; + std::atomic> + overrideBySynchronousMountPropsAtMountingAndroid_; std::atomic> perfIssuesEnabled_; std::atomic> perfMonitorV2Enabled_; std::atomic> preparedTextCacheSize_; std::atomic> preventShadowTreeCommitExhaustion_; std::atomic> redBoxV2Android_; std::atomic> redBoxV2IOS_; - std::atomic> shouldPressibilityUseW3CPointerEventsForHover_; - std::atomic> shouldTriggerResponderTransferOnScrollAndroid_; + std::atomic> + shouldPressibilityUseW3CPointerEventsForHover_; + std::atomic> + shouldTriggerResponderTransferOnScrollAndroid_; std::atomic> skipActivityIdentityAssertionOnHostPause_; std::atomic> syncAndroidClipBoundsWithOverflow_; std::atomic> traceTurboModulePromiseRejectionsOnAndroid_; std::atomic> updateRuntimeShadowNodeReferencesOnCommit_; - std::atomic> updateRuntimeShadowNodeReferencesOnCommitThread_; + std::atomic> + updateRuntimeShadowNodeReferencesOnCommitThread_; std::atomic> useAlwaysAvailableJSErrorHandling_; std::atomic> useFabricInterop_; std::atomic> useNativeViewConfigsInBridgelessMode_; diff --git a/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlagsDynamicProvider.h b/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlagsDynamicProvider.h index 4a3915b7b4c6..60640cd85c19 100644 --- a/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlagsDynamicProvider.h +++ b/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlagsDynamicProvider.h @@ -34,14 +34,17 @@ namespace facebook::react { * folly::dynamic object, but if the key is defined, the value must have the * correct type or otherwise throws an exception. */ -class ReactNativeFeatureFlagsDynamicProvider : public ReactNativeFeatureFlagsDefaults { +class ReactNativeFeatureFlagsDynamicProvider + : public ReactNativeFeatureFlagsDefaults { private: folly::dynamic values_; public: - ReactNativeFeatureFlagsDynamicProvider(folly::dynamic values): values_(std::move(values)) { + ReactNativeFeatureFlagsDynamicProvider(folly::dynamic values) + : values_(std::move(values)) { if (!values_.isObject()) { - throw std::invalid_argument("ReactNativeFeatureFlagsDynamicProvider: values must be an object"); + throw std::invalid_argument( + "ReactNativeFeatureFlagsDynamicProvider: values must be an object"); } } @@ -96,7 +99,8 @@ class ReactNativeFeatureFlagsDynamicProvider : public ReactNativeFeatureFlagsDef return value.getBool(); } - return ReactNativeFeatureFlagsDefaults::disableImageViewPreallocationAndroid(); + return ReactNativeFeatureFlagsDefaults:: + disableImageViewPreallocationAndroid(); } bool disableMountItemReorderingAndroid() override { @@ -123,7 +127,8 @@ class ReactNativeFeatureFlagsDynamicProvider : public ReactNativeFeatureFlagsDef return value.getBool(); } - return ReactNativeFeatureFlagsDefaults::disableTextLayoutManagerCacheAndroid(); + return ReactNativeFeatureFlagsDefaults:: + disableTextLayoutManagerCacheAndroid(); } bool disableViewPreallocationAndroid() override { @@ -150,7 +155,8 @@ class ReactNativeFeatureFlagsDynamicProvider : public ReactNativeFeatureFlagsDef return value.getBool(); } - return ReactNativeFeatureFlagsDefaults::enableAccumulatedUpdatesInRawPropsAndroid(); + return ReactNativeFeatureFlagsDefaults:: + enableAccumulatedUpdatesInRawPropsAndroid(); } bool enableAndroidFontWeightAdjustment() override { @@ -168,7 +174,8 @@ class ReactNativeFeatureFlagsDynamicProvider : public ReactNativeFeatureFlagsDef return value.getBool(); } - return ReactNativeFeatureFlagsDefaults::enableAndroidTextMeasurementOptimizations(); + return ReactNativeFeatureFlagsDefaults:: + enableAndroidTextMeasurementOptimizations(); } bool enableBridgelessArchitecture() override { @@ -195,7 +202,8 @@ class ReactNativeFeatureFlagsDynamicProvider : public ReactNativeFeatureFlagsDef return value.getBool(); } - return ReactNativeFeatureFlagsDefaults::enableCustomFocusSearchOnClippedElementsAndroid(); + return ReactNativeFeatureFlagsDefaults:: + enableCustomFocusSearchOnClippedElementsAndroid(); } bool enableDestroyShadowTreeRevisionAsync() override { @@ -204,7 +212,8 @@ class ReactNativeFeatureFlagsDynamicProvider : public ReactNativeFeatureFlagsDef return value.getBool(); } - return ReactNativeFeatureFlagsDefaults::enableDestroyShadowTreeRevisionAsync(); + return ReactNativeFeatureFlagsDefaults:: + enableDestroyShadowTreeRevisionAsync(); } bool enableDoubleMeasurementFixAndroid() override { @@ -258,7 +267,8 @@ class ReactNativeFeatureFlagsDynamicProvider : public ReactNativeFeatureFlagsDef return value.getBool(); } - return ReactNativeFeatureFlagsDefaults::enableFlexboxAutoMinSizeInStrictMode(); + return ReactNativeFeatureFlagsDefaults:: + enableFlexboxAutoMinSizeInStrictMode(); } bool enableFontScaleChangesUpdatingLayout() override { @@ -267,7 +277,8 @@ class ReactNativeFeatureFlagsDynamicProvider : public ReactNativeFeatureFlagsDef return value.getBool(); } - return ReactNativeFeatureFlagsDefaults::enableFontScaleChangesUpdatingLayout(); + return ReactNativeFeatureFlagsDefaults:: + enableFontScaleChangesUpdatingLayout(); } bool enableIOSCompressedTextFrameAdjustment() override { @@ -276,7 +287,8 @@ class ReactNativeFeatureFlagsDynamicProvider : public ReactNativeFeatureFlagsDef return value.getBool(); } - return ReactNativeFeatureFlagsDefaults::enableIOSCompressedTextFrameAdjustment(); + return ReactNativeFeatureFlagsDefaults:: + enableIOSCompressedTextFrameAdjustment(); } bool enableIOSTextBaselineOffsetPerLine() override { @@ -285,7 +297,8 @@ class ReactNativeFeatureFlagsDynamicProvider : public ReactNativeFeatureFlagsDef return value.getBool(); } - return ReactNativeFeatureFlagsDefaults::enableIOSTextBaselineOffsetPerLine(); + return ReactNativeFeatureFlagsDefaults:: + enableIOSTextBaselineOffsetPerLine(); } bool enableIOSViewClipToPaddingBox() override { @@ -321,7 +334,8 @@ class ReactNativeFeatureFlagsDynamicProvider : public ReactNativeFeatureFlagsDef return value.getBool(); } - return ReactNativeFeatureFlagsDefaults::enableImmediateUpdateModeForContentOffsetChanges(); + return ReactNativeFeatureFlagsDefaults:: + enableImmediateUpdateModeForContentOffsetChanges(); } bool enableImperativeFocus() override { @@ -339,7 +353,8 @@ class ReactNativeFeatureFlagsDynamicProvider : public ReactNativeFeatureFlagsDef return value.getBool(); } - return ReactNativeFeatureFlagsDefaults::enableInteropViewManagerClassLookUpOptimizationIOS(); + return ReactNativeFeatureFlagsDefaults:: + enableInteropViewManagerClassLookUpOptimizationIOS(); } bool enableIntersectionObserverByDefault() override { @@ -348,7 +363,8 @@ class ReactNativeFeatureFlagsDynamicProvider : public ReactNativeFeatureFlagsDef return value.getBool(); } - return ReactNativeFeatureFlagsDefaults::enableIntersectionObserverByDefault(); + return ReactNativeFeatureFlagsDefaults:: + enableIntersectionObserverByDefault(); } bool enableKeyEvents() override { @@ -384,7 +400,8 @@ class ReactNativeFeatureFlagsDynamicProvider : public ReactNativeFeatureFlagsDef return value.getBool(); } - return ReactNativeFeatureFlagsDefaults::enableModuleArgumentNSNullConversionIOS(); + return ReactNativeFeatureFlagsDefaults:: + enableModuleArgumentNSNullConversionIOS(); } bool enableMountingCoordinatorPullModelAndroid() override { @@ -393,7 +410,8 @@ class ReactNativeFeatureFlagsDynamicProvider : public ReactNativeFeatureFlagsDef return value.getBool(); } - return ReactNativeFeatureFlagsDefaults::enableMountingCoordinatorPullModelAndroid(); + return ReactNativeFeatureFlagsDefaults:: + enableMountingCoordinatorPullModelAndroid(); } bool enableMutationObserverByDefault() override { @@ -429,7 +447,8 @@ class ReactNativeFeatureFlagsDynamicProvider : public ReactNativeFeatureFlagsDef return value.getBool(); } - return ReactNativeFeatureFlagsDefaults::enablePropsUpdateReconciliationAndroid(); + return ReactNativeFeatureFlagsDefaults:: + enablePropsUpdateReconciliationAndroid(); } bool enableRuntimeSchedulerQueueClearingOnError() override { @@ -438,7 +457,8 @@ class ReactNativeFeatureFlagsDynamicProvider : public ReactNativeFeatureFlagsDef return value.getBool(); } - return ReactNativeFeatureFlagsDefaults::enableRuntimeSchedulerQueueClearingOnError(); + return ReactNativeFeatureFlagsDefaults:: + enableRuntimeSchedulerQueueClearingOnError(); } bool enableSchedulerDelegateInvalidation() override { @@ -447,7 +467,8 @@ class ReactNativeFeatureFlagsDynamicProvider : public ReactNativeFeatureFlagsDef return value.getBool(); } - return ReactNativeFeatureFlagsDefaults::enableSchedulerDelegateInvalidation(); + return ReactNativeFeatureFlagsDefaults:: + enableSchedulerDelegateInvalidation(); } bool enableSwiftUIBasedFilters() override { @@ -519,7 +540,8 @@ class ReactNativeFeatureFlagsDynamicProvider : public ReactNativeFeatureFlagsDef return value.getBool(); } - return ReactNativeFeatureFlagsDefaults::enableVirtualViewContainerStateExperimental(); + return ReactNativeFeatureFlagsDefaults:: + enableVirtualViewContainerStateExperimental(); } bool fixDifferentiatorParentTagForUnflattenCase() override { @@ -528,7 +550,8 @@ class ReactNativeFeatureFlagsDynamicProvider : public ReactNativeFeatureFlagsDef return value.getBool(); } - return ReactNativeFeatureFlagsDefaults::fixDifferentiatorParentTagForUnflattenCase(); + return ReactNativeFeatureFlagsDefaults:: + fixDifferentiatorParentTagForUnflattenCase(); } bool fixMappingOfEventPrioritiesBetweenFabricAndReact() override { @@ -537,7 +560,8 @@ class ReactNativeFeatureFlagsDynamicProvider : public ReactNativeFeatureFlagsDef return value.getBool(); } - return ReactNativeFeatureFlagsDefaults::fixMappingOfEventPrioritiesBetweenFabricAndReact(); + return ReactNativeFeatureFlagsDefaults:: + fixMappingOfEventPrioritiesBetweenFabricAndReact(); } bool fixYogaFlexBasisFitContentInMainAxis() override { @@ -546,7 +570,8 @@ class ReactNativeFeatureFlagsDynamicProvider : public ReactNativeFeatureFlagsDef return value.getBool(); } - return ReactNativeFeatureFlagsDefaults::fixYogaFlexBasisFitContentInMainAxis(); + return ReactNativeFeatureFlagsDefaults:: + fixYogaFlexBasisFitContentInMainAxis(); } bool fuseboxAssertSingleHostState() override { @@ -609,7 +634,8 @@ class ReactNativeFeatureFlagsDynamicProvider : public ReactNativeFeatureFlagsDef return value.getBool(); } - return ReactNativeFeatureFlagsDefaults::overrideBySynchronousMountPropsAtMountingAndroid(); + return ReactNativeFeatureFlagsDefaults:: + overrideBySynchronousMountPropsAtMountingAndroid(); } bool perfIssuesEnabled() override { @@ -672,7 +698,8 @@ class ReactNativeFeatureFlagsDynamicProvider : public ReactNativeFeatureFlagsDef return value.getBool(); } - return ReactNativeFeatureFlagsDefaults::shouldPressibilityUseW3CPointerEventsForHover(); + return ReactNativeFeatureFlagsDefaults:: + shouldPressibilityUseW3CPointerEventsForHover(); } bool shouldTriggerResponderTransferOnScrollAndroid() override { @@ -681,7 +708,8 @@ class ReactNativeFeatureFlagsDynamicProvider : public ReactNativeFeatureFlagsDef return value.getBool(); } - return ReactNativeFeatureFlagsDefaults::shouldTriggerResponderTransferOnScrollAndroid(); + return ReactNativeFeatureFlagsDefaults:: + shouldTriggerResponderTransferOnScrollAndroid(); } bool skipActivityIdentityAssertionOnHostPause() override { @@ -690,7 +718,8 @@ class ReactNativeFeatureFlagsDynamicProvider : public ReactNativeFeatureFlagsDef return value.getBool(); } - return ReactNativeFeatureFlagsDefaults::skipActivityIdentityAssertionOnHostPause(); + return ReactNativeFeatureFlagsDefaults:: + skipActivityIdentityAssertionOnHostPause(); } bool syncAndroidClipBoundsWithOverflow() override { @@ -708,7 +737,8 @@ class ReactNativeFeatureFlagsDynamicProvider : public ReactNativeFeatureFlagsDef return value.getBool(); } - return ReactNativeFeatureFlagsDefaults::traceTurboModulePromiseRejectionsOnAndroid(); + return ReactNativeFeatureFlagsDefaults:: + traceTurboModulePromiseRejectionsOnAndroid(); } bool updateRuntimeShadowNodeReferencesOnCommit() override { @@ -717,7 +747,8 @@ class ReactNativeFeatureFlagsDynamicProvider : public ReactNativeFeatureFlagsDef return value.getBool(); } - return ReactNativeFeatureFlagsDefaults::updateRuntimeShadowNodeReferencesOnCommit(); + return ReactNativeFeatureFlagsDefaults:: + updateRuntimeShadowNodeReferencesOnCommit(); } bool updateRuntimeShadowNodeReferencesOnCommitThread() override { @@ -726,7 +757,8 @@ class ReactNativeFeatureFlagsDynamicProvider : public ReactNativeFeatureFlagsDef return value.getBool(); } - return ReactNativeFeatureFlagsDefaults::updateRuntimeShadowNodeReferencesOnCommitThread(); + return ReactNativeFeatureFlagsDefaults:: + updateRuntimeShadowNodeReferencesOnCommitThread(); } bool useAlwaysAvailableJSErrorHandling() override { @@ -753,7 +785,8 @@ class ReactNativeFeatureFlagsDynamicProvider : public ReactNativeFeatureFlagsDef return value.getBool(); } - return ReactNativeFeatureFlagsDefaults::useNativeViewConfigsInBridgelessMode(); + return ReactNativeFeatureFlagsDefaults:: + useNativeViewConfigsInBridgelessMode(); } bool useNestedScrollViewAndroid() override { @@ -816,7 +849,8 @@ class ReactNativeFeatureFlagsDynamicProvider : public ReactNativeFeatureFlagsDef return value.getBool(); } - return ReactNativeFeatureFlagsDefaults::viewTransitionUseHardwareBitmapAndroid(); + return ReactNativeFeatureFlagsDefaults:: + viewTransitionUseHardwareBitmapAndroid(); } double virtualViewPrerenderRatio() override { diff --git a/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlagsOverridesOSSCanary.h b/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlagsOverridesOSSCanary.h index d6ef238ae241..491ecc41a8b9 100644 --- a/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlagsOverridesOSSCanary.h +++ b/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlagsOverridesOSSCanary.h @@ -23,9 +23,10 @@ namespace facebook::react { -class ReactNativeFeatureFlagsOverridesOSSCanary : public ReactNativeFeatureFlagsOverridesOSSStable { +class ReactNativeFeatureFlagsOverridesOSSCanary + : public ReactNativeFeatureFlagsOverridesOSSStable { public: - ReactNativeFeatureFlagsOverridesOSSCanary() = default; + ReactNativeFeatureFlagsOverridesOSSCanary() = default; bool cxxNativeAnimatedEnabled() override { return true; diff --git a/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlagsOverridesOSSExperimental.h b/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlagsOverridesOSSExperimental.h index 2618b40257bd..9ec4ca0cd0c1 100644 --- a/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlagsOverridesOSSExperimental.h +++ b/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlagsOverridesOSSExperimental.h @@ -23,9 +23,10 @@ namespace facebook::react { -class ReactNativeFeatureFlagsOverridesOSSExperimental : public ReactNativeFeatureFlagsOverridesOSSCanary { +class ReactNativeFeatureFlagsOverridesOSSExperimental + : public ReactNativeFeatureFlagsOverridesOSSCanary { public: - ReactNativeFeatureFlagsOverridesOSSExperimental() = default; + ReactNativeFeatureFlagsOverridesOSSExperimental() = default; bool enableFlexboxAutoMinSizeInStrictMode() override { return true; diff --git a/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlagsOverridesOSSStable.h b/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlagsOverridesOSSStable.h index d60006ec86c3..c4b88058d076 100644 --- a/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlagsOverridesOSSStable.h +++ b/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlagsOverridesOSSStable.h @@ -11,10 +11,10 @@ namespace facebook::react { -class ReactNativeFeatureFlagsOverridesOSSStable : public ReactNativeFeatureFlagsDefaults { +class ReactNativeFeatureFlagsOverridesOSSStable + : public ReactNativeFeatureFlagsDefaults { public: - bool useNativeViewConfigsInBridgelessMode() override - { + bool useNativeViewConfigsInBridgelessMode() 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 c000fc87cd3e..378cb17cd6c8 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/CxxTurboModuleUtils.h +++ b/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/CxxTurboModuleUtils.h @@ -15,7 +15,10 @@ namespace facebook::react { -std::unordered_map(std::shared_ptr jsInvoker)>> & +std::unordered_map< + std::string, + std::function< + std::shared_ptr(std::shared_ptr jsInvoker)>>& globalExportedCxxTurboModuleMap(); /** @@ -26,6 +29,7 @@ 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/TurboModule.h b/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/TurboModule.h index 4626a550c17e..250c97e7c8be 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/TurboModule.h +++ b/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/TurboModule.h @@ -37,7 +37,9 @@ 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 TurboModuleBinding; @@ -53,20 +55,21 @@ 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) { @@ -81,14 +84,20 @@ 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 @@ -102,31 +111,35 @@ 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_); @@ -148,9 +161,12 @@ class JSI_EXPORT TurboModule : public jsi::HostObject { * @deprecated Use TurboModuleProviderFunctionTypeWithRuntime instead. * Remove after React Native 0.84 is released. */ -using TurboModuleProviderFunctionType [[deprecated("Use TurboModuleProviderFunctionTypeWithRuntime instead")]] = - std::function(const std::string &name)>; +using TurboModuleProviderFunctionType + [[deprecated("Use TurboModuleProviderFunctionTypeWithRuntime instead")]] = + std::function(const std::string& name)>; using TurboModuleProviderFunctionTypeWithRuntime = - std::function(jsi::Runtime &runtime, const std::string &name)>; + std::function( + jsi::Runtime& runtime, + 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 ec3198ee9b2f..b8a2248368bc 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/TurboModuleBinding.h +++ b/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/TurboModuleBinding.h @@ -31,18 +31,22 @@ class TurboModuleBinding final { * TurboModuleProviderFunctionTypeWithRuntime instead. * Remove after React Native 0.84 is released. */ - [[deprecated("Use the overload that takes TurboModuleProviderFunctionTypeWithRuntime instead")]] - static void install( - jsi::Runtime &runtime, - TurboModuleProviderFunctionType &&moduleProvider, - TurboModuleProviderFunctionType &&legacyModuleProvider = nullptr, - std::shared_ptr longLivedObjectCollection = nullptr); + [[deprecated( + "Use the overload that takes TurboModuleProviderFunctionTypeWithRuntime instead")]] static void + install( + jsi::Runtime& runtime, + TurboModuleProviderFunctionType&& moduleProvider, + TurboModuleProviderFunctionType&& legacyModuleProvider = nullptr, + std::shared_ptr longLivedObjectCollection = + nullptr); static void install( - jsi::Runtime &runtime, - TurboModuleProviderFunctionTypeWithRuntime &&moduleProvider, - TurboModuleProviderFunctionTypeWithRuntime &&legacyModuleProvider = nullptr, - std::shared_ptr longLivedObjectCollection = nullptr); + jsi::Runtime& runtime, + TurboModuleProviderFunctionTypeWithRuntime&& moduleProvider, + TurboModuleProviderFunctionTypeWithRuntime&& legacyModuleProvider = + nullptr, + std::shared_ptr longLivedObjectCollection = + nullptr); ~TurboModuleBinding(); @@ -50,17 +54,18 @@ class TurboModuleBinding final { friend BridgelessNativeModuleProxy; TurboModuleBinding( - jsi::Runtime &runtime, - TurboModuleProviderFunctionTypeWithRuntime &&moduleProvider, + jsi::Runtime& runtime, + TurboModuleProviderFunctionTypeWithRuntime&& moduleProvider, std::shared_ptr longLivedObjectCollection); /** * 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_; TurboModuleProviderFunctionTypeWithRuntime 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 06c2045741ea..8a7d1c9edba8 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/TurboModulePerfLogger.h +++ b/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/TurboModulePerfLogger.h @@ -11,57 +11,71 @@ #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 @@ -70,10 +84,25 @@ 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 0c436aa13d7d..7968611db993 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/TurboModuleUtils.h +++ b/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/TurboModuleUtils.h @@ -16,16 +16,19 @@ 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 205297aa83b6..c7c912a6ad7b 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/TurboModuleWithJSIBindings.h +++ b/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/TurboModuleWithJSIBindings.h @@ -18,10 +18,12 @@ 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 8dba9d0bb75e..f694cf3d29b0 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 @@ -30,20 +30,22 @@ class JSI_EXPORT JavaInteropTurboModule : public JavaTurboModule { }; JavaInteropTurboModule( - const JavaTurboModule::InitParams ¶ms, - const std::vector &methodDescriptors); + const JavaTurboModule::InitParams& params, + 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 c42f1c7dbac0..0674f617aeb7 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,11 +18,14 @@ 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 { @@ -35,23 +38,23 @@ class JSI_EXPORT JavaTurboModule : public TurboModule { std::shared_ptr nativeMethodCallInvoker; }; - JavaTurboModule(const InitParams ¶ms); + JavaTurboModule(const InitParams& params); 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/tests/TurboModuleTestFixture.h b/packages/react-native/ReactCommon/react/nativemodule/core/tests/TurboModuleTestFixture.h index 7043bb30a139..c98f0595fb51 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/core/tests/TurboModuleTestFixture.h +++ b/packages/react-native/ReactCommon/react/nativemodule/core/tests/TurboModuleTestFixture.h @@ -20,34 +20,35 @@ 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, @@ -56,9 +57,13 @@ class TurboModuleTestFixture : public TurboModuleTestFixtureInternal, public ::t 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(); @@ -66,45 +71,54 @@ class TurboModuleTestFixture : public TurboModuleTestFixtureInternal, public ::t } 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") @@ -114,8 +128,10 @@ class TurboModuleTestFixture : public TurboModuleTestFixtureInternal, public ::t 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(); @@ -123,25 +139,28 @@ class TurboModuleTestFixture : public TurboModuleTestFixtureInternal, public ::t } 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 4896a412cfca..fa78ed5e6162 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/cputime/CPUTime.h +++ b/packages/react-native/ReactCommon/react/nativemodule/cputime/CPUTime.h @@ -26,8 +26,7 @@ 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); @@ -42,42 +41,40 @@ 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 2d4637b34398..c6e60b4f6662 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 315e40e3366d..4b5b905ec731 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 41f986e0b67c..ef674bcef307 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/devtoolsruntimesettings/DevToolsRuntimeSettingsModule.h +++ b/packages/react-native/ReactCommon/react/nativemodule/devtoolsruntimesettings/DevToolsRuntimeSettingsModule.h @@ -12,13 +12,16 @@ namespace facebook::react { class DevToolsRuntimeSettingsModule - : public NativeReactDevToolsRuntimeSettingsModuleCxxSpec { + : public NativeReactDevToolsRuntimeSettingsModuleCxxSpec< + DevToolsRuntimeSettingsModule> { 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 19157a9cd9da..1c6a1c84e7b8 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/dom/NativeDOM.h +++ b/packages/react-native/ReactCommon/react/nativemodule/dom/NativeDOM.h @@ -21,11 +21,14 @@ 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: @@ -33,15 +36,21 @@ 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`). @@ -49,68 +58,97 @@ 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 aff0dbf4fc9f..89c3e2f51283 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/fantomtestspecificmethods/NativeFantomTestSpecificMethods.h +++ b/packages/react-native/ReactCommon/react/nativemodule/fantomtestspecificmethods/NativeFantomTestSpecificMethods.h @@ -13,15 +13,22 @@ namespace facebook::react { struct FantomForcedCloneCommitHook; -class NativeFantomTestSpecificMethods : public NativeFantomTestSpecificMethodsCxxSpec { +class NativeFantomTestSpecificMethods + : public NativeFantomTestSpecificMethodsCxxSpec< + NativeFantomTestSpecificMethods> { 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); - void setRootNodeSize(jsi::Runtime &runtime, int surfaceId, float width, float height); + void setRootNodeSize( + jsi::Runtime& runtime, + int surfaceId, + float width, + float height); 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 66c537f9f4a7..85ca4d5d3526 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/fantomtestspecificmethods/internal/FantomForcedCloneCommitHook.h +++ b/packages/react-native/ReactCommon/react/nativemodule/fantomtestspecificmethods/internal/FantomForcedCloneCommitHook.h @@ -14,14 +14,16 @@ 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/featureflags/NativeReactNativeFeatureFlags.h b/packages/react-native/ReactCommon/react/nativemodule/featureflags/NativeReactNativeFeatureFlags.h index e96aad170678..885344b28b2b 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/featureflags/NativeReactNativeFeatureFlags.h +++ b/packages/react-native/ReactCommon/react/nativemodule/featureflags/NativeReactNativeFeatureFlags.h @@ -28,11 +28,13 @@ namespace facebook::react { class NativeReactNativeFeatureFlags - : public NativeReactNativeFeatureFlagsCxxSpec { + : public NativeReactNativeFeatureFlagsCxxSpec< + NativeReactNativeFeatureFlags> { public: NativeReactNativeFeatureFlags(std::shared_ptr jsInvoker); - static constexpr std::string_view kModuleName = "NativeReactNativeFeatureFlagsCxx"; + static constexpr std::string_view kModuleName = + "NativeReactNativeFeatureFlagsCxx"; bool commonTestFlag(jsi::Runtime& runtime); @@ -100,7 +102,8 @@ class NativeReactNativeFeatureFlags bool enableImperativeFocus(jsi::Runtime& runtime); - bool enableInteropViewManagerClassLookUpOptimizationIOS(jsi::Runtime& runtime); + bool enableInteropViewManagerClassLookUpOptimizationIOS( + jsi::Runtime& runtime); bool enableIntersectionObserverByDefault(jsi::Runtime& runtime); diff --git a/packages/react-native/ReactCommon/react/nativemodule/idlecallbacks/NativeIdleCallbacks.h b/packages/react-native/ReactCommon/react/nativemodule/idlecallbacks/NativeIdleCallbacks.h index 8ac5fc627c29..5fe2c126db53 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/idlecallbacks/NativeIdleCallbacks.h +++ b/packages/react-native/ReactCommon/react/nativemodule/idlecallbacks/NativeIdleCallbacks.h @@ -17,21 +17,25 @@ namespace facebook::react { using CallbackHandle = jsi::Object; -using NativeRequestIdleCallbackOptions = NativeIdleCallbacksRequestIdleCallbackOptions>; +using NativeRequestIdleCallbackOptions = + NativeIdleCallbacksRequestIdleCallbackOptions< + std::optional>; template <> struct Bridging - : NativeIdleCallbacksRequestIdleCallbackOptionsBridging {}; + : NativeIdleCallbacksRequestIdleCallbackOptionsBridging< + NativeRequestIdleCallbackOptions> {}; -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 7399355346be..8ee575e1241a 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/intersectionobserver/NativeIntersectionObserver.h +++ b/packages/react-native/ReactCommon/react/nativemodule/intersectionobserver/NativeIntersectionObserver.h @@ -23,67 +23,78 @@ 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 {}; + : NativeIntersectionObserverNativeIntersectionObserverEntryBridging< + NativeIntersectionObserverEntry> {}; -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 40b6949ea774..44068b8c96ff 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.h b/packages/react-native/ReactCommon/react/nativemodule/mutationobserver/NativeMutationObserver.h index fb590fa9a274..a58a24ac47d7 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/mutationobserver/NativeMutationObserver.h +++ b/packages/react-native/ReactCommon/react/nativemodule/mutationobserver/NativeMutationObserver.h @@ -19,17 +19,19 @@ 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 {}; + : NativeMutationObserverNativeMutationObserverObserveOptionsBridging< + NativeMutationObserverObserveOptions> {}; using NativeMutationRecord = NativeMutationObserverNativeMutationRecord< // mutationObserverId @@ -42,24 +44,31 @@ 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_{}; @@ -70,18 +79,20 @@ class NativeMutationObserver : public NativeMutationObserverCxxSpec 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 03b9f5f5e19a..33f6f785a7f3 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,9 +13,11 @@ 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; @@ -23,8 +25,8 @@ class SampleTurboModuleJSIBindings : public jni::JavaClass 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/viewtransition/NativeViewTransition.h b/packages/react-native/ReactCommon/react/nativemodule/viewtransition/NativeViewTransition.h index 55593f7c2f60..6fc537ac2bec 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/viewtransition/NativeViewTransition.h +++ b/packages/react-native/ReactCommon/react/nativemodule/viewtransition/NativeViewTransition.h @@ -20,18 +20,23 @@ namespace facebook::react { -class NativeViewTransition : public NativeViewTransitionCxxSpec { +class NativeViewTransition + : public NativeViewTransitionCxxSpec { public: explicit NativeViewTransition(std::shared_ptr jsInvoker); - std::optional - getViewTransitionInstance(jsi::Runtime &rt, const std::string &name, const std::string &pseudo); + std::optional getViewTransitionInstance( + jsi::Runtime& rt, + const std::string& name, + const std::string& pseudo); - jsi::Value findPseudoElementShadowNodeByTag(jsi::Runtime &rt, double reactTag); + jsi::Value findPseudoElementShadowNodeByTag( + jsi::Runtime& rt, + double reactTag); - void waitForTransitionAnimation(jsi::Runtime &rt, double animationId); + void waitForTransitionAnimation(jsi::Runtime& rt, double animationId); - void transitionAnimationFinished(jsi::Runtime &rt, double animationId); + void transitionAnimationFinished(jsi::Runtime& rt, double animationId); }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/nativemodule/webperformance/NativePerformance.h b/packages/react-native/ReactCommon/react/nativemodule/webperformance/NativePerformance.h index b2c0a9952e92..d065889205ad 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/webperformance/NativePerformance.h +++ b/packages/react-native/ReactCommon/react/nativemodule/webperformance/NativePerformance.h @@ -23,25 +23,26 @@ 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); } }; @@ -73,11 +74,13 @@ struct NativePerformanceEntry { }; template <> -struct Bridging : NativePerformanceRawPerformanceEntryBridging {}; +struct Bridging + : NativePerformanceRawPerformanceEntryBridging {}; template <> struct Bridging - : NativePerformancePerformanceObserverInitBridging {}; + : NativePerformancePerformanceObserverInitBridging< + NativePerformancePerformanceObserverObserveOptions> {}; class NativePerformance : public NativePerformanceCxxSpec { public: @@ -86,67 +89,84 @@ 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 @@ -161,17 +181,18 @@ 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 841a592c1c6d..2574b46729f0 100644 --- a/packages/react-native/ReactCommon/react/networking/NetworkReporter.h +++ b/packages/react-native/ReactCommon/react/networking/NetworkReporter.h @@ -46,7 +46,7 @@ struct ResourceTimingData { */ class NetworkReporter { public: - static NetworkReporter &getInstance(); + static NetworkReporter& getInstance(); /** * Returns whether network tracking over CDP is currently enabled. @@ -64,10 +64,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) @@ -81,7 +81,9 @@ 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 @@ -93,7 +95,10 @@ 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. @@ -101,7 +106,10 @@ 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 @@ -113,14 +121,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; /** * Report that a WebSocket connection is about to be created. @@ -129,7 +137,9 @@ class NetworkReporter { * reported to CDP only and have no Web Performance counterpart — in a * production (non dev or profiling) build, this method is a no-op. */ - void reportWebSocketCreated(const std::string &requestId, const std::string &url) const; + void reportWebSocketCreated( + const std::string& requestId, + const std::string& url) const; /** * Report that a WebSocket handshake (HTTP upgrade) request is about to be @@ -138,7 +148,9 @@ class NetworkReporter { * Corresponds to `Network.webSocketWillSendHandshakeRequest` in CDP. In a * production (non dev or profiling) build, this method is a no-op. */ - void reportWebSocketWillSendHandshakeRequest(const std::string &requestId, const Headers &headers) const; + void reportWebSocketWillSendHandshakeRequest( + const std::string& requestId, + const Headers& headers) const; /** * Report that a WebSocket handshake response was received and the @@ -148,9 +160,9 @@ class NetworkReporter { * production (non dev or profiling) build, this method is a no-op. */ void reportWebSocketHandshakeResponseReceived( - const std::string &requestId, + const std::string& requestId, uint16_t statusCode, - const Headers &headers) const; + const Headers& headers) const; /** * Report a WebSocket message sent over an open connection. `payloadData` @@ -160,7 +172,10 @@ class NetworkReporter { * Corresponds to `Network.webSocketFrameSent` in CDP. In a production * (non dev or profiling) build, this method is a no-op. */ - void reportWebSocketMessageSent(const std::string &requestId, const std::string &payloadData, bool isBinary) const; + void reportWebSocketMessageSent( + const std::string& requestId, + const std::string& payloadData, + bool isBinary) const; /** * Report a WebSocket message received over an open connection. @@ -170,8 +185,10 @@ class NetworkReporter { * Corresponds to `Network.webSocketFrameReceived` in CDP. In a production * (non dev or profiling) build, this method is a no-op. */ - void reportWebSocketMessageReceived(const std::string &requestId, const std::string &payloadData, bool isBinary) - const; + void reportWebSocketMessageReceived( + const std::string& requestId, + const std::string& payloadData, + bool isBinary) const; /** * Report that a WebSocket connection was closed, whether cleanly or due to @@ -180,7 +197,7 @@ class NetworkReporter { * Corresponds to `Network.webSocketClosed` in CDP. In a production (non dev * or profiling) build, this method is a no-op. */ - void reportWebSocketClosed(const std::string &requestId) const; + void reportWebSocketClosed(const std::string& requestId) const; /** * Store the fetched response body for a text or image network response. @@ -192,12 +209,15 @@ 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 9348cc3e98cf..c6c32751974d 100644 --- a/packages/react-native/ReactCommon/react/performance/cdpmetrics/CdpInteractionTypes.h +++ b/packages/react-native/ReactCommon/react/performance/cdpmetrics/CdpInteractionTypes.h @@ -12,9 +12,10 @@ 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 578b7ed32d19..fe054191bc02 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 PerformanceEntryReporterEventListener { 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/cdpmetrics/CdpPerfIssuesReporter.h b/packages/react-native/ReactCommon/react/performance/cdpmetrics/CdpPerfIssuesReporter.h index 617646eb061f..ce426e504b7c 100644 --- a/packages/react-native/ReactCommon/react/performance/cdpmetrics/CdpPerfIssuesReporter.h +++ b/packages/react-native/ReactCommon/react/performance/cdpmetrics/CdpPerfIssuesReporter.h @@ -26,8 +26,9 @@ class CdpPerfIssuesReporter : public PerformanceEntryReporterEventListener { public: explicit CdpPerfIssuesReporter(RuntimeExecutor runtimeExecutor); - void onMeasureEntry(const PerformanceMeasure &entry, const std::optional &detailProvider) - override; + void onMeasureEntry( + const PerformanceMeasure& entry, + const std::optional& detailProvider) 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 a9c44281c328..aa24bb30221d 100644 --- a/packages/react-native/ReactCommon/react/performance/timeline/CircularBuffer.h +++ b/packages/react-native/ReactCommon/react/performance/timeline/CircularBuffer.h @@ -25,8 +25,7 @@ namespace facebook::react { template class CircularBuffer { public: - explicit CircularBuffer(size_t maxSize) : maxSize_(maxSize) - { + explicit CircularBuffer(size_t maxSize) : maxSize_(maxSize) { entries_.reserve(maxSize_); } @@ -37,8 +36,7 @@ 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); @@ -51,18 +49,15 @@ 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; } @@ -70,13 +65,12 @@ 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; } @@ -91,8 +85,7 @@ class CircularBuffer { /** * Retrieves buffer entries, whether consumed or not */ - std::vector getEntries() const - { + std::vector getEntries() const { std::vector res; getEntries(res); return res; @@ -101,25 +94,27 @@ 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 291bb2ace829..3f87fd1a2418 100644 --- a/packages/react-native/ReactCommon/react/performance/timeline/PerformanceEntry.h +++ b/packages/react-native/ReactCommon/react/performance/timeline/PerformanceEntry.h @@ -38,7 +38,8 @@ struct PerformanceMark : AbstractPerformanceEntry { }; struct PerformanceMeasure : AbstractPerformanceEntry { - static constexpr PerformanceEntryType entryType = PerformanceEntryType::MEASURE; + static constexpr PerformanceEntryType entryType = + PerformanceEntryType::MEASURE; }; struct PerformanceEventTiming : AbstractPerformanceEntry { @@ -53,11 +54,13 @@ 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; @@ -80,10 +83,10 @@ using PerformanceEntry = std::variant< PerformanceResourceTiming>; struct PerformanceEntrySorter { - bool operator()(const PerformanceEntry &lhs, const PerformanceEntry &rhs) const - { + bool operator()(const PerformanceEntry& lhs, const PerformanceEntry& rhs) + const { 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 418b344fbbba..c3ce79d34127 100644 --- a/packages/react-native/ReactCommon/react/performance/timeline/PerformanceEntryBuffer.h +++ b/packages/react-native/ReactCommon/react/performance/timeline/PerformanceEntryBuffer.h @@ -28,11 +28,13 @@ 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 95163b5392ad..cfdaf81ff8d7 100644 --- a/packages/react-native/ReactCommon/react/performance/timeline/PerformanceEntryCircularBuffer.h +++ b/packages/react-native/ReactCommon/react/performance/timeline/PerformanceEntryCircularBuffer.h @@ -17,13 +17,15 @@ 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 5d895d5873e9..b65c6f949f52 100644 --- a/packages/react-native/ReactCommon/react/performance/timeline/PerformanceEntryKeyedBuffer.h +++ b/packages/react-native/ReactCommon/react/performance/timeline/PerformanceEntryKeyedBuffer.h @@ -18,16 +18,18 @@ 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 f9c584ab27cf..2dabf1775654 100644 --- a/packages/react-native/ReactCommon/react/performance/timeline/PerformanceEntryReporter.h +++ b/packages/react-native/ReactCommon/react/performance/timeline/PerformanceEntryReporter.h @@ -28,7 +28,8 @@ 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: @@ -38,56 +39,67 @@ 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; - - 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; + 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 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 addEventListener(PerformanceEntryReporterEventListener *listener); - void removeEventListener(PerformanceEntryReporterEventListener *listener); + void addEventListener(PerformanceEntryReporterEventListener* listener); + void removeEventListener(PerformanceEntryReporterEventListener* 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, - const std::optional &detailProvider = std::nullopt); + const std::optional& detailProvider = + std::nullopt); void reportEvent( - const std::string &name, + const std::string& name, HighResTimeStamp startTime, HighResDuration duration, HighResTimeStamp processingStart, @@ -98,7 +110,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, @@ -106,7 +118,7 @@ class PerformanceEntryReporter { HighResTimeStamp responseStart, HighResTimeStamp responseEnd, int responseStatus, - const std::string &contentType, + const std::string& contentType, int encodedBodySize, int decodedBodySize); @@ -116,17 +128,18 @@ 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 eventListeners_{}; + std::vector eventListeners_{}; - const inline PerformanceEntryBuffer &getBuffer(PerformanceEntryType entryType) const - { + const inline PerformanceEntryBuffer& getBuffer( + PerformanceEntryType entryType) const { switch (entryType) { case PerformanceEntryType::EVENT: return eventBuffer_; @@ -145,8 +158,7 @@ class PerformanceEntryReporter { } } - inline PerformanceEntryBuffer &getBufferRef(PerformanceEntryType entryType) - { + inline PerformanceEntryBuffer& getBufferRef(PerformanceEntryType entryType) { switch (entryType) { case PerformanceEntryType::EVENT: return eventBuffer_; @@ -165,14 +177,17 @@ class PerformanceEntryReporter { } } - void traceMark(const PerformanceMark &entry, UserTimingDetailProvider &&detailProvider) const; - void traceMeasure(const PerformanceMeasure &entry, const std::optional &detailProvider) - const; + void traceMark( + const PerformanceMark& entry, + UserTimingDetailProvider&& detailProvider) const; + void traceMeasure( + const PerformanceMeasure& entry, + const std::optional& 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 e604963e887b..fb094d07037e 100644 --- a/packages/react-native/ReactCommon/react/performance/timeline/PerformanceEntryReporterListeners.h +++ b/packages/react-native/ReactCommon/react/performance/timeline/PerformanceEntryReporterListeners.h @@ -21,12 +21,10 @@ class PerformanceEntryReporterEventListener { virtual ~PerformanceEntryReporterEventListener() = default; virtual void onMeasureEntry( - const PerformanceMeasure & /*entry*/, - const std::optional & /*detailProvider*/) - { - } + const PerformanceMeasure& /*entry*/, + const std::optional& /*detailProvider*/) {} - 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 a8335aea3a96..c4b08d4dcc46 100644 --- a/packages/react-native/ReactCommon/react/performance/timeline/PerformanceObserver.h +++ b/packages/react-native/ReactCommon/react/performance/timeline/PerformanceObserver.h @@ -20,7 +20,8 @@ namespace facebook::react { -using PerformanceObserverEntryTypeFilter = std::unordered_set; +using PerformanceObserverEntryTypeFilter = + std::unordered_set; using PerformanceObserverCallback = std::function; /** @@ -52,7 +53,8 @@ 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; @@ -61,17 +63,15 @@ class PerformanceObserver : public std::enable_shared_from_this create( - PerformanceObserverRegistry ®istry, - PerformanceObserverCallback &&callback) - { - return std::make_shared(PrivateUseCreateMethod(), registry, std::move(callback)); + PerformanceObserverRegistry& registry, + PerformanceObserverCallback&& callback) { + return std::make_shared( + PrivateUseCreateMethod(), registry, std::move(callback)); } ~PerformanceObserver() = default; @@ -79,7 +79,7 @@ class PerformanceObserver : public std::enable_shared_from_this, std::owner_less>> observers_; + std::set< + std::shared_ptr, + std::owner_less>> + observers_; }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/animated/AnimatedModule.h b/packages/react-native/ReactCommon/react/renderer/animated/AnimatedModule.h index 64077e82d4e1..03f694dce314 100644 --- a/packages/react-native/ReactCommon/react/renderer/animated/AnimatedModule.h +++ b/packages/react-native/ReactCommon/react/renderer/animated/AnimatedModule.h @@ -23,7 +23,8 @@ 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{}; @@ -145,60 +146,75 @@ class AnimatedModule : public NativeAnimatedModuleCxxSpec, publi 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 connectAnimatedNodeToShadowNodeFamily(jsi::Runtime &rt, Tag nodeTag, jsi::Object shadowNode); + void connectAnimatedNodeToShadowNodeFamily( + jsi::Runtime& rt, + Tag nodeTag, + jsi::Object shadowNode); - 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_; @@ -206,8 +222,10 @@ class AnimatedModule : public NativeAnimatedModuleCxxSpec, publi std::vector preOperations_; std::vector operations_; - void executeOperation(const Operation &operation, std::weak_ptr nodesManagerWeak); - void installJSIBindingsWithRuntime(jsi::Runtime &runtime) override; + void executeOperation( + const Operation& operation, + std::weak_ptr nodesManagerWeak); + 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 c2f783fe2e4c..ce526ec39c70 100644 --- a/packages/react-native/ReactCommon/react/renderer/animated/EventEmitterListener.h +++ b/packages/react-native/ReactCommon/react/renderer/animated/EventEmitterListener.h @@ -32,11 +32,10 @@ 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; @@ -45,16 +44,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); } @@ -65,7 +64,9 @@ 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 8926e69c1619..c0a073632ec9 100644 --- a/packages/react-native/ReactCommon/react/renderer/animated/MergedValueDispatcher.h +++ b/packages/react-native/ReactCommon/react/renderer/animated/MergedValueDispatcher.h @@ -21,8 +21,9 @@ 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. @@ -32,7 +33,9 @@ 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 @@ -40,7 +43,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.h b/packages/react-native/ReactCommon/react/renderer/animated/NativeAnimatedNodesManager.h index 28933e0f39e4..00e222e76d48 100644 --- a/packages/react-native/ReactCommon/react/renderer/animated/NativeAnimatedNodesManager.h +++ b/packages/react-native/ReactCommon/react/renderer/animated/NativeAnimatedNodesManager.h @@ -44,54 +44,68 @@ class Scheduler; using ValueListenerCallback = std::function; using UiTask = std::function; -using EndResult = NativeAnimatedTurboModuleEndResult, std::optional>; +using EndResult = NativeAnimatedTurboModuleEndResult< + bool, + std::optional, + std::optional>; using AnimationEndCallback = AsyncCallback; template <> -struct Bridging : NativeAnimatedTurboModuleEndResultBridging {}; +struct Bridging + : NativeAnimatedTurboModuleEndResultBridging {}; -class NativeAnimatedNodesManager : public std::enable_shared_from_this { +class NativeAnimatedNodesManager + : public std::enable_shared_from_this { public: - using DirectManipulationCallback = std::function; - using FabricCommitCallback = std::function &)>; - using StartOnRenderCallback = std::function &&, bool isAsync)>; + using DirectManipulationCallback = + std::function; + using FabricCommitCallback = + std::function&)>; + using StartOnRenderCallback = + std::function&&, bool isAsync)>; using StopOnRenderCallback = std::function; - using FrameRateListenerCallback = std::function; - using ResolvePlatformColor = std::function; + using FrameRateListenerCallback = + std::function; + using ResolvePlatformColor = std::function< + void(SurfaceId surfaceId, const RawValue& value, SharedColor& result)>; explicit NativeAnimatedNodesManager( - DirectManipulationCallback &&directManipulationCallback, - FabricCommitCallback &&fabricCommitCallback, - ResolvePlatformColor &&resolvePlatformColor, - StartOnRenderCallback &&startOnRenderCallback = nullptr, - StopOnRenderCallback &&stopOnRenderCallback = nullptr, - FrameRateListenerCallback &&frameRateListenerCallback = nullptr) noexcept; + DirectManipulationCallback&& directManipulationCallback, + FabricCommitCallback&& fabricCommitCallback, + ResolvePlatformColor&& resolvePlatformColor, + StartOnRenderCallback&& startOnRenderCallback = nullptr, + StopOnRenderCallback&& stopOnRenderCallback = nullptr, + FrameRateListenerCallback&& frameRateListenerCallback = nullptr) noexcept; - explicit NativeAnimatedNodesManager(std::shared_ptr animationBackend) noexcept; + explicit NativeAnimatedNodesManager( + std::shared_ptr animationBackend) noexcept; ~NativeAnimatedNodesManager() noexcept; - // Non-copyable and non-movable to prevent accidental copies or moves of this resource-heavy manager - NativeAnimatedNodesManager(const NativeAnimatedNodesManager &) = delete; - NativeAnimatedNodesManager &operator=(const NativeAnimatedNodesManager &) = delete; - NativeAnimatedNodesManager(NativeAnimatedNodesManager &&) = delete; - NativeAnimatedNodesManager &operator=(NativeAnimatedNodesManager &&) = delete; + // Non-copyable and non-movable to prevent accidental copies or moves of this + // resource-heavy manager + NativeAnimatedNodesManager(const NativeAnimatedNodesManager&) = delete; + NativeAnimatedNodesManager& operator=(const NativeAnimatedNodesManager&) = + delete; + NativeAnimatedNodesManager(NativeAnimatedNodesManager&&) = delete; + NativeAnimatedNodesManager& operator=(NativeAnimatedNodesManager&&) = delete; // Whether this instance was constructed to use the shared AnimationBackend. // Latched at construction, so it is immune to later flips of the // process-global useSharedAnimatedBackend() flag. - bool useSharedAnimatedBackend() const noexcept - { + bool useSharedAnimatedBackend() const noexcept { return useSharedAnimatedBackend_; } - template >> - T *getAnimatedNode(Tag tag) const + template < + typename T, + typename = std::enable_if_t>> + 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; } @@ -101,15 +115,17 @@ class NativeAnimatedNodesManager : public std::enable_shared_from_this family) noexcept; + void connectAnimatedNodeToShadowNodeFamily( + Tag propsNodeTag, + std::shared_ptr family) noexcept; void disconnectAnimatedNodes(Tag parentTag, Tag childTag) noexcept; @@ -128,11 +144,15 @@ class NativeAnimatedNodesManager : public std::enable_shared_from_this> &updates, - AnimationMutations &mutations, - AnimatedPropsBuilder &propsBuilder, + std::unordered_map< + Tag, + std::pair>& updates, + AnimationMutations& mutations, + AnimatedPropsBuilder& propsBuilder, bool hasLayoutUpdates = false); - AnimationMutations onAnimationFrameForBackend(AnimatedPropsBuilder &propsBuilder, AnimationTimestamp timestamp); + AnimationMutations onAnimationFrameForBackend( + AnimatedPropsBuilder& propsBuilder, + AnimationTimestamp timestamp); AnimationMutations pullAnimationMutations(AnimationTimestamp timestamp); #pragma mark - Drivers @@ -143,26 +163,35 @@ class NativeAnimatedNodesManager : public std::enable_shared_from_this 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, ShadowNodeFamily::Weak shadowNodeFamily = {}) noexcept; @@ -181,8 +210,7 @@ class NativeAnimatedNodesManager : public std::enable_shared_from_this lock(uiTasksMutex_); operations_.push_back(std::move(task)); @@ -198,7 +226,8 @@ class NativeAnimatedNodesManager : public std::enable_shared_from_this &finishedAnimationValueNodes = {}) noexcept; + void updateNodes( + const std::set& finishedAnimationValueNodes = {}) noexcept; folly::dynamic getManagedProps(Tag tag) const noexcept; @@ -210,7 +239,10 @@ class NativeAnimatedNodesManager : public std::enable_shared_from_this 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_; // Latched per-instance copy of which backend this manager uses, set from the - // constructor that ran (true for the shared-AnimationBackend ctor). Reads stay - // stable even when the global useSharedAnimatedBackend() flag is re-overridden - // on another RN runtime. + // constructor that ran (true for the shared-AnimationBackend ctor). Reads + // stay stable even when the global useSharedAnimatedBackend() flag is + // re-overridden on another RN runtime. const bool useSharedAnimatedBackend_; - 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_; @@ -280,8 +318,10 @@ class NativeAnimatedNodesManager : public std::enable_shared_from_this updateViewProps_{}; std::unordered_map updateViewPropsDirect_{}; - std::unordered_map> updateViewPropsForBackend_{}; - std::unordered_map> updateViewPropsDirectForBackend_{}; + std::unordered_map> + updateViewPropsForBackend_{}; + std::unordered_map> + updateViewPropsDirectForBackend_{}; std::unordered_set shouldRequestAsyncFlush_{}; /* * Sometimes a view is not longer connected to a PropsAnimatedNode, but diff --git a/packages/react-native/ReactCommon/react/renderer/animated/NativeAnimatedNodesManagerProvider.h b/packages/react-native/ReactCommon/react/renderer/animated/NativeAnimatedNodesManagerProvider.h index 9b1164d3278f..513d1964255c 100644 --- a/packages/react-native/ReactCommon/react/renderer/animated/NativeAnimatedNodesManagerProvider.h +++ b/packages/react-native/ReactCommon/react/renderer/animated/NativeAnimatedNodesManagerProvider.h @@ -18,16 +18,20 @@ class AnimatedMountingOverrideDelegate; class NativeAnimatedNodesManagerProvider { public: NativeAnimatedNodesManagerProvider( - NativeAnimatedNodesManager::StartOnRenderCallback startOnRenderCallback = nullptr, - NativeAnimatedNodesManager::StopOnRenderCallback stopOnRenderCallback = nullptr, - NativeAnimatedNodesManager::FrameRateListenerCallback frameRateListenerCallback = nullptr); + NativeAnimatedNodesManager::StartOnRenderCallback startOnRenderCallback = + nullptr, + NativeAnimatedNodesManager::StopOnRenderCallback stopOnRenderCallback = + nullptr, + NativeAnimatedNodesManager::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(); @@ -38,18 +42,22 @@ class NativeAnimatedNodesManagerProvider { std::shared_ptr eventEmitterListener_; std::shared_ptr nativeAnimatedDelegate_; - std::shared_ptr animatedMountingOverrideDelegate_; + std::shared_ptr + animatedMountingOverrideDelegate_; NativeAnimatedNodesManager::StartOnRenderCallback startOnRenderCallback_; NativeAnimatedNodesManager::StopOnRenderCallback stopOnRenderCallback_; - NativeAnimatedNodesManager::FrameRateListenerCallback frameRateListenerCallback_; + NativeAnimatedNodesManager::FrameRateListenerCallback + frameRateListenerCallback_; std::unique_ptr mergedValueDispatcher_; }; -class UIManagerNativeAnimatedDelegateImpl : public UIManagerNativeAnimatedDelegate { +class UIManagerNativeAnimatedDelegateImpl + : public UIManagerNativeAnimatedDelegate { public: - explicit UIManagerNativeAnimatedDelegateImpl(std::weak_ptr manager); + explicit UIManagerNativeAnimatedDelegateImpl( + std::weak_ptr manager); void runAnimationFrame() override; 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 528ac782b70e..5d810ae2b21b 100644 --- a/packages/react-native/ReactCommon/react/renderer/animated/drivers/AnimationDriver.h +++ b/packages/react-native/ReactCommon/react/renderer/animated/drivers/AnimationDriver.h @@ -29,23 +29,20 @@ 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_; } @@ -54,22 +51,21 @@ 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); } @@ -77,7 +73,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 4fb5b97bd66b..f99a74857c3d 100644 --- a/packages/react-native/ReactCommon/react/renderer/animated/drivers/AnimationDriverUtils.h +++ b/packages/react-native/ReactCommon/react/renderer/animated/drivers/AnimationDriverUtils.h @@ -30,8 +30,7 @@ inline double interpolate( double outputMin, double outputMax, std::string_view extrapolateLeft, - std::string_view extrapolateRight) -{ + std::string_view extrapolateRight) { auto result = inputValue; // Extrapolate @@ -58,7 +57,8 @@ 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 8991b22664e6..df94855f5879 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 6efd986dd666..abcde6210002 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 ce62c9c5fb03..87fe1e056a5e 100644 --- a/packages/react-native/ReactCommon/react/renderer/animated/drivers/SpringAnimationDriver.h +++ b/packages/react-native/ReactCommon/react/renderer/animated/drivers/SpringAnimationDriver.h @@ -22,14 +22,15 @@ 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 79cb51a1fb06..7e464fd99778 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 @@ -21,14 +21,15 @@ 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_; } @@ -42,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; } }; @@ -53,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.h b/packages/react-native/ReactCommon/react/renderer/animated/internal/AnimatedMountingOverrideDelegate.h index c32c3890583a..9dd5a669b9e4 100644 --- a/packages/react-native/ReactCommon/react/renderer/animated/internal/AnimatedMountingOverrideDelegate.h +++ b/packages/react-native/ReactCommon/react/renderer/animated/internal/AnimatedMountingOverrideDelegate.h @@ -19,20 +19,22 @@ 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 deb94193261c..b5604c103bef 100644 --- a/packages/react-native/ReactCommon/react/renderer/animated/internal/NativeAnimatedAllowlist.h +++ b/packages/react-native/ReactCommon/react/renderer/animated/internal/NativeAnimatedAllowlist.h @@ -12,8 +12,7 @@ namespace facebook::react { -inline const std::unordered_set &getDirectManipulationAllowlist() -{ +inline const 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 5167c1c8372e..101941e4a329 100644 --- a/packages/react-native/ReactCommon/react/renderer/animated/nodes/AdditionAnimatedNode.h +++ b/packages/react-native/ReactCommon/react/renderer/animated/nodes/AdditionAnimatedNode.h @@ -17,10 +17,11 @@ 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 fc7e3842f535..d26b9fae526f 100644 --- a/packages/react-native/ReactCommon/react/renderer/animated/nodes/AnimatedNode.h +++ b/packages/react-native/ReactCommon/react/renderer/animated/nodes/AnimatedNode.h @@ -44,19 +44,18 @@ 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_; } @@ -64,25 +63,23 @@ 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 @@ -91,7 +88,8 @@ 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; @@ -99,9 +97,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 eb04ad931b28..4a9e8c596528 100644 --- a/packages/react-native/ReactCommon/react/renderer/animated/nodes/ColorAnimatedNode.h +++ b/packages/react-native/ReactCommon/react/renderer/animated/nodes/ColorAnimatedNode.h @@ -18,7 +18,10 @@ 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 3be413383a33..ecf15ba25e05 100644 --- a/packages/react-native/ReactCommon/react/renderer/animated/nodes/DiffClampAnimatedNode.h +++ b/packages/react-native/ReactCommon/react/renderer/animated/nodes/DiffClampAnimatedNode.h @@ -17,7 +17,10 @@ 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 9227738db4c5..63bf599bebbf 100644 --- a/packages/react-native/ReactCommon/react/renderer/animated/nodes/DivisionAnimatedNode.h +++ b/packages/react-native/ReactCommon/react/renderer/animated/nodes/DivisionAnimatedNode.h @@ -17,10 +17,11 @@ 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 a6b29a6fd745..36d5cb375d29 100644 --- a/packages/react-native/ReactCommon/react/renderer/animated/nodes/InterpolationAnimatedNode.h +++ b/packages/react-native/ReactCommon/react/renderer/animated/nodes/InterpolationAnimatedNode.h @@ -20,7 +20,10 @@ 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; @@ -31,10 +34,10 @@ class InterpolationAnimatedNode final : public ValueAnimatedNode { double interpolateColor(double value); double interpolatePlatformColor(double value); - // Applies the optional easing stops to a segment's normalized ratio via binary - // search + linear interpolation. Returns the ratio unchanged when no easing is - // configured or when the ratio falls outside [0, 1] (so extrapolation behavior - // is preserved). + // Applies the optional easing stops to a segment's normalized ratio via + // binary search + linear interpolation. Returns the ratio unchanged when no + // easing is configured or when the ratio falls outside [0, 1] (so + // extrapolation behavior is preserved). double easeRatio(double ratio) const; SurfaceId resolveConnectedRootTag() const; @@ -43,8 +46,8 @@ class InterpolationAnimatedNode final : public ValueAnimatedNode { std::vector defaultOutputRanges_; std::vector colorOutputRanges_; std::vector platformColorOutputRanges_; - // Non-uniform easing stops (RDP-simplified, CSS `linear()`-style) baked from a - // JS interpolation `easing` function. `easingStopInputs_` are the stop + // Non-uniform easing stops (RDP-simplified, CSS `linear()`-style) baked from + // a JS interpolation `easing` function. `easingStopInputs_` are the stop // positions in [0, 1] (sorted), `easingStopOutputs_` the eased values. Both // empty when the interpolation has no custom easing. std::vector easingStopInputs_; 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 9d0a30c9b22e..78326347fe8a 100644 --- a/packages/react-native/ReactCommon/react/renderer/animated/nodes/ModulusAnimatedNode.h +++ b/packages/react-native/ReactCommon/react/renderer/animated/nodes/ModulusAnimatedNode.h @@ -17,7 +17,10 @@ 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 e402b3069eb0..e21e40aa5923 100644 --- a/packages/react-native/ReactCommon/react/renderer/animated/nodes/MultiplicationAnimatedNode.h +++ b/packages/react-native/ReactCommon/react/renderer/animated/nodes/MultiplicationAnimatedNode.h @@ -17,10 +17,11 @@ 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 eaaceaf10645..4be4c7596d9b 100644 --- a/packages/react-native/ReactCommon/react/renderer/animated/nodes/ObjectAnimatedNode.h +++ b/packages/react-native/ReactCommon/react/renderer/animated/nodes/ObjectAnimatedNode.h @@ -19,15 +19,20 @@ 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 f3bf6cd6b4f4..d80d4c67e6be 100644 --- a/packages/react-native/ReactCommon/react/renderer/animated/nodes/PropsAnimatedNode.h +++ b/packages/react-native/ReactCommon/react/renderer/animated/nodes/PropsAnimatedNode.h @@ -20,7 +20,10 @@ 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); // Only called when `useSharedAnimatedBackend`==true void connectToShadowNodeFamily(ShadowNodeFamily::Weak shadowNodeFamily); @@ -30,18 +33,15 @@ class PropsAnimatedNode final : public AnimatedNode { void disconnectFromView(Tag viewTag); void restoreDefaultValues(); - Tag connectedViewTag() const - { + Tag connectedViewTag() const { return connectedViewTag_; } - SurfaceId connectedRootTag() const - { + SurfaceId connectedRootTag() const { return connectedRootTag_; } - 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 dc5a03b03dd1..6ef2d991237f 100644 --- a/packages/react-native/ReactCommon/react/renderer/animated/nodes/RoundAnimatedNode.h +++ b/packages/react-native/ReactCommon/react/renderer/animated/nodes/RoundAnimatedNode.h @@ -23,7 +23,10 @@ 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 5e8031e0556d..20883209f941 100644 --- a/packages/react-native/ReactCommon/react/renderer/animated/nodes/StyleAnimatedNode.h +++ b/packages/react-native/ReactCommon/react/renderer/animated/nodes/StyleAnimatedNode.h @@ -18,11 +18,13 @@ 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 04e418b88f46..6a6159035ad7 100644 --- a/packages/react-native/ReactCommon/react/renderer/animated/nodes/SubtractionAnimatedNode.h +++ b/packages/react-native/ReactCommon/react/renderer/animated/nodes/SubtractionAnimatedNode.h @@ -18,10 +18,11 @@ 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 d147ced26daf..e60a3bbed6c5 100644 --- a/packages/react-native/ReactCommon/react/renderer/animated/nodes/TrackingAnimatedNode.h +++ b/packages/react-native/ReactCommon/react/renderer/animated/nodes/TrackingAnimatedNode.h @@ -17,7 +17,10 @@ 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 7cc6d1537ab6..dc587df1d05b 100644 --- a/packages/react-native/ReactCommon/react/renderer/animated/nodes/TransformAnimatedNode.h +++ b/packages/react-native/ReactCommon/react/renderer/animated/nodes/TransformAnimatedNode.h @@ -24,8 +24,11 @@ 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 e97a2ea5d260..930bdf701745 100644 --- a/packages/react-native/ReactCommon/react/renderer/animated/nodes/ValueAnimatedNode.h +++ b/packages/react-native/ReactCommon/react/renderer/animated/nodes/ValueAnimatedNode.h @@ -21,7 +21,10 @@ 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; @@ -29,10 +32,9 @@ 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_; } @@ -49,7 +51,10 @@ 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 47bcc9994956..20abf06e2594 100644 --- a/packages/react-native/ReactCommon/react/renderer/animated/tests/AnimationTestsBase.h +++ b/packages/react-native/ReactCommon/react/renderer/animated/tests/AnimationTestsBase.h @@ -22,15 +22,14 @@ 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; @@ -40,13 +39,11 @@ 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 db7e00f78c9a..6c7379ad8aa7 100644 --- a/packages/react-native/ReactCommon/react/renderer/animationbackend/AnimatedProps.h +++ b/packages/react-native/ReactCommon/react/renderer/animationbackend/AnimatedProps.h @@ -77,19 +77,18 @@ 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; } template -T get(const AnimatedPropBase &animatedProp) -{ - return static_cast &>(animatedProp).value; +T get(const AnimatedPropBase& animatedProp) { + return static_cast&>(animatedProp).value; } struct AnimatedProps { @@ -97,19 +96,22 @@ struct AnimatedProps { std::unique_ptr rawProps; }; -inline void cloneProp(BaseViewProps &viewProps, const AnimatedPropBase &animatedProp) -{ +inline void cloneProp( + BaseViewProps& viewProps, + const AnimatedPropBase& animatedProp) { switch (animatedProp.propName) { case OPACITY: viewProps.opacity = get(animatedProp); break; case WIDTH: - viewProps.yogaStyle.setDimension(yoga::Dimension::Width, get(animatedProp)); + viewProps.yogaStyle.setDimension( + yoga::Dimension::Width, get(animatedProp)); break; case HEIGHT: - viewProps.yogaStyle.setDimension(yoga::Dimension::Height, get(animatedProp)); + viewProps.yogaStyle.setDimension( + yoga::Dimension::Height, get(animatedProp)); break; case BORDER_RADII: @@ -117,33 +119,43 @@ inline void cloneProp(BaseViewProps &viewProps, const AnimatedPropBase &animated break; case BORDER_WIDTH: { - const auto &borderWidths = get>(animatedProp); + const auto& borderWidths = + get>(animatedProp); if (borderWidths.left.has_value()) { - viewProps.yogaStyle.setBorder(yoga::Edge::Left, borderWidths.left.value()); + viewProps.yogaStyle.setBorder( + yoga::Edge::Left, borderWidths.left.value()); } if (borderWidths.top.has_value()) { - viewProps.yogaStyle.setBorder(yoga::Edge::Top, borderWidths.top.value()); + viewProps.yogaStyle.setBorder( + yoga::Edge::Top, borderWidths.top.value()); } if (borderWidths.right.has_value()) { - viewProps.yogaStyle.setBorder(yoga::Edge::Right, borderWidths.right.value()); + viewProps.yogaStyle.setBorder( + yoga::Edge::Right, borderWidths.right.value()); } if (borderWidths.bottom.has_value()) { - viewProps.yogaStyle.setBorder(yoga::Edge::Bottom, borderWidths.bottom.value()); + viewProps.yogaStyle.setBorder( + yoga::Edge::Bottom, borderWidths.bottom.value()); } if (borderWidths.start.has_value()) { - viewProps.yogaStyle.setBorder(yoga::Edge::Start, borderWidths.start.value()); + viewProps.yogaStyle.setBorder( + yoga::Edge::Start, borderWidths.start.value()); } if (borderWidths.end.has_value()) { - viewProps.yogaStyle.setBorder(yoga::Edge::End, borderWidths.end.value()); + viewProps.yogaStyle.setBorder( + yoga::Edge::End, borderWidths.end.value()); } if (borderWidths.horizontal.has_value()) { - viewProps.yogaStyle.setBorder(yoga::Edge::Horizontal, borderWidths.horizontal.value()); + viewProps.yogaStyle.setBorder( + yoga::Edge::Horizontal, borderWidths.horizontal.value()); } if (borderWidths.vertical.has_value()) { - viewProps.yogaStyle.setBorder(yoga::Edge::Vertical, borderWidths.vertical.value()); + viewProps.yogaStyle.setBorder( + yoga::Edge::Vertical, borderWidths.vertical.value()); } if (borderWidths.all.has_value()) { - viewProps.yogaStyle.setBorder(yoga::Edge::All, borderWidths.all.value()); + viewProps.yogaStyle.setBorder( + yoga::Edge::All, borderWidths.all.value()); } break; } @@ -153,7 +165,8 @@ inline void cloneProp(BaseViewProps &viewProps, const AnimatedPropBase &animated break; case MARGIN: { - const auto &margins = get>(animatedProp); + const auto& margins = + get>(animatedProp); if (margins.left.has_value()) { viewProps.yogaStyle.setMargin(yoga::Edge::Left, margins.left.value()); } @@ -164,7 +177,8 @@ inline void cloneProp(BaseViewProps &viewProps, const AnimatedPropBase &animated viewProps.yogaStyle.setMargin(yoga::Edge::Right, margins.right.value()); } if (margins.bottom.has_value()) { - viewProps.yogaStyle.setMargin(yoga::Edge::Bottom, margins.bottom.value()); + viewProps.yogaStyle.setMargin( + yoga::Edge::Bottom, margins.bottom.value()); } if (margins.start.has_value()) { viewProps.yogaStyle.setMargin(yoga::Edge::Start, margins.start.value()); @@ -173,10 +187,12 @@ inline void cloneProp(BaseViewProps &viewProps, const AnimatedPropBase &animated viewProps.yogaStyle.setMargin(yoga::Edge::End, margins.end.value()); } if (margins.horizontal.has_value()) { - viewProps.yogaStyle.setMargin(yoga::Edge::Horizontal, margins.horizontal.value()); + viewProps.yogaStyle.setMargin( + yoga::Edge::Horizontal, margins.horizontal.value()); } if (margins.vertical.has_value()) { - viewProps.yogaStyle.setMargin(yoga::Edge::Vertical, margins.vertical.value()); + viewProps.yogaStyle.setMargin( + yoga::Edge::Vertical, margins.vertical.value()); } if (margins.all.has_value()) { viewProps.yogaStyle.setMargin(yoga::Edge::All, margins.all.value()); @@ -185,7 +201,8 @@ inline void cloneProp(BaseViewProps &viewProps, const AnimatedPropBase &animated } case PADDING: { - const auto &paddings = get>(animatedProp); + const auto& paddings = + get>(animatedProp); if (paddings.left.has_value()) { viewProps.yogaStyle.setPadding(yoga::Edge::Left, paddings.left.value()); } @@ -193,22 +210,27 @@ inline void cloneProp(BaseViewProps &viewProps, const AnimatedPropBase &animated viewProps.yogaStyle.setPadding(yoga::Edge::Top, paddings.top.value()); } if (paddings.right.has_value()) { - viewProps.yogaStyle.setPadding(yoga::Edge::Right, paddings.right.value()); + viewProps.yogaStyle.setPadding( + yoga::Edge::Right, paddings.right.value()); } if (paddings.bottom.has_value()) { - viewProps.yogaStyle.setPadding(yoga::Edge::Bottom, paddings.bottom.value()); + viewProps.yogaStyle.setPadding( + yoga::Edge::Bottom, paddings.bottom.value()); } if (paddings.start.has_value()) { - viewProps.yogaStyle.setPadding(yoga::Edge::Start, paddings.start.value()); + viewProps.yogaStyle.setPadding( + yoga::Edge::Start, paddings.start.value()); } if (paddings.end.has_value()) { viewProps.yogaStyle.setPadding(yoga::Edge::End, paddings.end.value()); } if (paddings.horizontal.has_value()) { - viewProps.yogaStyle.setPadding(yoga::Edge::Horizontal, paddings.horizontal.value()); + viewProps.yogaStyle.setPadding( + yoga::Edge::Horizontal, paddings.horizontal.value()); } if (paddings.vertical.has_value()) { - viewProps.yogaStyle.setPadding(yoga::Edge::Vertical, paddings.vertical.value()); + viewProps.yogaStyle.setPadding( + yoga::Edge::Vertical, paddings.vertical.value()); } if (paddings.all.has_value()) { viewProps.yogaStyle.setPadding(yoga::Edge::All, paddings.all.value()); @@ -217,30 +239,37 @@ inline void cloneProp(BaseViewProps &viewProps, const AnimatedPropBase &animated } case POSITION: { - const auto &positions = get>(animatedProp); + const auto& positions = + get>(animatedProp); if (positions.left.has_value()) { - viewProps.yogaStyle.setPosition(yoga::Edge::Left, positions.left.value()); + viewProps.yogaStyle.setPosition( + yoga::Edge::Left, positions.left.value()); } if (positions.top.has_value()) { viewProps.yogaStyle.setPosition(yoga::Edge::Top, positions.top.value()); } if (positions.right.has_value()) { - viewProps.yogaStyle.setPosition(yoga::Edge::Right, positions.right.value()); + viewProps.yogaStyle.setPosition( + yoga::Edge::Right, positions.right.value()); } if (positions.bottom.has_value()) { - viewProps.yogaStyle.setPosition(yoga::Edge::Bottom, positions.bottom.value()); + viewProps.yogaStyle.setPosition( + yoga::Edge::Bottom, positions.bottom.value()); } if (positions.start.has_value()) { - viewProps.yogaStyle.setPosition(yoga::Edge::Start, positions.start.value()); + viewProps.yogaStyle.setPosition( + yoga::Edge::Start, positions.start.value()); } if (positions.end.has_value()) { viewProps.yogaStyle.setPosition(yoga::Edge::End, positions.end.value()); } if (positions.horizontal.has_value()) { - viewProps.yogaStyle.setPosition(yoga::Edge::Horizontal, positions.horizontal.value()); + viewProps.yogaStyle.setPosition( + yoga::Edge::Horizontal, positions.horizontal.value()); } if (positions.vertical.has_value()) { - viewProps.yogaStyle.setPosition(yoga::Edge::Vertical, positions.vertical.value()); + viewProps.yogaStyle.setPosition( + yoga::Edge::Vertical, positions.vertical.value()); } if (positions.all.has_value()) { viewProps.yogaStyle.setPosition(yoga::Edge::All, positions.all.value()); @@ -313,7 +342,8 @@ inline void cloneProp(BaseViewProps &viewProps, const AnimatedPropBase &animated break; case ASPECT_RATIO: - viewProps.yogaStyle.setAspectRatio(get(animatedProp)); + viewProps.yogaStyle.setAspectRatio( + get(animatedProp)); break; case BOX_SIZING: @@ -325,19 +355,23 @@ inline void cloneProp(BaseViewProps &viewProps, const AnimatedPropBase &animated break; case FLEX_BASIS: - viewProps.yogaStyle.setFlexBasis(get(animatedProp)); + viewProps.yogaStyle.setFlexBasis( + get(animatedProp)); break; case FLEX_DIRECTION: - viewProps.yogaStyle.setFlexDirection(get(animatedProp)); + viewProps.yogaStyle.setFlexDirection( + get(animatedProp)); break; case ROW_GAP: - viewProps.yogaStyle.setGap(yoga::Gutter::Row, get(animatedProp)); + viewProps.yogaStyle.setGap( + yoga::Gutter::Row, get(animatedProp)); break; case COLUMN_GAP: - viewProps.yogaStyle.setGap(yoga::Gutter::Column, get(animatedProp)); + viewProps.yogaStyle.setGap( + yoga::Gutter::Column, get(animatedProp)); break; case FLEX_GROW: @@ -357,19 +391,23 @@ inline void cloneProp(BaseViewProps &viewProps, const AnimatedPropBase &animated break; case MAX_HEIGHT: - viewProps.yogaStyle.setMaxDimension(yoga::Dimension::Height, get(animatedProp)); + viewProps.yogaStyle.setMaxDimension( + yoga::Dimension::Height, get(animatedProp)); break; case MAX_WIDTH: - viewProps.yogaStyle.setMaxDimension(yoga::Dimension::Width, get(animatedProp)); + viewProps.yogaStyle.setMaxDimension( + yoga::Dimension::Width, get(animatedProp)); break; case MIN_HEIGHT: - viewProps.yogaStyle.setMinDimension(yoga::Dimension::Height, get(animatedProp)); + viewProps.yogaStyle.setMinDimension( + yoga::Dimension::Height, get(animatedProp)); break; case MIN_WIDTH: - viewProps.yogaStyle.setMinDimension(yoga::Dimension::Width, get(animatedProp)); + viewProps.yogaStyle.setMinDimension( + yoga::Dimension::Width, get(animatedProp)); break; case STYLE_OVERFLOW: @@ -377,7 +415,8 @@ inline void cloneProp(BaseViewProps &viewProps, const AnimatedPropBase &animated break; case POSITION_TYPE: - viewProps.yogaStyle.setPositionType(get(animatedProp)); + viewProps.yogaStyle.setPositionType( + get(animatedProp)); break; case Z_INDEX: diff --git a/packages/react-native/ReactCommon/react/renderer/animationbackend/AnimatedPropsBuilder.h b/packages/react-native/ReactCommon/react/renderer/animationbackend/AnimatedPropsBuilder.h index b3608ebd6926..f07f8a338720 100644 --- a/packages/react-native/ReactCommon/react/renderer/animationbackend/AnimatedPropsBuilder.h +++ b/packages/react-native/ReactCommon/react/renderer/animationbackend/AnimatedPropsBuilder.h @@ -16,224 +16,221 @@ 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 setBorderWidth(CascadedRectangleEdges &value) - { - props.push_back(std::make_unique>>(BORDER_WIDTH, value)); + void setBorderWidth(CascadedRectangleEdges& value) { + props.push_back(std::make_unique< + AnimatedProp>>( + BORDER_WIDTH, value)); } - void setBorderColor(CascadedBorderColors &value) - { - props.push_back(std::make_unique>(BORDER_COLOR, value)); + void setBorderColor(CascadedBorderColors& value) { + props.push_back(std::make_unique>( + BORDER_COLOR, value)); } - void setMargin(CascadedRectangleEdges &value) - { - props.push_back(std::make_unique>>(MARGIN, value)); + void setMargin(CascadedRectangleEdges& value) { + props.push_back(std::make_unique< + AnimatedProp>>( + MARGIN, value)); } - void setPadding(CascadedRectangleEdges &value) - { - props.push_back(std::make_unique>>(PADDING, value)); + void setPadding(CascadedRectangleEdges& value) { + props.push_back(std::make_unique< + AnimatedProp>>( + PADDING, value)); } - void setPosition(CascadedRectangleEdges &value) - { - props.push_back(std::make_unique>>(POSITION, value)); + void setPosition(CascadedRectangleEdges& value) { + props.push_back(std::make_unique< + AnimatedProp>>( + POSITION, value)); } - void setFlex(yoga::FloatOptional value) - { - props.push_back(std::make_unique>(FLEX, value)); + void setFlex(yoga::FloatOptional value) { + props.push_back( + std::make_unique>(FLEX, value)); } - void setTransform(const Transform &t) - { + void setTransform(const Transform& t) { props.push_back(std::make_unique>(TRANSFORM, t)); } - void setTransformOrigin(const TransformOrigin &value) - { - props.push_back(std::make_unique>(TRANSFORM_ORIGIN, value)); + void setTransformOrigin(const TransformOrigin& value) { + props.push_back(std::make_unique>( + TRANSFORM_ORIGIN, value)); } - void setBackgroundColor(SharedColor value) - { - props.push_back(std::make_unique>(BACKGROUND_COLOR, value)); + void setBackgroundColor(SharedColor value) { + props.push_back( + std::make_unique>(BACKGROUND_COLOR, value)); } - void setShadowColor(SharedColor value) - { - props.push_back(std::make_unique>(SHADOW_COLOR, value)); + void setShadowColor(SharedColor value) { + props.push_back( + std::make_unique>(SHADOW_COLOR, value)); } - void setShadowOpacity(Float value) - { - props.push_back(std::make_unique>(SHADOW_OPACITY, value)); + void setShadowOpacity(Float value) { + props.push_back( + std::make_unique>(SHADOW_OPACITY, value)); } - void setShadowRadius(Float value) - { - props.push_back(std::make_unique>(SHADOW_RADIUS, value)); + void setShadowRadius(Float value) { + props.push_back( + std::make_unique>(SHADOW_RADIUS, value)); } - void setShadowOffset(Size value) - { + void setShadowOffset(Size value) { props.push_back(std::make_unique>(SHADOW_OFFSET, value)); } - void setFilter(const std::vector &value) - { - props.push_back(std::make_unique>>(FILTER, std::move(value))); + void setFilter(const std::vector& value) { + props.push_back(std::make_unique>>( + FILTER, std::move(value))); } - void setOutlineColor(SharedColor value) - { - props.push_back(std::make_unique>(OUTLINE_COLOR, value)); + void setOutlineColor(SharedColor value) { + props.push_back( + std::make_unique>(OUTLINE_COLOR, value)); } - void setOutlineOffset(Float value) - { - props.push_back(std::make_unique>(OUTLINE_OFFSET, value)); + void setOutlineOffset(Float value) { + props.push_back( + std::make_unique>(OUTLINE_OFFSET, value)); } - void setOutlineStyle(OutlineStyle value) - { - props.push_back(std::make_unique>(OUTLINE_STYLE, value)); + void setOutlineStyle(OutlineStyle value) { + props.push_back( + std::make_unique>(OUTLINE_STYLE, value)); } - void setOutlineWidth(Float value) - { - props.push_back(std::make_unique>(OUTLINE_WIDTH, value)); + void setOutlineWidth(Float value) { + props.push_back( + std::make_unique>(OUTLINE_WIDTH, value)); } - void setAlignContent(yoga::Align value) - { - props.push_back(std::make_unique>(ALIGN_CONTENT, value)); + void setAlignContent(yoga::Align value) { + props.push_back( + std::make_unique>(ALIGN_CONTENT, value)); } - void setAlignItems(yoga::Align value) - { - props.push_back(std::make_unique>(ALIGN_ITEMS, value)); + void setAlignItems(yoga::Align value) { + props.push_back( + std::make_unique>(ALIGN_ITEMS, value)); } - void setAlignSelf(yoga::Align value) - { - props.push_back(std::make_unique>(ALIGN_SELF, value)); + void setAlignSelf(yoga::Align value) { + props.push_back( + std::make_unique>(ALIGN_SELF, value)); } - void setAspectRatio(yoga::FloatOptional value) - { - props.push_back(std::make_unique>(ASPECT_RATIO, value)); + void setAspectRatio(yoga::FloatOptional value) { + props.push_back(std::make_unique>( + ASPECT_RATIO, value)); } - void setBoxSizing(yoga::BoxSizing value) - { - props.push_back(std::make_unique>(BOX_SIZING, value)); + void setBoxSizing(yoga::BoxSizing value) { + props.push_back( + std::make_unique>(BOX_SIZING, value)); } - void setDisplay(yoga::Display value) - { - props.push_back(std::make_unique>(DISPLAY, value)); + void setDisplay(yoga::Display value) { + props.push_back( + std::make_unique>(DISPLAY, value)); } - void setFlexBasis(yoga::Style::SizeLength value) - { - props.push_back(std::make_unique>(FLEX_BASIS, value)); + void setFlexBasis(yoga::Style::SizeLength value) { + props.push_back(std::make_unique>( + FLEX_BASIS, value)); } - void setFlexDirection(yoga::FlexDirection value) - { - props.push_back(std::make_unique>(FLEX_DIRECTION, value)); + void setFlexDirection(yoga::FlexDirection value) { + props.push_back(std::make_unique>( + FLEX_DIRECTION, value)); } - void setRowGap(yoga::Style::Length value) - { - props.push_back(std::make_unique>(ROW_GAP, value)); + void setRowGap(yoga::Style::Length value) { + props.push_back( + std::make_unique>(ROW_GAP, value)); } - void setColumnGap(yoga::Style::Length value) - { - props.push_back(std::make_unique>(COLUMN_GAP, value)); + void setColumnGap(yoga::Style::Length value) { + props.push_back( + std::make_unique>(COLUMN_GAP, value)); } - void setFlexGrow(yoga::FloatOptional value) - { - props.push_back(std::make_unique>(FLEX_GROW, value)); + void setFlexGrow(yoga::FloatOptional value) { + props.push_back( + std::make_unique>(FLEX_GROW, value)); } - void setFlexShrink(yoga::FloatOptional value) - { - props.push_back(std::make_unique>(FLEX_SHRINK, value)); + void setFlexShrink(yoga::FloatOptional value) { + props.push_back(std::make_unique>( + FLEX_SHRINK, value)); } - void setFlexWrap(yoga::Wrap value) - { - props.push_back(std::make_unique>(FLEX_WRAP, value)); + void setFlexWrap(yoga::Wrap value) { + props.push_back( + std::make_unique>(FLEX_WRAP, value)); } - void setJustifyContent(yoga::Justify value) - { - props.push_back(std::make_unique>(JUSTIFY_CONTENT, value)); + void setJustifyContent(yoga::Justify value) { + props.push_back( + std::make_unique>(JUSTIFY_CONTENT, value)); } - void setMaxHeight(yoga::Style::SizeLength value) - { - props.push_back(std::make_unique>(MAX_HEIGHT, value)); + void setMaxHeight(yoga::Style::SizeLength value) { + props.push_back(std::make_unique>( + MAX_HEIGHT, value)); } - void setMaxWidth(yoga::Style::SizeLength value) - { - props.push_back(std::make_unique>(MAX_WIDTH, value)); + void setMaxWidth(yoga::Style::SizeLength value) { + props.push_back(std::make_unique>( + MAX_WIDTH, value)); } - void setMinHeight(yoga::Style::SizeLength value) - { - props.push_back(std::make_unique>(MIN_HEIGHT, value)); + void setMinHeight(yoga::Style::SizeLength value) { + props.push_back(std::make_unique>( + MIN_HEIGHT, value)); } - void setMinWidth(yoga::Style::SizeLength value) - { - props.push_back(std::make_unique>(MIN_WIDTH, value)); + void setMinWidth(yoga::Style::SizeLength value) { + props.push_back(std::make_unique>( + MIN_WIDTH, value)); } - void setOverflow(yoga::Overflow value) - { - props.push_back(std::make_unique>(STYLE_OVERFLOW, value)); + void setOverflow(yoga::Overflow value) { + props.push_back( + std::make_unique>(STYLE_OVERFLOW, value)); } - void setPositionType(yoga::PositionType value) - { - props.push_back(std::make_unique>(POSITION_TYPE, value)); + void setPositionType(yoga::PositionType value) { + props.push_back(std::make_unique>( + POSITION_TYPE, value)); } - void setZIndex(std::optional value) - { - props.push_back(std::make_unique>>(Z_INDEX, value)); + void setZIndex(std::optional value) { + props.push_back( + std::make_unique>>(Z_INDEX, value)); } - void setDirection(yoga::Direction value) - { - props.push_back(std::make_unique>(DIRECTION, value)); + void setDirection(yoga::Direction value) { + props.push_back( + std::make_unique>(DIRECTION, value)); } - void setBorderCurves(CascadedBorderCurves &value) - { - props.push_back(std::make_unique>(BORDER_CURVES, value)); + void setBorderCurves(CascadedBorderCurves& value) { + props.push_back(std::make_unique>( + BORDER_CURVES, value)); } - void setBorderStyles(CascadedBorderStyles &value) - { - props.push_back(std::make_unique>(BORDER_STYLES, value)); + void setBorderStyles(CascadedBorderStyles& value) { + props.push_back(std::make_unique>( + BORDER_STYLES, value)); } - void setPointerEvents(PointerEventsMode value) - { - props.push_back(std::make_unique>(POINTER_EVENTS, value)); + void setPointerEvents(PointerEventsMode value) { + props.push_back(std::make_unique>( + POINTER_EVENTS, value)); } - void setIsolation(Isolation value) - { - props.push_back(std::make_unique>(ISOLATION, value)); + void setIsolation(Isolation value) { + props.push_back( + std::make_unique>(ISOLATION, value)); } - void setCursor(Cursor value) - { + void setCursor(Cursor value) { props.push_back(std::make_unique>(CURSOR, value)); } - void setBoxShadow(const std::vector &value) - { - props.push_back(std::make_unique>>(BOX_SHADOW, value)); + void setBoxShadow(const std::vector& value) { + props.push_back(std::make_unique>>( + BOX_SHADOW, value)); } - void setMixBlendMode(BlendMode value) - { - props.push_back(std::make_unique>(MIX_BLEND_MODE, value)); + void setMixBlendMode(BlendMode value) { + props.push_back( + std::make_unique>(MIX_BLEND_MODE, value)); } - void setBackfaceVisibility(BackfaceVisibility value) - { - props.push_back(std::make_unique>(BACKFACE_VISIBILITY, value)); + void setBackfaceVisibility(BackfaceVisibility value) { + props.push_back(std::make_unique>( + BACKFACE_VISIBILITY, value)); } - 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/AnimatedPropsRegistry.h b/packages/react-native/ReactCommon/react/renderer/animationbackend/AnimatedPropsRegistry.h index 50cafc8f4b63..3eada4fcf67b 100644 --- a/packages/react-native/ReactCommon/react/renderer/animationbackend/AnimatedPropsRegistry.h +++ b/packages/react-native/ReactCommon/react/renderer/animationbackend/AnimatedPropsRegistry.h @@ -24,7 +24,8 @@ struct PropsSnapshot { struct SurfaceContext { std::unordered_map> pendingMap, map; - std::unordered_set> pendingFamilies, families; + std::unordered_set> pendingFamilies, + families; }; struct SurfaceUpdates { @@ -37,19 +38,25 @@ using SnapshotMap = std::unordered_map>; class AnimatedPropsRegistry { public: - void update(const std::unordered_map &surfaceUpdates); + void update( + const std::unordered_map& surfaceUpdates); void initializeSurface(SurfaceId surfaceId); void clear(SurfaceId surfaceId); void clearOnSurfaceStop(SurfaceId surfaceId); - std::pair> &, SnapshotMap &> getMap(SurfaceId surfaceId); + std::pair< + std::unordered_set>&, + SnapshotMap&> + getMap(SurfaceId surfaceId); private: std::unordered_map surfaceContexts_; std::mutex mutex_; }; -inline void updateProp(const PropName propName, BaseViewProps &viewProps, const PropsSnapshot &snapshot) -{ +inline void updateProp( + const PropName propName, + BaseViewProps& viewProps, + const PropsSnapshot& snapshot) { switch (propName) { case OPACITY: viewProps.opacity = snapshot.props.opacity; @@ -57,7 +64,8 @@ inline void updateProp(const PropName propName, BaseViewProps &viewProps, const case WIDTH: viewProps.yogaStyle.setDimension( - yoga::Dimension::Width, snapshot.props.yogaStyle.dimension(yoga::Dimension::Width)); + yoga::Dimension::Width, + snapshot.props.yogaStyle.dimension(yoga::Dimension::Width)); break; case HEIGHT: { @@ -103,48 +111,100 @@ inline void updateProp(const PropName propName, BaseViewProps &viewProps, const break; case MARGIN: - viewProps.yogaStyle.setMargin(yoga::Edge::Left, snapshot.props.yogaStyle.margin(yoga::Edge::Left)); - viewProps.yogaStyle.setMargin(yoga::Edge::Right, snapshot.props.yogaStyle.margin(yoga::Edge::Right)); - viewProps.yogaStyle.setMargin(yoga::Edge::Top, snapshot.props.yogaStyle.margin(yoga::Edge::Top)); - viewProps.yogaStyle.setMargin(yoga::Edge::Bottom, snapshot.props.yogaStyle.margin(yoga::Edge::Bottom)); - viewProps.yogaStyle.setMargin(yoga::Edge::Start, snapshot.props.yogaStyle.margin(yoga::Edge::Start)); - viewProps.yogaStyle.setMargin(yoga::Edge::End, snapshot.props.yogaStyle.margin(yoga::Edge::End)); - viewProps.yogaStyle.setMargin(yoga::Edge::Horizontal, snapshot.props.yogaStyle.margin(yoga::Edge::Horizontal)); - viewProps.yogaStyle.setMargin(yoga::Edge::Vertical, snapshot.props.yogaStyle.margin(yoga::Edge::Vertical)); + viewProps.yogaStyle.setMargin( + yoga::Edge::Left, snapshot.props.yogaStyle.margin(yoga::Edge::Left)); + viewProps.yogaStyle.setMargin( + yoga::Edge::Right, + snapshot.props.yogaStyle.margin(yoga::Edge::Right)); + viewProps.yogaStyle.setMargin( + yoga::Edge::Top, snapshot.props.yogaStyle.margin(yoga::Edge::Top)); + viewProps.yogaStyle.setMargin( + yoga::Edge::Bottom, + snapshot.props.yogaStyle.margin(yoga::Edge::Bottom)); + viewProps.yogaStyle.setMargin( + yoga::Edge::Start, + snapshot.props.yogaStyle.margin(yoga::Edge::Start)); + viewProps.yogaStyle.setMargin( + yoga::Edge::End, snapshot.props.yogaStyle.margin(yoga::Edge::End)); + viewProps.yogaStyle.setMargin( + yoga::Edge::Horizontal, + snapshot.props.yogaStyle.margin(yoga::Edge::Horizontal)); + viewProps.yogaStyle.setMargin( + yoga::Edge::Vertical, + snapshot.props.yogaStyle.margin(yoga::Edge::Vertical)); break; case PADDING: - viewProps.yogaStyle.setPadding(yoga::Edge::Left, snapshot.props.yogaStyle.padding(yoga::Edge::Left)); - viewProps.yogaStyle.setPadding(yoga::Edge::Right, snapshot.props.yogaStyle.padding(yoga::Edge::Right)); - viewProps.yogaStyle.setPadding(yoga::Edge::Top, snapshot.props.yogaStyle.padding(yoga::Edge::Top)); - viewProps.yogaStyle.setPadding(yoga::Edge::Bottom, snapshot.props.yogaStyle.padding(yoga::Edge::Bottom)); - viewProps.yogaStyle.setPadding(yoga::Edge::Start, snapshot.props.yogaStyle.padding(yoga::Edge::Start)); - viewProps.yogaStyle.setPadding(yoga::Edge::End, snapshot.props.yogaStyle.padding(yoga::Edge::End)); - viewProps.yogaStyle.setPadding(yoga::Edge::Horizontal, snapshot.props.yogaStyle.padding(yoga::Edge::Horizontal)); - viewProps.yogaStyle.setPadding(yoga::Edge::Vertical, snapshot.props.yogaStyle.padding(yoga::Edge::Vertical)); + viewProps.yogaStyle.setPadding( + yoga::Edge::Left, snapshot.props.yogaStyle.padding(yoga::Edge::Left)); + viewProps.yogaStyle.setPadding( + yoga::Edge::Right, + snapshot.props.yogaStyle.padding(yoga::Edge::Right)); + viewProps.yogaStyle.setPadding( + yoga::Edge::Top, snapshot.props.yogaStyle.padding(yoga::Edge::Top)); + viewProps.yogaStyle.setPadding( + yoga::Edge::Bottom, + snapshot.props.yogaStyle.padding(yoga::Edge::Bottom)); + viewProps.yogaStyle.setPadding( + yoga::Edge::Start, + snapshot.props.yogaStyle.padding(yoga::Edge::Start)); + viewProps.yogaStyle.setPadding( + yoga::Edge::End, snapshot.props.yogaStyle.padding(yoga::Edge::End)); + viewProps.yogaStyle.setPadding( + yoga::Edge::Horizontal, + snapshot.props.yogaStyle.padding(yoga::Edge::Horizontal)); + viewProps.yogaStyle.setPadding( + yoga::Edge::Vertical, + snapshot.props.yogaStyle.padding(yoga::Edge::Vertical)); break; case POSITION: - viewProps.yogaStyle.setPosition(yoga::Edge::Left, snapshot.props.yogaStyle.position(yoga::Edge::Left)); - viewProps.yogaStyle.setPosition(yoga::Edge::Right, snapshot.props.yogaStyle.position(yoga::Edge::Right)); - viewProps.yogaStyle.setPosition(yoga::Edge::Top, snapshot.props.yogaStyle.position(yoga::Edge::Top)); - viewProps.yogaStyle.setPosition(yoga::Edge::Bottom, snapshot.props.yogaStyle.position(yoga::Edge::Bottom)); - viewProps.yogaStyle.setPosition(yoga::Edge::Start, snapshot.props.yogaStyle.position(yoga::Edge::Start)); - viewProps.yogaStyle.setPosition(yoga::Edge::End, snapshot.props.yogaStyle.position(yoga::Edge::End)); viewProps.yogaStyle.setPosition( - yoga::Edge::Horizontal, snapshot.props.yogaStyle.position(yoga::Edge::Horizontal)); - viewProps.yogaStyle.setPosition(yoga::Edge::Vertical, snapshot.props.yogaStyle.position(yoga::Edge::Vertical)); + yoga::Edge::Left, + snapshot.props.yogaStyle.position(yoga::Edge::Left)); + viewProps.yogaStyle.setPosition( + yoga::Edge::Right, + snapshot.props.yogaStyle.position(yoga::Edge::Right)); + viewProps.yogaStyle.setPosition( + yoga::Edge::Top, snapshot.props.yogaStyle.position(yoga::Edge::Top)); + viewProps.yogaStyle.setPosition( + yoga::Edge::Bottom, + snapshot.props.yogaStyle.position(yoga::Edge::Bottom)); + viewProps.yogaStyle.setPosition( + yoga::Edge::Start, + snapshot.props.yogaStyle.position(yoga::Edge::Start)); + viewProps.yogaStyle.setPosition( + yoga::Edge::End, snapshot.props.yogaStyle.position(yoga::Edge::End)); + viewProps.yogaStyle.setPosition( + yoga::Edge::Horizontal, + snapshot.props.yogaStyle.position(yoga::Edge::Horizontal)); + viewProps.yogaStyle.setPosition( + yoga::Edge::Vertical, + snapshot.props.yogaStyle.position(yoga::Edge::Vertical)); break; case BORDER_WIDTH: - viewProps.yogaStyle.setBorder(yoga::Edge::Left, snapshot.props.yogaStyle.border(yoga::Edge::Left)); - viewProps.yogaStyle.setBorder(yoga::Edge::Right, snapshot.props.yogaStyle.border(yoga::Edge::Right)); - viewProps.yogaStyle.setBorder(yoga::Edge::Top, snapshot.props.yogaStyle.border(yoga::Edge::Top)); - viewProps.yogaStyle.setBorder(yoga::Edge::Bottom, snapshot.props.yogaStyle.border(yoga::Edge::Bottom)); - viewProps.yogaStyle.setBorder(yoga::Edge::Start, snapshot.props.yogaStyle.border(yoga::Edge::Start)); - viewProps.yogaStyle.setBorder(yoga::Edge::End, snapshot.props.yogaStyle.border(yoga::Edge::End)); - viewProps.yogaStyle.setBorder(yoga::Edge::Horizontal, snapshot.props.yogaStyle.border(yoga::Edge::Horizontal)); - viewProps.yogaStyle.setBorder(yoga::Edge::Vertical, snapshot.props.yogaStyle.border(yoga::Edge::Vertical)); + viewProps.yogaStyle.setBorder( + yoga::Edge::Left, snapshot.props.yogaStyle.border(yoga::Edge::Left)); + viewProps.yogaStyle.setBorder( + yoga::Edge::Right, + snapshot.props.yogaStyle.border(yoga::Edge::Right)); + viewProps.yogaStyle.setBorder( + yoga::Edge::Top, snapshot.props.yogaStyle.border(yoga::Edge::Top)); + viewProps.yogaStyle.setBorder( + yoga::Edge::Bottom, + snapshot.props.yogaStyle.border(yoga::Edge::Bottom)); + viewProps.yogaStyle.setBorder( + yoga::Edge::Start, + snapshot.props.yogaStyle.border(yoga::Edge::Start)); + viewProps.yogaStyle.setBorder( + yoga::Edge::End, snapshot.props.yogaStyle.border(yoga::Edge::End)); + viewProps.yogaStyle.setBorder( + yoga::Edge::Horizontal, + snapshot.props.yogaStyle.border(yoga::Edge::Horizontal)); + viewProps.yogaStyle.setBorder( + yoga::Edge::Vertical, + snapshot.props.yogaStyle.border(yoga::Edge::Vertical)); break; case BORDER_COLOR: @@ -172,7 +232,8 @@ inline void updateProp(const PropName propName, BaseViewProps &viewProps, const break; case ALIGN_CONTENT: - viewProps.yogaStyle.setAlignContent(snapshot.props.yogaStyle.alignContent()); + viewProps.yogaStyle.setAlignContent( + snapshot.props.yogaStyle.alignContent()); break; case ALIGN_ITEMS: @@ -184,7 +245,8 @@ inline void updateProp(const PropName propName, BaseViewProps &viewProps, const break; case ASPECT_RATIO: - viewProps.yogaStyle.setAspectRatio(snapshot.props.yogaStyle.aspectRatio()); + viewProps.yogaStyle.setAspectRatio( + snapshot.props.yogaStyle.aspectRatio()); break; case BOX_SIZING: @@ -200,15 +262,19 @@ inline void updateProp(const PropName propName, BaseViewProps &viewProps, const break; case FLEX_DIRECTION: - viewProps.yogaStyle.setFlexDirection(snapshot.props.yogaStyle.flexDirection()); + viewProps.yogaStyle.setFlexDirection( + snapshot.props.yogaStyle.flexDirection()); break; case ROW_GAP: - viewProps.yogaStyle.setGap(yoga::Gutter::Row, snapshot.props.yogaStyle.gap(yoga::Gutter::Row)); + viewProps.yogaStyle.setGap( + yoga::Gutter::Row, snapshot.props.yogaStyle.gap(yoga::Gutter::Row)); break; case COLUMN_GAP: - viewProps.yogaStyle.setGap(yoga::Gutter::Column, snapshot.props.yogaStyle.gap(yoga::Gutter::Column)); + viewProps.yogaStyle.setGap( + yoga::Gutter::Column, + snapshot.props.yogaStyle.gap(yoga::Gutter::Column)); break; case FLEX_GROW: @@ -224,27 +290,32 @@ inline void updateProp(const PropName propName, BaseViewProps &viewProps, const break; case JUSTIFY_CONTENT: - viewProps.yogaStyle.setJustifyContent(snapshot.props.yogaStyle.justifyContent()); + viewProps.yogaStyle.setJustifyContent( + snapshot.props.yogaStyle.justifyContent()); break; case MAX_HEIGHT: viewProps.yogaStyle.setMaxDimension( - yoga::Dimension::Height, snapshot.props.yogaStyle.maxDimension(yoga::Dimension::Height)); + yoga::Dimension::Height, + snapshot.props.yogaStyle.maxDimension(yoga::Dimension::Height)); break; case MAX_WIDTH: viewProps.yogaStyle.setMaxDimension( - yoga::Dimension::Width, snapshot.props.yogaStyle.maxDimension(yoga::Dimension::Width)); + yoga::Dimension::Width, + snapshot.props.yogaStyle.maxDimension(yoga::Dimension::Width)); break; case MIN_HEIGHT: viewProps.yogaStyle.setMinDimension( - yoga::Dimension::Height, snapshot.props.yogaStyle.minDimension(yoga::Dimension::Height)); + yoga::Dimension::Height, + snapshot.props.yogaStyle.minDimension(yoga::Dimension::Height)); break; case MIN_WIDTH: viewProps.yogaStyle.setMinDimension( - yoga::Dimension::Width, snapshot.props.yogaStyle.minDimension(yoga::Dimension::Width)); + yoga::Dimension::Width, + snapshot.props.yogaStyle.minDimension(yoga::Dimension::Width)); break; case STYLE_OVERFLOW: @@ -252,7 +323,8 @@ inline void updateProp(const PropName propName, BaseViewProps &viewProps, const break; case POSITION_TYPE: - viewProps.yogaStyle.setPositionType(snapshot.props.yogaStyle.positionType()); + viewProps.yogaStyle.setPositionType( + snapshot.props.yogaStyle.positionType()); break; case Z_INDEX: diff --git a/packages/react-native/ReactCommon/react/renderer/animationbackend/AnimatedPropsSerializer.h b/packages/react-native/ReactCommon/react/renderer/animationbackend/AnimatedPropsSerializer.h index 7d568160ec36..5f3850e3aec2 100644 --- a/packages/react-native/ReactCommon/react/renderer/animationbackend/AnimatedPropsSerializer.h +++ b/packages/react-native/ReactCommon/react/renderer/animationbackend/AnimatedPropsSerializer.h @@ -12,6 +12,6 @@ namespace facebook::react::animationbackend { -folly::dynamic packAnimatedProps(const AnimatedProps &animatedProps); +folly::dynamic packAnimatedProps(const AnimatedProps& animatedProps); } // namespace facebook::react::animationbackend diff --git a/packages/react-native/ReactCommon/react/renderer/animationbackend/AnimationBackend.h b/packages/react-native/ReactCommon/react/renderer/animationbackend/AnimationBackend.h index c01ff23a8e71..44f046bf6fb7 100644 --- a/packages/react-native/ReactCommon/react/renderer/animationbackend/AnimationBackend.h +++ b/packages/react-native/ReactCommon/react/renderer/animationbackend/AnimationBackend.h @@ -51,27 +51,28 @@ class AnimationBackend : public UIManagerAnimationBackend { AnimationBackend( std::shared_ptr animationChoreographer, std::shared_ptr uiManager); - void commitUpdates(SurfaceId surfaceId, SurfaceUpdates &surfaceUpdates); - void synchronouslyUpdateProps(const std::unordered_map &updates); - void requestAsyncFlushForSurfaces(const std::set &surfaces); + void commitUpdates(SurfaceId surfaceId, SurfaceUpdates& surfaceUpdates); + void synchronouslyUpdateProps( + const std::unordered_map& updates); + void requestAsyncFlushForSurfaces(const std::set& surfaces); void clearRegistry(SurfaceId surfaceId) override; void clearRegistryOnSurfaceStop(SurfaceId surfaceId) override; void registerJSInvoker(std::shared_ptr jsInvoker) override; void onAnimationFrame(AnimationTimestamp timestamp) override; void trigger() override; - void pushAnimationMutations(const Callback &callback) override; - CallbackId start(const Callback &callback) override; + void pushAnimationMutations(const Callback& callback) override; + CallbackId start(const Callback& callback) override; void stop(CallbackId callbackId) override; private: void unpackMutations( - AnimationMutations &mutations, - std::unordered_map &surfaceUpdates, - std::set &asyncFlushSurfaces); + AnimationMutations& mutations, + std::unordered_map& surfaceUpdates, + std::set& asyncFlushSurfaces); void applySurfaceUpdates( - std::unordered_map &surfaceUpdates, - const std::set &asyncFlushSurfaces); + std::unordered_map& surfaceUpdates, + const std::set& asyncFlushSurfaces); void applyMutations(AnimationMutations mutations); std::vector callbacks; std::shared_ptr animatedPropsRegistry_; diff --git a/packages/react-native/ReactCommon/react/renderer/animationbackend/AnimationBackendCommitHook.h b/packages/react-native/ReactCommon/react/renderer/animationbackend/AnimationBackendCommitHook.h index a9dd272ff345..8a291be14d96 100644 --- a/packages/react-native/ReactCommon/react/renderer/animationbackend/AnimationBackendCommitHook.h +++ b/packages/react-native/ReactCommon/react/renderer/animationbackend/AnimationBackendCommitHook.h @@ -18,14 +18,17 @@ class AnimationBackendCommitHook : public UIManagerCommitHook { std::shared_ptr animatedPropsRegistry_; public: - AnimationBackendCommitHook(UIManager &uiManager, std::shared_ptr animatedPropsRegistry); + AnimationBackendCommitHook( + UIManager& uiManager, + std::shared_ptr animatedPropsRegistry); RootShadowNode::Unshared shadowTreeWillCommit( - const ShadowTree &shadowTree, - const RootShadowNode::Shared &oldRootShadowNode, - const RootShadowNode::Unshared &newRootShadowNode, - const ShadowTreeCommitOptions &commitOptions) noexcept override; - void commitHookWasRegistered(const UIManager &uiManager) noexcept override {} - void commitHookWasUnregistered(const UIManager &uiManager) noexcept override {} + const ShadowTree& shadowTree, + const RootShadowNode::Shared& oldRootShadowNode, + const RootShadowNode::Unshared& newRootShadowNode, + const ShadowTreeCommitOptions& commitOptions) noexcept override; + void commitHookWasRegistered(const UIManager& uiManager) noexcept override {} + void commitHookWasUnregistered(const UIManager& uiManager) noexcept override { + } }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/animationbackend/AnimationChoreographer.h b/packages/react-native/ReactCommon/react/renderer/animationbackend/AnimationChoreographer.h index 94be54e3a219..d89db70d39b9 100644 --- a/packages/react-native/ReactCommon/react/renderer/animationbackend/AnimationChoreographer.h +++ b/packages/react-native/ReactCommon/react/renderer/animationbackend/AnimationChoreographer.h @@ -13,8 +13,8 @@ namespace facebook::react { /* - * This class serves as an interface for native animation frame scheduling that can be used as abstraction in - * ReactCxxPlatform. + * This class serves as an interface for native animation frame scheduling that + * can be used as abstraction in ReactCxxPlatform. */ class AnimationChoreographer { public: @@ -22,16 +22,16 @@ class AnimationChoreographer { virtual void resume() = 0; virtual void pause() = 0; - virtual AnimationTimestamp now() const - { - return HighResTimeStamp::now().toChronoSteadyClockTimePoint().time_since_epoch(); + virtual AnimationTimestamp now() const { + return HighResTimeStamp::now() + .toChronoSteadyClockTimePoint() + .time_since_epoch(); } - void setAnimationBackend(std::weak_ptr animationBackend) - { + void setAnimationBackend( + std::weak_ptr animationBackend) { animationBackend_ = animationBackend; } - void onAnimationFrame(AnimationTimestamp timestamp) const - { + void onAnimationFrame(AnimationTimestamp timestamp) const { if (auto animationBackend = animationBackend_.lock()) { animationBackend->onAnimationFrame(timestamp); } diff --git a/packages/react-native/ReactCommon/react/renderer/animations/LayoutAnimationCallbackWrapper.h b/packages/react-native/ReactCommon/react/renderer/animations/LayoutAnimationCallbackWrapper.h index 53ba7915c490..64c52d42615d 100644 --- a/packages/react-native/ReactCommon/react/renderer/animations/LayoutAnimationCallbackWrapper.h +++ b/packages/react-native/ReactCommon/react/renderer/animations/LayoutAnimationCallbackWrapper.h @@ -14,14 +14,11 @@ 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.h b/packages/react-native/ReactCommon/react/renderer/animations/LayoutAnimationDriver.h index 7e22dfe8d156..3ddbc0884d4e 100644 --- a/packages/react-native/ReactCommon/react/renderer/animations/LayoutAnimationDriver.h +++ b/packages/react-native/ReactCommon/react/renderer/animations/LayoutAnimationDriver.h @@ -17,15 +17,18 @@ 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.h b/packages/react-native/ReactCommon/react/renderer/animations/LayoutAnimationKeyFrameManager.h index 977be17b0a45..1de8349848dc 100644 --- a/packages/react-native/ReactCommon/react/renderer/animations/LayoutAnimationKeyFrameManager.h +++ b/packages/react-native/ReactCommon/react/renderer/animations/LayoutAnimationKeyFrameManager.h @@ -24,32 +24,36 @@ 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; @@ -66,18 +70,20 @@ class LayoutAnimationKeyFrameManager : public UIManagerAnimationDelegate, public 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); @@ -94,8 +100,9 @@ class LayoutAnimationKeyFrameManager : public UIManagerAnimationDelegate, public */ 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, @@ -106,30 +113,34 @@ class LayoutAnimationKeyFrameManager : public UIManagerAnimationDelegate, public * @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_{}; @@ -138,37 +149,38 @@ class LayoutAnimationKeyFrameManager : public UIManagerAnimationDelegate, public 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 1eb38ae28225..2dd7cbc23e33 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(std::string param) return {}; } -static inline std::optional parseAnimationProperty(std::string param) -{ +static inline std::optional parseAnimationProperty( + std::string param) { if (param == "opacity") { return AnimationProperty::Opacity; } @@ -58,9 +58,10 @@ static inline std::optional parseAnimationProperty(std::strin 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, @@ -78,12 +79,14 @@ parseAnimationConfig(const folly::dynamic &config, double defaultDuration, bool } 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 {}; } @@ -91,17 +94,21 @@ parseAnimationConfig(const folly::dynamic &config, double defaultDuration, bool 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; @@ -117,7 +124,8 @@ parseAnimationConfig(const folly::dynamic &config, double defaultDuration, bool 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 {}; } } @@ -127,17 +135,20 @@ parseAnimationConfig(const folly::dynamic &config, double defaultDuration, bool 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 {}; } } @@ -147,7 +158,8 @@ parseAnimationConfig(const folly::dynamic &config, double defaultDuration, bool 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 {}; } } @@ -162,8 +174,8 @@ parseAnimationConfig(const folly::dynamic &config, double defaultDuration, bool } // 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 b43c53474fbc..7793de3bd188 100644 --- a/packages/react-native/ReactCommon/react/renderer/animations/primitives.h +++ b/packages/react-native/ReactCommon/react/renderer/animations/primitives.h @@ -27,13 +27,20 @@ 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/utils.h b/packages/react-native/ReactCommon/react/renderer/animations/utils.h index 1f471d0d0a95..2414ba9246e3 100644 --- a/packages/react-native/ReactCommon/react/renderer/animations/utils.h +++ b/packages/react-native/ReactCommon/react/renderer/animations/utils.h @@ -14,20 +14,21 @@ 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); @@ -40,21 +41,25 @@ static inline void handleShouldFirstComeBeforeSecondRemovesOnly(ShadowViewMutati 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) { @@ -65,33 +70,40 @@ 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; } } @@ -110,7 +122,9 @@ static inline bool shouldFirstComeBeforeSecondMutation( return false; } -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.h b/packages/react-native/ReactCommon/react/renderer/attributedstring/AttributedString.h index 2a729d48378e..a22a8176d002 100644 --- a/packages/react-native/ReactCommon/react/renderer/attributedstring/AttributedString.h +++ b/packages/react-native/ReactCommon/react/renderer/attributedstring/AttributedString.h @@ -41,9 +41,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 { @@ -57,31 +57,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). @@ -91,11 +91,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 @@ -113,8 +113,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, @@ -125,12 +125,13 @@ 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.h b/packages/react-native/ReactCommon/react/renderer/attributedstring/AttributedStringBox.h index f335dfde8afd..bdd6b7cdf751 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,19 +57,21 @@ class AttributedStringBox final { std::shared_ptr opaquePointer_; }; -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()); default: react_native_assert(false && "Invalid AttributedStringBox::Mode"); return 0; diff --git a/packages/react-native/ReactCommon/react/renderer/attributedstring/ParagraphAttributes.h b/packages/react-native/ReactCommon/react/renderer/attributedstring/ParagraphAttributes.h index 367ec8c3e0d7..ac8dbbff388a 100644 --- a/packages/react-native/ReactCommon/react/renderer/attributedstring/ParagraphAttributes.h +++ b/packages/react-native/ReactCommon/react/renderer/attributedstring/ParagraphAttributes.h @@ -82,7 +82,7 @@ class ParagraphAttributes : public DebugStringConvertible { */ std::optional textAlignVertical{}; - bool operator==(const ParagraphAttributes &rhs) const; + bool operator==(const ParagraphAttributes& rhs) const; #pragma mark - DebugStringConvertible @@ -97,8 +97,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 fdf10451752f..3b8329eb6539 100644 --- a/packages/react-native/ReactCommon/react/renderer/attributedstring/PlaceholderAttributedString.h +++ b/packages/react-native/ReactCommon/react/renderer/attributedstring/PlaceholderAttributedString.h @@ -17,12 +17,14 @@ 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 683c993bf968..ddaa9523b4e9 100644 --- a/packages/react-native/ReactCommon/react/renderer/attributedstring/TextAttributes.h +++ b/packages/react-native/ReactCommon/react/renderer/attributedstring/TextAttributes.h @@ -28,7 +28,7 @@ namespace facebook::react { struct TextEffectInfo { std::string name; folly::dynamic props; - bool operator==(const TextEffectInfo &) const = default; + bool operator==(const TextEffectInfo&) const = default; }; class TextAttributes; @@ -104,7 +104,7 @@ class TextAttributes : public DebugStringConvertible { #pragma mark - Operators - bool operator==(const TextAttributes &rhs) const; + bool operator==(const TextAttributes& rhs) const; #pragma mark - DebugStringConvertible @@ -119,18 +119,17 @@ namespace std { template <> struct hash { - size_t operator()(const facebook::react::TextEffectInfo &info) const - { + size_t operator()(const facebook::react::TextEffectInfo& info) const { return facebook::react::hash_combine(info.name, info.props); } }; template <> struct hash { - size_t operator()(const facebook::react::TextAttributes &textAttributes) const - { + size_t operator()( + const facebook::react::TextAttributes& textAttributes) const { size_t textEffectsHash = 0; - for (const auto &effect : textAttributes.textEffects) { + for (const auto& effect : textAttributes.textEffects) { facebook::react::hash_combine(textEffectsHash, effect); } return facebook::react::hash_combine( diff --git a/packages/react-native/ReactCommon/react/renderer/attributedstring/conversions.h b/packages/react-native/ReactCommon/react/renderer/attributedstring/conversions.h index beed96737801..529a6dd2fb6b 100644 --- a/packages/react-native/ReactCommon/react/renderer/attributedstring/conversions.h +++ b/packages/react-native/ReactCommon/react/renderer/attributedstring/conversions.h @@ -35,8 +35,7 @@ namespace facebook::react { -inline std::string toString(const DynamicTypeRamp &dynamicTypeRamp) -{ +inline std::string toString(const DynamicTypeRamp& dynamicTypeRamp) { switch (dynamicTypeRamp) { case DynamicTypeRamp::Caption2: return "caption2"; @@ -69,8 +68,10 @@ 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; @@ -112,8 +113,7 @@ inline void fromRawValue(const PropsParserContext &context, const RawValue &valu result = DynamicTypeRamp::Body; } -inline std::string toString(const EllipsizeMode &ellipsisMode) -{ +inline std::string toString(const EllipsizeMode& ellipsisMode) { switch (ellipsisMode) { case EllipsizeMode::Clip: return "clip"; @@ -132,8 +132,10 @@ 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; @@ -161,8 +163,7 @@ inline void fromRawValue(const PropsParserContext &context, const RawValue &valu result = EllipsizeMode::Tail; } -inline std::string toString(const TextBreakStrategy &textBreakStrategy) -{ +inline std::string toString(const TextBreakStrategy& textBreakStrategy) { switch (textBreakStrategy) { case TextBreakStrategy::Simple: return "simple"; @@ -177,8 +178,10 @@ 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,8 +205,10 @@ inline void fromRawValue(const PropsParserContext &context, const RawValue &valu 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; @@ -272,13 +277,14 @@ inline void fromRawValue(const PropsParserContext &context, const RawValue &valu 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; @@ -303,8 +309,7 @@ inline void fromRawValue(const PropsParserContext &context, const RawValue &valu result = FontStyle::Normal; } -inline std::string toString(const FontStyle &fontStyle) -{ +inline std::string toString(const FontStyle& fontStyle) { switch (fontStyle) { case FontStyle::Normal: return "normal"; @@ -320,8 +325,8 @@ inline std::string toString(const FontStyle &fontStyle) return "normal"; } -inline std::optional fontVariantFromCSSFontVariant(CSSFontVariant cssVariant) -{ +inline std::optional fontVariantFromCSSFontVariant( + CSSFontVariant cssVariant) { switch (cssVariant) { case CSSFontVariant::SmallCaps: return FontVariant::SmallCaps; @@ -385,14 +390,15 @@ inline std::optional fontVariantFromCSSFontVariant(CSSFontVariant c } } -inline void -parseProcessedFontVariant(const PropsParserContext & /*context*/, const RawValue &value, FontVariant &result) -{ +inline void parseProcessedFontVariant( + 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") { @@ -402,7 +408,8 @@ parseProcessedFontVariant(const PropsParserContext & /*context*/, const RawValue } 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") { @@ -428,19 +435,26 @@ parseProcessedFontVariant(const PropsParserContext & /*context*/, const RawValue } 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 { @@ -452,8 +466,9 @@ parseProcessedFontVariant(const PropsParserContext & /*context*/, const RawValue } } -inline void parseUnprocessedFontVariantString(const std::string &value, FontVariant &result) -{ +inline void parseUnprocessedFontVariantString( + const std::string& value, + FontVariant& result) { auto fontVariantList = parseCSSProperty(value); if (!std::holds_alternative(fontVariantList)) { result = FontVariant::Default; @@ -461,15 +476,17 @@ inline void parseUnprocessedFontVariantString(const std::string &value, FontVari } result = FontVariant::Default; - for (const auto &cssVariant : std::get(fontVariantList)) { + for (const auto& cssVariant : std::get(fontVariantList)) { if (auto fv = fontVariantFromCSSFontVariant(cssVariant)) { result = (FontVariant)((int)result | (int)*fv); } } } -inline void parseUnprocessedFontVariant(const PropsParserContext &context, const RawValue &value, FontVariant &result) -{ +inline void parseUnprocessedFontVariant( + const PropsParserContext& context, + const RawValue& value, + FontVariant& result) { if (value.hasType()) { parseUnprocessedFontVariantString((std::string)value, result); } else { @@ -477,8 +494,10 @@ inline void parseUnprocessedFontVariant(const PropsParserContext &context, const } } -inline void fromRawValue(const PropsParserContext &context, const RawValue &value, FontVariant &result) -{ +inline void fromRawValue( + const PropsParserContext& context, + const RawValue& value, + FontVariant& result) { if (ReactNativeFeatureFlags::enableNativeCSSParsing()) { parseUnprocessedFontVariant(context, value, result); } else { @@ -486,8 +505,7 @@ inline void fromRawValue(const PropsParserContext &context, const RawValue &valu } } -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) { @@ -573,8 +591,10 @@ 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; @@ -603,8 +623,7 @@ inline void fromRawValue(const PropsParserContext &context, const RawValue &valu result = TextTransform::None; } -inline std::string toString(const TextTransform &textTransform) -{ +inline std::string toString(const TextTransform& textTransform) { switch (textTransform) { case TextTransform::None: return "none"; @@ -624,8 +643,10 @@ 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; @@ -656,8 +677,7 @@ inline void fromRawValue(const PropsParserContext &context, const RawValue &valu result = TextAlignment::Natural; } -inline std::string toString(const TextAlignment &textAlignment) -{ +inline std::string toString(const TextAlignment& textAlignment) { switch (textAlignment) { case TextAlignment::Natural: return "auto"; @@ -680,8 +700,10 @@ 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; @@ -707,8 +729,7 @@ inline void fromRawValue(const PropsParserContext & /*context*/, const RawValue result = TextAlignmentVertical::Auto; } -inline std::string toString(const TextAlignmentVertical &textAlignment) -{ +inline std::string toString(const TextAlignmentVertical& textAlignment) { switch (textAlignment) { case TextAlignmentVertical::Auto: return "auto"; @@ -725,8 +746,10 @@ 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; @@ -750,8 +773,7 @@ inline void fromRawValue(const PropsParserContext &context, const RawValue &valu result = WritingDirection::Natural; } -inline std::string toString(const WritingDirection &writingDirection) -{ +inline std::string toString(const WritingDirection& writingDirection) { switch (writingDirection) { case WritingDirection::Natural: return "auto"; @@ -766,8 +788,10 @@ 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; @@ -793,8 +817,7 @@ inline void fromRawValue(const PropsParserContext &context, const RawValue &valu result = LineBreakStrategy::None; } -inline std::string toString(const LineBreakStrategy &lineBreakStrategy) -{ +inline std::string toString(const LineBreakStrategy& lineBreakStrategy) { switch (lineBreakStrategy) { case LineBreakStrategy::None: return "none"; @@ -811,8 +834,10 @@ 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; @@ -842,8 +867,7 @@ inline void fromRawValue(const PropsParserContext & /*context*/, const RawValue result = LineBreakMode::Word; } -inline std::string toString(const LineBreakMode &lineBreakMode) -{ +inline std::string toString(const LineBreakMode& lineBreakMode) { switch (lineBreakMode) { case LineBreakMode::Word: return "wordWrapping"; @@ -864,8 +888,10 @@ 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; @@ -876,7 +902,9 @@ inline void fromRawValue(const PropsParserContext &context, const RawValue &valu } 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 { @@ -893,8 +921,8 @@ inline void fromRawValue(const PropsParserContext &context, const RawValue &valu result = TextDecorationLineType::None; } -inline std::string toString(const TextDecorationLineType &textDecorationLineType) -{ +inline std::string toString( + const TextDecorationLineType& textDecorationLineType) { switch (textDecorationLineType) { case TextDecorationLineType::None: return "none"; @@ -912,8 +940,10 @@ inline std::string toString(const TextDecorationLineType &textDecorationLineType 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; @@ -941,8 +971,7 @@ inline void fromRawValue(const PropsParserContext &context, const RawValue &valu result = TextDecorationStyle::Solid; } -inline std::string toString(const TextDecorationStyle &textDecorationStyle) -{ +inline std::string toString(const TextDecorationStyle& textDecorationStyle) { switch (textDecorationStyle) { case TextDecorationStyle::Solid: return "solid"; @@ -962,8 +991,7 @@ 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"; @@ -978,8 +1006,10 @@ 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; @@ -1004,11 +1034,10 @@ inline void fromRawValue(const PropsParserContext &context, const RawValue &valu } 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( @@ -1075,8 +1104,10 @@ 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"); @@ -1089,9 +1120,9 @@ inline void fromRawValue(const PropsParserContext &context, const RawValue &valu } } -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 @@ -1159,26 +1190,36 @@ 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 ¶graphAttributes) -{ +inline MapBuffer toMapBuffer(const ParagraphAttributes& paragraphAttributes) { 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) { @@ -1260,14 +1301,15 @@ 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); @@ -1279,7 +1321,8 @@ 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)); @@ -1292,13 +1335,16 @@ inline MapBuffer toMapBuffer(const TextAttributes &textAttributes) builder.putMapBuffer(TA_KEY_FONT_VARIANT, fontVariantMap); } if (textAttributes.fontVariationSettings.has_value()) { - builder.putString(TA_KEY_FONT_VARIATION_SETTINGS, *textAttributes.fontVariationSettings); + builder.putString( + TA_KEY_FONT_VARIATION_SETTINGS, *textAttributes.fontVariationSettings); } 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); @@ -1310,46 +1356,64 @@ 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)); @@ -1359,7 +1423,8 @@ inline MapBuffer toMapBuffer(const TextAttributes &textAttributes) for (size_t i = 0; i < textAttributes.textEffects.size(); i++) { auto effectBuilder = MapBufferBuilder(); effectBuilder.putString(TE_KEY_NAME, textAttributes.textEffects[i].name); - effectBuilder.putString(TE_KEY_PROPS, folly::toJson(textAttributes.textEffects[i].props)); + effectBuilder.putString( + TE_KEY_PROPS, folly::toJson(textAttributes.textEffects[i].props)); effectsBuilder.putMapBuffer(i, effectBuilder.build()); } builder.putMapBuffer(TA_KEY_TEXT_EFFECTS, effectsBuilder.build()); @@ -1367,8 +1432,7 @@ 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); @@ -1377,8 +1441,11 @@ 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); @@ -1386,8 +1453,7 @@ 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; @@ -1396,11 +1462,14 @@ 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 37ad9265edc6..6ba8ffe28954 100644 --- a/packages/react-native/ReactCommon/react/renderer/attributedstring/primitives.h +++ b/packages/react-native/ReactCommon/react/renderer/attributedstring/primitives.h @@ -97,7 +97,8 @@ enum class TextAlignment { Left, // Visually left aligned. Center, // Visually centered. Right, // Visually right aligned. - Justified, // Fully-justified. The last line in a paragraph is natural-aligned. + Justified, // Fully-justified. The last line in a paragraph is + // natural-aligned. Start, // Aligned to the start side of the paragraph direction. End // Aligned to the end side of the paragraph direction. }; @@ -134,7 +135,12 @@ 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, Wavy }; diff --git a/packages/react-native/ReactCommon/react/renderer/bridging/bridging.h b/packages/react-native/ReactCommon/react/renderer/bridging/bridging.h index 38da825acdd1..bd17c3234569 100644 --- a/packages/react-native/ReactCommon/react/renderer/bridging/bridging.h +++ b/packages/react-native/ReactCommon/react/renderer/bridging/bridging.h @@ -15,8 +15,9 @@ 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 @@ -28,16 +29,20 @@ 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 ef0bbc50ecd7..d10ea3536dac 100644 --- a/packages/react-native/ReactCommon/react/renderer/componentregistry/ComponentDescriptorFactory.h +++ b/packages/react-native/ReactCommon/react/renderer/componentregistry/ComponentDescriptorFactory.h @@ -22,9 +22,10 @@ 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 f1e6c7a4010f..175d9bd6e7d9 100644 --- a/packages/react-native/ReactCommon/react/renderer/componentregistry/ComponentDescriptorProvider.h +++ b/packages/react-native/ReactCommon/react/renderer/componentregistry/ComponentDescriptorProvider.h @@ -18,7 +18,8 @@ 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 ¶meters); +using ComponentDescriptorConstructor = ComponentDescriptor::Unique( + const ComponentDescriptorParameters& parameters); /* * Represents a unified way to construct an instance of a particular stored @@ -35,15 +36,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 ¶meters) -{ +ComponentDescriptor::Unique concreteComponentDescriptorConstructor( + const ComponentDescriptorParameters& parameters) { static_assert( std::is_base_of::value, "ComponentDescriptorT must be a descendant of ComponentDescriptor"); @@ -56,8 +57,7 @@ ComponentDescriptor::Unique concreteComponentDescriptorConstructor(const Compone * 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 9d9bad369453..1a23997add05 100644 --- a/packages/react-native/ReactCommon/react/renderer/componentregistry/ComponentDescriptorProviderRegistry.h +++ b/packages/react-native/ReactCommon/react/renderer/componentregistry/ComponentDescriptorProviderRegistry.h @@ -16,7 +16,8 @@ namespace facebook::react { -using ComponentDescriptorProviderRequest = std::function; +using ComponentDescriptorProviderRequest = + std::function; /* * Registry of `ComponentDescriptorProvider`s (and managed @@ -31,7 +32,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 @@ -41,7 +42,8 @@ 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 @@ -49,7 +51,7 @@ class ComponentDescriptorProviderRegistry final { * The methods can be called on any thread. */ ComponentDescriptorRegistry::Shared createComponentDescriptorRegistry( - const ComponentDescriptorParameters ¶meters) const; + const ComponentDescriptorParameters& parameters) const; private: friend class ComponentDescriptorRegistry; @@ -57,9 +59,12 @@ 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 54e5ff55259f..641a99c384fe 100644 --- a/packages/react-native/ReactCommon/react/renderer/componentregistry/ComponentDescriptorRegistry.h +++ b/packages/react-native/ReactCommon/react/renderer/componentregistry/ComponentDescriptorRegistry.h @@ -21,7 +21,8 @@ namespace facebook::react { class ComponentDescriptorProviderRegistry; class ComponentDescriptorRegistry; -using SharedComponentDescriptorRegistry = std::shared_ptr; +using SharedComponentDescriptorRegistry = + std::shared_ptr; /* * Registry of particular `ComponentDescriptor`s. @@ -36,7 +37,7 @@ class ComponentDescriptorRegistry { */ ComponentDescriptorRegistry( ComponentDescriptorParameters parameters, - const ComponentDescriptorProviderRegistry &providerRegistry, + const ComponentDescriptorProviderRegistry& providerRegistry, std::shared_ptr contextContainer); /* @@ -44,21 +45,24 @@ 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 @@ -67,14 +71,17 @@ 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 1b2bbaf005d5..e0c9d23463e6 100644 --- a/packages/react-native/ReactCommon/react/renderer/componentregistry/native/NativeComponentRegistryBinding.h +++ b/packages/react-native/ReactCommon/react/renderer/componentregistry/native/NativeComponentRegistryBinding.h @@ -17,12 +17,15 @@ 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.h b/packages/react-native/ReactCommon/react/renderer/components/image/ImageComponentDescriptor.h index ff6417774db8..35bce183c025 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/image/ImageComponentDescriptor.h +++ b/packages/react-native/ReactCommon/react/renderer/components/image/ImageComponentDescriptor.h @@ -19,11 +19,13 @@ extern const char ImageManagerKey[]; /* * Descriptor for component. */ -class ImageComponentDescriptor final : public ConcreteComponentDescriptor { +class ImageComponentDescriptor final + : public ConcreteComponentDescriptor { public: - explicit ImageComponentDescriptor(const ComponentDescriptorParameters ¶meters); + explicit ImageComponentDescriptor( + const ComponentDescriptorParameters& parameters); - 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 b995bfad3fbc..67ab60bb9a95 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 e53e1995d38c..7e92b3ae8221 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/image/ImageProps.h +++ b/packages/react-native/ReactCommon/react/renderer/components/image/ImageProps.h @@ -18,10 +18,16 @@ 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 @@ -42,7 +48,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 3ecd4672d12d..1bcb0d813101 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/image/ImageShadowNode.h +++ b/packages/react-native/ReactCommon/react/renderer/components/image/ImageShadowNode.h @@ -22,13 +22,15 @@ extern const char ImageComponentName[]; /* * `ShadowNode` for component. */ -class ImageShadowNode final - : public ConcreteViewShadowNode { +class ImageShadowNode final : public ConcreteViewShadowNode< + ImageComponentName, + ImageProps, + ImageEventEmitter, + ImageState> { public: using ConcreteViewShadowNode::ConcreteViewShadowNode; - static ShadowNodeTraits BaseTraits() - { + static ShadowNodeTraits BaseTraits() { auto traits = ConcreteViewShadowNode::BaseTraits(); traits.set(ShadowNodeTraits::Trait::LeafYogaNode); return traits; @@ -37,13 +39,12 @@ class ImageShadowNode final /* * 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 718dd12620b5..fac7d154b57e 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/image/ImageState.h +++ b/packages/react-native/ReactCommon/react/renderer/components/image/ImageState.h @@ -24,12 +24,13 @@ 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. @@ -40,20 +41,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 902a99949d8b..87775e04da6d 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/image/conversions.h +++ b/packages/react-native/ReactCommon/react/renderer/components/image/conversions.h @@ -17,8 +17,10 @@ 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, @@ -37,10 +39,12 @@ inline void fromRawValue(const PropsParserContext & /* context */, const RawValu 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")}; } @@ -76,22 +80,27 @@ inline void fromRawValue(const PropsParserContext & /* context */, const RawValu } 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; @@ -111,13 +120,14 @@ inline void fromRawValue(const PropsParserContext & /* context */, const RawValu 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"; @@ -147,8 +157,7 @@ inline void fromRawValue(const PropsParserContext & /* context */, const RawValu } } -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 1f524310d8c3..fb252fd46523 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/inputaccessory/InputAccessoryComponentDescriptor.h +++ b/packages/react-native/ReactCommon/react/renderer/components/inputaccessory/InputAccessoryComponentDescriptor.h @@ -16,17 +16,23 @@ 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 5de0b82ea0c9..15cbea43434b 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/inputaccessory/InputAccessoryShadowNode.h +++ b/packages/react-native/ReactCommon/react/renderer/components/inputaccessory/InputAccessoryShadowNode.h @@ -27,8 +27,7 @@ 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 75e5c9ca0b38..e415c67681e3 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/LegacyViewManagerInteropViewProps.h b/packages/react-native/ReactCommon/react/renderer/components/legacyviewmanagerinterop/LegacyViewManagerInteropViewProps.h index a6a1c8c191fd..d202bae3f89c 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/legacyviewmanagerinterop/LegacyViewManagerInteropViewProps.h +++ b/packages/react-native/ReactCommon/react/renderer/components/legacyviewmanagerinterop/LegacyViewManagerInteropViewProps.h @@ -18,9 +18,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 674fe898f770..4d7e63ed14f0 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/legacyviewmanagerinterop/UnstableLegacyViewManagerAutomaticComponentDescriptor.h +++ b/packages/react-native/ReactCommon/react/renderer/components/legacyviewmanagerinterop/UnstableLegacyViewManagerAutomaticComponentDescriptor.h @@ -17,16 +17,16 @@ namespace facebook::react { class UnstableLegacyViewManagerAutomaticComponentDescriptor final - : public ConcreteComponentDescriptor { + : public ConcreteComponentDescriptor< + LegacyViewManagerAndroidInteropShadowNode> { public: using ConcreteComponentDescriptor::ConcreteComponentDescriptor; UnstableLegacyViewManagerAutomaticComponentDescriptor( - const ComponentDescriptorParameters ¶meters, + const ComponentDescriptorParameters& parameters, 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 bc6a7767f139..a4e371bbd649 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/legacyviewmanagerinterop/UnstableLegacyViewManagerAutomaticShadowNode.h +++ b/packages/react-native/ReactCommon/react/renderer/components/legacyviewmanagerinterop/UnstableLegacyViewManagerAutomaticShadowNode.h @@ -16,8 +16,9 @@ namespace facebook::react { extern const char LegacyViewManagerAndroidInteropComponentName[]; -using LegacyViewManagerAndroidInteropShadowNode = - ConcreteViewShadowNode; +using LegacyViewManagerAndroidInteropShadowNode = ConcreteViewShadowNode< + LegacyViewManagerAndroidInteropComponentName, + LegacyViewManagerInteropViewProps>; } // 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 e3ba08bbd944..dbd21bdf6d2e 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/legacyviewmanagerinterop/UnstableLegacyViewManagerInteropComponentDescriptor.h +++ b/packages/react-native/ReactCommon/react/renderer/components/legacyviewmanagerinterop/UnstableLegacyViewManagerInteropComponentDescriptor.h @@ -21,15 +21,16 @@ 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> { + : public ConcreteComponentDescriptor< + ConcreteViewShadowNode> { public: UnstableLegacyViewManagerInteropComponentDescriptor( - const ComponentDescriptorParameters ¶meters) - : ConcreteComponentDescriptor>(parameters) - { - } + const ComponentDescriptorParameters& parameters) + : ConcreteComponentDescriptor< + ConcreteViewShadowNode>( + parameters) {} private: }; diff --git a/packages/react-native/ReactCommon/react/renderer/components/legacyviewmanagerinterop/platform/ios/react/renderer/components/legacyviewmanagerinterop/LegacyViewManagerInteropComponentDescriptor.h b/packages/react-native/ReactCommon/react/renderer/components/legacyviewmanagerinterop/platform/ios/react/renderer/components/legacyviewmanagerinterop/LegacyViewManagerInteropComponentDescriptor.h index ca36068592ea..31d9da6d5624 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/legacyviewmanagerinterop/platform/ios/react/renderer/components/legacyviewmanagerinterop/LegacyViewManagerInteropComponentDescriptor.h +++ b/packages/react-native/ReactCommon/react/renderer/components/legacyviewmanagerinterop/platform/ios/react/renderer/components/legacyviewmanagerinterop/LegacyViewManagerInteropComponentDescriptor.h @@ -19,7 +19,8 @@ class LegacyViewManagerInteropComponentDescriptor final public: using ConcreteComponentDescriptor::ConcreteComponentDescriptor; - LegacyViewManagerInteropComponentDescriptor(const ComponentDescriptorParameters ¶meters); + LegacyViewManagerInteropComponentDescriptor( + const ComponentDescriptorParameters& parameters); /* * Returns `name` and `handle` based on a `flavor`, not on static data from * `LegacyViewManagerInteropShadowNode`. @@ -28,7 +29,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/modal/ModalHostViewComponentDescriptor.h b/packages/react-native/ReactCommon/react/renderer/components/modal/ModalHostViewComponentDescriptor.h index f48c41fb114d..51f60b9c503f 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/modal/ModalHostViewComponentDescriptor.h +++ b/packages/react-native/ReactCommon/react/renderer/components/modal/ModalHostViewComponentDescriptor.h @@ -17,27 +17,36 @@ 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(); - - layoutableShadowNode.setSize(Size{.width = stateData.screenSize.width, .height = stateData.screenSize.height}); + 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.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 3964dee4b933..7a37ba1885ff 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/modal/ModalHostViewShadowNode.h +++ b/packages/react-native/ReactCommon/react/renderer/components/modal/ModalHostViewShadowNode.h @@ -27,8 +27,7 @@ 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 eec349a35fbb..76879cf7347b 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/modal/ModalHostViewState.h +++ b/packages/react-native/ReactCommon/react/renderer/components/modal/ModalHostViewState.h @@ -25,13 +25,15 @@ 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 5806aa51093c..5de417806352 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,27 +16,31 @@ namespace facebook::react { /* * Descriptor for component. */ -class AndroidProgressBarComponentDescriptor final : public ConcreteComponentDescriptor { +class AndroidProgressBarComponentDescriptor final + : public ConcreteComponentDescriptor { public: - AndroidProgressBarComponentDescriptor(const ComponentDescriptorParameters ¶meters) + AndroidProgressBarComponentDescriptor( + const ComponentDescriptorParameters& parameters) : 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 d9aa7a46a685..9eeb3bee3c4f 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,12 +16,14 @@ 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 92b4dc61f8b0..7b28d992ba64 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,8 +26,7 @@ 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); @@ -36,11 +35,14 @@ 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 92f0201a2cac..8d636a7019f1 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,8 +14,7 @@ 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.h b/packages/react-native/ReactCommon/react/renderer/components/root/RootProps.h index 1003f5202f83..57423128c5f6 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/root/RootProps.h +++ b/packages/react-native/ReactCommon/react/renderer/components/root/RootProps.h @@ -19,12 +19,15 @@ 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 LayoutConstraints &layoutConstraints, - const LayoutContext &layoutContext); + const PropsParserContext& context, + const RootProps& sourceProps, + const RawProps& rawProps); + RootProps( + 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 2676a1307689..fce4754d52c9 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,15 +44,16 @@ class RootShadowNode final : public ConcreteViewShadowNode *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 a03c7c968d2e..f8a391570443 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/safeareaview/SafeAreaViewComponentDescriptor.h +++ b/packages/react-native/ReactCommon/react/renderer/components/safeareaview/SafeAreaViewComponentDescriptor.h @@ -15,12 +15,15 @@ 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 ed073709833f..43c9f1320558 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/safeareaview/SafeAreaViewShadowNode.h +++ b/packages/react-native/ReactCommon/react/renderer/components/safeareaview/SafeAreaViewShadowNode.h @@ -20,8 +20,11 @@ extern const char SafeAreaViewComponentName[]; /* * `ShadowNode` for component. */ -class SafeAreaViewShadowNode final - : public ConcreteViewShadowNode { +class SafeAreaViewShadowNode final : public ConcreteViewShadowNode< + SafeAreaViewComponentName, + SafeAreaViewProps, + ViewEventEmitter, + SafeAreaViewState> { 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 7ca383fdb510..355440875323 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/safeareaview/SafeAreaViewState.h +++ b/packages/react-native/ReactCommon/react/renderer/components/safeareaview/SafeAreaViewState.h @@ -23,14 +23,15 @@ 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 f6de1cd07fd5..0ea853b9b361 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/scrollview/BaseScrollViewProps.h +++ b/packages/react-native/ReactCommon/react/renderer/components/scrollview/BaseScrollViewProps.h @@ -20,12 +20,15 @@ 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 @@ -43,7 +46,8 @@ 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}; @@ -65,7 +69,8 @@ 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 fb2cd8b44fd5..a9fccb459a6b 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/scrollview/ScrollEvent.h +++ b/packages/react-native/ReactCommon/react/renderer/components/scrollview/ScrollEvent.h @@ -34,10 +34,11 @@ 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 { @@ -46,23 +47,22 @@ 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 84415e8fd377..bde164951fad 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/scrollview/ScrollViewComponentDescriptor.h +++ b/packages/react-native/ReactCommon/react/renderer/components/scrollview/ScrollViewComponentDescriptor.h @@ -12,6 +12,7 @@ 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 a3ae532996f3..23be8b1f15d9 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/scrollview/ScrollViewEventEmitter.h +++ b/packages/react-native/ReactCommon/react/renderer/components/scrollview/ScrollViewEventEmitter.h @@ -22,15 +22,16 @@ 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 0362662ccf5b..a0fbcf4ca1e9 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/scrollview/ScrollViewShadowNode.h +++ b/packages/react-native/ReactCommon/react/renderer/components/scrollview/ScrollViewShadowNode.h @@ -21,15 +21,18 @@ extern const char ScrollViewComponentName[]; /* * `ShadowNode` for component. */ -class ScrollViewShadowNode final - : public ConcreteViewShadowNode { +class ScrollViewShadowNode final : public ConcreteViewShadowNode< + ScrollViewComponentName, + ScrollViewProps, + ScrollViewEventEmitter, + ScrollViewState> { 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 72d706a1abd1..821393e3e56d 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/scrollview/ScrollViewState.h +++ b/packages/react-native/ReactCommon/react/renderer/components/scrollview/ScrollViewState.h @@ -23,7 +23,10 @@ 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; @@ -44,14 +47,16 @@ 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 bd1b92fcb1dd..ff0534154af1 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/scrollview/conversions.h +++ b/packages/react-native/ReactCommon/react/renderer/components/scrollview/conversions.h @@ -14,8 +14,10 @@ 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; @@ -32,8 +34,10 @@ inline void fromRawValue(const PropsParserContext &context, const RawValue &valu 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; @@ -50,9 +54,10 @@ inline void fromRawValue(const PropsParserContext &context, const RawValue &valu 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; @@ -69,9 +74,10 @@ fromRawValue(const PropsParserContext &context, const RawValue &value, ScrollVie 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; @@ -92,23 +98,27 @@ fromRawValue(const PropsParserContext &context, const RawValue &value, ContentIn 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"; @@ -121,8 +131,7 @@ 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"; @@ -133,8 +142,7 @@ 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"; @@ -145,8 +153,7 @@ 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"; @@ -159,13 +166,14 @@ 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 c8f62f28c496..bd93114bad8b 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,12 +18,15 @@ 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 @@ -40,7 +43,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 cb75ebb7ac16..56d66bfd9d1f 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/scrollview/primitives.h +++ b/packages/react-native/ReactCommon/react/renderer/components/scrollview/primitives.h @@ -18,14 +18,20 @@ 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 = default; + bool operator==(const ScrollViewMaintainVisibleContentPosition& rhs) const = + default; }; } // namespace facebook::react 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 1f1e2e177427..841d5be49e03 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,23 +17,25 @@ namespace facebook::react { /* * Descriptor for component. */ -class AndroidSwitchComponentDescriptor final : public ConcreteComponentDescriptor { +class AndroidSwitchComponentDescriptor final + : public ConcreteComponentDescriptor { public: - AndroidSwitchComponentDescriptor(const ComponentDescriptorParameters ¶meters) + AndroidSwitchComponentDescriptor( + const ComponentDescriptorParameters& parameters) : 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 370aad59a462..37ea646899c3 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,10 +15,9 @@ 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 491426f40207..c79ea2fbf1d0 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,13 +21,14 @@ extern const char AndroidSwitchComponentName[]; /* * `ShadowNode` for component. */ -class AndroidSwitchShadowNode final - : public ConcreteViewShadowNode { +class AndroidSwitchShadowNode final : public ConcreteViewShadowNode< + AndroidSwitchComponentName, + AndroidSwitchProps, + AndroidSwitchEventEmitter> { public: using ConcreteViewShadowNode::ConcreteViewShadowNode; - static ShadowNodeTraits BaseTraits() - { + static ShadowNodeTraits BaseTraits() { auto traits = ConcreteViewShadowNode::BaseTraits(); traits.set(ShadowNodeTraits::Trait::LeafYogaNode); traits.set(ShadowNodeTraits::Trait::MeasurableYogaNode); @@ -36,11 +37,14 @@ class AndroidSwitchShadowNode final // 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 0d39a055f06a..de4cef29aaa3 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,14 +16,13 @@ namespace facebook::react { /* * Descriptor for component. */ -class SwitchComponentDescriptor final : public ConcreteComponentDescriptor { +class SwitchComponentDescriptor final + : public ConcreteComponentDescriptor { public: - SwitchComponentDescriptor(const ComponentDescriptorParameters ¶meters) : ConcreteComponentDescriptor(parameters) - { - } + SwitchComponentDescriptor(const ComponentDescriptorParameters& parameters) + : 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 878a2cc81774..2cffdf139f5d 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,13 +18,14 @@ extern const char AppleSwitchComponentName[]; /* * `ShadowNode` for component. */ -class SwitchShadowNode final - : public ConcreteViewShadowNode { +class SwitchShadowNode final : public ConcreteViewShadowNode< + AppleSwitchComponentName, + SwitchProps, + SwitchEventEmitter> { public: using ConcreteViewShadowNode::ConcreteViewShadowNode; - static ShadowNodeTraits BaseTraits() - { + static ShadowNodeTraits BaseTraits() { auto traits = ConcreteViewShadowNode::BaseTraits(); traits.set(ShadowNodeTraits::Trait::LeafYogaNode); traits.set(ShadowNodeTraits::Trait::MeasurableYogaNode); @@ -33,7 +34,9 @@ class SwitchShadowNode final #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/BaseParagraphComponentDescriptor.h b/packages/react-native/ReactCommon/react/renderer/components/text/BaseParagraphComponentDescriptor.h index 8c7c8aab798f..9ad4cd7e5ed7 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/text/BaseParagraphComponentDescriptor.h +++ b/packages/react-native/ReactCommon/react/renderer/components/text/BaseParagraphComponentDescriptor.h @@ -13,28 +13,28 @@ namespace facebook::react { -constexpr const char *const TextLayoutManagerKey = "TextLayoutManager"; +constexpr const char* const TextLayoutManagerKey = "TextLayoutManager"; template -class BaseParagraphComponentDescriptor : public ConcreteComponentDescriptor { +class BaseParagraphComponentDescriptor + : public ConcreteComponentDescriptor { public: - explicit BaseParagraphComponentDescriptor(const ComponentDescriptorParameters ¶meters) + explicit BaseParagraphComponentDescriptor( + const ComponentDescriptorParameters& parameters) : ConcreteComponentDescriptor(parameters), - textLayoutManager_(getManagerByName(this->contextContainer_, TextLayoutManagerKey)) - { - } + textLayoutManager_(getManagerByName( + this->contextContainer_, + TextLayoutManagerKey)) {} - ComponentName getComponentName() const override - { + ComponentName getComponentName() const override { return ShadowNodeT::Name(); } protected: - void adopt(ShadowNode &shadowNode) const override - { + void adopt(ShadowNode& shadowNode) const override { ConcreteComponentDescriptor::adopt(shadowNode); - auto ¶graphShadowNode = static_cast(shadowNode); + auto& paragraphShadowNode = 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/BaseParagraphProps.h b/packages/react-native/ReactCommon/react/renderer/components/text/BaseParagraphProps.h index 72ba6e0fb3dd..defabb15fa45 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/text/BaseParagraphProps.h +++ b/packages/react-native/ReactCommon/react/renderer/components/text/BaseParagraphProps.h @@ -27,12 +27,15 @@ class BaseParagraphProps : public ViewProps, public BaseTextProps { public: BaseParagraphProps() = default; BaseParagraphProps( - const PropsParserContext &context, - const BaseParagraphProps &sourceProps, - const RawProps &rawProps); - - void - setProp(const PropsParserContext &context, RawPropsPropNameHash hash, const char *propName, const RawValue &value); + const PropsParserContext& context, + const BaseParagraphProps& sourceProps, + const RawProps& rawProps); + + 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.h b/packages/react-native/ReactCommon/react/renderer/components/text/BaseTextProps.h index 732288d87c44..12d113d62490 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/text/BaseTextProps.h +++ b/packages/react-native/ReactCommon/react/renderer/components/text/BaseTextProps.h @@ -21,10 +21,16 @@ 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 @@ -37,7 +43,9 @@ 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.h b/packages/react-native/ReactCommon/react/renderer/components/text/BaseTextShadowNode.h index 09d88b9b3c43..5d50e92a2c96 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 3f64c6e8cb7a..fd709394174b 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/text/ParagraphComponentDescriptor.h +++ b/packages/react-native/ReactCommon/react/renderer/components/text/ParagraphComponentDescriptor.h @@ -14,7 +14,8 @@ namespace facebook::react { /* * Descriptor for component. */ -class ParagraphComponentDescriptor final : public BaseParagraphComponentDescriptor { +class ParagraphComponentDescriptor final + : public BaseParagraphComponentDescriptor { public: using BaseParagraphComponentDescriptor::BaseParagraphComponentDescriptor; }; 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 d571b914d874..c9af92e99e02 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.h b/packages/react-native/ReactCommon/react/renderer/components/text/ParagraphShadowNode.h index 704088cbaae6..77c599ec5460 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/text/ParagraphShadowNode.h +++ b/packages/react-native/ReactCommon/react/renderer/components/text/ParagraphShadowNode.h @@ -26,21 +26,25 @@ extern const char ParagraphComponentName[]; * containing and displaying text. Text content is represented as nested * and components. */ -class ParagraphShadowNode - : public ConcreteViewShadowNode, - public BaseTextShadowNode { +class ParagraphShadowNode : public ConcreteViewShadowNode< + ParagraphComponentName, + ParagraphProps, + ParagraphEventEmitter, + ParagraphState>, + 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); @@ -62,15 +66,18 @@ class ParagraphShadowNode * `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 @@ -84,41 +91,44 @@ class ParagraphShadowNode }; 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 MeasuredPreparedTextLayout &layout); + void updateStateIfNeeded( + const Content& content, + const MeasuredPreparedTextLayout& 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 */ - MeasuredPreparedTextLayout *findUsableLayout(); + MeasuredPreparedTextLayout* 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 92a67af3139b..1f50f7afc443 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/text/RawTextComponentDescriptor.h +++ b/packages/react-native/ReactCommon/react/renderer/components/text/RawTextComponentDescriptor.h @@ -12,6 +12,7 @@ namespace facebook::react { -using RawTextComponentDescriptor = ConcreteComponentDescriptor; +using RawTextComponentDescriptor = + ConcreteComponentDescriptor; } // namespace facebook::react 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 fb8cea5dbbcc..4a0862544130 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/text/RawTextProps.h +++ b/packages/react-native/ReactCommon/react/renderer/components/text/RawTextProps.h @@ -22,7 +22,10 @@ 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 @@ -36,7 +39,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 940916f8b483..7d04c781c081 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/text/RawTextShadowNode.h +++ b/packages/react-native/ReactCommon/react/renderer/components/text/RawTextShadowNode.h @@ -20,7 +20,10 @@ extern const char RawTextComponentName[]; * is represented as ``. * component must not have any children. */ -class RawTextShadowNode : public ConcreteShadowNode { +class RawTextShadowNode : public ConcreteShadowNode< + RawTextComponentName, + ShadowNode, + RawTextProps> { public: using ConcreteShadowNode::ConcreteShadowNode; }; diff --git a/packages/react-native/ReactCommon/react/renderer/components/text/SelectableParagraphShadowNode.h b/packages/react-native/ReactCommon/react/renderer/components/text/SelectableParagraphShadowNode.h index 8574dd601abd..b955a92d0dbd 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/text/SelectableParagraphShadowNode.h +++ b/packages/react-native/ReactCommon/react/renderer/components/text/SelectableParagraphShadowNode.h @@ -12,19 +12,18 @@ namespace facebook::react { /* - * ShadowNode for selectable Paragraph components, which may map to different native component than Paragraph. + * ShadowNode for selectable Paragraph components, which may map to different + * native component than Paragraph. */ class SelectableParagraphShadowNode : public ParagraphShadowNode { public: using ParagraphShadowNode::ParagraphShadowNode; - static constexpr ComponentName Name() - { + static constexpr ComponentName Name() { return "SelectableParagraph"; } - static ComponentHandle Handle() - { + static ComponentHandle Handle() { return ComponentHandle(Name()); } }; diff --git a/packages/react-native/ReactCommon/react/renderer/components/text/TextEffectComponentDescriptor.h b/packages/react-native/ReactCommon/react/renderer/components/text/TextEffectComponentDescriptor.h index 4fb2917f0ae6..fa62e391275c 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/text/TextEffectComponentDescriptor.h +++ b/packages/react-native/ReactCommon/react/renderer/components/text/TextEffectComponentDescriptor.h @@ -12,6 +12,7 @@ namespace facebook::react { -using TextEffectComponentDescriptor = ConcreteComponentDescriptor; +using TextEffectComponentDescriptor = + ConcreteComponentDescriptor; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/components/text/TextEffectProps.h b/packages/react-native/ReactCommon/react/renderer/components/text/TextEffectProps.h index 42cb2ffa62db..8550ee531dd7 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/text/TextEffectProps.h +++ b/packages/react-native/ReactCommon/react/renderer/components/text/TextEffectProps.h @@ -16,14 +16,17 @@ namespace facebook::react { class TextEffectProps : public Props { public: TextEffectProps() = default; - TextEffectProps(const PropsParserContext &context, const TextEffectProps &sourceProps, const RawProps &rawProps); + TextEffectProps( + const PropsParserContext& context, + const TextEffectProps& sourceProps, + const RawProps& rawProps); std::string effectName; folly::dynamic effectProps; #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/TextEffectShadowNode.h b/packages/react-native/ReactCommon/react/renderer/components/text/TextEffectShadowNode.h index 60185ce039b9..9b9c6b762d79 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/text/TextEffectShadowNode.h +++ b/packages/react-native/ReactCommon/react/renderer/components/text/TextEffectShadowNode.h @@ -17,8 +17,11 @@ extern const char TextEffectComponentName[]; using TextEffectEventEmitter = TouchEventEmitter; -class TextEffectShadowNode - : public ConcreteShadowNode { +class TextEffectShadowNode : public ConcreteShadowNode< + TextEffectComponentName, + ShadowNode, + TextEffectProps, + TextEffectEventEmitter> { public: using ConcreteShadowNode::ConcreteShadowNode; }; 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 164a8e5358cd..2cb00fc39cf7 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/text/TextProps.h +++ b/packages/react-native/ReactCommon/react/renderer/components/text/TextProps.h @@ -18,10 +18,16 @@ 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 @@ -31,7 +37,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 1fb00e59a255..695aba56cbc8 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/text/TextShadowNode.h +++ b/packages/react-native/ReactCommon/react/renderer/components/text/TextShadowNode.h @@ -20,11 +20,14 @@ extern const char TextComponentName[]; using TextEventEmitter = TouchEventEmitter; -class TextShadowNode : public ConcreteShadowNode, +class TextShadowNode : public ConcreteShadowNode< + TextComponentName, + ShadowNode, + TextProps, + TextEventEmitter>, public BaseTextShadowNode { public: - static ShadowNodeTraits BaseTraits() - { + static ShadowNodeTraits BaseTraits() { auto traits = ConcreteShadowNode::BaseTraits(); #ifdef ANDROID traits.set(ShadowNodeTraits::Trait::FormsView); @@ -35,11 +38,17 @@ class TextShadowNode : public ConcreteShadowNode; - - TextShadowNode(const ShadowNodeFragment &fragment, const ShadowNodeFamily::Shared &family, ShadowNodeTraits traits) - : BaseShadowNode(fragment, family, traits), BaseTextShadowNode() - { + using BaseShadowNode = ConcreteShadowNode< + TextComponentName, + ShadowNode, + TextProps, + TextEventEmitter>; + + 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.h b/packages/react-native/ReactCommon/react/renderer/components/text/platform/android/react/renderer/components/text/HostPlatformParagraphProps.h index 93b6f1002ff3..1082b822b3b1 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,12 +28,15 @@ 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 @@ -49,7 +52,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 6596b55a6acd..c4e4644c54b2 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,21 +65,22 @@ 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 5740fa5927ba..af246ab2b478 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,8 +14,10 @@ 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; @@ -32,8 +34,7 @@ inline void fromRawValue(const PropsParserContext & /*context*/, const RawValue } } -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 593671dcc928..42580904dbfd 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/text/stateConversions.h +++ b/packages/react-native/ReactCommon/react/renderer/components/text/stateConversions.h @@ -17,8 +17,7 @@ namespace facebook::react { #ifdef RN_SERIALIZABLE_STATE -inline MapBuffer toMapBuffer(const ParagraphState ¶graphState) -{ +inline MapBuffer toMapBuffer(const ParagraphState& paragraphState) { 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/textinput/BaseTextInputProps.h b/packages/react-native/ReactCommon/react/renderer/components/textinput/BaseTextInputProps.h index 8994a42231e7..5802350a2ee9 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/textinput/BaseTextInputProps.h +++ b/packages/react-native/ReactCommon/react/renderer/components/textinput/BaseTextInputProps.h @@ -22,12 +22,15 @@ class BaseTextInputProps : public ViewProps, public BaseTextProps { public: BaseTextInputProps() = default; BaseTextInputProps( - const PropsParserContext &context, - const BaseTextInputProps &sourceProps, - const RawProps &rawProps); - - void - setProp(const PropsParserContext &context, RawPropsPropNameHash hash, const char *propName, const RawValue &value); + const PropsParserContext& context, + const BaseTextInputProps& sourceProps, + const RawProps& rawProps); + + 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 8fef1a5f9571..a8cf1c5e541d 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/textinput/BaseTextInputShadowNode.h +++ b/packages/react-native/ReactCommon/react/renderer/components/textinput/BaseTextInputShadowNode.h @@ -25,8 +25,7 @@ namespace facebook::react { -inline ShadowView shadowViewFromShadowNode(const ShadowNode &shadowNode) -{ +inline ShadowView shadowViewFromShadowNode(const ShadowNode& shadowNode) { auto shadowView = ShadowView{shadowNode}; // Clearing `props` and `state` (which we don't use) allows avoiding retain // cycles. @@ -38,17 +37,27 @@ inline ShadowView shadowViewFromShadowNode(const ShadowNode &shadowNode) /* * Base `ShadowNode` for component. */ -template -class BaseTextInputShadowNode - : public ConcreteViewShadowNode, - public BaseTextShadowNode { +template < + const char* concreteComponentName, + typename ViewPropsT, + typename ViewEventEmitterT, + typename StateDataT> +class BaseTextInputShadowNode : public ConcreteViewShadowNode< + concreteComponentName, + ViewPropsT, + ViewEventEmitterT, + StateDataT>, + public BaseTextShadowNode { public: - using BaseShadowNode = ConcreteViewShadowNode; + using BaseShadowNode = ConcreteViewShadowNode< + concreteComponentName, + ViewPropsT, + ViewEventEmitterT, + StateDataT>; using BaseShadowNode::ConcreteViewShadowNode; - static ShadowNodeTraits BaseTraits() - { + static ShadowNodeTraits BaseTraits() { auto traits = BaseShadowNode::BaseTraits(); traits.set(ShadowNodeTraits::Trait::LeafYogaNode); traits.set(ShadowNodeTraits::Trait::MeasurableYogaNode); @@ -61,16 +70,17 @@ class BaseTextInputShadowNode * `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{ @@ -88,15 +98,13 @@ class BaseTextInputShadowNode 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()) { @@ -106,17 +114,22 @@ class BaseTextInputShadowNode // 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; } } @@ -124,8 +137,8 @@ class BaseTextInputShadowNode /* * 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 { @@ -151,42 +164,42 @@ class BaseTextInputShadowNode /* * 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 = shadowViewFromShadowNode(*this)}); + attributedString.appendFragment(AttributedString::Fragment{ + .string = props.text, + .textAttributes = textAttributes, + .parentShadowView = shadowViewFromShadowNode(*this)}); auto attachments = BaseTextShadowNode::Attachments{}; - BaseTextShadowNode::buildAttributedString(textAttributes, *this, attributedString, attachments); + BaseTextShadowNode::buildAttributedString( + textAttributes, *this, attributedString, attachments); attributedString.setBaseTextAttributes(textAttributes); return attributedString; } @@ -196,22 +209,27 @@ class BaseTextInputShadowNode * 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); @@ -219,12 +237,13 @@ class BaseTextInputShadowNode 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 a3f2e01c130c..dbce57515938 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/textinput/TextInputEventEmitter.h +++ b/packages/react-native/ReactCommon/react/renderer/components/textinput/TextInputEventEmitter.h @@ -35,23 +35,25 @@ 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 9f728d9335f5..d278f6818b75 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/textinput/TextInputState.h +++ b/packages/react-native/ReactCommon/react/renderer/components/textinput/TextInputState.h @@ -28,9 +28,7 @@ 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 de4bcdc64436..8acd9781c379 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/textinput/baseConversions.h +++ b/packages/react-native/ReactCommon/react/renderer/components/textinput/baseConversions.h @@ -14,8 +14,10 @@ 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; @@ -28,8 +30,7 @@ inline void fromRawValue(const PropsParserContext & /*context*/, const RawValue } } -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 fb44034605b5..bdb6e7a99a03 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,87 +24,102 @@ namespace facebook::react { /* * Descriptor for component. */ -class AndroidTextInputComponentDescriptor final : public ConcreteComponentDescriptor { +class AndroidTextInputComponentDescriptor final + : public ConcreteComponentDescriptor { public: - AndroidTextInputComponentDescriptor(const ComponentDescriptorParameters ¶meters) + AndroidTextInputComponentDescriptor( + const ComponentDescriptorParameters& parameters) : 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 @@ -112,11 +127,13 @@ class AndroidTextInputComponentDescriptor final : public ConcreteComponentDescri // 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()); } @@ -144,7 +161,8 @@ class AndroidTextInputComponentDescriptor final : public ConcreteComponentDescri }; // 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 d43f97bf811f..26753b62d728 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 @@ fromRawValue(const PropsParserContext &context, const RawValue &value, AndroidTe } } -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,12 +66,15 @@ 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; @@ -131,7 +134,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.h b/packages/react-native/ReactCommon/react/renderer/components/textinput/platform/android/react/renderer/components/androidtextinput/AndroidTextInputShadowNode.h index 8a1d6d969904..97e0b18664fb 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,8 +30,7 @@ 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); @@ -44,40 +43,47 @@ 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 9655ba81a762..b5d5eec15229 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,18 +31,22 @@ 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 4ad058cf7a5c..c361114f6533 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,20 +15,19 @@ namespace facebook::react { /* * Descriptor for component. */ -class TextInputComponentDescriptor final : public ConcreteComponentDescriptor { +class TextInputComponentDescriptor final + : public ConcreteComponentDescriptor { public: - TextInputComponentDescriptor(const ComponentDescriptorParameters ¶meters) + TextInputComponentDescriptor(const ComponentDescriptorParameters& parameters) : 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.h b/packages/react-native/ReactCommon/react/renderer/components/textinput/platform/ios/react/renderer/components/iostextinput/TextInputProps.h index 317fff3cbf62..40964f33d171 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,7 +23,10 @@ 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 96e9de4525a6..af9524b605fe 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,8 +19,11 @@ extern const char TextInputComponentName[]; /* * `ShadowNode` for component. */ -class TextInputShadowNode final - : public BaseTextInputShadowNode { +class TextInputShadowNode final : public BaseTextInputShadowNode< + TextInputComponentName, + TextInputProps, + TextInputEventEmitter, + TextInputState> { 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 9de9d0e8831e..bf967317c760 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,8 +13,10 @@ 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; @@ -35,8 +37,10 @@ inline void fromRawValue(const PropsParserContext &context, const RawValue &valu 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; @@ -53,8 +57,10 @@ inline void fromRawValue(const PropsParserContext &context, const RawValue &valu 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; @@ -119,9 +125,10 @@ inline void fromRawValue(const PropsParserContext &context, const RawValue &valu 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; @@ -142,8 +149,10 @@ fromRawValue(const PropsParserContext &context, const RawValue &value, TextInput 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 942eeeb8805b..a5ace05d6424 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,7 +92,8 @@ 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`. @@ -147,7 +148,8 @@ 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 54921b3fca46..8039fbf56b1c 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,20 +15,36 @@ 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, @@ -36,45 +52,107 @@ 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 bd96cf9156b4..e73046568de7 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/unimplementedview/UnimplementedViewComponentDescriptor.h +++ b/packages/react-native/ReactCommon/react/renderer/components/unimplementedview/UnimplementedViewComponentDescriptor.h @@ -16,7 +16,8 @@ namespace facebook::react { /* * Descriptor for component. */ -class UnimplementedViewComponentDescriptor final : public ConcreteComponentDescriptor { +class UnimplementedViewComponentDescriptor final + : public ConcreteComponentDescriptor { public: using ConcreteComponentDescriptor::ConcreteComponentDescriptor; @@ -31,8 +32,10 @@ class UnimplementedViewComponentDescriptor final : public ConcreteComponentDescr * 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 46490716e4be..93a5833fa5bc 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 ea9f75a8b35f..405c81e647fd 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/unimplementedview/UnimplementedViewShadowNode.h +++ b/packages/react-native/ReactCommon/react/renderer/components/unimplementedview/UnimplementedViewShadowNode.h @@ -14,6 +14,8 @@ namespace facebook::react { extern const char UnimplementedViewComponentName[]; -using UnimplementedViewShadowNode = ConcreteViewShadowNode; +using UnimplementedViewShadowNode = ConcreteViewShadowNode< + UnimplementedViewComponentName, + UnimplementedViewProps>; } // 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 07452872140d..5caacd7da2b6 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/view/AccessibilityPrimitives.h +++ b/packages/react-native/ReactCommon/react/renderer/components/view/AccessibilityPrimitives.h @@ -36,13 +36,15 @@ 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); } @@ -51,8 +53,9 @@ 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; } @@ -65,18 +68,21 @@ struct AccessibilityState { CheckedState checked{CheckedState::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; } 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; } @@ -87,9 +93,11 @@ 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; } enum class ImportantForAccessibility : uint8_t { 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 c664b8461e2f..7c798c1cf3e0 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/view/AccessibilityProps.h +++ b/packages/react-native/ReactCommon/react/renderer/components/view/AccessibilityProps.h @@ -19,12 +19,15 @@ 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 @@ -33,7 +36,8 @@ 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; @@ -53,7 +57,8 @@ 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.h b/packages/react-native/ReactCommon/react/renderer/components/view/BackgroundImagePropsConversions.h index aaea4da730db..d33c701c0121 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/view/BackgroundImagePropsConversions.h +++ b/packages/react-native/ReactCommon/react/renderer/components/view/BackgroundImagePropsConversions.h @@ -15,24 +15,29 @@ 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); - -void parseUnprocessedBackgroundImageString(const std::string &value, std::vector &result); - -inline void fromRawValue(const PropsParserContext &context, const RawValue &value, std::vector &result) -{ + const PropsParserContext& context, + const std::vector& 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) { 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 c8473d65b388..eeeabd8c9a18 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/view/BaseTouch.h +++ b/packages/react-native/ReactCommon/react/renderer/components/view/BaseTouch.h @@ -69,26 +69,29 @@ 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 e556d1e97547..4b3c59b95bfc 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,7 +64,8 @@ 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 7554ba7cad86..b1c3f33e394b 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/view/BaseViewProps.h +++ b/packages/react-native/ReactCommon/react/renderer/components/view/BaseViewProps.h @@ -32,13 +32,17 @@ class BaseViewProps : public YogaStylableProps, public AccessibilityProps { public: BaseViewProps() = default; BaseViewProps( - 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); + 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); #pragma mark - Props @@ -112,12 +116,14 @@ 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 c3cb54348757..89c7d2413755 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/view/BoxShadowPropsConversions.h +++ b/packages/react-native/ReactCommon/react/renderer/components/view/BoxShadowPropsConversions.h @@ -22,9 +22,10 @@ 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 = {}; @@ -33,8 +34,9 @@ parseProcessedBoxShadow(const PropsParserContext &context, const RawValue &value 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 @@ -43,7 +45,8 @@ parseProcessedBoxShadow(const PropsParserContext &context, const RawValue &value return; } - auto rawBoxShadowMap = static_cast>(rawBoxShadow); + auto rawBoxShadowMap = + static_cast>(rawBoxShadow); BoxShadow boxShadow{}; auto offsetX = rawBoxShadowMap.find("offsetX"); react_native_expect(offsetX != rawBoxShadowMap.end()); @@ -103,7 +106,11 @@ parseProcessedBoxShadow(const PropsParserContext &context, const RawValue &value 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); @@ -112,11 +119,12 @@ parseProcessedBoxShadow(const PropsParserContext &context, const RawValue &value 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 {}; } @@ -130,15 +138,16 @@ 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 { @@ -148,8 +157,9 @@ inline void parseUnprocessedBoxShadowString(std::string &&value, std::vector parseBoxShadowRawValue(const PropsParserContext &context, const RawValue &value) -{ +inline std::optional parseBoxShadowRawValue( + const PropsParserContext& context, + const RawValue& value) { if (!value.hasType>()) { return {}; } @@ -225,11 +235,10 @@ inline std::optional parseBoxShadowRawValue(const PropsParserContext } 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 { @@ -239,20 +248,24 @@ 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 de02ce2016f6..9ed428ae24dc 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,8 +42,7 @@ 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; } @@ -57,8 +56,9 @@ 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,8 +72,7 @@ inline SharedColor coerceColor(const RawValue &value, const PropsParserContext & 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 3d7d68a95936..ca3578c8d5f3 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/view/ConcreteViewShadowNode.h +++ b/packages/react-native/ReactCommon/react/renderer/components/view/ConcreteViewShadowNode.h @@ -23,7 +23,7 @@ namespace facebook::react { * For example: , , but not , . */ template < - const char *concreteComponentName, + const char* concreteComponentName, typename ViewPropsT = ViewProps, typename ViewEventEmitterT = ViewEventEmitter, typename StateDataT = StateData> @@ -34,7 +34,9 @@ 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"); @@ -43,21 +45,25 @@ class ConcreteViewShadowNode : public ConcreteShadowNode< "ViewPropsT must be a descendant of AccessibilityProps"); public: - using BaseShadowNode = - ConcreteShadowNode; + using BaseShadowNode = ConcreteShadowNode< + concreteComponentName, + YogaLayoutableShadowNode, + ViewPropsT, + ViewEventEmitterT, + StateDataT>; 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(); } @@ -65,8 +71,7 @@ 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); @@ -74,28 +79,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); @@ -110,7 +115,9 @@ 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 c24851104535..f1eafc616196 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/view/FilterPropsConversions.h +++ b/packages/react-native/ReactCommon/react/renderer/components/view/FilterPropsConversions.h @@ -22,9 +22,10 @@ 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 = {}; @@ -33,8 +34,9 @@ parseProcessedFilter(const PropsParserContext &context, const RawValue &value, s 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 @@ -43,17 +45,22 @@ parseProcessedFilter(const PropsParserContext &context, const RawValue &value, s return; } - auto rawFilterFunction = static_cast>(rawFilterPrimitive); + auto rawFilterFunction = + static_cast>( + rawFilterPrimitive); FilterFunction filterFunction{}; auto filterType = filterTypeFromString(rawFilterFunction.begin()->first); if (!filterType.has_value()) { - LOG(ERROR) << "Could not parse FilterFunction: " << rawFilterFunction.begin()->first; + LOG(ERROR) << "Could not parse FilterFunction: " + << rawFilterFunction.begin()->first; result = {}; return; } filterFunction.type = *filterType; 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"); @@ -95,7 +102,11 @@ parseProcessedFilter(const PropsParserContext &context, const RawValue &value, s 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; @@ -108,10 +119,9 @@ parseProcessedFilter(const PropsParserContext &context, const RawValue &value, s result = filter; } -inline FilterType filterTypeFromVariant(const CSSFilterFunction &filter) -{ +inline FilterType filterTypeFromVariant(const CSSFilterFunction& filter) { return std::visit( - [](auto &&filter) -> FilterType { + [](auto&& filter) -> FilterType { using FilterT = std::decay_t; if constexpr (std::is_same_v) { @@ -148,10 +158,10 @@ inline FilterType filterTypeFromVariant(const CSSFilterFunction &filter) filter); } -inline std::optional fromCSSFilter(const CSSFilterFunction &cssFilter) -{ +inline std::optional fromCSSFilter( + const CSSFilterFunction& cssFilter) { return std::visit( - [&](auto &&filter) -> std::optional { + [&](auto&& filter) -> std::optional { using FilterT = std::decay_t; if constexpr (std::is_same_v) { @@ -167,7 +177,8 @@ inline std::optional fromCSSFilter(const CSSFilterFunction &cssF 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 {}; } @@ -183,9 +194,12 @@ inline std::optional fromCSSFilter(const CSSFilterFunction &cssF } 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), @@ -203,15 +217,16 @@ inline std::optional fromCSSFilter(const CSSFilterFunction &cssF 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 { @@ -221,10 +236,12 @@ inline void parseUnprocessedFilterString(std::string &&value, std::vector 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)); } @@ -234,7 +251,8 @@ inline std::optional parseDropShadow(const PropsParserContext &c if (!value.hasType>()) { return {}; } - auto rawDropShadow = static_cast>(value); + auto rawDropShadow = + static_cast>(value); DropShadowParams dropShadowParams{}; @@ -262,7 +280,8 @@ inline std::optional parseDropShadow(const PropsParserContext &c 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 {}; } @@ -281,21 +300,24 @@ inline std::optional parseDropShadow(const PropsParserContext &c } } - 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); @@ -309,7 +331,8 @@ inline std::optional parseFilterRawValue(const PropsParserContex 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 { @@ -328,11 +351,10 @@ inline std::optional parseFilterRawValue(const PropsParserContex } 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 { @@ -342,9 +364,10 @@ 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>()) { @@ -354,8 +377,10 @@ parseUnprocessedFilter(const PropsParserContext &context, const RawValue &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) { 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 39250be8df81..fdeae8854e76 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/view/LayoutConformanceComponentDescriptor.h +++ b/packages/react-native/ReactCommon/react/renderer/components/view/LayoutConformanceComponentDescriptor.h @@ -12,6 +12,7 @@ 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 6e80c3508e6f..7425ece1123e 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/view/LayoutConformanceProps.h +++ b/packages/react-native/ReactCommon/react/renderer/components/view/LayoutConformanceProps.h @@ -21,13 +21,16 @@ 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 9621c6295b1c..2f1cfdd89eb4 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/view/LayoutConformanceShadowNode.h +++ b/packages/react-native/ReactCommon/react/renderer/components/view/LayoutConformanceShadowNode.h @@ -14,12 +14,14 @@ 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 218782c5e684..9f4e029963e5 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/view/PointerEvent.h +++ b/packages/react-native/ReactCommon/react/renderer/components/view/PointerEvent.h @@ -119,15 +119,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 94819dc3cbf1..299f332d42e2 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/view/TouchEvent.h +++ b/packages/react-native/ReactCommon/react/renderer/components/view/TouchEvent.h @@ -39,9 +39,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 7f8fa707cc9a..517205118330 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/view/TouchEventEmitter.h +++ b/packages/react-native/ReactCommon/react/renderer/components/view/TouchEventEmitter.h @@ -43,8 +43,14 @@ 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 e1958134b4c8..e2581d311689 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/view/ViewComponentDescriptor.h +++ b/packages/react-native/ReactCommon/react/renderer/components/view/ViewComponentDescriptor.h @@ -12,12 +12,11 @@ namespace facebook::react { -class ViewComponentDescriptor : public ConcreteComponentDescriptor { +class ViewComponentDescriptor + : public ConcreteComponentDescriptor { public: - ViewComponentDescriptor(const ComponentDescriptorParameters ¶meters) - : ConcreteComponentDescriptor(parameters) - { - } + ViewComponentDescriptor(const ComponentDescriptorParameters& parameters) + : 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 55bf085c7d25..c9ad50ca5b8b 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/view/ViewPropsInterpolation.h +++ b/packages/react-native/ReactCommon/react/renderer/components/view/ViewPropsInterpolation.h @@ -23,19 +23,24 @@ 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())); - - interpolatedProps->opacity = - oldViewProps->opacity + (newViewProps->opacity - oldViewProps->opacity) * animationProgress; - interpolatedProps->transform = - Transform::Interpolate(animationProgress, oldViewProps->transform, newViewProps->transform, size); + 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); // Android uses RawProps, not props, to update props on the platform... // Since interpolated props don't interpolate at all using RawProps, we need @@ -48,7 +53,8 @@ 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.h b/packages/react-native/ReactCommon/react/renderer/components/view/ViewShadowNode.h index bc1a94e52ede..21e736c3bc4e 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/view/ViewShadowNode.h +++ b/packages/react-native/ReactCommon/react/renderer/components/view/ViewShadowNode.h @@ -20,11 +20,19 @@ using ViewShadowNodeProps = ViewProps; /* * `ShadowNode` for component. */ -class ViewShadowNode final : public ConcreteViewShadowNode { +class ViewShadowNode final : public ConcreteViewShadowNode< + ViewComponentName, + ViewProps, + ViewEventEmitter> { public: - ViewShadowNode(const ShadowNodeFragment &fragment, const ShadowNodeFamily::Shared &family, ShadowNodeTraits traits); - - ViewShadowNode(const ShadowNode &sourceShadowNode, const ShadowNodeFragment &fragment); + ViewShadowNode( + const ShadowNodeFragment& fragment, + const ShadowNodeFamily::Shared& family, + ShadowNodeTraits traits); + + ViewShadowNode( + const ShadowNode& sourceShadowNode, + const ShadowNodeFragment& fragment); private: void initialize() noexcept; 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 905b98ecaa66..5b600eb03c35 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/view/YogaLayoutableShadowNode.h +++ b/packages/react-native/ReactCommon/react/renderer/components/view/YogaLayoutableShadowNode.h @@ -34,13 +34,17 @@ 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 @@ -50,10 +54,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(); @@ -81,7 +85,9 @@ 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; @@ -92,8 +98,9 @@ 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. @@ -114,14 +121,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 @@ -134,8 +141,11 @@ class YogaLayoutableShadowNode : public LayoutableShadowNode { * ShadowTree has been constructed, but before it has been is laid out or * committed. */ - void - configureYogaTree(float pointScaleFactor, Float fontSizeMultiplier, YGErrata defaultErrata, bool swapLeftAndRight); + void configureYogaTree( + float pointScaleFactor, + Float fontSizeMultiplier, + YGErrata defaultErrata, + bool swapLeftAndRight); /** * Return an errata based on a `layoutConformance` prop if given, otherwise @@ -146,19 +156,27 @@ 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 @@ -195,7 +213,9 @@ 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 6febf08d5ce4..1f7dfa908a98 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/view/YogaStylableProps.h +++ b/packages/react-native/ReactCommon/react/renderer/components/view/YogaStylableProps.h @@ -19,13 +19,17 @@ class YogaStylableProps : public Props { public: YogaStylableProps() = default; YogaStylableProps( - 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); + 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); #pragma mark - Props yoga::Style yogaStyle{}; @@ -67,9 +71,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 d9c0283a025e..a7c412ad802e 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/view/accessibilityPropsConversions.h +++ b/packages/react-native/ReactCommon/react/renderer/components/view/accessibilityPropsConversions.h @@ -19,8 +19,7 @@ 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,8 +107,10 @@ 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; @@ -120,7 +121,7 @@ inline void fromRawValue(const PropsParserContext &context, const RawValue &valu 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; @@ -130,8 +131,10 @@ inline void fromRawValue(const PropsParserContext &context, const RawValue &valu } } -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()) { @@ -169,8 +172,8 @@ inline void fromRawValue(const PropsParserContext &context, const RawValue &valu } } -inline std::string toString(const ImportantForAccessibility &importantForAccessibility) -{ +inline std::string toString( + const ImportantForAccessibility& importantForAccessibility) { switch (importantForAccessibility) { case ImportantForAccessibility::Auto: return "auto"; @@ -183,8 +186,10 @@ inline std::string toString(const ImportantForAccessibility &importantForAccessi } } -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()) { @@ -206,8 +211,10 @@ inline void fromRawValue(const PropsParserContext &context, const RawValue &valu } } -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"); @@ -224,8 +231,10 @@ inline void fromRawValue(const PropsParserContext &context, const RawValue &valu } } -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"); @@ -257,8 +266,10 @@ inline void fromRawValue(const PropsParserContext & /*unused*/, const RawValue & } } -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>()) { @@ -266,8 +277,10 @@ inline void fromRawValue(const PropsParserContext &context, const RawValue &valu } } -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()) { @@ -287,8 +300,7 @@ inline void fromRawValue(const PropsParserContext &context, const RawValue &valu } } -inline std::string toString(const AccessibilityRole &accessibilityRole) -{ +inline std::string toString(const AccessibilityRole& accessibilityRole) { switch (accessibilityRole) { case AccessibilityRole::None: return "none"; @@ -378,8 +390,10 @@ 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; @@ -476,8 +490,7 @@ inline void fromRawValue(const PropsParserContext &context, const RawValue &valu result = AccessibilityRole::None; } -inline std::string toString(const Role &role) -{ +inline std::string toString(const Role& role) { switch (role) { case Role::Alert: return "alert"; @@ -617,8 +630,10 @@ 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; @@ -767,8 +782,7 @@ inline void fromRawValue(const PropsParserContext &context, const RawValue &valu result = Role::None; } -inline std::string toString(AccessibilityLiveRegion accessibilityLiveRegion) -{ +inline std::string toString(AccessibilityLiveRegion accessibilityLiveRegion) { switch (accessibilityLiveRegion) { case AccessibilityLiveRegion::None: return "none"; @@ -780,8 +794,7 @@ 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"; @@ -794,8 +807,7 @@ 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() + "'"; @@ -803,8 +815,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]); @@ -816,10 +828,11 @@ inline std::string toString(std::vector accessibilityAction 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 c6c2c88a4981..50f523e9c207 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/view/conversions.h +++ b/packages/react-native/ReactCommon/react/renderer/components/view/conversions.h @@ -52,9 +52,10 @@ 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(); } @@ -62,8 +63,7 @@ inline Float floatFromYogaFloat(float value) return (Float)value; } -inline float yogaFloatFromFloat(Float value) -{ +inline float yogaFloatFromFloat(Float value) { if (!std::isfinite(value)) { return YGUndefined; } @@ -81,8 +81,7 @@ 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(); } @@ -90,8 +89,7 @@ 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(); } @@ -100,21 +98,22 @@ 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; @@ -125,8 +124,7 @@ static inline PositionType positionTypeFromYogaPositionType(yoga::PositionType p } } -inline DisplayType displayTypeFromYGDisplay(YGDisplay display) -{ +inline DisplayType displayTypeFromYGDisplay(YGDisplay display) { switch (display) { case YGDisplayNone: return DisplayType::None; @@ -139,8 +137,7 @@ inline DisplayType displayTypeFromYGDisplay(YGDisplay display) } } -inline LayoutMetrics layoutMetricsFromYogaNode(yoga::Node &yogaNode) -{ +inline LayoutMetrics layoutMetricsFromYogaNode(yoga::Node& yogaNode) { auto layoutMetrics = LayoutMetrics{}; layoutMetrics.frame = Rect{ @@ -159,23 +156,30 @@ 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.displayType = displayTypeFromYGDisplay(YGNodeStyleGetDisplay(&yogaNode)); - - layoutMetrics.positionType = positionTypeFromYogaPositionType(yogaNode.style().positionType()); - - layoutMetrics.layoutDirection = YGNodeLayoutGetDirection(&yogaNode) == YGDirectionRTL ? LayoutDirection::RightToLeft - : LayoutDirection::LeftToRight; + 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.positionType = + positionTypeFromYogaPositionType(yogaNode.style().positionType()); + + 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; @@ -186,8 +190,10 @@ 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()) { @@ -209,8 +215,10 @@ inline void fromRawValue(const PropsParserContext &context, const RawValue &valu 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()) { @@ -236,8 +244,10 @@ inline void fromRawValue(const PropsParserContext &context, const RawValue &valu 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()) { @@ -256,8 +266,10 @@ inline void fromRawValue(const PropsParserContext & /*context*/, const RawValue 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()) { @@ -291,8 +303,10 @@ inline void fromRawValue(const PropsParserContext &context, const RawValue &valu 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()) { @@ -339,8 +353,10 @@ inline void fromRawValue(const PropsParserContext &context, const RawValue &valu 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()) { @@ -362,8 +378,10 @@ inline void fromRawValue(const PropsParserContext &context, const RawValue &valu 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()) { @@ -385,8 +403,10 @@ inline void fromRawValue(const PropsParserContext &context, const RawValue &valu 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()) { @@ -409,8 +429,10 @@ inline void fromRawValue(const PropsParserContext &context, const RawValue &valu 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()) { @@ -432,8 +454,10 @@ inline void fromRawValue(const PropsParserContext &context, const RawValue &valu 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; @@ -454,10 +478,12 @@ inline void fromRawValue(const PropsParserContext & /*context*/, const RawValue } 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; } } @@ -465,8 +491,10 @@ inline void fromRawValue(const PropsParserContext & /*context*/, const RawValue 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; @@ -478,7 +506,8 @@ inline void fromRawValue(const PropsParserContext &context, const RawValue &valu } 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); @@ -489,24 +518,31 @@ inline void fromRawValue(const PropsParserContext &context, const RawValue &valu 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 yoga::FloatOptional convertAspectRatio(const PropsParserContext & /*context*/, const RawValue &value) -{ +inline yoga::FloatOptional convertAspectRatio( + const PropsParserContext& /*context*/, + const RawValue& value) { if (value.hasType()) { return yoga::FloatOptional((float)value); } - if (ReactNativeFeatureFlags::enableNativeCSSParsing() && value.hasType()) { + if (ReactNativeFeatureFlags::enableNativeCSSParsing() && + value.hasType()) { auto ratio = parseCSSProperty((std::string)value); if (std::holds_alternative(ratio)) { auto r = std::get(ratio); @@ -518,8 +554,7 @@ inline yoga::FloatOptional convertAspectRatio(const PropsParserContext & /*conte return {}; } -inline std::optional toRadians(const RawValue &value) -{ +inline std::optional toRadians(const RawValue& value) { if (value.hasType()) { return (Float)value; } @@ -529,14 +564,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); } @@ -552,13 +587,15 @@ 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 ValueUnit cssLengthPercentageToValueUnit(const std::variant &value) -{ +inline ValueUnit cssLengthPercentageToValueUnit( + const std::variant& value) { if (std::holds_alternative(value)) { auto len = std::get(value); if (len.unit != CSSLengthUnit::Px) { @@ -570,37 +607,49 @@ inline ValueUnit cssLengthPercentageToValueUnit(const std::variant fromCSSTransformFunction(const CSSTransformFunction &cssTransform) -{ +inline std::optional fromCSSTransformFunction( + const CSSTransformFunction& cssTransform) { constexpr auto Zero = ValueUnit(0, UnitType::Point); constexpr auto One = ValueUnit(1, UnitType::Point); return std::visit( - [&](auto &&func) -> std::optional { + [&](auto&& func) -> std::optional { using T = std::decay_t; if constexpr (std::is_same_v) { auto radians = static_cast(func.degrees * M_PI / 180.0f); return TransformOperation{ - .type = TransformOperationType::Rotate, .x = Zero, .y = Zero, .z = ValueUnit(radians, UnitType::Point)}; + .type = TransformOperationType::Rotate, + .x = Zero, + .y = Zero, + .z = ValueUnit(radians, UnitType::Point)}; } if constexpr (std::is_same_v) { auto radians = static_cast(func.degrees * M_PI / 180.0f); return TransformOperation{ - .type = TransformOperationType::Rotate, .x = ValueUnit(radians, UnitType::Point), .y = Zero, .z = Zero}; + .type = TransformOperationType::Rotate, + .x = ValueUnit(radians, UnitType::Point), + .y = Zero, + .z = Zero}; } if constexpr (std::is_same_v) { auto radians = static_cast(func.degrees * M_PI / 180.0f); return TransformOperation{ - .type = TransformOperationType::Rotate, .x = Zero, .y = ValueUnit(radians, UnitType::Point), .z = Zero}; + .type = TransformOperationType::Rotate, + .x = Zero, + .y = ValueUnit(radians, UnitType::Point), + .z = Zero}; } if constexpr (std::is_same_v) { auto radians = static_cast(func.degrees * M_PI / 180.0f); return TransformOperation{ - .type = TransformOperationType::Rotate, .x = Zero, .y = Zero, .z = ValueUnit(radians, UnitType::Point)}; + .type = TransformOperationType::Rotate, + .x = Zero, + .y = Zero, + .z = ValueUnit(radians, UnitType::Point)}; } if constexpr (std::is_same_v) { @@ -609,7 +658,11 @@ inline std::optional fromCSSTransformFunction(const CSSTrans if (!x || !y) { return std::nullopt; } - return TransformOperation{.type = TransformOperationType::Translate, .x = x, .y = y, .z = Zero}; + return TransformOperation{ + .type = TransformOperationType::Translate, + .x = x, + .y = y, + .z = Zero}; } if constexpr (std::is_same_v) { @@ -617,7 +670,11 @@ inline std::optional fromCSSTransformFunction(const CSSTrans if (!x) { return std::nullopt; } - return TransformOperation{.type = TransformOperationType::Translate, .x = x, .y = Zero, .z = Zero}; + return TransformOperation{ + .type = TransformOperationType::Translate, + .x = x, + .y = Zero, + .z = Zero}; } if constexpr (std::is_same_v) { @@ -625,7 +682,11 @@ inline std::optional fromCSSTransformFunction(const CSSTrans if (!y) { return std::nullopt; } - return TransformOperation{.type = TransformOperationType::Translate, .x = Zero, .y = y, .z = Zero}; + return TransformOperation{ + .type = TransformOperationType::Translate, + .x = Zero, + .y = y, + .z = Zero}; } if constexpr (std::is_same_v) { @@ -635,7 +696,10 @@ inline std::optional fromCSSTransformFunction(const CSSTrans return std::nullopt; } return TransformOperation{ - .type = TransformOperationType::Translate, .x = x, .y = y, .z = ValueUnit(func.z.value, UnitType::Point)}; + .type = TransformOperationType::Translate, + .x = x, + .y = y, + .z = ValueUnit(func.z.value, UnitType::Point)}; } if constexpr (std::is_same_v) { @@ -648,24 +712,36 @@ inline std::optional fromCSSTransformFunction(const CSSTrans if constexpr (std::is_same_v) { return TransformOperation{ - .type = TransformOperationType::Scale, .x = ValueUnit(func.value, UnitType::Point), .y = One, .z = One}; + .type = TransformOperationType::Scale, + .x = ValueUnit(func.value, UnitType::Point), + .y = One, + .z = One}; } if constexpr (std::is_same_v) { return TransformOperation{ - .type = TransformOperationType::Scale, .x = One, .y = ValueUnit(func.value, UnitType::Point), .z = One}; + .type = TransformOperationType::Scale, + .x = One, + .y = ValueUnit(func.value, UnitType::Point), + .z = One}; } if constexpr (std::is_same_v) { auto radians = static_cast(func.degrees * M_PI / 180.0f); return TransformOperation{ - .type = TransformOperationType::Skew, .x = ValueUnit(radians, UnitType::Point), .y = Zero, .z = Zero}; + .type = TransformOperationType::Skew, + .x = ValueUnit(radians, UnitType::Point), + .y = Zero, + .z = Zero}; } if constexpr (std::is_same_v) { auto radians = static_cast(func.degrees * M_PI / 180.0f); return TransformOperation{ - .type = TransformOperationType::Skew, .x = Zero, .y = ValueUnit(radians, UnitType::Point), .z = Zero}; + .type = TransformOperationType::Skew, + .x = Zero, + .y = ValueUnit(radians, UnitType::Point), + .z = Zero}; } if constexpr (std::is_same_v) { @@ -680,14 +756,20 @@ inline std::optional fromCSSTransformFunction(const CSSTrans } if constexpr (std::is_same_v) { - return TransformOperation{.type = TransformOperationType::Arbitrary, .x = Zero, .y = Zero, .z = Zero}; + return TransformOperation{ + .type = TransformOperationType::Arbitrary, + .x = Zero, + .y = Zero, + .z = Zero}; } }, cssTransform); } -inline void parseProcessedTransform(const PropsParserContext & /*context*/, const RawValue &value, Transform &result) -{ +inline void parseProcessedTransform( + const PropsParserContext& /*context*/, + const RawValue& value, + Transform& result) { auto transformMatrix = Transform{}; react_native_expect(value.hasType>()); if (!value.hasType>()) { @@ -696,13 +778,14 @@ inline void parseProcessedTransform(const PropsParserContext & /*context*/, cons } 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; @@ -710,7 +793,7 @@ inline void parseProcessedTransform(const PropsParserContext & /*context*/, cons auto pair = configurationPair.begin(); auto operation = pair->first; - auto ¶meters = pair->second; + auto& parameters = pair->second; auto Zero = ValueUnit(0, UnitType::Point); auto One = ValueUnit(1, UnitType::Point); @@ -764,20 +847,22 @@ inline void parseProcessedTransform(const PropsParserContext & /*context*/, cons 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()) { @@ -785,9 +870,11 @@ inline void parseProcessedTransform(const PropsParserContext & /*context*/, cons 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()) { @@ -795,9 +882,11 @@ inline void parseProcessedTransform(const PropsParserContext & /*context*/, cons 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()) { @@ -805,9 +894,11 @@ inline void parseProcessedTransform(const PropsParserContext & /*context*/, cons 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 = {}; @@ -815,44 +906,44 @@ inline void parseProcessedTransform(const PropsParserContext & /*context*/, cons } 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 = {}; @@ -877,8 +968,11 @@ inline void parseProcessedTransform(const PropsParserContext & /*context*/, cons 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) { @@ -886,8 +980,11 @@ inline void parseProcessedTransform(const PropsParserContext & /*context*/, cons 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) { @@ -895,8 +992,11 @@ inline void parseProcessedTransform(const PropsParserContext & /*context*/, cons 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()) { @@ -904,9 +1004,11 @@ inline void parseProcessedTransform(const PropsParserContext & /*context*/, cons 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()) { @@ -914,17 +1016,20 @@ inline void parseProcessedTransform(const PropsParserContext & /*context*/, cons 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 parseUnprocessedTransformString(const std::string &value, Transform &result) -{ +inline void parseUnprocessedTransformString( + const std::string& value, + Transform& result) { auto transformList = parseCSSProperty(value); if (!std::holds_alternative(transformList)) { result = {}; @@ -932,9 +1037,9 @@ inline void parseUnprocessedTransformString(const std::string &value, Transform } auto transformMatrix = Transform{}; - const auto &cssFuncs = std::get(transformList); + const auto& cssFuncs = std::get(transformList); transformMatrix.operations.reserve(cssFuncs.size()); - for (const auto &cssFunc : cssFuncs) { + for (const auto& cssFunc : cssFuncs) { auto op = fromCSSTransformFunction(cssFunc); if (!op.has_value()) { result = {}; @@ -944,7 +1049,7 @@ inline void parseUnprocessedTransformString(const std::string &value, Transform if (op->type == TransformOperationType::Arbitrary) { // CSSMatrix: expand 6-value 2D matrix to 4x4 matrix if (std::holds_alternative(cssFunc)) { - const auto &m = std::get(cssFunc); + const auto& m = std::get(cssFunc); transformMatrix.matrix[0] = m.values[0]; transformMatrix.matrix[1] = m.values[1]; transformMatrix.matrix[2] = 0; @@ -970,8 +1075,10 @@ inline void parseUnprocessedTransformString(const std::string &value, Transform result = transformMatrix; } -inline void parseUnprocessedTransform(const PropsParserContext &context, const RawValue &value, Transform &result) -{ +inline void parseUnprocessedTransform( + const PropsParserContext& context, + const RawValue& value, + Transform& result) { if (value.hasType()) { parseUnprocessedTransformString((std::string)value, result); } else { @@ -979,8 +1086,10 @@ inline void parseUnprocessedTransform(const PropsParserContext &context, const R } } -inline void fromRawValue(const PropsParserContext &context, const RawValue &value, Transform &result) -{ +inline void fromRawValue( + const PropsParserContext& context, + const RawValue& value, + Transform& result) { if (ReactNativeFeatureFlags::enableNativeCSSParsing()) { parseUnprocessedTransform(context, value, result); } else { @@ -988,9 +1097,10 @@ inline void fromRawValue(const PropsParserContext &context, const RawValue &valu } } -inline void -parseProcessedTransformOrigin(const PropsParserContext & /*context*/, const RawValue &value, TransformOrigin &result) -{ +inline void parseProcessedTransformOrigin( + const PropsParserContext& /*context*/, + const RawValue& value, + TransformOrigin& result) { if (!value.hasType>()) { result = {}; return; @@ -1023,15 +1133,16 @@ parseProcessedTransformOrigin(const PropsParserContext & /*context*/, const RawV result = transformOrigin; } -inline void parseUnprocessedTransformOriginString(const std::string &value, TransformOrigin &result) -{ +inline void parseUnprocessedTransformOriginString( + const std::string& value, + TransformOrigin& result) { auto cssOrigin = parseCSSProperty(value); if (!std::holds_alternative(cssOrigin)) { result = {}; return; } - const auto &origin = std::get(cssOrigin); + const auto& origin = std::get(cssOrigin); TransformOrigin transformOrigin; auto x = cssLengthPercentageToValueUnit(origin.x); @@ -1053,9 +1164,10 @@ inline void parseUnprocessedTransformOriginString(const std::string &value, Tran result = transformOrigin; } -inline void -parseUnprocessedTransformOrigin(const PropsParserContext &context, const RawValue &value, TransformOrigin &result) -{ +inline void parseUnprocessedTransformOrigin( + const PropsParserContext& context, + const RawValue& value, + TransformOrigin& result) { if (value.hasType()) { parseUnprocessedTransformOriginString((std::string)value, result); } else { @@ -1063,8 +1175,10 @@ parseUnprocessedTransformOrigin(const PropsParserContext &context, const RawValu } } -inline void fromRawValue(const PropsParserContext &context, const RawValue &value, TransformOrigin &result) -{ +inline void fromRawValue( + const PropsParserContext& context, + const RawValue& value, + TransformOrigin& result) { if (ReactNativeFeatureFlags::enableNativeCSSParsing()) { parseUnprocessedTransformOrigin(context, value, result); } else { @@ -1072,8 +1186,10 @@ inline void fromRawValue(const PropsParserContext &context, const RawValue &valu } } -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()) { @@ -1100,8 +1216,7 @@ inline void fromRawValue(const PropsParserContext &context, const RawValue &valu react_native_expect(false); } -inline std::string toString(PointerEventsMode value) -{ +inline std::string toString(PointerEventsMode value) { switch (value) { case PointerEventsMode::Auto: return "auto"; @@ -1114,8 +1229,10 @@ 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()) { @@ -1138,8 +1255,10 @@ inline void fromRawValue(const PropsParserContext &context, const RawValue &valu 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()) { @@ -1158,8 +1277,10 @@ inline void fromRawValue(const PropsParserContext &context, const RawValue &valu 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()) { @@ -1182,8 +1303,10 @@ inline void fromRawValue(const PropsParserContext &context, const RawValue &valu 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()) { @@ -1206,8 +1329,10 @@ inline void fromRawValue(const PropsParserContext &context, const RawValue &valu 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()) { @@ -1362,8 +1487,10 @@ inline void fromRawValue(const PropsParserContext &context, const RawValue &valu 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()) { @@ -1381,8 +1508,10 @@ inline void fromRawValue(const PropsParserContext & /*context*/, const RawValue } } -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()) { @@ -1400,9 +1529,10 @@ inline void fromRawValue(const PropsParserContext & /*context*/, const RawValue 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 = {}; @@ -1412,7 +1542,7 @@ fromRawValue(const PropsParserContext & /*context*/, const RawValue &value, std: 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") { @@ -1420,14 +1550,17 @@ fromRawValue(const PropsParserContext & /*context*/, const RawValue &value, std: } 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); @@ -1439,7 +1572,8 @@ fromRawValue(const PropsParserContext & /*context*/, const RawValue &value, std: 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); @@ -1456,9 +1590,10 @@ fromRawValue(const PropsParserContext & /*context*/, const RawValue &value, std: 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 = {}; @@ -1468,9 +1603,11 @@ fromRawValue(const PropsParserContext & /*context*/, const RawValue &value, std: 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; @@ -1513,9 +1650,10 @@ fromRawValue(const PropsParserContext & /*context*/, const RawValue &value, std: 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 = {}; @@ -1525,9 +1663,11 @@ fromRawValue(const PropsParserContext & /*context*/, const RawValue &value, std: 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; @@ -1566,8 +1706,10 @@ fromRawValue(const PropsParserContext & /*context*/, const RawValue &value, std: 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()) { @@ -1587,8 +1729,7 @@ inline void fromRawValue(const PropsParserContext & /*context*/, const RawValue #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("{"); @@ -1601,48 +1742,39 @@ 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()) { @@ -1656,8 +1788,7 @@ 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()) { @@ -1677,8 +1808,7 @@ 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"; } @@ -1686,8 +1816,7 @@ inline std::string toString(const yoga::FloatOptional &value) return toString(value.unwrap()); } -inline std::string toString(const LayoutConformance &value) -{ +inline std::string toString(const LayoutConformance& value) { switch (value) { case LayoutConformance::Strict: return "strict"; @@ -1696,22 +1825,24 @@ 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 += "[ " + toString(m[0]) + " " + toString(m[1]) + " " + toString(m[2]) + " " + toString(m[3]) + " ]\n"; - result += "[ " + toString(m[4]) + " " + toString(m[5]) + " " + toString(m[6]) + " " + toString(m[7]) + " ]\n"; - result += "[ " + toString(m[8]) + " " + toString(m[9]) + " " + toString(m[10]) + " " + toString(m[11]) + " ]\n"; - result += "[ " + toString(m[12]) + " " + toString(m[13]) + " " + toString(m[14]) + " " + toString(m[15]) + " ]"; + result += "[ " + toString(m[0]) + " " + toString(m[1]) + " " + + toString(m[2]) + " " + toString(m[3]) + " ]\n"; + result += "[ " + toString(m[4]) + " " + toString(m[5]) + " " + + toString(m[6]) + " " + toString(m[7]) + " ]\n"; + result += "[ " + toString(m[8]) + " " + toString(m[9]) + " " + + toString(m[10]) + " " + toString(m[11]) + " ]\n"; + result += "[ " + toString(m[12]) + " " + toString(m[13]) + " " + + toString(m[14]) + " " + toString(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 += ", "; } @@ -1723,17 +1854,23 @@ inline std::string toString(const Transform &transform) break; } case TransformOperationType::Rotate: { - 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 += R"({"rotateX": ")" + toString(operation.x.value) + "rad\"}"; - } else if (operation.x.value == 0 && operation.y.value != 0 && operation.z.value == 0) { + } else if ( + operation.x.value == 0 && operation.y.value != 0 && + operation.z.value == 0) { result += R"({"rotateY": ")" + toString(operation.y.value) + "rad\"}"; - } else if (operation.x.value == 0 && operation.y.value == 0 && operation.z.value != 0) { + } else if ( + operation.x.value == 0 && operation.y.value == 0 && + operation.z.value != 0) { result += R"({"rotateZ": ")" + toString(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\": " + toString(operation.x.value) + "}"; } else if (operation.y.value == 1 && operation.z.value == 1) { result += "{\"scaleX\": " + toString(operation.x.value) + "}"; @@ -1745,9 +1882,11 @@ 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 += toString(operation.x.value) + ", " + toString(operation.y.value); + result += + toString(operation.x.value) + ", " + toString(operation.y.value); result += "]}"; } else if (operation.x.value != 0 && operation.y.value == 0) { result += "{\"translateX\": " + toString(operation.x.value) + "}"; 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 154be6f017b3..c318cb60afa6 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,13 +24,17 @@ class HostPlatformViewProps : public BaseViewProps { public: HostPlatformViewProps() = default; HostPlatformViewProps( - 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); + 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); #pragma mark - Props @@ -61,7 +65,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 16b32af2b939..8550d2716372 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 4703f5fee5aa..7d1b8174092d 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 @@ -30,8 +30,7 @@ struct NativeDrawable { bool borderless{false}; std::optional alpha{}; - bool operator==(const Ripple &rhs) const - { + bool operator==(const Ripple& rhs) const { return std::tie( this->color, this->colorResourcePaths, @@ -39,7 +38,13 @@ struct NativeDrawable { this->borderless, this->rippleRadius, this->alpha) == - std::tie(rhs.color, rhs.colorResourcePaths, rhs.colorFallback, rhs.borderless, rhs.rippleRadius, rhs.alpha); + std::tie( + rhs.color, + rhs.colorResourcePaths, + rhs.colorFallback, + rhs.borderless, + rhs.rippleRadius, + rhs.alpha); } }; @@ -47,8 +52,7 @@ 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; } @@ -61,25 +65,29 @@ 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{ .themeAttr = (std::string)attrIterator->second, @@ -101,12 +109,15 @@ static inline void fromRawValue(const PropsParserContext &context, const RawValu // of vector (which would assert on the string value). bool handledAsResourcePaths = false; if (color->second.hasType>()) { - auto colorMap = (std::unordered_map)color->second; + auto colorMap = + (std::unordered_map)color->second; auto pathsIt = colorMap.find("resource_paths"); - if (pathsIt != colorMap.end() && pathsIt->second.hasType>()) { + if (pathsIt != colorMap.end() && + pathsIt->second.hasType>()) { parsedColorResourcePaths = (std::vector)pathsIt->second; auto fallbackIt = colorMap.find("fallback"); - if (fallbackIt != colorMap.end() && fallbackIt->second.hasType()) { + if (fallbackIt != colorMap.end() && + fallbackIt->second.hasType()) { parsedColorFallback = (std::string)fallbackIt->second; } handledAsResourcePaths = true; @@ -133,11 +144,14 @@ static inline void fromRawValue(const PropsParserContext &context, const RawValu .color = parsedColor, .colorResourcePaths = parsedColorResourcePaths, .colorFallback = parsedColorFallback, - .rippleRadius = rippleRadius != map.end() && rippleRadius->second.hasType() + .rippleRadius = rippleRadius != map.end() && + rippleRadius->second.hasType() ? (Float)rippleRadius->second : std::optional{}, - .borderless = - borderless != map.end() && borderless->second.hasType() ? (bool)borderless->second : false, + .borderless = borderless != map.end() && + borderless->second.hasType() + ? (bool)borderless->second + : false, .alpha = parsedAlpha, }, .kind = 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 032e6377aaf6..f0785d02d1db 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,18 +12,15 @@ 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/platform/tvos/react/renderer/components/view/HostPlatformViewProps.h b/packages/react-native/ReactCommon/react/renderer/components/view/platform/tvos/react/renderer/components/view/HostPlatformViewProps.h index b50dd4f4f2b0..8ce8c04794ce 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/view/platform/tvos/react/renderer/components/view/HostPlatformViewProps.h +++ b/packages/react-native/ReactCommon/react/renderer/components/view/platform/tvos/react/renderer/components/view/HostPlatformViewProps.h @@ -16,12 +16,15 @@ class HostPlatformViewProps : public BaseViewProps { public: HostPlatformViewProps() = default; HostPlatformViewProps( - const PropsParserContext &context, - const HostPlatformViewProps &sourceProps, - const RawProps &rawProps); + const PropsParserContext& context, + const HostPlatformViewProps& 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); bool focusable{false}; }; diff --git a/packages/react-native/ReactCommon/react/renderer/components/view/platform/tvos/react/renderer/components/view/HostPlatformViewTraitsInitializer.h b/packages/react-native/ReactCommon/react/renderer/components/view/platform/tvos/react/renderer/components/view/HostPlatformViewTraitsInitializer.h index a423f3192a6b..88debe19dffb 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/view/platform/tvos/react/renderer/components/view/HostPlatformViewTraitsInitializer.h +++ b/packages/react-native/ReactCommon/react/renderer/components/view/platform/tvos/react/renderer/components/view/HostPlatformViewTraitsInitializer.h @@ -12,18 +12,15 @@ 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 aa7e385229f6..d1213e01160a 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/view/primitives.h +++ b/packages/react-native/ReactCommon/react/renderer/components/view/primitives.h @@ -69,19 +69,16 @@ 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; } @@ -97,7 +94,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 { @@ -159,26 +156,29 @@ 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 = default; + bool operator==(const CascadedRectangleEdges& rhs) const = default; }; template @@ -200,8 +200,7 @@ 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; @@ -213,7 +212,8 @@ 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 = */ @@ -223,7 +223,7 @@ struct CascadedRectangleCorners { }; } - bool operator==(const CascadedRectangleCorners &rhs) const = default; + bool operator==(const CascadedRectangleCorners& rhs) const = default; }; using BorderWidths = RectangleEdges; @@ -245,12 +245,12 @@ struct BorderMetrics { BorderCurves borderCurves{}; BorderStyles borderStyles{}; - bool operator==(const BorderMetrics &rhs) const = default; + bool operator==(const BorderMetrics& rhs) const = default; }; -inline bool areBorderRadiiCircular(const BorderRadii &borderRadii) -{ - return borderRadii.isUniform() && borderRadii.topLeft.horizontal == borderRadii.topLeft.vertical; +inline bool areBorderRadiiCircular(const BorderRadii& borderRadii) { + return borderRadii.isUniform() && + borderRadii.topLeft.horizontal == borderRadii.topLeft.vertical; } } // namespace facebook::react 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 5b19dfc2c077..310e9c86fd4f 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/view/propsConversions.h +++ b/packages/react-native/ReactCommon/react/renderer/components/view/propsConversions.h @@ -16,57 +16,123 @@ 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, @@ -98,7 +164,11 @@ convertRawProp(const PropsParserContext &context, const RawProps &rawProps, cons 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, @@ -121,22 +191,38 @@ convertRawProp(const PropsParserContext &context, const RawProps &rawProps, cons 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, @@ -150,12 +236,20 @@ convertRawProp(const PropsParserContext &context, const RawProps &rawProps, cons 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, @@ -178,7 +272,11 @@ convertRawProp(const PropsParserContext &context, const RawProps &rawProps, cons 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, @@ -192,7 +290,11 @@ convertRawProp(const PropsParserContext &context, const RawProps &rawProps, cons 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, @@ -224,7 +326,11 @@ convertRawProp(const PropsParserContext &context, const RawProps &rawProps, cons 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, @@ -247,21 +353,38 @@ convertRawProp(const PropsParserContext &context, const RawProps &rawProps, cons 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, @@ -275,7 +398,11 @@ convertRawProp(const PropsParserContext &context, const RawProps &rawProps, cons 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, @@ -307,7 +434,11 @@ convertRawProp(const PropsParserContext &context, const RawProps &rawProps, cons 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, @@ -330,158 +461,282 @@ convertRawProp(const PropsParserContext &context, const RawProps &rawProps, cons 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), + {})); { - const auto *rawValue = rawProps.at("aspectRatio"); + const auto* rawValue = rawProps.at("aspectRatio"); if (rawValue != nullptr) { - yogaStyle.setAspectRatio(rawValue->hasValue() ? convertAspectRatio(context, *rawValue) : yogaStyle.aspectRatio()); + yogaStyle.setAspectRatio( + rawValue->hasValue() ? convertAspectRatio(context, *rawValue) + : yogaStyle.aspectRatio()); } else { yogaStyle.setAspectRatio(sourceValue.aspectRatio()); } } - yogaStyle.setBoxSizing( - convertRawProp(context, rawProps, "boxSizing", sourceValue.boxSizing(), yogaStyle.boxSizing())); + yogaStyle.setBoxSizing(convertRawProp( + context, + rawProps, + "boxSizing", + sourceValue.boxSizing(), + yogaStyle.boxSizing())); return yogaStyle; } struct CascadedRectangleCornersNames { - const char *topLeft; - const char *topRight; - const char *bottomLeft; - const char *bottomRight; - const char *topStart; - const char *topEnd; - const char *bottomStart; - const char *bottomEnd; - const char *endEnd; - const char *endStart; - const char *startEnd; - const char *startStart; - const char *all; + const char* topLeft; + const char* topRight; + const char* bottomLeft; + const char* bottomRight; + const char* topStart; + const char* topEnd; + const char* bottomStart; + const char* bottomEnd; + const char* endEnd; + const char* endStart; + const char* startEnd; + const char* startStart; + const char* all; }; struct CascadedRectangleEdgesNames { - const char *left; - const char *right; - const char *top; - const char *bottom; - const char *start; - const char *end; - const char *horizontal; - const char *vertical; - const char *block; - const char *blockEnd; - const char *blockStart; - const char *all; + const char* left; + const char* right; + const char* top; + const char* bottom; + const char* start; + const char* end; + const char* horizontal; + const char* vertical; + const char* block; + const char* blockEnd; + const char* blockStart; + const char* all; }; // This can be deleted when non-iterator ViewProp parsing is deleted template static inline CascadedRectangleCorners convertRawProp( - const PropsParserContext &context, - const RawProps &rawProps, - const CascadedRectangleCornersNames &names, - const CascadedRectangleCorners &sourceValue, - const CascadedRectangleCorners &defaultValue) -{ + const PropsParserContext& context, + const RawProps& rawProps, + const CascadedRectangleCornersNames& names, + const CascadedRectangleCorners& sourceValue, + const CascadedRectangleCorners& defaultValue) { CascadedRectangleCorners result; - result.topLeft = convertRawProp(context, rawProps, names.topLeft, sourceValue.topLeft, defaultValue.topLeft); - result.topRight = convertRawProp(context, rawProps, names.topRight, sourceValue.topRight, defaultValue.topRight); - result.bottomLeft = - convertRawProp(context, rawProps, names.bottomLeft, sourceValue.bottomLeft, defaultValue.bottomLeft); - result.bottomRight = - convertRawProp(context, rawProps, names.bottomRight, sourceValue.bottomRight, defaultValue.bottomRight); - - result.topStart = convertRawProp(context, rawProps, names.topStart, sourceValue.topStart, defaultValue.topStart); - result.topEnd = convertRawProp(context, rawProps, names.topEnd, sourceValue.topEnd, defaultValue.topEnd); - result.bottomStart = - convertRawProp(context, rawProps, names.bottomStart, sourceValue.bottomStart, defaultValue.bottomStart); - result.bottomEnd = convertRawProp(context, rawProps, names.bottomEnd, sourceValue.bottomEnd, defaultValue.bottomEnd); - result.endEnd = convertRawProp(context, rawProps, names.endEnd, sourceValue.endEnd, defaultValue.endEnd); - result.endStart = convertRawProp(context, rawProps, names.endStart, sourceValue.endStart, defaultValue.endStart); - result.startEnd = convertRawProp(context, rawProps, names.startEnd, sourceValue.startEnd, defaultValue.startEnd); - result.startStart = - convertRawProp(context, rawProps, names.startStart, sourceValue.startStart, defaultValue.startStart); - - result.all = convertRawProp(context, rawProps, names.all, sourceValue.all, defaultValue.all); + result.topLeft = convertRawProp( + context, + rawProps, + names.topLeft, + sourceValue.topLeft, + defaultValue.topLeft); + result.topRight = convertRawProp( + context, + rawProps, + names.topRight, + sourceValue.topRight, + defaultValue.topRight); + result.bottomLeft = convertRawProp( + context, + rawProps, + names.bottomLeft, + sourceValue.bottomLeft, + defaultValue.bottomLeft); + result.bottomRight = convertRawProp( + context, + rawProps, + names.bottomRight, + sourceValue.bottomRight, + defaultValue.bottomRight); + + result.topStart = convertRawProp( + context, + rawProps, + names.topStart, + sourceValue.topStart, + defaultValue.topStart); + result.topEnd = convertRawProp( + context, rawProps, names.topEnd, sourceValue.topEnd, defaultValue.topEnd); + result.bottomStart = convertRawProp( + context, + rawProps, + names.bottomStart, + sourceValue.bottomStart, + defaultValue.bottomStart); + result.bottomEnd = convertRawProp( + context, + rawProps, + names.bottomEnd, + sourceValue.bottomEnd, + defaultValue.bottomEnd); + result.endEnd = convertRawProp( + context, rawProps, names.endEnd, sourceValue.endEnd, defaultValue.endEnd); + result.endStart = convertRawProp( + context, + rawProps, + names.endStart, + sourceValue.endStart, + defaultValue.endStart); + result.startEnd = convertRawProp( + context, + rawProps, + names.startEnd, + sourceValue.startEnd, + defaultValue.startEnd); + result.startStart = convertRawProp( + context, + rawProps, + names.startStart, + sourceValue.startStart, + defaultValue.startStart); + + result.all = convertRawProp( + context, rawProps, names.all, sourceValue.all, defaultValue.all); return result; } template static inline CascadedRectangleEdges convertRawProp( - const PropsParserContext &context, - const RawProps &rawProps, - const CascadedRectangleEdgesNames &names, - const CascadedRectangleEdges &sourceValue, - const CascadedRectangleEdges &defaultValue) -{ + const PropsParserContext& context, + const RawProps& rawProps, + const CascadedRectangleEdgesNames& names, + const CascadedRectangleEdges& sourceValue, + const CascadedRectangleEdges& defaultValue) { CascadedRectangleEdges result; - result.left = convertRawProp(context, rawProps, names.left, sourceValue.left, defaultValue.left); - result.right = convertRawProp(context, rawProps, names.right, sourceValue.right, defaultValue.right); - result.top = convertRawProp(context, rawProps, names.top, sourceValue.top, defaultValue.top); - result.bottom = convertRawProp(context, rawProps, names.bottom, sourceValue.bottom, defaultValue.bottom); - - result.start = convertRawProp(context, rawProps, names.start, sourceValue.start, defaultValue.start); - result.end = convertRawProp(context, rawProps, names.end, sourceValue.end, defaultValue.end); - result.horizontal = - convertRawProp(context, rawProps, names.horizontal, sourceValue.horizontal, defaultValue.horizontal); - result.vertical = convertRawProp(context, rawProps, names.vertical, sourceValue.vertical, defaultValue.vertical); - result.block = convertRawProp(context, rawProps, names.block, sourceValue.block, defaultValue.block); - result.blockEnd = convertRawProp(context, rawProps, names.blockEnd, sourceValue.blockEnd, defaultValue.blockEnd); - result.blockStart = - convertRawProp(context, rawProps, names.blockStart, sourceValue.blockStart, defaultValue.blockStart); + result.left = convertRawProp( + context, rawProps, names.left, sourceValue.left, defaultValue.left); + result.right = convertRawProp( + context, rawProps, names.right, sourceValue.right, defaultValue.right); + result.top = convertRawProp( + context, rawProps, names.top, sourceValue.top, defaultValue.top); + result.bottom = convertRawProp( + context, rawProps, names.bottom, sourceValue.bottom, defaultValue.bottom); + + result.start = convertRawProp( + context, rawProps, names.start, sourceValue.start, defaultValue.start); + result.end = convertRawProp( + context, rawProps, names.end, sourceValue.end, defaultValue.end); + result.horizontal = convertRawProp( + context, + rawProps, + names.horizontal, + sourceValue.horizontal, + defaultValue.horizontal); + result.vertical = convertRawProp( + context, + rawProps, + names.vertical, + sourceValue.vertical, + defaultValue.vertical); + result.block = convertRawProp( + context, rawProps, names.block, sourceValue.block, defaultValue.block); + result.blockEnd = convertRawProp( + context, + rawProps, + names.blockEnd, + sourceValue.blockEnd, + defaultValue.blockEnd); + result.blockStart = convertRawProp( + context, + rawProps, + names.blockStart, + sourceValue.blockStart, + defaultValue.blockStart); - result.all = convertRawProp(context, rawProps, names.all, sourceValue.all, defaultValue.all); + result.all = convertRawProp( + context, rawProps, names.all, sourceValue.all, defaultValue.all); 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( @@ -503,7 +758,11 @@ 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, @@ -511,27 +770,47 @@ 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, @@ -577,7 +856,11 @@ 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, @@ -585,9 +868,17 @@ 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, @@ -595,7 +886,11 @@ 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, @@ -617,13 +912,29 @@ 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/virtualview/VirtualViewComponentDescriptor.h b/packages/react-native/ReactCommon/react/renderer/components/virtualview/VirtualViewComponentDescriptor.h index 9a01e3e664ca..b1f725fb106f 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/virtualview/VirtualViewComponentDescriptor.h +++ b/packages/react-native/ReactCommon/react/renderer/components/virtualview/VirtualViewComponentDescriptor.h @@ -15,5 +15,6 @@ 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 7b1d1fc6cc0d..1bb3411501ad 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/virtualview/VirtualViewShadowNode.h +++ b/packages/react-native/ReactCommon/react/renderer/components/virtualview/VirtualViewShadowNode.h @@ -18,13 +18,14 @@ constexpr const char VirtualViewComponentName[] = "VirtualView"; /* * `ShadowNode` for component. */ -class VirtualViewShadowNode final - : public ConcreteViewShadowNode { +class VirtualViewShadowNode final : public ConcreteViewShadowNode< + VirtualViewComponentName, + VirtualViewProps, + 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 51df90e7f261..2bc68d8a2bef 100644 --- a/packages/react-native/ReactCommon/react/renderer/consistency/ScopedShadowTreeRevisionLock.h +++ b/packages/react-native/ReactCommon/react/renderer/consistency/ScopedShadowTreeRevisionLock.h @@ -23,31 +23,32 @@ 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 371f238ececa..aa12f01db390 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/ComponentDescriptor.h +++ b/packages/react-native/ReactCommon/react/renderer/core/ComponentDescriptor.h @@ -46,14 +46,16 @@ class ComponentDescriptor { */ using Flavor = std::shared_ptr; - explicit ComponentDescriptor(const ComponentDescriptorParameters ¶meters, RawPropsParser &&rawPropsParser = {}); + explicit ComponentDescriptor( + const ComponentDescriptorParameters& parameters, + 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. @@ -77,22 +79,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 @@ -101,26 +103,32 @@ 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; @@ -143,7 +151,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 5c5773028d31..d01c3bd530ac 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/ConcreteComponentDescriptor.h +++ b/packages/react-native/ReactCommon/react/renderer/core/ConcreteComponentDescriptor.h @@ -30,7 +30,9 @@ 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; @@ -39,15 +41,15 @@ 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 ¶meters, - RawPropsParser &&rawPropsParser = {}) - : ComponentDescriptor(parameters, std::move(rawPropsParser)) - { + const ComponentDescriptorParameters& parameters, + RawPropsParser&& rawPropsParser = {}) + : ComponentDescriptor(parameters, std::move(rawPropsParser)) { // The parser's `keys_` / `nameToIndex_` are only consumed by // `RawProps::at()`, which is reached exclusively through the classic // per-field `convertRawProp` path. When `ConcreteProps` opts into the @@ -62,35 +64,32 @@ class ConcreteComponentDescriptor : public ComponentDescriptor { } } - 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); @@ -100,16 +99,18 @@ 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 @@ -133,8 +134,10 @@ class ConcreteComponentDescriptor : public ComponentDescriptor { // - Classic (the fallback for any `ConcreteProps` that doesn't opt in, // and the only path when the flag is off): parse + per-field // `convertRawProp` via the 3-arg ctor. - constexpr bool kSupportsIteratorSetter = HasIteratorSetterCtor; - const bool useIteratorSetter = kSupportsIteratorSetter && ReactNativeFeatureFlags::enableCppPropsIteratorSetter(); + constexpr bool kSupportsIteratorSetter = + HasIteratorSetterCtor; + const bool useIteratorSetter = kSupportsIteratorSetter && + ReactNativeFeatureFlags::enableCppPropsIteratorSetter(); std::shared_ptr shadowNodeProps; if constexpr (kSupportsIteratorSetter) { @@ -151,13 +154,16 @@ class ConcreteComponentDescriptor : public ComponentDescriptor { bool fallbackToDynamicRawPropsAccumulation = true; if (ReactNativeFeatureFlags::enableExclusivePropsUpdateAndroid() && ReactNativeFeatureFlags::enableAccumulatedUpdatesInRawPropsAndroid()) { - // When exclusive props update is enabled, we only apply Props 1.5 processing - // (raw props merging) when Props 2.0 is not available. + // When exclusive props update is enabled, we only apply Props 1.5 + // processing (raw props merging) when Props 2.0 is not available. if (ReactNativeFeatureFlags::enablePropsUpdateReconciliationAndroid()) { // Cast to base Props reference to safely call virtual method - const auto &baseProps = static_cast(*shadowNodeProps); - if (strcmp(ShadowNodeT::Name(), baseProps.getDiffPropsImplementationTarget()) == 0) { - // Props 2.0 supported for this component, Props 1.5 processing can be skipped + const auto& baseProps = static_cast(*shadowNodeProps); + if (strcmp( + ShadowNodeT::Name(), + baseProps.getDiffPropsImplementationTarget()) == 0) { + // Props 2.0 supported for this component, Props 1.5 processing can be + // skipped fallbackToDynamicRawPropsAccumulation = false; } } @@ -169,28 +175,32 @@ class ConcreteComponentDescriptor : public ComponentDescriptor { if constexpr (kSupportsIteratorSetter) { if (useIteratorSetter) { - rawProps.forEachItem([&](std::string_view name, const RawValue &value) { - shadowNodeProps->setProp(context, RAW_PROPS_KEY_HASH(name), name.data(), value); + rawProps.forEachItem([&](std::string_view name, const RawValue& value) { + shadowNodeProps->setProp( + context, RAW_PROPS_KEY_HASH(name), name.data(), value); }); } } 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; @@ -199,31 +209,37 @@ 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 ac069108548c..b516fbe9d8c0 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/ConcreteShadowNode.h +++ b/packages/react-native/ReactCommon/react/renderer/core/ConcreteShadowNode.h @@ -34,7 +34,9 @@ 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_; @@ -52,13 +54,11 @@ 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,8 +66,7 @@ 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(); } @@ -78,11 +77,15 @@ class ConcreteShadowNode : public BaseShadowNodeT { * iterator-setter path is disabled (per-class via the * `HasIteratorSetterCtor` concept, or globally via the runtime flag). */ - 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); } /* @@ -92,36 +95,36 @@ class ConcreteShadowNode : public BaseShadowNodeT { * `PropsT::setProp`. Available when `PropsT` satisfies * `HasIteratorSetterCtor`. */ - static UnsharedConcreteProps Props(const Props::Shared &baseProps) - { - return std::make_shared(baseProps ? static_cast(*baseProps) : *defaultSharedProps()); + static UnsharedConcreteProps Props(const Props::Shared& baseProps) { + return std::make_shared( + baseProps ? static_cast(*baseProps) + : *defaultSharedProps()); } #ifdef RN_SERIALIZABLE_STATE static void initializeDynamicProps( UnsharedConcreteProps props, - const RawProps &rawProps, - const Props::Shared &baseProps = nullptr) - { + const RawProps& rawProps, + const Props::Shared& baseProps = nullptr) { if (baseProps) { - props->initializeDynamicProps(static_cast(*baseProps), rawProps); + props->initializeDynamicProps( + static_cast(*baseProps), rawProps); } else { props->initializeDynamicProps(*defaultSharedProps(), rawProps); } } #endif - 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 {}; } @@ -129,19 +132,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_); } @@ -149,29 +152,28 @@ 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 46ecb31aaf2a..99904a867c79 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/ConcreteState.h +++ b/packages/react-native/ReactCommon/react/renderer/core/ConcreteState.h @@ -24,13 +24,16 @@ namespace facebook::react { #ifdef RN_SERIALIZABLE_STATE template concept StateDataWithMapBuffer = requires(StateDataT stateData) { - { stateData.getMapBuffer() } -> std::same_as; -}; + { + stateData.getMapBuffer() + } -> std::same_as; + }; template -concept StateDataWithJNIReference = requires(StateDataT stateData) { - { stateData.getJNIReference() } -> std::same_as>; -}; +concept StateDataWithJNIReference = + requires(StateDataT stateData) { + { stateData.getJNIReference() } -> std::same_as>; + }; #endif /* @@ -49,22 +52,23 @@ 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()); } /* @@ -73,10 +77,12 @@ 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); @@ -91,9 +97,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) { @@ -102,27 +108,25 @@ 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 { @@ -130,8 +134,7 @@ 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 2944a9e14e33..7af0f24c666f 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/DynamicEventPayload.h +++ b/packages/react-native/ReactCommon/react/renderer/core/DynamicEventPayload.h @@ -16,16 +16,17 @@ namespace facebook::react { * EventPayload sent from android native via JNI. */ struct DynamicEventPayload : public EventPayload { - explicit DynamicEventPayload(folly::dynamic &&payload); + explicit DynamicEventPayload(folly::dynamic&& payload); - static SharedEventPayload create(folly::dynamic &&payload); + static SharedEventPayload create(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; protected: folly::dynamic payload_; diff --git a/packages/react-native/ReactCommon/react/renderer/core/DynamicPointerEvent.h b/packages/react-native/ReactCommon/react/renderer/core/DynamicPointerEvent.h index 4d65ea980c12..a7dda623872c 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/DynamicPointerEvent.h +++ b/packages/react-native/ReactCommon/react/renderer/core/DynamicPointerEvent.h @@ -18,9 +18,9 @@ namespace facebook::react { * Payload of PointerEvent sent from android native via JNI. */ struct DynamicPointerEvent : public DynamicEventPayload { - explicit DynamicPointerEvent(folly::dynamic &&payload); + explicit DynamicPointerEvent(folly::dynamic&& payload); - const std::optional> &getHitPathForEventListener() const; + const std::optional>& getHitPathForEventListener() const; private: std::optional> hitPathForEventListener_; diff --git a/packages/react-native/ReactCommon/react/renderer/core/DynamicPropsUtilities.h b/packages/react-native/ReactCommon/react/renderer/core/DynamicPropsUtilities.h index a49d43b4f0a7..c318b77309cd 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/DynamicPropsUtilities.h +++ b/packages/react-native/ReactCommon/react/renderer/core/DynamicPropsUtilities.h @@ -43,9 +43,13 @@ 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 diffDynamicProps(const folly::dynamic &oldProps, const folly::dynamic &newProps); +folly::dynamic mergeDynamicProps( + const folly::dynamic& source, + const folly::dynamic& patch, + NullValueStrategy nullValueStrategy); + +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 3740b457e785..de5cabccbe0b 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/EventBeat.h +++ b/packages/react-native/ReactCommon/react/renderer/core/EventBeat.h @@ -55,17 +55,20 @@ 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 @@ -144,7 +147,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 88a9a953e423..f68cf5bd4d99 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,12 +51,14 @@ 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 /* @@ -67,7 +69,8 @@ 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 f3e9a4c334e7..4fea7a276c7b 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/EventEmitter.h +++ b/packages/react-native/ReactCommon/react/renderer/core/EventEmitter.h @@ -36,11 +36,13 @@ 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; @@ -59,16 +61,16 @@ class EventEmitter { /* * Sets a weak reference to the cooresponding ShadowNodeFamily */ - void setShadowNodeFamily(std::weak_ptr shadowNodeFamily); + void setShadowNodeFamily( + std::weak_ptr shadowNodeFamily); - 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; @@ -84,18 +86,19 @@ 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, - const ValueFactory &payloadFactory, + const ValueFactory& payloadFactory, RawEvent::Category category, HighResTimeStamp eventTimestamp) const; void dispatchEvent( std::string type, - folly::dynamic &&payload, + folly::dynamic&& payload, RawEvent::Category category = RawEvent::Category::Unspecified) const; void dispatchEvent( @@ -105,7 +108,7 @@ class EventEmitter { void dispatchEvent( std::string type, - folly::dynamic &&payload, + folly::dynamic&& payload, RawEvent::Category category, HighResTimeStamp eventTimestamp) const; @@ -115,18 +118,29 @@ class EventEmitter { RawEvent::Category category, HighResTimeStamp eventTimestamp) 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, const ValueFactory &payloadFactory, HighResTimeStamp eventTimestamp) const; + void dispatchUniqueEvent( + std::string type, + const ValueFactory& payloadFactory, + HighResTimeStamp eventTimestamp) const; void dispatchUniqueEvent(std::string type, SharedEventPayload payload) const; - void dispatchUniqueEvent(std::string type, folly::dynamic &&payload, HighResTimeStamp eventTimestamp) const; + void dispatchUniqueEvent( + std::string type, + folly::dynamic&& payload, + HighResTimeStamp eventTimestamp) const; - void dispatchUniqueEvent(std::string type, SharedEventPayload payload, HighResTimeStamp eventTimestamp) const; + void dispatchUniqueEvent( + std::string type, + SharedEventPayload payload, + HighResTimeStamp eventTimestamp) const; private: friend class UIManagerBinding; diff --git a/packages/react-native/ReactCommon/react/renderer/core/EventListener.h b/packages/react-native/ReactCommon/react/renderer/core/EventListener.h index 4535e4fb8bbc..1d5e72168dd9 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 30e2d73fae5e..f0a00ac9196e 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 a632ffc9e443..b73593dab386 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/EventPipe.h +++ b/packages/react-native/ReactCommon/react/renderer/core/EventPipe.h @@ -20,13 +20,13 @@ namespace facebook::react { using EventPipe = std::function; -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 f525767478aa..3d4bb7cdbed0 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/EventQueue.h +++ b/packages/react-native/ReactCommon/react/renderer/core/EventQueue.h @@ -37,26 +37,30 @@ 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. @@ -70,9 +74,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 d1abcd99bff9..5c1c9f2b0d1e 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 9e11ceca4e8a..aa7bd22e271b 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/EventTarget.h +++ b/packages/react-native/ReactCommon/react/renderer/core/EventTarget.h @@ -34,7 +34,9 @@ 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 @@ -46,18 +48,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); + void retain(jsi::Runtime& runtime); /* * Releases the instance handler by nulling a strong reference to it. */ - void release(jsi::Runtime &runtime); + void release(jsi::Runtime& runtime); /* * 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 e916bb24b891..17f5a3d2763f 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/InstanceHandle.h +++ b/packages/react-native/ReactCommon/react/renderer/core/InstanceHandle.h @@ -17,13 +17,16 @@ 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 a87af612f598..bd405be908d2 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/LayoutConstraints.h +++ b/packages/react-native/ReactCommon/react/renderer/core/LayoutConstraints.h @@ -20,18 +20,21 @@ 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); } @@ -41,9 +44,12 @@ inline bool operator==(const LayoutConstraints &lhs, const LayoutConstraints &rh 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 f54f90159d40..cb01c3eefa12 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 @@ -66,8 +66,7 @@ struct LayoutContext { Size viewportSize{}; }; -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, diff --git a/packages/react-native/ReactCommon/react/renderer/core/LayoutMetrics.h b/packages/react-native/ReactCommon/react/renderer/core/LayoutMetrics.h index cc20fae6e0f1..0d0f2faf5470 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/LayoutMetrics.h +++ b/packages/react-native/ReactCommon/react/renderer/core/LayoutMetrics.h @@ -50,44 +50,45 @@ 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; }; /* @@ -96,13 +97,15 @@ 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 @@ -113,8 +116,7 @@ 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.h b/packages/react-native/ReactCommon/react/renderer/core/LayoutableShadowNode.h index e983dce2ad31..7ec834c6a3d1 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/LayoutableShadowNode.h +++ b/packages/react-native/ReactCommon/react/renderer/core/LayoutableShadowNode.h @@ -31,11 +31,13 @@ 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}; @@ -43,7 +45,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` @@ -51,8 +53,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); /* @@ -62,35 +64,43 @@ 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. @@ -137,7 +147,9 @@ 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: @@ -150,7 +162,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 a197824f1bff..df4fa60eb3c0 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/Props.h +++ b/packages/react-native/ReactCommon/react/renderer/core/Props.h @@ -30,10 +30,11 @@ 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; @@ -41,8 +42,8 @@ class Props : public virtual Sealable, public virtual DebugStringConvertible { virtual ~Props() = default; #endif - Props(const Props &other) = default; - Props &operator=(const Props &other) = delete; + Props(const Props& other) = default; + Props& operator=(const Props& other) = delete; /** * Set a prop value via iteration (see enableIterator above). @@ -54,8 +55,11 @@ 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; @@ -63,14 +67,14 @@ class Props : public virtual Sealable, public virtual DebugStringConvertible { folly::dynamic rawProps = folly::dynamic::object(); void initializeDynamicProps( - const Props &sourceProps, - const RawProps &rawProps, - [[maybe_unused]] const std::function &filterObjectKeys = nullptr); + const Props& sourceProps, + const RawProps& rawProps, + [[maybe_unused]] const std::function& + filterObjectKeys = nullptr); virtual ComponentName getDiffPropsImplementationTarget() const; - virtual folly::dynamic getDiffProps(const Props *prevProps) const - { + virtual folly::dynamic getDiffProps(const Props* prevProps) const { return folly::dynamic::object(); } #endif @@ -107,7 +111,8 @@ auto memberFunctionClass(T C::*) -> C; * fields would never be reached by the iterator-setter dispatch. */ template -concept DeclaresOwnSetProp = std::is_same_v; +concept DeclaresOwnSetProp = + std::is_same_v; /* * Internal: `T` exposes a `setProp(ctx, hash, name, value) -> void` callable @@ -115,7 +120,11 @@ concept DeclaresOwnSetProp = std::is_same_v concept HasSetProp = DeclaresOwnSetProp && - requires(T &t, const PropsParserContext &ctx, RawPropsPropNameHash hash, const char *name, const RawValue &value) { + requires(T& t, + const PropsParserContext& ctx, + RawPropsPropNameHash hash, + const char* name, + const RawValue& value) { { t.setProp(ctx, hash, name, value) } -> std::same_as; }; @@ -144,6 +153,7 @@ concept HasSetProp = DeclaresOwnSetProp && * for that component regardless of the runtime flag. */ template -concept HasIteratorSetterCtor = std::copy_constructible && std::derived_from && HasSetProp; +concept HasIteratorSetterCtor = + std::copy_constructible && std::derived_from && HasSetProp; } // 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 b6cc947972f4..b109ad34bd54 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/PropsMacros.h +++ b/packages/react-native/ReactCommon/react/renderer/core/PropsMacros.h @@ -21,7 +21,7 @@ // Get hash at compile-time. sizeof(str) - 1 == strlen #define CONSTEXPR_RAW_PROPS_KEY_HASH(s) \ - ([]() constexpr -> RawPropsPropNameHash { \ + ([]() constexpr->RawPropsPropNameHash { \ CLANG_PRAGMA("clang diagnostic push") \ CLANG_PRAGMA("clang diagnostic ignored \"-Wshadow\"") \ return RAW_PROPS_KEY_HASH(s); \ @@ -40,60 +40,89 @@ // 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 b5abcfc30969..dee30506aa38 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 e6f5c07def98..dafb501ca788 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/RawProps.h +++ b/packages/react-native/ReactCommon/react/renderer/core/RawProps.h @@ -49,13 +49,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. @@ -65,7 +65,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. @@ -79,7 +79,9 @@ 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. @@ -91,11 +93,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 noexcept; + const RawValue* at(const char* name) const noexcept; // Deprecated: Use at(name) instead. This overload exists for backwards // compatibility with callers that pass prefix/suffix separately. - 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; /* * Iterates the underlying source object and invokes `fn(name, value)` for @@ -104,13 +107,13 @@ class RawProps final { * (no `folly::dynamic` materialization). For `Mode::Dynamic` it walks * `dynamic_.items()`. For `Mode::Empty` it is a no-op. * - * The callback signature is `void(std::string_view name, const RawValue &value)`. - * The view points into storage owned by `forEachItem` for the duration of - * the call and is null-terminated (i.e. `name.data()` is a valid C string). + * The callback signature is `void(std::string_view name, const RawValue + * &value)`. The view points into storage owned by `forEachItem` for the + * duration of the call and is null-terminated (i.e. `name.data()` is a valid + * C string). */ template - void forEachItem(Fn fn) const - { + void forEachItem(Fn fn) const { switch (mode_) { case Mode::Empty: return; @@ -122,12 +125,13 @@ class RawProps final { auto name = names.getValueAtIndex(*runtime_, i).getString(*runtime_); auto propValue = object.getProperty(*runtime_, name); auto nameUtf8 = name.utf8(*runtime_); - fn(std::string_view{nameUtf8}, RawValue{*runtime_, std::move(propValue)}); + fn(std::string_view{nameUtf8}, + RawValue{*runtime_, std::move(propValue)}); } return; } case Mode::Dynamic: - for (const auto &pair : dynamic_.items()) { + for (const auto& pair : dynamic_.items()) { fn(std::string_view{pair.first.getString()}, RawValue{pair.second}); } return; @@ -139,7 +143,7 @@ class RawProps final { private: friend class RawPropsParser; - mutable const RawPropsParser *parser_{nullptr}; + mutable const RawPropsParser* parser_{nullptr}; /* * Source artefacts: @@ -149,7 +153,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`. @@ -177,8 +181,10 @@ class RawProps final { * Java. */ template -concept RawPropsFilterable = requires(RawProps &rawProps) { - { T::filterRawProps(rawProps) } -> std::same_as; -}; +concept RawPropsFilterable = requires(RawProps& rawProps) { + { + T::filterRawProps(rawProps) + } -> std::same_as; + }; } // 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 15f438af59c3..1ccd5be8e5c8 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/RawPropsKeyMap.h +++ b/packages/react-native/ReactCommon/react/renderer/core/RawPropsKeyMap.h @@ -46,8 +46,10 @@ 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 c98379b4f833..385dca6b9f38 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/RawPropsParser.h +++ b/packages/react-native/ReactCommon/react/renderer/core/RawPropsParser.h @@ -28,15 +28,17 @@ class RawPropsParser final { * To be used by `ConcreteComponentDescriptor` only. */ RawPropsParser() = default; - [[deprecated]] explicit RawPropsParser(bool /* ignored */) : RawPropsParser() {} + [[deprecated]] explicit RawPropsParser(bool /* ignored */) + : RawPropsParser() {} /* * 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. @@ -60,7 +62,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`. @@ -70,7 +72,8 @@ class RawPropsParser final { /* * To be used by `RawProps` only. */ - const RawValue *at(const RawProps &rawProps, std::string_view key) const noexcept; + const RawValue* at(const RawProps& rawProps, std::string_view 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 c63b2aad7e4b..e2a9f6714cbf 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/RawPropsPrimitives.h +++ b/packages/react-native/ReactCommon/react/renderer/core/RawPropsPrimitives.h @@ -16,14 +16,17 @@ 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 560b54a67a40..f6fa78e0f7a8 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/RawValue.h +++ b/packages/react-native/ReactCommon/react/renderer/core/RawValue.h @@ -57,54 +57,48 @@ 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)); } } @@ -116,23 +110,21 @@ 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); } } @@ -141,133 +133,158 @@ 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; } @@ -282,32 +299,34 @@ 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; } @@ -317,117 +336,133 @@ 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"); } - 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)); @@ -437,28 +472,30 @@ 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)); @@ -468,7 +505,8 @@ 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; @@ -476,22 +514,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); @@ -508,7 +546,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 99a96bef25bd..f85a9a01b7be 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/ReactEventPriority.h +++ b/packages/react-native/ReactCommon/react/renderer/core/ReactEventPriority.h @@ -37,9 +37,10 @@ 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 84bdffabbf23..de546adf143c 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.h b/packages/react-native/ReactCommon/react/renderer/core/Sealable.h index 55930d460084..72603b510f0a 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/Sealable.h +++ b/packages/react-native/ReactCommon/react/renderer/core/Sealable.h @@ -49,8 +49,7 @@ namespace facebook::react { class Sealable { public: inline void seal() const {} - inline bool getSealed() const - { + inline bool getSealed() const { return true; } inline void ensureUnsealed() const {} @@ -62,11 +61,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 1b3a6d8404ab..da4efee7dced 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/ShadowNode.h +++ b/packages/react-native/ReactCommon/react/renderer/core/ShadowNode.h @@ -28,34 +28,38 @@ 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: - using SharedListOfShared - [[deprecated("Use std::shared_ptr>> instead")]] = - std::shared_ptr>>; - using UnsharedListOfShared - [[deprecated("Use std::shared_ptr>> instead")]] = - std::shared_ptr>>; - using UnsharedListOfWeak [[deprecated("Use std::shared_ptr>> instead")]] = + using SharedListOfShared [[deprecated( + "Use std::shared_ptr>> instead")]] = + std::shared_ptr>>; + using UnsharedListOfShared [[deprecated( + "Use std::shared_ptr>> instead")]] = + std::shared_ptr>>; + using UnsharedListOfWeak [[deprecated( + "Use std::shared_ptr>> instead")]] = std::shared_ptr>>; - using AncestorList = - std::vector /* parentNode */, int /* childIndex */>>; + using AncestorList = std::vector /* parentNode */, + int /* childIndex */>>; - static std::shared_ptr>> emptySharedShadowNodeSharedList(); + static std::shared_ptr>> + emptySharedShadowNodeSharedList(); /* * 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{}; } @@ -68,27 +72,32 @@ class ShadowNode : public Sealable, public DebugStringConvertible, public jsi::N /* * 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; ~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 @@ -98,8 +107,9 @@ class ShadowNode : public Sealable, public DebugStringConvertible, public jsi::N * 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 @@ -109,16 +119,19 @@ class ShadowNode : public Sealable, public DebugStringConvertible, public jsi::N * Returns `nullptr` if the operation cannot be performed successfully. */ std::shared_ptr cloneMultiple( - const std::unordered_set> &familiesToUpdate, - const std::function< - std::shared_ptr(const ShadowNode &oldShadowNode, const ShadowNodeFragment &fragment)> &callback) - const; + const std::unordered_set>& + familiesToUpdate, + const std::function( + 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 @@ -130,17 +143,17 @@ class ShadowNode : public Sealable, public DebugStringConvertible, public jsi::N */ 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. @@ -150,7 +163,7 @@ class ShadowNode : public Sealable, public DebugStringConvertible, public jsi::N /* * 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 @@ -170,16 +183,16 @@ class ShadowNode : public Sealable, public DebugStringConvertible, public jsi::N 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()); /* @@ -199,19 +212,21 @@ class ShadowNode : public Sealable, public DebugStringConvertible, public jsi::N * 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 @@ -231,7 +246,8 @@ class ShadowNode : public Sealable, public DebugStringConvertible, public jsi::N protected: Props::Shared props_; - std::shared_ptr>> children_; + std::shared_ptr>> + children_; State::Shared state_; int orderIndex_; @@ -257,7 +273,8 @@ class ShadowNode : public Sealable, public DebugStringConvertible, public jsi::N * 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. @@ -270,7 +287,9 @@ class ShadowNode : public Sealable, public DebugStringConvertible, public jsi::N */ mutable std::atomic hasBeenMounted_{false}; - static Props::Shared propsForClonedShadowNode(const ShadowNode &sourceShadowNode, const Props::Shared &props); + static Props::Shared propsForClonedShadowNode( + const ShadowNode& sourceShadowNode, + const Props::Shared& props); protected: /* @@ -285,10 +304,13 @@ class ShadowNode : public Sealable, public DebugStringConvertible, public jsi::N 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 d32b4458c0bf..b0a1bd45282b 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/ShadowNodeFamily.h +++ b/packages/react-native/ReactCommon/react/renderer/core/ShadowNodeFamily.h @@ -45,21 +45,22 @@ 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); + void setParent(const ShadowNodeFamily::Shared& parent); /* * Returns a handle (or name) associated with the component. @@ -70,7 +71,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 +82,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,13 +92,14 @@ class ShadowNodeFamily final : public jsi::NativeState { * @param callback will be executed when an unmounted instance of * ShadowNodeFamily is destroyed. */ - void onUnmountedFamilyDestroyed(std::function callback); + void onUnmountedFamilyDestroyed( + std::function callback); /* * Sets and gets the most recent state. */ std::shared_ptr getMostRecentState() const; - void setMostRecentState(const std::shared_ptr &state); + void setMostRecentState(const std::shared_ptr& state); /** * Mark this ShadowNodeFamily as mounted. @@ -107,7 +109,9 @@ class ShadowNodeFamily final : public jsi::NativeState { /* * Dispatches a state update with given priority. */ - void dispatchRawState(StateUpdate &&stateUpdate, EventQueue::UpdateMode updateMode); + void dispatchRawState( + StateUpdate&& stateUpdate, + EventQueue::UpdateMode updateMode); /* * Holds currently applied native props. `nullptr` if setNativeProps API is @@ -122,9 +126,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); + void setInstanceHandle(InstanceHandle::Shared& instanceHandle); /** * Override destructor to call onUnmountedFamilyDestroyedCallback() for @@ -141,13 +145,15 @@ 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_; std::shared_ptr mostRecentState_; mutable std::shared_mutex mutex_; - std::function onUnmountedFamilyDestroyedCallback_ = nullptr; + std::function + onUnmountedFamilyDestroyedCallback_ = nullptr; /* * Deprecated. @@ -173,7 +179,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 c03c97722902..d97cc078f10b 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/ShadowNodeFragment.h +++ b/packages/react-native/ReactCommon/react/renderer/core/ShadowNodeFragment.h @@ -23,9 +23,10 @@ namespace facebook::react { * retain ownership of them. */ struct ShadowNodeFragment { - const Props::Shared &props = propsPlaceholder(); - const std::shared_ptr>> &children = childrenPlaceholder(); - const State::Shared &state = statePlaceholder(); + const Props::Shared& props = propsPlaceholder(); + const std::shared_ptr>>& + children = childrenPlaceholder(); + const State::Shared& state = statePlaceholder(); const bool runtimeShadowNodeReference = true; /* @@ -33,9 +34,11 @@ 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 std::shared_ptr>> &childrenPlaceholder(); - static const State::Shared &statePlaceholder(); + static const Props::Shared& propsPlaceholder(); + static const std::shared_ptr< + const std::vector>>& + 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 cb401a161ced..a6896b846783 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/ShadowNodeTraits.h +++ b/packages/react-native/ReactCommon/react/renderer/core/ShadowNodeTraits.h @@ -96,23 +96,19 @@ 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.h b/packages/react-native/ReactCommon/react/renderer/core/State.h index fab24360dea7..21980378075f 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,8 +77,7 @@ 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 22fb42fd94bc..bca7bc4be046 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/StateData.h +++ b/packages/react-native/ReactCommon/react/renderer/core/StateData.h @@ -24,9 +24,8 @@ struct StateData final { #ifdef RN_SERIALIZABLE_STATE StateData() = default; - StateData(const StateData &previousState, folly::dynamic data) {} - folly::dynamic getDynamic() const - { + StateData(const StateData& previousState, folly::dynamic data) {} + folly::dynamic getDynamic() const { return {}; } #endif diff --git a/packages/react-native/ReactCommon/react/renderer/core/StatePipe.h b/packages/react-native/ReactCommon/react/renderer/core/StatePipe.h index a32a00b81111..0b2b65c46729 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 c4b75217e059..d1a8e381f6c7 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/StateUpdate.h +++ b/packages/react-native/ReactCommon/react/renderer/core/StateUpdate.h @@ -18,7 +18,8 @@ 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 ddf262293e32..ba554335f540 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 205929a8e020..b0e1398ffac4 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 d40427c40ded..22761fd56fc9 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/conversions.h +++ b/packages/react-native/ReactCommon/react/renderer/core/conversions.h @@ -11,8 +11,7 @@ namespace facebook::react { -inline std::string toString(const LayoutDirection &layoutDirection) -{ +inline std::string toString(const LayoutDirection& layoutDirection) { switch (layoutDirection) { case LayoutDirection::Undefined: return "undefined"; @@ -23,8 +22,7 @@ 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; @@ -35,8 +33,7 @@ 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; @@ -49,8 +46,7 @@ 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"; @@ -63,15 +59,16 @@ 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 37fcc87ca379..e9c8b579d3aa 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/graphicsConversions.h +++ b/packages/react-native/ReactCommon/react/renderer/core/graphicsConversions.h @@ -32,28 +32,27 @@ 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"; @@ -74,8 +73,7 @@ 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; @@ -83,11 +81,13 @@ 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,11 +112,13 @@ inline void fromRawValue(const PropsParserContext & /*context*/, const RawValue } } -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") { @@ -144,8 +146,10 @@ inline void fromRawValue(const PropsParserContext & /*context*/, const RawValue } } -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}; @@ -154,7 +158,7 @@ inline void fromRawValue(const PropsParserContext & /*context*/, const RawValue 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") { @@ -176,7 +180,11 @@ inline void fromRawValue(const PropsParserContext & /*context*/, const RawValue 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(); @@ -187,8 +195,7 @@ inline void fromRawValue(const PropsParserContext & /*context*/, const RawValue } #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; @@ -198,17 +205,23 @@ 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") { @@ -230,7 +243,11 @@ inline void fromRawValue(const PropsParserContext & /*context*/, const RawValue 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(); } @@ -244,31 +261,29 @@ inline void fromRawValue(const PropsParserContext & /*context*/, const RawValue #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 94a1e70545e8..e7012d2789a3 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/propsConversions.h +++ b/packages/react-native/ReactCommon/react/renderer/core/propsConversions.h @@ -17,8 +17,7 @@ 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,17 +25,15 @@ 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); @@ -44,8 +41,7 @@ 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); @@ -53,8 +49,7 @@ 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); @@ -62,20 +57,18 @@ 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; @@ -89,8 +82,11 @@ 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; @@ -100,28 +96,34 @@ void fromRawValue(const PropsParserContext &context, const RawValue &rawValue, T } 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); @@ -138,14 +140,16 @@ void fromRawValue(const PropsParserContext &context, const RawValue &rawValue, s } 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); @@ -163,13 +167,12 @@ void fromRawValue(const PropsParserContext &context, const RawValue &rawValue, s template T convertRawProp( - const PropsParserContext &context, - const RawProps &rawProps, - const char *name, - const T &sourceValue, - const U &defaultValue) -{ - const auto *rawValue = rawProps.at(name); + const PropsParserContext& context, + const RawProps& rawProps, + const char* name, + const T& sourceValue, + const U& defaultValue) { + const auto* rawValue = rawProps.at(name); if (rawValue == nullptr) [[likely]] { return sourceValue; } @@ -184,7 +187,7 @@ 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 // TODO: report this using ErrorUtils so it's more visible to the user LOG(ERROR) << "Error while converting prop '" << name << "': " << e.what(); 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 3a0ac5f5cdae..4ba4ee25344d 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/tests/TestComponent.h +++ b/packages/react-native/ReactCommon/react/renderer/core/tests/TestComponent.h @@ -29,10 +29,9 @@ 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 @@ -45,10 +44,11 @@ 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,26 +57,30 @@ class TestShadowNode; using SharedTestShadowNode = std::shared_ptr; -class TestShadowNode final : public ConcreteViewShadowNode { +class TestShadowNode final : public ConcreteViewShadowNode< + TestComponentName, + TestProps, + ViewEventEmitter, + TestState> { 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 bf7bcb1a7908..7f89682335e9 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 08dfe44648a1..4e2255f180cf 100644 --- a/packages/react-native/ReactCommon/react/renderer/css/CSSAngleUnit.h +++ b/packages/react-native/ReactCommon/react/renderer/css/CSSAngleUnit.h @@ -30,8 +30,7 @@ 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; @@ -49,8 +48,7 @@ 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 75daa6853d85..0ef7ee2b782b 100644 --- a/packages/react-native/ReactCommon/react/renderer/css/CSSBackgroundImage.h +++ b/packages/react-native/ReactCommon/react/renderer/css/CSSBackgroundImage.h @@ -67,19 +67,19 @@ 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(CSSValueParser &parser) -> std::optional - { + static constexpr auto consume(CSSValueParser& parser) + -> std::optional { return parseLinearGradientDirection(parser); } private: - static constexpr std::optional parseLinearGradientDirection(CSSValueParser &parser) - { + static constexpr std::optional + parseLinearGradientDirection(CSSValueParser& parser) { auto angle = parser.parseNextValue(); if (std::holds_alternative(angle)) { return CSSLinearGradientDirection{std::get(angle)}; @@ -105,10 +105,17 @@ struct CSSDataTypeParser { if (std::holds_alternative(secondaryPeek)) { auto kw = std::get(secondaryPeek); bool isCompatible = false; - if (primaryDir == CSSGradientDirectionKeyword::Top || primaryDir == CSSGradientDirectionKeyword::Bottom) { - isCompatible = (kw == CSSGradientDirectionKeyword::Left || kw == CSSGradientDirectionKeyword::Right); - } else if (primaryDir == CSSGradientDirectionKeyword::Left || primaryDir == CSSGradientDirectionKeyword::Right) { - isCompatible = (kw == CSSGradientDirectionKeyword::Top || kw == CSSGradientDirectionKeyword::Bottom); + if (primaryDir == CSSGradientDirectionKeyword::Top || + primaryDir == CSSGradientDirectionKeyword::Bottom) { + isCompatible = + (kw == CSSGradientDirectionKeyword::Left || + kw == CSSGradientDirectionKeyword::Right); + } else if ( + primaryDir == CSSGradientDirectionKeyword::Left || + primaryDir == CSSGradientDirectionKeyword::Right) { + isCompatible = + (kw == CSSGradientDirectionKeyword::Top || + kw == CSSGradientDirectionKeyword::Bottom); } if (isCompatible) { parser.parseNextValue(); @@ -118,36 +125,44 @@ struct CSSDataTypeParser { if (primaryDir == CSSGradientDirectionKeyword::Top) { if (secondaryDir == CSSGradientDirectionKeyword::Left) { - return CSSLinearGradientDirection{CSSLinearGradientDirectionKeyword::ToTopLeft}; + return CSSLinearGradientDirection{ + CSSLinearGradientDirectionKeyword::ToTopLeft}; } else if (secondaryDir == CSSGradientDirectionKeyword::Right) { - return CSSLinearGradientDirection{CSSLinearGradientDirectionKeyword::ToTopRight}; + return CSSLinearGradientDirection{ + CSSLinearGradientDirectionKeyword::ToTopRight}; } else { // "to top" = 0 degrees return CSSLinearGradientDirection{CSSAngle{0.0f}}; } } else if (primaryDir == CSSGradientDirectionKeyword::Bottom) { if (secondaryDir == CSSGradientDirectionKeyword::Left) { - return CSSLinearGradientDirection{CSSLinearGradientDirectionKeyword::ToBottomLeft}; + return CSSLinearGradientDirection{ + CSSLinearGradientDirectionKeyword::ToBottomLeft}; } else if (secondaryDir == CSSGradientDirectionKeyword::Right) { - return CSSLinearGradientDirection{CSSLinearGradientDirectionKeyword::ToBottomRight}; + return CSSLinearGradientDirection{ + CSSLinearGradientDirectionKeyword::ToBottomRight}; } else { // "to bottom" = 180 degrees return CSSLinearGradientDirection{CSSAngle{180.0f}}; } } else if (primaryDir == CSSGradientDirectionKeyword::Left) { if (secondaryDir == CSSGradientDirectionKeyword::Top) { - return CSSLinearGradientDirection{CSSLinearGradientDirectionKeyword::ToTopLeft}; + return CSSLinearGradientDirection{ + CSSLinearGradientDirectionKeyword::ToTopLeft}; } else if (secondaryDir == CSSGradientDirectionKeyword::Bottom) { - return CSSLinearGradientDirection{CSSLinearGradientDirectionKeyword::ToBottomLeft}; + return CSSLinearGradientDirection{ + CSSLinearGradientDirectionKeyword::ToBottomLeft}; } else { // "to left" = 270 degrees return CSSLinearGradientDirection{CSSAngle{270.0f}}; } } else if (primaryDir == CSSGradientDirectionKeyword::Right) { if (secondaryDir == CSSGradientDirectionKeyword::Top) { - return CSSLinearGradientDirection{CSSLinearGradientDirectionKeyword::ToTopRight}; + return CSSLinearGradientDirection{ + CSSLinearGradientDirectionKeyword::ToTopRight}; } else if (secondaryDir == CSSGradientDirectionKeyword::Bottom) { - return CSSLinearGradientDirection{CSSLinearGradientDirectionKeyword::ToBottomRight}; + return CSSLinearGradientDirection{ + CSSLinearGradientDirectionKeyword::ToBottomRight}; } else { // "to right" = 90 degrees return CSSLinearGradientDirection{CSSAngle{90.0f}}; @@ -164,21 +179,20 @@ 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 = default; + bool operator==(const CSSColorHint& rhs) const = default; }; template <> struct CSSDataTypeParser { - static auto consume(CSSValueParser &parser) -> std::optional - { + static auto consume(CSSValueParser& parser) -> std::optional { return parseCSSColorHint(parser); } private: - static std::optional parseCSSColorHint(CSSValueParser &parser) - { + static std::optional parseCSSColorHint(CSSValueParser& parser) { auto position = parser.parseNextValue(); if (std::holds_alternative(position)) { return CSSColorHint{std::get(position)}; @@ -196,8 +210,7 @@ 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; } @@ -232,14 +245,14 @@ struct CSSColorStop { template <> struct CSSDataTypeParser { - static constexpr auto consume(CSSValueParser &parser) -> std::optional - { + static constexpr auto consume(CSSValueParser& parser) + -> std::optional { return parseCSSColorStop(parser); } private: - static constexpr std::optional parseCSSColorStop(CSSValueParser &parser) - { + static constexpr std::optional parseCSSColorStop( + CSSValueParser& parser) { auto color = parser.parseNextValue(); if (!std::holds_alternative(color)) { return {}; @@ -248,7 +261,8 @@ struct CSSDataTypeParser { CSSColorStop colorStop; colorStop.color = std::get(color); - auto startPosition = parser.parseNextValue(CSSDelimiter::Whitespace); + auto startPosition = + parser.parseNextValue(CSSDelimiter::Whitespace); if (std::holds_alternative(startPosition)) { colorStop.startPosition = std::get(startPosition); } else if (std::holds_alternative(startPosition)) { @@ -258,7 +272,8 @@ struct CSSDataTypeParser { if (colorStop.startPosition) { // Try to parse second optional position (supports both lengths and // percentages) - auto endPosition = parser.parseNextValue(CSSDelimiter::Whitespace); + auto endPosition = + parser.parseNextValue(CSSDelimiter::Whitespace); if (std::holds_alternative(endPosition)) { colorStop.endPosition = std::get(endPosition); } else if (std::holds_alternative(endPosition)) { @@ -273,13 +288,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( - CSSValueParser &parser) - { + static std::pair>, int> + parseGradientColorStopsAndHints(CSSValueParser& parser) { std::vector> items; int colorStopCount = 0; @@ -298,7 +313,8 @@ struct CSSLinearGradientFunction { if (!prevColorStop) { return {}; } - auto nextColorStop = parser.peekNextValue(CSSDelimiter::Comma); + auto nextColorStop = + parser.peekNextValue(CSSDelimiter::Comma); if (!std::holds_alternative(nextColorStop)) { return {}; } @@ -320,8 +336,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")) { @@ -345,9 +361,8 @@ 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")) { @@ -370,13 +385,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(CSSValueParser &syntaxParser) -> std::optional - { + static auto consume(CSSValueParser& syntaxParser) + -> std::optional { auto sizeX = syntaxParser.parseNextValue(); if (std::holds_alternative(sizeX)) { return {}; @@ -393,7 +408,8 @@ 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 { @@ -409,7 +425,8 @@ struct CSSDataTypeParser { static_assert(CSSDataType); -using CSSRadialGradientSize = std::variant; +using CSSRadialGradientSize = + std::variant; struct CSSRadialGradientPosition { std::optional> top{}; @@ -417,23 +434,24 @@ struct CSSRadialGradientPosition { std::optional> left{}; std::optional> right{}; - bool operator==(const CSSRadialGradientPosition &rhs) const = default; + bool operator==(const CSSRadialGradientPosition& rhs) const = default; }; 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, CSSValueParser &parser) - -> std::optional - { + static auto consumeFunctionBlock( + const CSSFunctionBlock& func, + CSSValueParser& parser) -> std::optional { if (!iequals(func.name, "radial-gradient")) { return {}; } @@ -449,34 +467,40 @@ struct CSSDataTypeParser { std::optional sizeResult; - auto sizeKeywordResult = parser.parseNextValue(); + auto sizeKeywordResult = + parser.parseNextValue(); - if (std::holds_alternative(sizeKeywordResult)) { - sizeResult = CSSRadialGradientSize{std::get(sizeKeywordResult)}; + if (std::holds_alternative( + sizeKeywordResult)) { + sizeResult = CSSRadialGradientSize{ + std::get(sizeKeywordResult)}; parser.syntaxParser().consumeWhitespace(); } else { - auto explicitSizeResult = parser.parseNextValue(); - if (std::holds_alternative(explicitSizeResult)) { - auto explicitSize = std::get(explicitSizeResult); + auto explicitSizeResult = + parser.parseNextValue(); + 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 {}; } @@ -505,14 +529,16 @@ 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 {}; @@ -525,21 +551,24 @@ struct CSSDataTypeParser { if (hasAtKeyword) { parser.syntaxParser().consumeWhitespace(); - std::vector> positionKeywordValues; + std::vector> + positionKeywordValues; for (int i = 0; i < 2; i++) { auto keywordFound = false; auto valueFound = false; - auto positionKeywordResult = parser.parseNextValue(); + auto positionKeywordResult = + parser.parseNextValue(); std::optional positionKeyword; - if (std::holds_alternative(positionKeywordResult)) { - positionKeyword = - static_cast(to_underlying(std::get(positionKeywordResult))); + if (std::holds_alternative( + positionKeywordResult)) { + positionKeyword = static_cast(to_underlying( + std::get(positionKeywordResult))); } 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 {}; @@ -552,12 +581,14 @@ struct CSSDataTypeParser { parser.syntaxParser().consumeWhitespace(); - auto lengthPercentageValue = parser.parseNextValue(); + auto lengthPercentageValue = + parser.parseNextValue(); 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()) { @@ -599,7 +630,8 @@ 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 { @@ -615,14 +647,17 @@ 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 @@ -676,7 +711,8 @@ 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 { @@ -697,7 +733,8 @@ 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 { @@ -723,19 +760,25 @@ 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); @@ -775,7 +818,8 @@ struct CSSDataTypeParser { } parser.syntaxParser().consumeDelimiter(CSSDelimiter::Comma); - auto [items, colorStopCount] = CSSLinearGradientFunction::parseGradientColorStopsAndHints(parser); + auto [items, colorStopCount] = + CSSLinearGradientFunction::parseGradientColorStopsAndHints(parser); if (items.empty() || colorStopCount < 2) { return {}; @@ -790,9 +834,9 @@ static_assert(CSSDataType); template <> struct CSSDataTypeParser { - static auto consumeFunctionBlock(const CSSFunctionBlock &func, CSSValueParser &parser) - -> std::optional - { + static auto consumeFunctionBlock( + const CSSFunctionBlock& func, + CSSValueParser& parser) -> std::optional { if (!iequals(func.name, "linear-gradient")) { return {}; } @@ -808,7 +852,8 @@ 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 {}; @@ -826,7 +871,8 @@ static_assert(CSSDataType); * Representation of * https://www.w3.org/TR/css-backgrounds-3/#background-image */ -using CSSBackgroundImage = CSSCompoundDataType; +using CSSBackgroundImage = + CSSCompoundDataType; /** * Representation of diff --git a/packages/react-native/ReactCommon/react/renderer/css/CSSColor.h b/packages/react-native/ReactCommon/react/renderer/css/CSSColor.h index 91924cf389d6..8528f74212d9 100644 --- a/packages/react-native/ReactCommon/react/renderer/css/CSSColor.h +++ b/packages/react-native/ReactCommon/react/renderer/css/CSSColor.h @@ -26,18 +26,17 @@ 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 { if (token.type() == CSSTokenType::Ident) { return parseCSSNamedColor(token.stringValue()); } else if (token.type() == CSSTokenType::Hash) { @@ -47,9 +46,9 @@ struct CSSDataTypeParser { return {}; } - static constexpr auto consumeFunctionBlock(const CSSFunctionBlock &func, CSSValueParser &parser) - -> std::optional - { + static constexpr auto consumeFunctionBlock( + const CSSFunctionBlock& func, + CSSValueParser& 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 76c7da2b5292..614274499c85 100644 --- a/packages/react-native/ReactCommon/react/renderer/css/CSSColorFunction.h +++ b/packages/react-native/ReactCommon/react/renderer/css/CSSColorFunction.h @@ -25,8 +25,7 @@ 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 +35,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,19 +44,18 @@ constexpr std::optional normalizeNumberComponent(const std::variant 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)) { @@ -67,8 +65,7 @@ inline std::optional normalizeHueComponent(const std::variant 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); @@ -106,8 +103,8 @@ inline std::tuple 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); @@ -132,11 +129,13 @@ inline std::tuple 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,8 +152,7 @@ constexpr std::optional normalizeComponent( } template -constexpr bool isLegacyColorFunction(CSSValueParser &parser) -{ +constexpr bool isLegacyColorFunction(CSSValueParser& parser) { auto saved = parser.syntaxParser(); auto next = parser.parseNextValue(); if (std::holds_alternative(next)) { @@ -174,8 +172,8 @@ constexpr bool isLegacyColorFunction(CSSValueParser &parser) * https://www.w3.org/TR/css-color-4/#typedef-legacy-rgb-syntax */ template -constexpr std::optional parseLegacyRgbFunction(CSSValueParser &parser) -{ +constexpr std::optional parseLegacyRgbFunction( + CSSValueParser& parser) { auto rawRed = parser.parseNextValue(); bool usesNumber = std::holds_alternative(rawRed); @@ -184,19 +182,27 @@ constexpr std::optional parseLegacyRgbFunction(CSSValueParser &parser) return {}; } - auto green = usesNumber ? normalizeNumberComponent(parser.parseNextValue(CSSDelimiter::Comma)) - : normalizeComponent(parser.parseNextValue(CSSDelimiter::Comma), 255.0f); + auto green = usesNumber + ? normalizeNumberComponent( + parser.parseNextValue(CSSDelimiter::Comma)) + : normalizeComponent( + parser.parseNextValue(CSSDelimiter::Comma), 255.0f); if (!green.has_value()) { return {}; } - auto blue = usesNumber ? normalizeNumberComponent(parser.parseNextValue(CSSDelimiter::Comma)) - : normalizeComponent(parser.parseNextValue(CSSDelimiter::Comma), 255.0f); + auto blue = usesNumber + ? normalizeNumberComponent( + parser.parseNextValue(CSSDelimiter::Comma)) + : normalizeComponent( + parser.parseNextValue(CSSDelimiter::Comma), 255.0f); if (!blue.has_value()) { return {}; } - auto alpha = normalizeComponent(parser.parseNextValue(CSSDelimiter::Comma), 1.0f); + auto alpha = normalizeComponent( + parser.parseNextValue(CSSDelimiter::Comma), + 1.0f); return CSSColor{ .r = clamp255Component(*red), @@ -212,25 +218,32 @@ constexpr std::optional parseLegacyRgbFunction(CSSValueParser &parser) * https://www.w3.org/TR/css-color-4/#typedef-modern-rgb-syntax */ template -constexpr std::optional parseModernRgbFunction(CSSValueParser &parser) -{ - auto red = normalizeComponent(parser.parseNextValue(), 255.0f); +constexpr std::optional parseModernRgbFunction( + CSSValueParser& parser) { + auto red = normalizeComponent( + parser.parseNextValue(), 255.0f); if (!red.has_value()) { return {}; } - auto green = normalizeComponent(parser.parseNextValue(CSSDelimiter::Whitespace), 255.0f); + auto green = normalizeComponent( + parser.parseNextValue(CSSDelimiter::Whitespace), + 255.0f); if (!green.has_value()) { return {}; } - auto blue = normalizeComponent(parser.parseNextValue(CSSDelimiter::Whitespace), 255.0f); + auto blue = normalizeComponent( + parser.parseNextValue(CSSDelimiter::Whitespace), + 255.0f); if (!blue.has_value()) { return {}; } - auto alpha = - normalizeComponent(parser.parseNextValue(CSSDelimiter::SolidusOrWhitespace), 1.0f); + auto alpha = normalizeComponent( + parser.parseNextValue( + CSSDelimiter::SolidusOrWhitespace), + 1.0f); return CSSColor{ .r = clamp255Component(*red), @@ -245,8 +258,7 @@ constexpr std::optional parseModernRgbFunction(CSSValueParser &parser) * https://www.w3.org/TR/css-color-4/#funcdef-rgb */ template -constexpr std::optional parseRgbFunction(CSSValueParser &parser) -{ +constexpr std::optional parseRgbFunction(CSSValueParser& parser) { if (isLegacyColorFunction(parser)) { return parseLegacyRgbFunction(parser); } else { @@ -260,24 +272,27 @@ constexpr std::optional parseRgbFunction(CSSValueParser &parser) * https://www.w3.org/TR/css-color-4/#typedef-legacy-hsl-syntax */ template -inline std::optional parseLegacyHslFunction(CSSValueParser &parser) -{ +inline std::optional parseLegacyHslFunction(CSSValueParser& parser) { auto h = normalizeHueComponent(parser.parseNextValue()); if (!h.has_value()) { return {}; } - auto s = normalizeComponent(parser.parseNextValue(CSSDelimiter::Comma), 100.0f); + auto s = normalizeComponent( + parser.parseNextValue(CSSDelimiter::Comma), 100.0f); if (!s.has_value()) { return {}; } - auto l = normalizeComponent(parser.parseNextValue(CSSDelimiter::Comma), 100.0f); + auto l = normalizeComponent( + parser.parseNextValue(CSSDelimiter::Comma), 100.0f); if (!l.has_value()) { return {}; } - auto a = normalizeComponent(parser.parseNextValue(CSSDelimiter::Comma), 1.0f); + auto a = normalizeComponent( + parser.parseNextValue(CSSDelimiter::Comma), + 1.0f); auto [r, g, b] = hslToRgb(*h, *s, *l); @@ -294,24 +309,30 @@ inline std::optional parseLegacyHslFunction(CSSValueParser &parser) * it is valid. https://www.w3.org/TR/css-color-4/#typedef-modern-hsl-syntax */ template -inline std::optional parseModernHslFunction(CSSValueParser &parser) -{ +inline std::optional parseModernHslFunction(CSSValueParser& parser) { auto h = normalizeHueComponent(parser.parseNextValue()); if (!h.has_value()) { return {}; } - auto s = normalizeComponent(parser.parseNextValue(CSSDelimiter::Whitespace), 100.0f); + auto s = normalizeComponent( + parser.parseNextValue(CSSDelimiter::Whitespace), + 100.0f); if (!s.has_value()) { return {}; } - auto l = normalizeComponent(parser.parseNextValue(CSSDelimiter::Whitespace), 100.0f); + auto l = normalizeComponent( + parser.parseNextValue(CSSDelimiter::Whitespace), + 100.0f); if (!l.has_value()) { return {}; } - auto a = normalizeComponent(parser.parseNextValue(CSSDelimiter::SolidusOrWhitespace), 1.0f); + auto a = normalizeComponent( + parser.parseNextValue( + CSSDelimiter::SolidusOrWhitespace), + 1.0f); auto [r, g, b] = hslToRgb(*h, *s, *l); @@ -328,8 +349,7 @@ inline std::optional parseModernHslFunction(CSSValueParser &parser) * https://www.w3.org/TR/css-color-4/#funcdef-hsl */ template -inline std::optional parseHslFunction(CSSValueParser &parser) -{ +inline std::optional parseHslFunction(CSSValueParser& parser) { if (isLegacyColorFunction(parser)) { return parseLegacyHslFunction(parser); } else { @@ -342,24 +362,30 @@ inline std::optional parseHslFunction(CSSValueParser &parser) * https://www.w3.org/TR/css-color-4/#funcdef-hwb */ template -inline std::optional parseHwbFunction(CSSValueParser &parser) -{ +inline std::optional parseHwbFunction(CSSValueParser& parser) { auto h = normalizeHueComponent(parser.parseNextValue()); if (!h.has_value()) { return {}; } - auto w = normalizeComponent(parser.parseNextValue(CSSDelimiter::Whitespace), 100.0f); + auto w = normalizeComponent( + parser.parseNextValue(CSSDelimiter::Whitespace), + 100.0f); if (!w.has_value()) { return {}; } - auto b = normalizeComponent(parser.parseNextValue(CSSDelimiter::Whitespace), 100.0f); + auto b = normalizeComponent( + parser.parseNextValue(CSSDelimiter::Whitespace), + 100.0f); if (!b.has_value()) { return {}; } - auto a = normalizeComponent(parser.parseNextValue(CSSDelimiter::SolidusOrWhitespace), 1.0f); + auto a = normalizeComponent( + parser.parseNextValue( + CSSDelimiter::SolidusOrWhitespace), + 1.0f); auto [red, green, blue] = hwbToRgb(*h, *w, *b); @@ -379,8 +405,9 @@ inline std::optional parseHwbFunction(CSSValueParser &parser) * https://www.w3.org/TR/css-color-4/#typedef-color-function */ template -constexpr std::optional parseCSSColorFunction(std::string_view colorFunction, CSSValueParser &parser) -{ +constexpr std::optional parseCSSColorFunction( + std::string_view colorFunction, + CSSValueParser& 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 72fa717ca1e1..f44257d74df8 100644 --- a/packages/react-native/ReactCommon/react/renderer/css/CSSCompoundDataType.h +++ b/packages/react-native/ReactCommon/react/renderer/css/CSSCompoundDataType.h @@ -35,7 +35,8 @@ concept CSSValidCompoundDataType = detail::is_variant_of_data_types::value; * data types. */ template -concept CSSMaybeCompoundDataType = CSSDataType || CSSValidCompoundDataType; +concept CSSMaybeCompoundDataType = + CSSDataType || CSSValidCompoundDataType; namespace detail { @@ -43,24 +44,53 @@ namespace detail { template struct merge_data_types; -template -struct merge_data_types, std::variant, RestT...> { - using type = typename merge_data_types, RestT...>::type; +template < + CSSDataType... AlllowedTypes1T, + CSSDataType... AlllowedTypes2T, + CSSMaybeCompoundDataType... RestT> +struct merge_data_types< + std::variant, + std::variant, + RestT...> { + using type = typename merge_data_types< + std::variant, + RestT...>::type; }; -template -struct merge_data_types, RestT...> { - using type = typename merge_data_types, RestT...>::type; +template < + CSSDataType AlllowedType1T, + CSSDataType... AlllowedTypes2T, + CSSMaybeCompoundDataType... RestT> +struct merge_data_types< + AlllowedType1T, + std::variant, + RestT...> { + using type = typename merge_data_types< + std::variant, + RestT...>::type; }; -template -struct merge_data_types, AlllowedType2T, RestT...> { - using type = typename merge_data_types, RestT...>::type; +template < + CSSDataType AlllowedType2T, + CSSDataType... AlllowedTypes1T, + CSSMaybeCompoundDataType... RestT> +struct merge_data_types< + std::variant, + AlllowedType2T, + RestT...> { + using type = typename merge_data_types< + std::variant, + RestT...>::type; }; -template +template < + CSSDataType AlllowedType1T, + CSSDataType AlllowedType2T, + CSSMaybeCompoundDataType... RestT> struct merge_data_types { - using type = typename merge_data_types, RestT...>::type; + using type = typename merge_data_types< + std::variant, + RestT...>::type; }; template @@ -90,6 +120,7 @@ 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 99437d08ba3f..5dea88b526b2 100644 --- a/packages/react-native/ReactCommon/react/renderer/css/CSSDataType.h +++ b/packages/react-native/ReactCommon/react/renderer/css/CSSDataType.h @@ -31,9 +31,10 @@ struct CSSDataTypeParser {}; * function block scope. */ template -concept CSSFunctionBlockSink = requires(const CSSFunctionBlock &func, CSSValueParser &parser) { - { T::consumeFunctionBlock(func, parser) } -> std::convertible_to; -}; +concept CSSFunctionBlockSink = + requires(const CSSFunctionBlock& func, CSSValueParser& parser) { + { T::consumeFunctionBlock(func, parser) } -> std::convertible_to; + }; /** * Accepts a CSS simple block and may parse it into a concrete representation. @@ -41,41 +42,48 @@ concept CSSFunctionBlockSink = requires(const CSSFunctionBlock &func, CSSValuePa * block scope. */ template -concept CSSSimpleBlockSink = requires(const CSSSimpleBlock &block, CSSValueParser &parser) { - { T::consumeSimpleBlock(block, parser) } -> std::convertible_to; -}; +concept CSSSimpleBlockSink = + requires(const CSSSimpleBlock& block, CSSValueParser& parser) { + { T::consumeSimpleBlock(block, parser) } -> std::convertible_to; + }; /** * Accepts a CSS preserved token and may parse it into a concrete * representation. */ template -concept CSSPreservedTokenSink = requires(const CSSPreservedToken &token) { - { T::consumePreservedToken(token) } -> std::convertible_to; -}; +concept CSSPreservedTokenSink = requires(const CSSPreservedToken& token) { + { + T::consumePreservedToken(token) + } -> std::convertible_to; + }; /** * Accepts a CSSValueParser to be able to parse compounded values spanning * multiple component values. */ template -concept CSSParserSink = requires(CSSValueParser &parser) { - { T::consume(parser) } -> std::convertible_to; -}; +concept CSSParserSink = requires(CSSValueParser& parser) { + { + T::consume(parser) + } -> std::convertible_to; + }; /** * Represents a valid specialization of CSSDataTypeParser */ template -concept CSSValidDataTypeParser = - ((CSSFunctionBlockSink || CSSSimpleBlockSink || CSSPreservedTokenSink) && - !CSSParserSink) || +concept CSSValidDataTypeParser = ((CSSFunctionBlockSink || + CSSSimpleBlockSink || + CSSPreservedTokenSink) && + !CSSParserSink) || CSSParserSink; /** * Concrete representation for a CSS data type */ template -concept CSSDataType = CSSValidDataTypeParser, std::optional> && std::equality_comparable; +concept CSSDataType = CSSValidDataTypeParser < CSSDataTypeParser, +std::optional < T >> &&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 cfc0fd519185..48f77e1d99b4 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, CSSValueParser &parser) - -> std::optional - { + static constexpr auto consumeFunctionBlock( + const CSSFunctionBlock& func, + CSSValueParser& parser) -> std::optional { if (!iequals(func.name, Name)) { return {}; } @@ -60,20 +60,22 @@ 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, CSSValueParser &parser) - -> std::optional - { + static constexpr auto consumeFunctionBlock( + const CSSFunctionBlock& func, + CSSValueParser& parser) -> std::optional { if (!iequals(func.name, "blur")) { return {}; } auto len = parser.parseNextValue(); - return CSSBlurFilter{std::holds_alternative(len) ? std::get(len) : CSSLength{}}; + return CSSBlurFilter{ + std::holds_alternative(len) ? std::get(len) + : CSSLength{}}; } }; @@ -85,12 +87,13 @@ 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); @@ -100,12 +103,13 @@ 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); @@ -118,14 +122,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, CSSValueParser &parser) - -> std::optional - { + static constexpr auto consumeFunctionBlock( + const CSSFunctionBlock& func, + CSSValueParser& parser) -> std::optional { if (!iequals(func.name, "drop-shadow")) { return {}; } @@ -147,7 +151,8 @@ struct CSSDataTypeParser { } } - auto secondVal = parser.parseNextValue(CSSDelimiter::Whitespace); + auto secondVal = + parser.parseNextValue(CSSDelimiter::Whitespace); if (std::holds_alternative(secondVal)) { if (color.has_value()) { return {}; @@ -173,22 +178,27 @@ struct CSSDataTypeParser { } private: - static constexpr std::optional> parseLengths(CSSLength offsetX, CSSValueParser &parser) - { + static constexpr std::optional> parseLengths( + CSSLength offsetX, + CSSValueParser& parser) { auto offsetY = parser.parseNextValue(CSSDelimiter::Whitespace); if (!std::holds_alternative(offsetY)) { return {}; } - auto standardDeviation = parser.parseNextValue(CSSDelimiter::Whitespace); - if (std::holds_alternative(standardDeviation) && std::get(standardDeviation).value < 0.0f) { + auto standardDeviation = + parser.parseNextValue(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{}}; } }; @@ -200,12 +210,13 @@ 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); @@ -215,20 +226,23 @@ 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, CSSValueParser &parser) - -> std::optional - { + static constexpr auto consumeFunctionBlock( + const CSSFunctionBlock& func, + CSSValueParser& parser) -> std::optional { if (!iequals(func.name, "hue-rotate")) { return {}; } auto angle = parser.parseNextValue(); - return CSSHueRotateFilter{std::holds_alternative(angle) ? std::get(angle).degrees : 0.0f}; + return CSSHueRotateFilter{ + std::holds_alternative(angle) + ? std::get(angle).degrees + : 0.0f}; } }; @@ -240,11 +254,12 @@ 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); @@ -254,11 +269,13 @@ 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); @@ -268,12 +285,13 @@ 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); @@ -283,11 +301,12 @@ 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 b4749170fe43..9303ebfc2ba7 100644 --- a/packages/react-native/ReactCommon/react/renderer/css/CSSFontVariant.h +++ b/packages/react-native/ReactCommon/react/renderer/css/CSSFontVariant.h @@ -26,7 +26,8 @@ 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 89d126a4e43f..8caf1ec13a02 100644 --- a/packages/react-native/ReactCommon/react/renderer/css/CSSHexColor.h +++ b/packages/react-native/ReactCommon/react/renderer/css/CSSHexColor.h @@ -20,8 +20,7 @@ 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; @@ -41,16 +40,15 @@ 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; } @@ -70,8 +68,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{ @@ -84,7 +82,8 @@ constexpr std::optional parseCSSHexColor(std::string_view hexColorValu 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 f75901853c86..6f0b87cb83f3 100644 --- a/packages/react-native/ReactCommon/react/renderer/css/CSSKeyword.h +++ b/packages/react-native/ReactCommon/react/renderer/css/CSSKeyword.h @@ -124,7 +124,8 @@ enum class CSSKeyword : uint8_t { */ template concept CSSKeywordSet = - std::is_enum_v && std::is_same_v, std::underlying_type_t>; + std::is_enum_v && std::is_same_v < std::underlying_type_t, +std::underlying_type_t < CSSKeyword >> ; /** * CSS-wide keywords. @@ -254,8 +255,7 @@ 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(At) @@ -361,8 +361,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 900b9d93972f..130d84f1ab56 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,7 +42,8 @@ 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 1fc1a62cb630..b09199832a8e 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 98004ec4a096..138537d01c92 100644 --- a/packages/react-native/ReactCommon/react/renderer/css/CSSList.h +++ b/packages/react-native/ReactCommon/react/renderer/css/CSSList.h @@ -28,17 +28,20 @@ struct CSSList : public std::vector {}; template struct CSSDataTypeParser> { - static inline auto consume(CSSValueParser &parser) -> std::optional> - { + static inline auto consume(CSSValueParser& parser) + -> std::optional> { CSSList result; - for (auto nextValue = parser.parseNextValue(); !std::holds_alternative(nextValue); + for (auto nextValue = parser.parseNextValue(); + !std::holds_alternative(nextValue); nextValue = parser.parseNextValue(Delimeter)) { // 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::monostate>) { + [&](auto&& v) { + if constexpr (!std::is_same_v< + std::remove_cvref_t, + std::monostate>) { result.push_back(std::forward(v)); } }, @@ -67,6 +70,7 @@ 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 f77b7d338634..4ed3065c96bc 100644 --- a/packages/react-native/ReactCommon/react/renderer/css/CSSNamedColor.h +++ b/packages/react-native/ReactCommon/react/renderer/css/CSSNamedColor.h @@ -20,8 +20,7 @@ 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 d66eb56b3a1f..366c94ece6a6 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 39c4c2cb640f..42ed92aaf87a 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 6440f101b195..7ea09ceaae2e 100644 --- a/packages/react-native/ReactCommon/react/renderer/css/CSSRatio.h +++ b/packages/react-native/ReactCommon/react/renderer/css/CSSRatio.h @@ -24,22 +24,23 @@ 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(CSSValueParser &parser) -> std::optional - { + static constexpr auto consume(CSSValueParser& parser) + -> std::optional { // = [ / ]? // https://www.w3.org/TR/css-values-4/#ratio auto numerator = parser.parseNextValue(); @@ -50,9 +51,12 @@ struct CSSDataTypeParser { auto numeratorValue = std::get(numerator).value; if (numeratorValue >= 0) { auto denominator = parser.peekNextValue(CSSDelimiter::Solidus); - if (std::holds_alternative(denominator) && std::get(denominator).value >= 0) { + if (std::holds_alternative(denominator) && + std::get(denominator).value >= 0) { parser.parseNextValue(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 3e0788fc9ad9..9363ff427422 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,15 +46,20 @@ static_assert(CSSDataType); template <> struct CSSDataTypeParser { - static constexpr auto consume(CSSValueParser &parser) -> std::optional - { + static constexpr auto consume(CSSValueParser& parser) + -> std::optional { std::optional color{}; bool inset{false}; - std::optional> lengths{}; + std::optional> + lengths{}; - for (auto nextValue = parser.parseNextValue(); + for (auto nextValue = + parser + .parseNextValue(); !std::holds_alternative(nextValue); - nextValue = parser.parseNextValue(CSSDelimiter::Whitespace)) { + nextValue = + parser.parseNextValue( + CSSDelimiter::Whitespace)) { if (std::holds_alternative(nextValue)) { if (lengths.has_value()) { return {}; @@ -98,29 +103,40 @@ struct CSSDataTypeParser { } private: - static constexpr auto parseRestLengths(CSSLength offsetX, CSSValueParser &parser) - -> std::optional> - { + static constexpr auto parseRestLengths( + CSSLength offsetX, + CSSValueParser& parser) + -> std::optional> { auto offsetY = parser.parseNextValue(CSSDelimiter::Whitespace); if (std::holds_alternative(offsetY)) { return {}; } - auto blurRadius = parser.parseNextValue(CSSDelimiter::Whitespace); + auto blurRadius = + parser.parseNextValue(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 = parser.parseNextValue(CSSDelimiter::Whitespace); + auto spreadDistance = + parser.parseNextValue(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 248c9378395b..6c40a12a5a9c 100644 --- a/packages/react-native/ReactCommon/react/renderer/css/CSSSyntaxParser.h +++ b/packages/react-native/ReactCommon/react/renderer/css/CSSSyntaxParser.h @@ -39,7 +39,8 @@ 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. @@ -48,8 +49,8 @@ concept CSSSyntaxVisitorReturn = std::is_default_constructible_v && std::equa * 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; }; @@ -58,9 +59,10 @@ concept CSSFunctionVisitor = * 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 @@ -68,8 +70,8 @@ concept CSSPreservedTokenVisitor = CSSSyntaxVisitorReturn && requires(T * 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; }; @@ -78,15 +80,16 @@ concept CSSSimpleBlockVisitor = */ 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; @@ -111,7 +114,9 @@ enum class CSSDelimiter { * https://www.w3.org/TR/css-syntax-3/#component-value */ class CSSSyntaxParser { - template ... VisitorsT> + template < + CSSSyntaxVisitorReturn ReturnT, + CSSComponentValueVisitor... VisitorsT> friend struct CSSComponentValueVisitorDispatcher; friend class CSSValueParser; @@ -120,13 +125,14 @@ 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 @@ -155,26 +161,25 @@ 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(); } @@ -183,8 +188,7 @@ 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; } @@ -212,14 +216,16 @@ 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; @@ -235,26 +241,23 @@ class CSSSyntaxParser { /** * Returns the current token without consuming it. */ - constexpr const CSSToken &peek() const - { + constexpr const CSSToken& peek() const { return currentToken_; } 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 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_; } @@ -264,12 +267,15 @@ class CSSSyntaxParser { CSSTokenType terminator_{CSSTokenType::EndOfFile}; }; -template ... VisitorsT> +template < + CSSSyntaxVisitorReturn ReturnT, + CSSComponentValueVisitor... 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; @@ -295,17 +301,20 @@ 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; @@ -321,9 +330,8 @@ 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(); @@ -333,11 +341,13 @@ 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; } @@ -348,16 +358,14 @@ 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(); @@ -375,15 +383,13 @@ 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{}) { @@ -393,8 +399,7 @@ struct CSSComponentValueVisitorDispatcher { return visitPreservedToken(rest...); } - constexpr std::optional visitPreservedToken() - { + constexpr std::optional visitPreservedToken() { return {}; } }; @@ -402,15 +407,17 @@ 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 4194ea179924..e7e363365dd4 100644 --- a/packages/react-native/ReactCommon/react/renderer/css/CSSToken.h +++ b/packages/react-native/ReactCommon/react/renderer/css/CSSToken.h @@ -44,39 +44,35 @@ 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 17e3e6ccd708..208866ef57af 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)) { @@ -87,32 +87,28 @@ 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(); } @@ -121,8 +117,7 @@ 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))) { @@ -140,16 +135,17 @@ 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? @@ -161,14 +157,16 @@ 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(); @@ -178,8 +176,7 @@ 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() == '(') { @@ -191,8 +188,7 @@ 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(); @@ -201,8 +197,7 @@ 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(); @@ -210,36 +205,32 @@ 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 d287ce5327e1..2f922a94233c 100644 --- a/packages/react-native/ReactCommon/react/renderer/css/CSSTransform.h +++ b/packages/react-native/ReactCommon/react/renderer/css/CSSTransform.h @@ -26,12 +26,17 @@ namespace facebook::react { namespace detail { -template - requires(std::is_same_v>) +template < + typename DataT, + TemplateStringLiteral Name, + CSSDataType... AllowedComponentsT> + requires(std::is_same_v< + decltype(DataT::value), + std::variant>) struct CSSVariantComponentTransformParser { - static constexpr auto consumeFunctionBlock(const CSSFunctionBlock &func, CSSValueParser &parser) - -> std::optional - { + static constexpr auto consumeFunctionBlock( + const CSSFunctionBlock& func, + CSSValueParser& parser) -> std::optional { if (!iequals(func.name, Name)) { return {}; } @@ -39,8 +44,10 @@ struct CSSVariantComponentTransformParser { auto val = parser.parseNextValue(); return std::visit( - [&](auto &&v) -> std::optional { - if constexpr (std::is_same_v, std::monostate>) { + [&](auto&& v) -> std::optional { + if constexpr (std::is_same_v< + std::remove_cvref_t, + std::monostate>) { return {}; } else { return DataT{.value = std::forward(v)}; @@ -53,9 +60,9 @@ struct CSSVariantComponentTransformParser { template requires(std::is_same_v) struct CSSNumberPercentTransformParser { - static constexpr auto consumeFunctionBlock(const CSSFunctionBlock &func, CSSValueParser &parser) - -> std::optional - { + static constexpr auto consumeFunctionBlock( + const CSSFunctionBlock& func, + CSSValueParser& parser) -> std::optional { if (!iequals(func.name, Name)) { return {}; } @@ -66,17 +73,18 @@ 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, CSSValueParser &parser) - -> std::optional - { + static constexpr auto consumeFunctionBlock( + const CSSFunctionBlock& func, + CSSValueParser& parser) -> std::optional { if (!iequals(func.name, Name)) { return {}; } @@ -87,7 +95,9 @@ 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, }; } }; @@ -100,21 +110,22 @@ 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, CSSValueParser &parser) - -> std::optional - { + static constexpr auto consumeFunctionBlock( + const CSSFunctionBlock& func, + CSSValueParser& parser) -> std::optional { if (!iequals(func.name, "matrix")) { return {}; } CSSMatrix matrix{}; for (int i = 0; i < 6; i++) { - auto value = parser.parseNextValue(i == 0 ? CSSDelimiter::None : CSSDelimiter::Comma); + auto value = parser.parseNextValue( + i == 0 ? CSSDelimiter::None : CSSDelimiter::Comma); if (std::holds_alternative(value)) { return {}; } @@ -134,14 +145,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, CSSValueParser &parser) - -> std::optional - { + static constexpr auto consumeFunctionBlock( + const CSSFunctionBlock& func, + CSSValueParser& parser) -> std::optional { if (!iequals(func.name, "translate")) { return {}; } @@ -178,14 +189,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, CSSValueParser &parser) - -> std::optional - { + static constexpr auto consumeFunctionBlock( + const CSSFunctionBlock& func, + CSSValueParser& parser) -> std::optional { if (!iequals(func.name, "translate3d")) { return {}; } @@ -206,10 +217,14 @@ 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), }; } @@ -223,12 +238,16 @@ 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 {}; + : public detail::CSSVariantComponentTransformParser< + CSSTranslateX, + "translateX", + CSSLength, + CSSPercentage> {}; static_assert(CSSDataType); @@ -238,12 +257,16 @@ 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 {}; + : public detail::CSSVariantComponentTransformParser< + CSSTranslateY, + "translateY", + CSSLength, + CSSPercentage> {}; static_assert(CSSDataType); @@ -254,14 +277,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, CSSValueParser &parser) - -> std::optional - { + static constexpr auto consumeFunctionBlock( + const CSSFunctionBlock& func, + CSSValueParser& parser) -> std::optional { if (!iequals(func.name, "scale")) { return {}; } @@ -273,14 +296,17 @@ struct CSSDataTypeParser { return {}; } - auto y = parser.parseNextValue(CSSDelimiter::Comma); + auto y = + parser.parseNextValue(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}; } @@ -294,11 +320,12 @@ 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); @@ -308,11 +335,12 @@ 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); @@ -322,11 +350,12 @@ 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); @@ -336,11 +365,12 @@ 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); @@ -350,11 +380,12 @@ 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); @@ -364,11 +395,12 @@ 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); @@ -378,11 +410,12 @@ 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); @@ -392,11 +425,12 @@ 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); @@ -406,20 +440,21 @@ 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, CSSValueParser &parser) - -> std::optional - { + static constexpr auto consumeFunctionBlock( + const CSSFunctionBlock& func, + CSSValueParser& parser) -> std::optional { if (!iequals(func.name, "perspective")) { return {}; } auto value = parser.parseNextValue(); - 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 f2ed5baa8b2d..d850ae8313b6 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(CSSValueParser &parser) -> std::optional - { + static constexpr auto consume(CSSValueParser& parser) + -> std::optional { // [ left | center | right | top | bottom | ] // | // [ left | center | right | ] @@ -54,21 +54,27 @@ struct CSSDataTypeParser { // | // [ [ center | left | right ] && [ center | top | bottom ] ] ? - auto firstValue = parser.parseNextValue(); + auto firstValue = + parser.parseNextValue(); if (std::holds_alternative(firstValue)) { return {}; } - auto secondValue = parser.parseNextValue(CSSDelimiter::Whitespace); + auto secondValue = + parser.parseNextValue( + CSSDelimiter::Whitespace); if (std::holds_alternative(secondValue)) { return singleValue(firstValue); } - auto thirdValue = parser.parseNextValue(CSSDelimiter::Whitespace); + auto thirdValue = + parser.parseNextValue(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); } @@ -85,8 +91,11 @@ struct CSSDataTypeParser { private: static constexpr CSSTransformOrigin singleValue( - const std::variant &value) - { + const std::variant< + std::monostate, + CSSLength, + CSSPercentage, + CSSTransformOriginKeyword>& value) { CSSTransformOrigin result{}; if (std::holds_alternative(value)) { @@ -97,11 +106,13 @@ 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)); } } @@ -109,10 +120,17 @@ struct CSSDataTypeParser { } static constexpr std::optional xyLengthPercentageValue( - const std::variant &val1, - const std::variant &val2, - const std::variant &val3) - { + const std::variant< + std::monostate, + CSSLength, + CSSPercentage, + CSSTransformOriginKeyword>& val1, + const std::variant< + std::monostate, + CSSLength, + CSSPercentage, + CSSTransformOriginKeyword>& val2, + const std::variant& val3) { CSSTransformOrigin result{}; if (std::holds_alternative(val1)) { @@ -149,39 +167,42 @@ 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 a0cc05d027b2..2cba0cad8eca 100644 --- a/packages/react-native/ReactCommon/react/renderer/css/CSSValueParser.h +++ b/packages/react-native/ReactCommon/react/renderer/css/CSSValueParser.h @@ -20,10 +20,11 @@ namespace facebook::react { class CSSValueParser { public: - explicit constexpr CSSValueParser(CSSSyntaxParser &parser) : parser_{&parser} {} + explicit constexpr CSSValueParser(CSSSyntaxParser& parser) + : parser_{&parser} {} - constexpr CSSValueParser(const CSSValueParser &) = default; - constexpr CSSValueParser &operator=(const CSSValueParser &) = default; + constexpr CSSValueParser(const CSSValueParser&) = default; + constexpr CSSValueParser& operator=(const CSSValueParser&) = default; /** * Attempts to parse the next CSS value of a given set of data types, at the @@ -31,8 +32,9 @@ class CSSValueParser { */ template constexpr auto parseNextValue(CSSDelimiter delimiter = CSSDelimiter::None) - -> CSSVariantWithTypes, std::monostate> - { + -> CSSVariantWithTypes< + CSSMergedDataTypes, + std::monostate> { return consumeValue(delimiter, CSSMergedDataTypes{}); } @@ -42,8 +44,9 @@ class CSSValueParser { */ template constexpr auto peekNextValue(CSSDelimiter delimiter = CSSDelimiter::None) - -> CSSVariantWithTypes, std::monostate> - { + -> CSSVariantWithTypes< + CSSMergedDataTypes, + std::monostate> { auto savedParser = *parser_; auto ret = consumeValue(delimiter, CSSMergedDataTypes{}); *parser_ = savedParser; @@ -55,13 +58,11 @@ class CSSValueParser { * syntax-level operations like consumeWhitespace(), consumeDelimiter(), * and isFinished(). */ - constexpr CSSSyntaxParser &syntaxParser() - { + constexpr CSSSyntaxParser& syntaxParser() { return *parser_; } - constexpr const CSSSyntaxParser &syntaxParser() const - { + constexpr const CSSSyntaxParser& syntaxParser() const { return *parser_; } @@ -75,11 +76,12 @@ class CSSValueParser { template constexpr std::variant consumeValue( CSSDelimiter delimiter, - std::variant /*unused*/) - { + std::variant /*unused*/) { using ReturnT = std::variant; - auto consumedValue = tryConsumeParser...>(delimiter); + auto consumedValue = + tryConsumeParser...>( + delimiter); if (!std::holds_alternative(consumedValue)) { return consumedValue; @@ -87,28 +89,36 @@ class CSSValueParser { return parser_->consumeComponentValue( delimiter, - [&](const CSSPreservedToken &token) { - return tryConsumePreservedToken...>(token); + [&](const CSSPreservedToken& token) { + return tryConsumePreservedToken< + ReturnT, + CSSDataTypeParser...>(token); }, - [&](const CSSSimpleBlock &block, CSSSyntaxParser &blockParser) { + [&](const CSSSimpleBlock& block, CSSSyntaxParser& blockParser) { CSSValueParser valueParser(blockParser); - return tryConsumeSimpleBlock...>(block, valueParser); + return tryConsumeSimpleBlock< + ReturnT, + CSSDataTypeParser...>(block, valueParser); }, - [&](const CSSFunctionBlock &func, CSSSyntaxParser &blockParser) { + [&](const CSSFunctionBlock& func, CSSSyntaxParser& blockParser) { CSSValueParser valueParser(blockParser); - return tryConsumeFunctionBlock...>(func, valueParser); + return tryConsumeFunctionBlock< + ReturnT, + CSSDataTypeParser...>(func, valueParser); }); } template - constexpr ReturnT tryConsumePreservedToken(const CSSPreservedToken & /*token*/) - { + constexpr ReturnT tryConsumePreservedToken( + const CSSPreservedToken& /*token*/) { return {}; } - template - constexpr ReturnT tryConsumePreservedToken(const CSSPreservedToken &token) - { + template < + typename ReturnT, + CSSValidDataTypeParser ParserT, + CSSValidDataTypeParser... RestParserT> + constexpr ReturnT tryConsumePreservedToken(const CSSPreservedToken& token) { if constexpr (CSSPreservedTokenSink) { if (auto ret = ParserT::consumePreservedToken(token)) { return *ret; @@ -119,14 +129,19 @@ class CSSValueParser { } template - constexpr ReturnT tryConsumeSimpleBlock(const CSSSimpleBlock & /*token*/, CSSValueParser & /*blockParser*/) - { + constexpr ReturnT tryConsumeSimpleBlock( + const CSSSimpleBlock& /*token*/, + CSSValueParser& /*blockParser*/) { return {}; } - template - constexpr ReturnT tryConsumeSimpleBlock(const CSSSimpleBlock &block, CSSValueParser &blockParser) - { + template < + typename ReturnT, + CSSValidDataTypeParser ParserT, + CSSValidDataTypeParser... RestParserT> + constexpr ReturnT tryConsumeSimpleBlock( + const CSSSimpleBlock& block, + CSSValueParser& blockParser) { if constexpr (CSSSimpleBlockSink) { auto currentParser = blockParser; if (auto ret = ParserT::consumeSimpleBlock(block, blockParser)) { @@ -139,14 +154,19 @@ class CSSValueParser { } template - constexpr ReturnT tryConsumeFunctionBlock(const CSSFunctionBlock & /*func*/, CSSValueParser & /*blockParser*/) - { + constexpr ReturnT tryConsumeFunctionBlock( + const CSSFunctionBlock& /*func*/, + CSSValueParser& /*blockParser*/) { return {}; } - template - constexpr ReturnT tryConsumeFunctionBlock(const CSSFunctionBlock &func, CSSValueParser &blockParser) - { + template < + typename ReturnT, + CSSValidDataTypeParser ParserT, + CSSValidDataTypeParser... RestParserT> + constexpr ReturnT tryConsumeFunctionBlock( + const CSSFunctionBlock& func, + CSSValueParser& blockParser) { if constexpr (CSSFunctionBlockSink) { auto currentParser = blockParser; if (auto ret = ParserT::consumeFunctionBlock(func, blockParser)) { @@ -159,14 +179,15 @@ class CSSValueParser { } template - constexpr ReturnT tryConsumeParser(CSSDelimiter /*delimiter*/) - { + constexpr ReturnT tryConsumeParser(CSSDelimiter /*delimiter*/) { return {}; } - template - constexpr ReturnT tryConsumeParser(CSSDelimiter delimiter) - { + template < + typename ReturnT, + CSSValidDataTypeParser ParserT, + CSSValidDataTypeParser... RestParserT> + constexpr ReturnT tryConsumeParser(CSSDelimiter delimiter) { if constexpr (CSSParserSink) { auto originalParser = *parser_; if (parser_->consumeDelimiter(delimiter)) { @@ -180,7 +201,7 @@ class CSSValueParser { return tryConsumeParser(delimiter); } - CSSSyntaxParser *parser_; + CSSSyntaxParser* parser_; }; /** @@ -188,9 +209,9 @@ class CSSValueParser { * on syntax error. */ template -constexpr auto parseCSSProperty(std::string_view css) - -> CSSVariantWithTypes, std::monostate> -{ +constexpr auto parseCSSProperty(std::string_view css) -> CSSVariantWithTypes< + CSSMergedDataTypes, + std::monostate> { CSSSyntaxParser syntaxParser(css); CSSValueParser parser(syntaxParser); diff --git a/packages/react-native/ReactCommon/react/renderer/css/CSSZero.h b/packages/react-native/ReactCommon/react/renderer/css/CSSZero.h index 8f24fcc04c87..5f0865f4dd2e 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/debug/DebugStringConvertible.h b/packages/react-native/ReactCommon/react/renderer/debug/DebugStringConvertible.h index 726531a2837e..92d823f0661c 100644 --- a/packages/react-native/ReactCommon/react/renderer/debug/DebugStringConvertible.h +++ b/packages/react-native/ReactCommon/react/renderer/debug/DebugStringConvertible.h @@ -22,8 +22,10 @@ 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}; @@ -66,12 +68,15 @@ 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 @@ -85,37 +90,31 @@ 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 double& value); std::string toString(double doubleValue, char suffix); #if RN_DEBUG_STRING_CONVERTIBLE -std::string toString(const void *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"; } @@ -123,8 +122,7 @@ 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]); @@ -169,32 +167,33 @@ 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 ""; } @@ -207,8 +206,10 @@ std::string getDebugPropsDescription(const T &object, DebugStringConvertibleOpti 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()) { @@ -220,8 +221,9 @@ std::string getDebugPropsDescription(const T &object, DebugStringConvertibleOpti } template -std::string getDebugChildrenDescription(const T &object, DebugStringConvertibleOptions options) -{ +std::string getDebugChildrenDescription( + const T& object, + DebugStringConvertibleOptions options) { if (options.depth >= options.maximumDepth) { return ""; } @@ -243,8 +245,9 @@ std::string getDebugChildrenDescription(const T &object, DebugStringConvertibleO } 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); @@ -263,78 +266,88 @@ std::string getDebugDescription(const T &object, DebugStringConvertibleOptions o 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; @@ -342,14 +355,14 @@ std::vector getDebugChildren(const std::array &array, DebugStringCon // `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; @@ -357,23 +370,26 @@ std::vector getDebugChildren(const std::unordered_set &set, DebugSt // `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)"; } /* @@ -385,13 +401,11 @@ 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 dd9e79039595..bd200e2041be 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 1270f181360c..4ffcfca122e8 100644 --- a/packages/react-native/ReactCommon/react/renderer/debug/debugStringConvertibleUtils.h +++ b/packages/react-native/ReactCommon/react/renderer/debug/debugStringConvertibleUtils.h @@ -19,51 +19,59 @@ 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 8cdb424a8eb5..1a3a36bffc07 100644 --- a/packages/react-native/ReactCommon/react/renderer/dom/DOM.h +++ b/packages/react-native/ReactCommon/react/renderer/dom/DOM.h @@ -61,54 +61,72 @@ struct DOMBorderWidthRounded { }; std::shared_ptr getParentNode( - const RootShadowNode::Shared ¤tRevision, - const ShadowNode &shadowNode); + const RootShadowNode::Shared& currentRevision, + const ShadowNode& shadowNode); std::shared_ptr getElementById( - const std::shared_ptr ¤tRevision, - const std::string &id); + const std::shared_ptr& currentRevision, + const std::string& id); std::vector> getChildNodes( - const RootShadowNode::Shared ¤tRevision, - const ShadowNode &shadowNode); + const RootShadowNode::Shared& currentRevision, + const ShadowNode& shadowNode); -bool isConnected(const RootShadowNode::Shared ¤tRevision, const ShadowNode &shadowNode); +bool isConnected( + const RootShadowNode::Shared& currentRevision, + const ShadowNode& shadowNode); uint_fast16_t compareDocumentPosition( - const RootShadowNode::Shared ¤tRevision, - const ShadowNode &shadowNode, - const ShadowNode &otherShadowNode); + const RootShadowNode::Shared& currentRevision, + const ShadowNode& shadowNode, + const ShadowNode& otherShadowNode); -std::string getTextContent(const RootShadowNode::Shared ¤tRevision, const ShadowNode &shadowNode); +std::string getTextContent( + const RootShadowNode::Shared& currentRevision, + const ShadowNode& shadowNode); DOMRect getBoundingClientRect( - const RootShadowNode::Shared ¤tRevision, - const ShadowNode &shadowNode, + const RootShadowNode::Shared& currentRevision, + const ShadowNode& shadowNode, bool includeTransform); -DOMOffset getOffset(const RootShadowNode::Shared ¤tRevision, const ShadowNode &shadowNode); +DOMOffset getOffset( + const RootShadowNode::Shared& currentRevision, + const ShadowNode& shadowNode); -DOMPoint getScrollPosition(const RootShadowNode::Shared ¤tRevision, const ShadowNode &shadowNode); +DOMPoint getScrollPosition( + const RootShadowNode::Shared& currentRevision, + const ShadowNode& shadowNode); -DOMSizeRounded getScrollSize(const RootShadowNode::Shared ¤tRevision, const ShadowNode &shadowNode); +DOMSizeRounded getScrollSize( + const RootShadowNode::Shared& currentRevision, + const ShadowNode& shadowNode); -DOMSizeRounded getInnerSize(const RootShadowNode::Shared ¤tRevision, const ShadowNode &shadowNode); +DOMSizeRounded getInnerSize( + const RootShadowNode::Shared& currentRevision, + const ShadowNode& shadowNode); -DOMBorderWidthRounded getBorderWidth(const RootShadowNode::Shared ¤tRevision, const ShadowNode &shadowNode); +DOMBorderWidthRounded getBorderWidth( + const RootShadowNode::Shared& currentRevision, + 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 ¤tRevision, const ShadowNode &shadowNode); +RNMeasureRect measure( + const RootShadowNode::Shared& currentRevision, + const ShadowNode& shadowNode); -DOMRect measureInWindow(const RootShadowNode::Shared ¤tRevision, const ShadowNode &shadowNode); +DOMRect measureInWindow( + const RootShadowNode::Shared& currentRevision, + 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 ¤tRevision, - const ShadowNode &shadowNode, - const ShadowNode &relativeToShadowNode); + const RootShadowNode::Shared& currentRevision, + const ShadowNode& shadowNode, + const ShadowNode& relativeToShadowNode); } // namespace facebook::react::dom diff --git a/packages/react-native/ReactCommon/react/renderer/element/ComponentBuilder.h b/packages/react-native/ReactCommon/react/renderer/element/ComponentBuilder.h index 508cd5c0de05..071ed044dc3f 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,7 +48,8 @@ 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 251cb49c49d5..01d94fd31c6a 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,16 +52,14 @@ 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; } @@ -69,8 +67,7 @@ class Element final { /* * Sets `surfaceId`. */ - Element &surfaceId(SurfaceId surfaceId) - { + Element& surfaceId(SurfaceId surfaceId) { fragment_.surfaceId = surfaceId; return *this; } @@ -78,8 +75,7 @@ class Element final { /* * Sets `props`. */ - Element &props(SharedConcreteProps props) - { + Element& props(SharedConcreteProps props) { fragment_.props = props; return *this; } @@ -87,8 +83,7 @@ class Element final { /* * Sets `props` using callback. */ - Element &props(std::function callback) - { + Element& props(std::function callback) { fragment_.props = callback(); return *this; } @@ -96,10 +91,12 @@ 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); }; @@ -109,11 +106,10 @@ 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; @@ -124,13 +120,15 @@ 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; } @@ -138,22 +136,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 316c4256dc23..88a7459a44da 100644 --- a/packages/react-native/ReactCommon/react/renderer/element/ElementFragment.h +++ b/packages/react-native/ReactCommon/react/renderer/element/ElementFragment.h @@ -26,9 +26,11 @@ 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 48277f9f2fc3..c6966c1897e6 100644 --- a/packages/react-native/ReactCommon/react/renderer/element/testUtils.h +++ b/packages/react-native/ReactCommon/react/renderer/element/testUtils.h @@ -19,21 +19,31 @@ 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 d156126f251c..1945f5e31e0d 100644 --- a/packages/react-native/ReactCommon/react/renderer/graphics/BackgroundImage.h +++ b/packages/react-native/ReactCommon/react/renderer/graphics/BackgroundImage.h @@ -15,12 +15,11 @@ 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 << "["; @@ -29,7 +28,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 37a2693896bc..5ef4c7d3dce0 100644 --- a/packages/react-native/ReactCommon/react/renderer/graphics/BackgroundPosition.h +++ b/packages/react-native/ReactCommon/react/renderer/graphics/BackgroundPosition.h @@ -18,9 +18,11 @@ 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; }; } // 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 15edff00a407..160e66d404a6 100644 --- a/packages/react-native/ReactCommon/react/renderer/graphics/BackgroundRepeat.h +++ b/packages/react-native/ReactCommon/react/renderer/graphics/BackgroundRepeat.h @@ -22,7 +22,7 @@ struct BackgroundRepeat { BackgroundRepeat() {} - 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 5b0f52cee7e1..37e697a7e52d 100644 --- a/packages/react-native/ReactCommon/react/renderer/graphics/BackgroundSize.h +++ b/packages/react-native/ReactCommon/react/renderer/graphics/BackgroundSize.h @@ -18,21 +18,20 @@ 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; }; 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 25a1c91232b6..00e7b0a5c743 100644 --- a/packages/react-native/ReactCommon/react/renderer/graphics/BlendMode.h +++ b/packages/react-native/ReactCommon/react/renderer/graphics/BlendMode.h @@ -32,8 +32,8 @@ enum class BlendMode { PlusLighter, }; -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") { @@ -73,8 +73,7 @@ inline std::optional blendModeFromString(std::string_view blendModeNa } } -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 f8be37cc06e1..b519487ef316 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,8 +23,7 @@ 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; @@ -38,8 +37,7 @@ 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 16905f62a3d2..76445126b8b5 100644 --- a/packages/react-native/ReactCommon/react/renderer/graphics/Color.h +++ b/packages/react-native/ReactCommon/react/renderer/graphics/Color.h @@ -33,28 +33,23 @@ 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; } @@ -64,7 +59,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); @@ -79,8 +74,7 @@ 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 @@ -89,8 +83,7 @@ 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 b3136d4238b0..8b0ec465b971 100644 --- a/packages/react-native/ReactCommon/react/renderer/graphics/ColorStop.h +++ b/packages/react-native/ReactCommon/react/renderer/graphics/ColorStop.h @@ -20,7 +20,7 @@ namespace facebook::react { struct ColorStop { - bool operator==(const ColorStop &other) const = default; + bool operator==(const ColorStop& other) const = default; SharedColor color; ValueUnit position; @@ -29,8 +29,7 @@ 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 << " "; @@ -41,7 +40,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 f4c1c2613080..fc6ca122e6a5 100644 --- a/packages/react-native/ReactCommon/react/renderer/graphics/Filter.h +++ b/packages/react-native/ReactCommon/react/renderer/graphics/Filter.h @@ -30,8 +30,8 @@ enum class FilterType { DropShadow }; -inline std::optional filterTypeFromString(std::string_view filterName) -{ +inline std::optional filterTypeFromString( + std::string_view filterName) { if (filterName == "blur") { return FilterType::Blur; } else if (filterName == "brightness") { @@ -57,8 +57,7 @@ inline std::optional filterTypeFromString(std::string_view filterNam } } -inline std::string toString(const FilterType &filterType) -{ +inline std::string toString(const FilterType& filterType) { switch (filterType) { case FilterType::Blur: return "blur"; @@ -86,7 +85,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{}; @@ -94,8 +93,7 @@ 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; @@ -107,20 +105,19 @@ 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; @@ -129,8 +126,7 @@ 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 9b9b2a1e630e..941c4a1c28ab 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 57168c953b19..29c7a2bba19e 100644 --- a/packages/react-native/ReactCommon/react/renderer/graphics/LinearGradient.h +++ b/packages/react-native/ReactCommon/react/renderer/graphics/LinearGradient.h @@ -21,9 +21,9 @@ namespace facebook::react { -enum class [[deprecated("Use std::holds_alternative")]] GradientDirectionType { - Angle, - Keyword, +enum class [[deprecated("Use std::holds_alternative")]] GradientDirectionType{ + Angle, + Keyword, }; enum class GradientKeyword : uint8_t { @@ -39,14 +39,14 @@ struct LinearGradient { GradientDirection direction; std::vector colorStops; - bool operator==(const LinearGradient &other) const = default; + bool operator==(const LinearGradient& other) const = default; #ifdef RN_SERIALIZABLE_STATE folly::dynamic toDynamic() const; #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 c9bf3297d0b3..6865e9b490e7 100644 --- a/packages/react-native/ReactCommon/react/renderer/graphics/Point.h +++ b/packages/react-native/ReactCommon/react/renderer/graphics/Point.h @@ -19,51 +19,45 @@ 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; }; } // namespace facebook::react @@ -72,8 +66,7 @@ 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 012487e7f828..7b8c53a7b6c9 100644 --- a/packages/react-native/ReactCommon/react/renderer/graphics/RadialGradient.h +++ b/packages/react-native/ReactCommon/react/renderer/graphics/RadialGradient.h @@ -29,13 +29,18 @@ 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 = default; + bool operator==(const Dimensions& other) const = default; #ifdef RN_SERIALIZABLE_STATE folly::dynamic toDynamic() const; @@ -44,7 +49,7 @@ struct RadialGradientSize { std::variant value; - bool operator==(const RadialGradientSize &other) const = default; + bool operator==(const RadialGradientSize& other) const = default; #ifdef RN_SERIALIZABLE_STATE folly::dynamic toDynamic() const; @@ -57,7 +62,7 @@ struct RadialGradientPosition { std::optional right; std::optional bottom; - bool operator==(const RadialGradientPosition &other) const = default; + bool operator==(const RadialGradientPosition& other) const = default; #ifdef RN_SERIALIZABLE_STATE folly::dynamic toDynamic() const; @@ -70,14 +75,14 @@ struct RadialGradient { RadialGradientPosition position; std::vector colorStops; - bool operator==(const RadialGradient &other) const = default; + bool operator==(const RadialGradient& other) const = default; #ifdef RN_SERIALIZABLE_STATE folly::dynamic toDynamic() const; #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 a9a4dcb9057c..d7870e82511c 100644 --- a/packages/react-native/ReactCommon/react/renderer/graphics/Rect.h +++ b/packages/react-native/ReactCommon/react/renderer/graphics/Rect.h @@ -24,39 +24,31 @@ struct Rect { Point origin{.x = 0, .y = 0}; Size size{.width = 0, .height = 0}; - bool operator==(const Rect &rhs) const noexcept = default; + bool operator==(const Rect& rhs) const noexcept = default; - 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()); @@ -65,18 +57,19 @@ 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; @@ -85,11 +78,16 @@ 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; @@ -111,7 +109,9 @@ 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}}; } }; @@ -121,8 +121,7 @@ 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 00b3f9a109ef..0ee2841bf0b8 100644 --- a/packages/react-native/ReactCommon/react/renderer/graphics/RectangleCorners.h +++ b/packages/react-native/ReactCommon/react/renderer/graphics/RectangleCorners.h @@ -25,11 +25,11 @@ struct RectangleCorners { T bottomLeft{}; T bottomRight{}; - bool operator==(const RectangleCorners &rhs) const noexcept = default; + bool operator==(const RectangleCorners& rhs) const noexcept = default; - bool isUniform() const noexcept - { - return topLeft == topRight && topLeft == bottomLeft && topLeft == bottomRight; + bool isUniform() const noexcept { + return topLeft == topRight && topLeft == bottomLeft && + topLeft == bottomRight; } }; @@ -44,9 +44,13 @@ 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 cccfcbd909a8..e6341d7f225a 100644 --- a/packages/react-native/ReactCommon/react/renderer/graphics/RectangleEdges.h +++ b/packages/react-native/ReactCommon/react/renderer/graphics/RectangleEdges.h @@ -26,10 +26,9 @@ struct RectangleEdges { T right{}; T bottom{}; - bool operator==(const RectangleEdges &rhs) const noexcept = default; + bool operator==(const RectangleEdges& rhs) const noexcept = default; - bool isUniform() const noexcept - { + bool isUniform() const noexcept { return left == top && left == right && left == bottom; } @@ -40,15 +39,25 @@ 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}; } /* @@ -59,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}}; @@ -71,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}}; @@ -86,9 +95,10 @@ 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 bde0a19f0d27..8fbb462bcf4d 100644 --- a/packages/react-native/ReactCommon/react/renderer/graphics/Size.h +++ b/packages/react-native/ReactCommon/react/renderer/graphics/Size.h @@ -22,23 +22,20 @@ 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); } @@ -48,8 +45,7 @@ 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.h b/packages/react-native/ReactCommon/react/renderer/graphics/Transform.h index 2f3a69021426..3f0c80b61eb4 100644 --- a/packages/react-native/ReactCommon/react/renderer/graphics/Transform.h +++ b/packages/react-native/ReactCommon/react/renderer/graphics/Transform.h @@ -23,8 +23,7 @@ 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; @@ -35,33 +34,41 @@ 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 = default; - 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 operator==(const TransformOrigin& other) const = default; + 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); } @@ -74,16 +81,18 @@ 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]`). @@ -141,34 +150,37 @@ 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; /* * 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 ¢er) const; + Rect applyWithCenter(const Rect& rect, const Point& center) const; /** * Convert to folly::dynamic. */ - operator folly::dynamic() const - { + operator folly::dynamic() const { return folly::dynamic::array( matrix[0], matrix[1], @@ -192,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 @@ -219,8 +231,7 @@ 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/TransformUtils.h b/packages/react-native/ReactCommon/react/renderer/graphics/TransformUtils.h index c12d264a0d36..7b62a93c05c4 100644 --- a/packages/react-native/ReactCommon/react/renderer/graphics/TransformUtils.h +++ b/packages/react-native/ReactCommon/react/renderer/graphics/TransformUtils.h @@ -19,10 +19,9 @@ namespace facebook::react { * (e.g., "50%"). */ inline void serializeTransformOperationValue( - const std::string &operationName, - const ValueUnit &valueUnit, - folly::dynamic &resultArray) -{ + const std::string& operationName, + const ValueUnit& valueUnit, + folly::dynamic& resultArray) { folly::dynamic result = folly::dynamic::object(); if (valueUnit.unit == UnitType::Percent) { result[operationName] = std::to_string(valueUnit.value) + "%"; @@ -33,27 +32,28 @@ inline void serializeTransformOperationValue( } inline void serializeTransformAxis( - const TransformOperation &operation, - const std::string &operationName, + const TransformOperation& operation, + const std::string& operationName, float defaultValue, - folly::dynamic &resultTranslateArray) -{ + folly::dynamic& resultTranslateArray) { if (operation.x.value != defaultValue) { - serializeTransformOperationValue(operationName + "X", operation.x, resultTranslateArray); + serializeTransformOperationValue( + operationName + "X", operation.x, resultTranslateArray); } if (operation.y.value != defaultValue) { - serializeTransformOperationValue(operationName + "Y", operation.y, resultTranslateArray); + serializeTransformOperationValue( + operationName + "Y", operation.y, resultTranslateArray); } if (operation.z.value != defaultValue) { - serializeTransformOperationValue(operationName + "Z", operation.z, resultTranslateArray); + serializeTransformOperationValue( + operationName + "Z", operation.z, resultTranslateArray); } } inline void updateTransformProps( - const Transform &transform, - const TransformOperation &operation, - folly::dynamic &resultTranslateArray) -{ + const Transform& transform, + const TransformOperation& operation, + folly::dynamic& resultTranslateArray) { // See serialization rules in: // react-native-github/packages/react-native/ReactCommon/react/renderer/components/view/conversions.h?lines=592 std::string operationName; @@ -61,9 +61,11 @@ inline void updateTransformProps( case TransformOperationType::Scale: operationName = "scale"; if (operation.x == operation.y && operation.x == operation.z) { - serializeTransformOperationValue(operationName, operation.x, resultTranslateArray); + serializeTransformOperationValue( + operationName, operation.x, resultTranslateArray); } else { - serializeTransformAxis(operation, operationName, 1.0f, resultTranslateArray); + serializeTransformAxis( + operation, operationName, 1.0f, resultTranslateArray); } return; case TransformOperationType::Translate: diff --git a/packages/react-native/ReactCommon/react/renderer/graphics/ValueUnit.h b/packages/react-native/ReactCommon/react/renderer/graphics/ValueUnit.h index ff654387062f..978b47525a64 100644 --- a/packages/react-native/ReactCommon/react/renderer/graphics/ValueUnit.h +++ b/packages/react-native/ReactCommon/react/renderer/graphics/ValueUnit.h @@ -29,10 +29,9 @@ struct ValueUnit { constexpr ValueUnit() = default; constexpr ValueUnit(float v, UnitType u) : value(v), unit(u) {} - constexpr bool operator==(const ValueUnit &other) const = default; + constexpr bool operator==(const ValueUnit& other) const = default; - constexpr float resolve(float referenceLength) const - { + constexpr float resolve(float referenceLength) const { switch (unit) { case UnitType::Point: return value; @@ -44,8 +43,7 @@ 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 7bd48ce15b46..f7addff956f0 100644 --- a/packages/react-native/ReactCommon/react/renderer/graphics/fromRawValueShared.h +++ b/packages/react-native/ReactCommon/react/renderer/graphics/fromRawValueShared.h @@ -16,18 +16,19 @@ #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 (ReactNativeFeatureFlags::enableNativeCSSParsing() && value.hasType()) { + if (ReactNativeFeatureFlags::enableNativeCSSParsing() && + value.hasType()) { auto cssColor = parseCSSProperty((std::string)value); if (std::holds_alternative(cssColor)) { auto c = std::get(cssColor); @@ -57,7 +58,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 bfbefc3832a3..9752be6b7f0c 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,28 +40,23 @@ 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 cf5a7c2ce1f1..f34f4a708fe9 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 @@ -26,18 +26,21 @@ 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>()) { // Mixed array + string values, so read as a map of RawValue (a map of @@ -46,7 +49,8 @@ parsePlatformColor(const ContextContainer &contextContainer, int32_t surfaceId, std::vector resourcePaths; auto resourcePathsIt = map.find("resource_paths"); - if (resourcePathsIt != map.end() && resourcePathsIt->second.hasType>()) { + if (resourcePathsIt != map.end() && + resourcePathsIt->second.hasType>()) { resourcePaths = (std::vector)resourcePathsIt->second; } @@ -55,14 +59,18 @@ parsePlatformColor(const ContextContainer &contextContainer, int32_t surfaceId, // Cache the (costly) JNI results. A cached nullopt is an explicit miss, // distinct from a path that resolves to transparent (ARGB 0). static std::mutex getColorCacheMutex; - static folly::EvictingCacheMap> getColorCache(64); + static folly::EvictingCacheMap> + getColorCache(64); // 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); std::optional resolvedColor; @@ -72,18 +80,23 @@ parsePlatformColor(const ContextContainer &contextContainer, int32_t surfaceId, if (iterator != getColorCache.end()) { resolvedColor = iterator->second; } else { - const auto &fabricUIManager = contextContainer.at>("FabricUIManager"); + const auto& fabricUIManager = + contextContainer.at>("FabricUIManager"); // Boxed Integer: null is an explicit miss; a non-null value may be 0 // (transparent black). 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])); } - auto boxedColor = getColorFromJava(fabricUIManager, surfaceId, *javaResourcePaths); + auto boxedColor = + getColorFromJava(fabricUIManager, surfaceId, *javaResourcePaths); if (boxedColor) { resolvedColor = static_cast(boxedColor->value()); } @@ -100,10 +113,12 @@ parsePlatformColor(const ContextContainer &contextContainer, int32_t surfaceId, // same parser iOS Fabric uses). if (!resolved) { auto fallbackIt = map.find("fallback"); - if (fallbackIt != map.end() && fallbackIt->second.hasType()) { - auto cssColor = parseCSSProperty((std::string)fallbackIt->second); + if (fallbackIt != map.end() && + fallbackIt->second.hasType()) { + auto cssColor = + parseCSSProperty((std::string)fallbackIt->second); if (std::holds_alternative(cssColor)) { - const auto &c = std::get(cssColor); + const auto& c = std::get(cssColor); color = hostPlatformColorFromRGBA(c.r, c.g, c.b, c.a); } } @@ -113,10 +128,13 @@ parsePlatformColor(const ContextContainer &contextContainer, int32_t surfaceId, 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 0ae822a1f396..4947fe896aa9 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 a13540363420..1a88db1c7f29 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,13 +19,12 @@ 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)), @@ -34,33 +33,27 @@ 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 3a0e863fda0d..0526f892f48f 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,9 +15,10 @@ 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; @@ -26,10 +27,13 @@ parsePlatformColor(const ContextContainer & /*contextContainer*/, int32_t /*surf 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 a7dd98139991..a7c2f485c190 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,26 +22,24 @@ 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; // Returns the UndefinedColor sentinel (null underlying UIColor) on a miss, so // callers can tell a miss from a name that resolves to transparent. Callers // reaching into getUIColor() must null-check it. - 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{ @@ -50,10 +48,9 @@ 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(); } @@ -74,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, @@ -86,38 +83,31 @@ inline Color hostPlatformColorFromRGBA(uint8_t r, uint8_t g, uint8_t b, uint8_t 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; } @@ -125,8 +115,7 @@ 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 3ff2aa38cfd5..30ecd79ba1ec 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,12 +15,18 @@ 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/RCTPlatformColorUtils.h b/packages/react-native/ReactCommon/react/renderer/graphics/platform/ios/react/renderer/graphics/RCTPlatformColorUtils.h index ad021c1e413f..d7384492037d 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 @@ -17,13 +17,16 @@ struct Color; NS_ASSUME_NONNULL_BEGIN -facebook::react::ColorComponents RCTPlatformColorComponentsFromSemanticItems(std::vector &semanticItems); -UIColor *RCTPlatformColorFromSemanticItems(std::vector &semanticItems); +facebook::react::ColorComponents RCTPlatformColorComponentsFromSemanticItems( + std::vector& semanticItems); +UIColor* RCTPlatformColorFromSemanticItems( + std::vector& semanticItems); // Like RCTPlatformColorFromSemanticItems but returns nil on a miss, so callers // can tell a miss from a name that resolves to transparent. -UIColor *_Nullable RCTPlatformColorFromSemanticItemsOrNil(std::vector &semanticItems); +UIColor* _Nullable RCTPlatformColorFromSemanticItemsOrNil( + std::vector& semanticItems); // Precondition: `color` is a resolved color, never the miss sentinel, so the // result stays _Nonnull. -UIColor *RCTPlatformColorFromColor(const facebook::react::Color &color); +UIColor* RCTPlatformColorFromColor(const facebook::react::Color& color); NS_ASSUME_NONNULL_END diff --git a/packages/react-native/ReactCommon/react/renderer/graphics/rounding.h b/packages/react-native/ReactCommon/react/renderer/graphics/rounding.h index be34277849f6..09c05339c592 100644 --- a/packages/react-native/ReactCommon/react/renderer/graphics/rounding.h +++ b/packages/react-native/ReactCommon/react/renderer/graphics/rounding.h @@ -23,70 +23,60 @@ 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 bb86c18f8f73..a5076a8bf435 100644 --- a/packages/react-native/ReactCommon/react/renderer/imagemanager/ImageManager.h +++ b/packages/react-native/ReactCommon/react/renderer/imagemanager/ImageManager.h @@ -23,20 +23,20 @@ namespace facebook::react { */ 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: #ifdef ANDROID std::shared_ptr contextContainer_{}; #endif - 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 a2901b1a0c30..d5fa1c707080 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,26 +58,27 @@ 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 95a1d4f8d30c..70930342ef8c 100644 --- a/packages/react-native/ReactCommon/react/renderer/imagemanager/ImageResponseObserver.h +++ b/packages/react-native/ReactCommon/react/renderer/imagemanager/ImageResponseObserver.h @@ -19,9 +19,10 @@ 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 c659d83ac40c..43a3421a1445 100644 --- a/packages/react-native/ReactCommon/react/renderer/imagemanager/ImageResponseObserverCoordinator.h +++ b/packages/react-native/ReactCommon/react/renderer/imagemanager/ImageResponseObserverCoordinator.h @@ -25,7 +25,9 @@ namespace facebook::react { */ class ImageResponseObserverCoordinator { public: - ImageResponseObserverCoordinator(SharedFunction<> resumeFunction, SharedFunction<> cancelationFunction); + ImageResponseObserverCoordinator( + SharedFunction<> resumeFunction, + SharedFunction<> cancelationFunction); /* * Interested parties may observe the image response. @@ -37,24 +39,28 @@ class ImageResponseObserverCoordinator { /* * Interested parties may stop observing the image response. */ - void removeObserver(const std::shared_ptr &observer) const; + void removeObserver( + const std::shared_ptr& 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: /* diff --git a/packages/react-native/ReactCommon/react/renderer/imagemanager/ImageTelemetry.h b/packages/react-native/ReactCommon/react/renderer/imagemanager/ImageTelemetry.h index 1d207c286cb6..430e0e62e730 100644 --- a/packages/react-native/ReactCommon/react/renderer/imagemanager/ImageTelemetry.h +++ b/packages/react-native/ReactCommon/react/renderer/imagemanager/ImageTelemetry.h @@ -18,8 +18,7 @@ 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.h b/packages/react-native/ReactCommon/react/renderer/imagemanager/platform/android/react/renderer/imagemanager/ImageFetcher.h index c733b789bc5d..59a1d617b4e3 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 @@ -23,19 +23,19 @@ 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; void flushImageRequests(); private: friend class ImageManager; ImageRequest requestImage( - const ImageSource &imageSource, + const ImageSource& imageSource, SurfaceId surfaceId, - const ImageRequestParams &imageRequestParams, + const ImageRequestParams& imageRequestParams, Tag tag); std::unordered_map> items_; 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 d28bf2b3a63f..b7442bc2af12 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 @@ -44,9 +44,7 @@ class ImageRequestParams { progressiveRenderingEnabled(progressiveRenderingEnabled), loadingIndicatorSource(std::move(loadingIndicatorSource)), analyticTag(std::move(analyticTag)), - size(size) - { - } + size(size) {} Float blurRadius{}; ImageSource defaultSource{}; @@ -62,7 +60,7 @@ class ImageRequestParams { std::string analyticTag{}; Size size{}; - bool operator==(const ImageRequestParams &rhs) const = default; + bool operator==(const ImageRequestParams& rhs) const = default; }; struct ImageRequestItem { 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 f68374914a9d..b27d294aac5c 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 @@ -40,8 +40,7 @@ constexpr MapBuffer::Key IS_KEY_VIEW_WIDTH = 16; constexpr MapBuffer::Key IS_KEY_VIEW_HEIGHT = 17; constexpr MapBuffer::Key IS_KEY_CACHE_CONTROL = 18; -inline std::string cacheStrategyToString(ImageSource::CacheStategy cache) -{ +inline std::string cacheStrategyToString(ImageSource::CacheStategy cache) { switch (cache) { case ImageSource::CacheStategy::Reload: return "reload"; @@ -55,46 +54,66 @@ inline std::string cacheStrategyToString(ImageSource::CacheStategy cache) } } -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_IMAGE_WIDTH, static_cast(imageSource.size.width)); - builder.putInt(IS_KEY_IMAGE_HEIGHT, static_cast(imageSource.size.height)); - builder.putString(IS_KEY_CACHE_CONTROL, cacheStrategyToString(imageSource.cache)); + builder.putInt( + IS_KEY_IMAGE_WIDTH, static_cast(imageSource.size.width)); + builder.putInt( + IS_KEY_IMAGE_HEIGHT, static_cast(imageSource.size.height)); + builder.putString( + IS_KEY_CACHE_CONTROL, cacheStrategyToString(imageSource.cache)); } -inline void serializeImageRequestParams(MapBufferBuilder &builder, const ImageRequestParams &imageRequestParams) -{ - builder.putInt(IS_KEY_VIEW_WIDTH, static_cast(imageRequestParams.size.width)); - builder.putInt(IS_KEY_VIEW_HEIGHT, static_cast(imageRequestParams.size.height)); +inline void serializeImageRequestParams( + MapBufferBuilder& builder, + const ImageRequestParams& imageRequestParams) { + builder.putInt( + IS_KEY_VIEW_WIDTH, static_cast(imageRequestParams.size.width)); + builder.putInt( + IS_KEY_VIEW_HEIGHT, static_cast(imageRequestParams.size.height)); 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 (ReactNativeFeatureFlags::enableImageTransparentTintColor()) { if (imageRequestParams.tintColor.has_value()) { - builder.putInt(IS_KEY_TINT_COLOR, toAndroidRepr(imageRequestParams.tintColor.value())); + builder.putInt( + IS_KEY_TINT_COLOR, + toAndroidRepr(imageRequestParams.tintColor.value())); } } else { // pre-`std::optional` behavior - SharedColor tintColor = imageRequestParams.tintColor.value_or(SharedColor{}); + SharedColor tintColor = + imageRequestParams.tintColor.value_or(SharedColor{}); if (isColorMeaningful(tintColor)) { builder.putInt(IS_KEY_TINT_COLOR, toAndroidRepr(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); @@ -104,11 +123,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 a30f0103dda9..612f7bdac42d 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,7 +18,7 @@ class ImageRequestParams { Float blurRadius{}; - bool operator==(const ImageRequestParams &rhs) const = default; + bool operator==(const ImageRequestParams& rhs) const = default; }; } // namespace facebook::react 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 389f950ed317..67aa24366bc1 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,7 +18,7 @@ class ImageRequestParams { Float blurRadius{}; - bool operator==(const ImageRequestParams &rhs) const = default; + bool operator==(const ImageRequestParams& rhs) const = default; }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/imagemanager/primitives.h b/packages/react-native/ReactCommon/react/renderer/imagemanager/primitives.h index 66407cdd6fb1..1cfc87a3a36b 100644 --- a/packages/react-native/ReactCommon/react/renderer/imagemanager/primitives.h +++ b/packages/react-native/ReactCommon/react/renderer/imagemanager/primitives.h @@ -34,14 +34,12 @@ 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); } #ifdef RN_SERIALIZABLE_STATE - folly::dynamic toDynamic() const - { + folly::dynamic toDynamic() const { folly::dynamic imageSourceResult = folly::dynamic::object(); switch (type) { case ImageSource::Type::Remote: @@ -85,7 +83,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; @@ -95,30 +93,41 @@ 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"; @@ -132,8 +141,7 @@ class ImageSource { } } - std::string toString(const CacheStategy &cacheValue) const - { + std::string toString(const CacheStategy& cacheValue) const { switch (cacheValue) { case ImageSource::CacheStategy::Default: return "default"; @@ -152,8 +160,7 @@ 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 091aa8369173..a967ed7bf40b 100644 --- a/packages/react-native/ReactCommon/react/renderer/leakchecker/LeakChecker.h +++ b/packages/react-native/ReactCommon/react/renderer/leakchecker/LeakChecker.h @@ -21,7 +21,8 @@ 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 18f18811a5e5..474d97da7ae5 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 07b64bdfba99..fe3362ae4828 100644 --- a/packages/react-native/ReactCommon/react/renderer/mapbuffer/MapBuffer.h +++ b/packages/react-native/ReactCommon/react/renderer/mapbuffer/MapBuffer.h @@ -79,7 +79,8 @@ 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) @@ -102,27 +103,27 @@ class MapBuffer { // Homogeneous arrays of raw elements stored contiguously in the dynamic // data section. Unlike Map, they carry no per-element key/type overhead, so // a batch of N values costs ~N*elementSize bytes instead of N*12-byte - // buckets. The bucket value packs [offset][byteLength]; the element count is - // recovered as byteLength / elementSize. + // buckets. The bucket value packs [offset][byteLength]; the element count + // is recovered as byteLength / elementSize. IntBuffer = 6, DoubleBuffer = 7, // A homogeneous, ordered array of nested MapBuffers. The bucket value packs - // [offset][byteLength] for the whole list region; within it each child stays - // framed as [int32 childSize][child bytes]. Distinct from `Map` so that a - // list of MapBuffers is self-describing (a single Map and a list are + // [offset][byteLength] for the whole list region; within it each child + // stays framed as [int32 childSize][child bytes]. Distinct from `Map` so + // that a list of MapBuffers is self-describing (a single Map and a list are // byte-distinct in payload but previously shared the `Map` type tag). MapBufferList = 8, }; 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; @@ -145,7 +146,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 2963c77a9b36..f8b390400c2b 100644 --- a/packages/react-native/ReactCommon/react/renderer/mapbuffer/MapBufferBuilder.h +++ b/packages/react-native/ReactCommon/react/renderer/mapbuffer/MapBufferBuilder.h @@ -33,15 +33,17 @@ 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); - void putIntBuffer(MapBuffer::Key key, const std::vector &value); + void putIntBuffer(MapBuffer::Key key, const std::vector& value); - void putDoubleBuffer(MapBuffer::Key key, const std::vector &value); + void putDoubleBuffer(MapBuffer::Key key, const std::vector& value); MapBuffer build(); @@ -56,7 +58,11 @@ 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.h b/packages/react-native/ReactCommon/react/renderer/mounting/Differentiator.h index e764498b4768..f0305dfcf5ca 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 89902c50f9be..c65366062176 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,7 +61,8 @@ 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 @@ -92,7 +93,7 @@ class MountingCoordinator final { */ bool waitForTransaction(std::chrono::duration timeout) const; - const TelemetryController &getTelemetryController() const; + const TelemetryController& getTelemetryController() const; ShadowTreeRevision getBaseRevision() const; @@ -101,7 +102,8 @@ class MountingCoordinator final { * `MountingOverrideDelegate` only. */ public: - 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. @@ -130,7 +132,8 @@ 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 1e96eff36793..c6e57993dd49 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 7841b5a2a64c..277e9f4e307c 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,26 +43,28 @@ 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. @@ -81,7 +83,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 f462271b03a6..8c6f91e101d1 100644 --- a/packages/react-native/ReactCommon/react/renderer/mounting/ShadowTree.h +++ b/packages/react-native/ReactCommon/react/renderer/mounting/ShadowTree.h @@ -23,7 +23,8 @@ namespace facebook::react { -using ShadowTreeCommitTransaction = std::function; +using ShadowTreeCommitTransaction = std::function; /* * Represents a result of a `commit` operation. @@ -87,10 +88,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(); @@ -112,12 +113,16 @@ 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 @@ -145,8 +150,8 @@ class ShadowTree final { std::shared_ptr getMountingCoordinator() const; /** - * Promotes the current React revision to be merged into the main branch of the - * ShadowTree. + * Promotes the current React revision to be merged into the main branch of + * the ShadowTree. */ void promoteReactRevision() const; @@ -164,19 +169,28 @@ class ShadowTree final { void scheduleReactRevisionPromotion() const; const SurfaceId surfaceId_; - const ShadowTreeDelegate &delegate_; + const ShadowTreeDelegate& delegate_; mutable std::shared_mutex revisionMutex_; mutable std::recursive_mutex revisionMutexRecursive_; - mutable CommitMode commitMode_{CommitMode::Normal}; // Protected by `revisionMutex_`. + mutable CommitMode commitMode_{ + CommitMode::Normal}; // Protected by `revisionMutex_`. mutable ShadowTreeRevision currentRevision_; // Protected by `revisionMutex_`. - mutable std::optional currentReactRevision_; // Protected by `revisionMutex_`. - mutable std::optional reactRevisionToBePromoted_; // Protected by `revisionMutex_`. - mutable std::vector queuedReactRevisions_; // Protected by `revisionMutex_`. - mutable std::vector promotedReactRevisions_; // Protected by `revisionMutex_`. + mutable std::optional + currentReactRevision_; // Protected by `revisionMutex_`. + mutable std::optional + reactRevisionToBePromoted_; // Protected by `revisionMutex_`. + mutable std::vector + queuedReactRevisions_; // Protected by `revisionMutex_`. + mutable std::vector + promotedReactRevisions_; // Protected by `revisionMutex_`. std::shared_ptr mountingCoordinator_; - using UniqueLock = std::variant, std::unique_lock>; - using SharedLock = std::variant, std::unique_lock>; + using UniqueLock = std::variant< + std::unique_lock, + std::unique_lock>; + using SharedLock = std::variant< + std::shared_lock, + std::unique_lock>; inline UniqueLock uniqueRevisionLock(bool defer = false) const; inline SharedLock sharedRevisionLock() const; diff --git a/packages/react-native/ReactCommon/react/renderer/mounting/ShadowTreeDelegate.h b/packages/react-native/ReactCommon/react/renderer/mounting/ShadowTreeDelegate.h index 4cdeab320afd..ddbc056652cf 100644 --- a/packages/react-native/ReactCommon/react/renderer/mounting/ShadowTreeDelegate.h +++ b/packages/react-native/ReactCommon/react/renderer/mounting/ShadowTreeDelegate.h @@ -27,10 +27,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. @@ -42,24 +42,25 @@ class ShadowTreeDelegate { /* * Called right after Shadow Tree commits a new React revision of the tree. */ - virtual void shadowTreeDidFinishReactCommit(const ShadowTree &shadowTree) const = 0; + virtual void shadowTreeDidFinishReactCommit( + const ShadowTree& shadowTree) const = 0; /* * Called right after Shadow Tree promotes a React revision of the tree to * be merged. */ - virtual void shadowTreeDidPromoteReactRevision(const ShadowTree &shadowTree) const = 0; + virtual void shadowTreeDidPromoteReactRevision( + const ShadowTree& shadowTree) const = 0; /* * Called right after a Shadow Tree commits a new tree, reporting the nodes * whose layout changed in this commit. */ virtual void shadowTreeDidCommit( - const ShadowTree & /*shadowTree*/, - const RootShadowNode::Shared & /*rootShadowNode*/, - const std::vector & /*affectedLayoutableNodes*/) const - { - } + const ShadowTree& /*shadowTree*/, + const RootShadowNode::Shared& /*rootShadowNode*/, + const std::vector< + const LayoutableShadowNode*>& /*affectedLayoutableNodes*/) const {} virtual ~ShadowTreeDelegate() noexcept = default; }; diff --git a/packages/react-native/ReactCommon/react/renderer/mounting/ShadowTreeRegistry.h b/packages/react-native/ReactCommon/react/renderer/mounting/ShadowTreeRegistry.h index 73cf5af69929..92d824e7f650 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,18 +47,23 @@ 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 d8b1031eb310..c1bd73cc2cb5 100644 --- a/packages/react-native/ReactCommon/react/renderer/mounting/ShadowView.h +++ b/packages/react-native/ReactCommon/react/renderer/mounting/ShadowView.h @@ -23,18 +23,18 @@ 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; ComponentName componentName{}; ComponentHandle componentHandle{}; @@ -49,9 +49,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 @@ -62,8 +62,7 @@ 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 a34f9654b7eb..0aef25d12250 100644 --- a/packages/react-native/ReactCommon/react/renderer/mounting/ShadowViewMutation.h +++ b/packages/react-native/ReactCommon/react/renderer/mounting/ShadowViewMutation.h @@ -39,44 +39,55 @@ 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 @@ -105,16 +116,21 @@ 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 dddca1e0da97..f28af1a1d9f3 100644 --- a/packages/react-native/ReactCommon/react/renderer/mounting/TelemetryController.h +++ b/packages/react-native/ReactCommon/react/renderer/mounting/TelemetryController.h @@ -17,8 +17,9 @@ namespace facebook::react { class MountingCoordinator; -using MountingTransactionCallback = - std::function; +using MountingTransactionCallback = std::function; /* * Provides convenient tools for aggregating and accessing telemetry data @@ -30,25 +31,26 @@ 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 b1f005d128a9..7b3ab79152f5 100644 --- a/packages/react-native/ReactCommon/react/renderer/mounting/internal/CullingContext.h +++ b/packages/react-native/ReactCommon/react/renderer/mounting/internal/CullingContext.h @@ -20,9 +20,10 @@ 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 c8f954deba15..ee4323ef9ffc 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,18 +41,16 @@ 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 inOtherTree() const - { + bool inOtherTree() const { return this->otherTreePair != nullptr; } }; 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 b85b1e13be46..a6a80e2507e1 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 0fad716a4df1..e9c1810b67bf 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,16 +43,18 @@ class StubView final { Tag parentTag{NO_VIEW_TAG}; }; -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, + const StubView& stubView, + DebugStringConvertibleOptions options); +std::vector getDebugChildren( + 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 58dd4f19b6f1..fbb3921c5ae4 100644 --- a/packages/react-native/ReactCommon/react/renderer/mounting/stubs/StubViewTree.h +++ b/packages/react-native/ReactCommon/react/renderer/mounting/stubs/StubViewTree.h @@ -18,18 +18,21 @@ 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. @@ -41,8 +44,7 @@ class StubViewTree { */ std::vector takeMountingLogs(); - bool hasTag(Tag tag) const - { + bool hasTag(Tag tag) const { return registry_.find(tag) != registry_.end(); } @@ -51,15 +53,15 @@ 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); - 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); } // namespace facebook::react 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 0e03e715196e..d0829f339e6e 100644 --- a/packages/react-native/ReactCommon/react/renderer/mounting/stubs/stubs.h +++ b/packages/react-native/ReactCommon/react/renderer/mounting/stubs/stubs.h @@ -17,12 +17,14 @@ 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/updateMountedFlag.h b/packages/react-native/ReactCommon/react/renderer/mounting/updateMountedFlag.h index 8d290e84aaa2..eb03317bdf43 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 8181a8079e71..162ee030df87 100644 --- a/packages/react-native/ReactCommon/react/renderer/observers/events/EventPerformanceLogger.h +++ b/packages/react-native/ReactCommon/react/renderer/observers/events/EventPerformanceLogger.h @@ -24,14 +24,16 @@ 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; @@ -39,11 +41,14 @@ 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 { @@ -60,8 +65,7 @@ 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 4a689f18469d..ca77b70ea6f2 100644 --- a/packages/react-native/ReactCommon/react/renderer/observers/intersection/IntersectionObserver.h +++ b/packages/react-native/ReactCommon/react/renderer/observers/intersection/IntersectionObserver.h @@ -28,7 +28,8 @@ 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; @@ -39,9 +40,10 @@ 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); } }; @@ -58,39 +60,37 @@ 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,7 +100,8 @@ 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.h b/packages/react-native/ReactCommon/react/renderer/observers/intersection/IntersectionObserverManager.h index 06e7daa0a704..c68dde1ce1c8 100644 --- a/packages/react-native/ReactCommon/react/renderer/observers/intersection/IntersectionObserverManager.h +++ b/packages/react-native/ReactCommon/react/renderer/observers/intersection/IntersectionObserverManager.h @@ -19,55 +19,65 @@ 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>> observersBySurfaceId_; + mutable std::unordered_map< + SurfaceId, + std::vector>> + 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_; @@ -82,9 +92,12 @@ class IntersectionObserverManager final : public UIManagerMountHook, // 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 610354f05047..73a0fc4a5a39 100644 --- a/packages/react-native/ReactCommon/react/renderer/observers/intersection/IntersectionObserverState.h +++ b/packages/react-native/ReactCommon/react/renderer/observers/intersection/IntersectionObserverState.h @@ -25,16 +25,21 @@ 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; 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.h b/packages/react-native/ReactCommon/react/renderer/observers/mutation/MutationObserver.h index becead06d14b..2af8e29bd13d 100644 --- a/packages/react-native/ReactCommon/react/renderer/observers/mutation/MutationObserver.h +++ b/packages/react-native/ReactCommon/react/renderer/observers/mutation/MutationObserver.h @@ -27,45 +27,49 @@ 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 587bc526fa9d..530214330692 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,35 +26,38 @@ 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> observersBySurfaceId_; + std::unordered_map< + SurfaceId, + 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 922e1c7701a2..1f1d561ade62 100644 --- a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeScheduler.h +++ b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeScheduler.h @@ -22,7 +22,8 @@ namespace facebook::react { using RuntimeSchedulerRenderingUpdate = std::function; using SurfaceId = int32_t; -using RuntimeSchedulerTaskErrorHandler = std::function; +using RuntimeSchedulerTaskErrorHandler = + std::function; extern const char RuntimeSchedulerKey[]; @@ -34,27 +35,39 @@ class RuntimeSchedulerBase : public facebook::hermes::IEventLoopControl { using facebook::hermes::IEventLoopControl::scheduleTask; - 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 @@ -69,19 +82,19 @@ class RuntimeScheduler final : public 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; /// IEventLoopControl implementation, forwarded to the underlying fork. - void scheduleTask(const std::function &task) override; + void scheduleTask(const std::function& task) override; uint64_t registerTaskQueueSource() override; @@ -94,7 +107,7 @@ class RuntimeScheduler 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. @@ -102,17 +115,23 @@ class RuntimeScheduler 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; 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. @@ -120,7 +139,7 @@ class RuntimeScheduler 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 @@ -153,26 +172,33 @@ class RuntimeScheduler 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 *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.h b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeSchedulerBinding.h index 6e1c2a79c91c..1987b1146f9c 100644 --- a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeSchedulerBinding.h +++ b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeSchedulerBinding.h @@ -27,14 +27,15 @@ 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 @@ -44,7 +45,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 590b27a70480..e66eb643e2a2 100644 --- a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeSchedulerCallInvoker.h +++ b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeSchedulerCallInvoker.h @@ -21,9 +21,10 @@ 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 5900c33a9f4e..309ead75b11e 100644 --- a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeSchedulerEventTimingDelegate.h +++ b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeSchedulerEventTimingDelegate.h @@ -20,7 +20,8 @@ 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 614aed82e811..be58f754aaa6 100644 --- a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeSchedulerIntersectionObserverDelegate.h +++ b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeSchedulerIntersectionObserverDelegate.h @@ -18,7 +18,8 @@ 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 7306df99b973..40f87e0bf2bb 100644 --- a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeScheduler_Legacy.h +++ b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeScheduler_Legacy.h @@ -29,19 +29,19 @@ 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; /// IEventLoopControl implementation. No-op for legacy scheduler. - void scheduleTask(const std::function &task) override; + void scheduleTask(const std::function& task) override; uint64_t registerTaskQueueSource() override; void unregisterTaskQueueSource(uint64_t sourceId) override; @@ -52,7 +52,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. @@ -60,25 +60,31 @@ 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. @@ -86,7 +92,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 @@ -119,22 +125,32 @@ 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::vector>, TaskPriorityComparer> taskQueue_; + std::priority_queue< + std::shared_ptr, + std::vector>, + TaskPriorityComparer> + taskQueue_; const RuntimeExecutor runtimeExecutor_; SchedulerPriority currentPriority_{SchedulerPriority::NormalPriority}; @@ -146,7 +162,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 @@ -154,7 +170,10 @@ 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 @@ -173,7 +192,8 @@ 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 624676b22755..43529414cdeb 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,11 +43,11 @@ 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; /// IEventLoopControl implementation. \p task is always scheduled as an idle /// task. - void scheduleTask(const std::function &task) override; + void scheduleTask(const std::function& task) override; uint64_t registerTaskQueueSource() override; @@ -60,35 +60,41 @@ 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. @@ -96,7 +102,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 @@ -131,7 +137,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 @@ -139,17 +145,23 @@ 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: /// Monotonic counter handing out IDs for IEventLoopControl task queue @@ -158,9 +170,13 @@ class RuntimeScheduler_Modern final : public RuntimeSchedulerBase { std::atomic syncTaskRequests_{0}; - std::priority_queue, std::vector>, TaskPriorityComparer> taskQueue_; + std::priority_queue< + std::shared_ptr, + std::vector>, + TaskPriorityComparer> + taskQueue_; - Task *currentTask_{}; + Task* currentTask_{}; HighResTimeStamp lastYieldingOpportunity_; HighResDuration longestPeriodWithoutYieldingOpportunity_; @@ -175,7 +191,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(); @@ -187,20 +203,24 @@ 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); + void + executeTask(jsi::Runtime& runtime, Task& task, bool didUserCallbackTimeout); void updateRendering(HighResTimeStamp taskEndTime); - void handleTaskError(jsi::Runtime &runtime, jsi::JSError &error); + void handleTaskError(jsi::Runtime& runtime, jsi::JSError& error); void clearQueues(); 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 @@ -220,11 +240,14 @@ 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}; - - PerformanceEntryReporter *performanceEntryReporter_{nullptr}; - RuntimeSchedulerIntersectionObserverDelegate *intersectionObserverDelegate_{nullptr}; + std::atomic + shadowTreeRevisionConsistencyManager_{nullptr}; + std::atomic eventTimingDelegate_{ + 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 df109665581e..68523e4a26bf 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 0ec4dfaf38ea..615525f4b007 100644 --- a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/Task.h +++ b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/Task.h @@ -23,12 +23,18 @@ 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: #ifndef RCT_REMOVE_LEGACY_ARCH @@ -42,13 +48,14 @@ 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 b5e52894ba14..85cfd7f16792 100644 --- a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/primitives.h +++ b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/primitives.h @@ -12,15 +12,17 @@ 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 55c763f2a57b..a93767e59573 100644 --- a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/tests/StubClock.h +++ b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/tests/StubClock.h @@ -13,23 +13,19 @@ 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 4d82dc1df680..a0c838c0eb50 100644 --- a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/tests/StubErrorUtils.h +++ b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/tests/StubErrorUtils.h @@ -17,15 +17,17 @@ 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; } @@ -36,8 +38,7 @@ 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") { @@ -46,7 +47,10 @@ 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(); }); @@ -55,8 +59,7 @@ 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 95a8e16f7ce5..2f190c5f79af 100644 --- a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/tests/StubQueue.h +++ b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/tests/StubQueue.h @@ -12,8 +12,7 @@ class StubQueue { public: - void runOnQueue(std::function &&func) - { + void runOnQueue(std::function&& func) { { std::lock_guard lock(mutex_); callbackQueue_.push(func); @@ -22,15 +21,13 @@ 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_); @@ -45,23 +42,22 @@ 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: @@ -69,5 +65,6 @@ 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 bc0b7b17d802..71c2c46478a3 100644 --- a/packages/react-native/ReactCommon/react/renderer/scheduler/Scheduler.h +++ b/packages/react-native/ReactCommon/react/renderer/scheduler/Scheduler.h @@ -40,9 +40,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 @@ -50,15 +50,17 @@ class Scheduler final : public UIManagerDelegate { /* * Registers and unregisters a `SurfaceHandler` object in the `Scheduler`. */ - 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 +69,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 +84,36 @@ 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 uiManagerShouldSynchronouslyUpdateViewOnUIThread( + Tag tag, + const folly::dynamic& props) override; + void uiManagerDidUpdateShadowTree( + const std::unordered_map& tagToProps) override; void uiManagerDidCaptureViewSnapshot(Tag tag, SurfaceId surfaceId) override; - void uiManagerDidSetViewSnapshot(Tag sourceTag, Tag targetTag, SurfaceId surfaceId) override; + void uiManagerDidSetViewSnapshot( + Tag sourceTag, + Tag targetTag, + SurfaceId surfaceId) override; void uiManagerDidClearPendingSnapshots() override; - void uiManagerShouldAddEventListener(std::shared_ptr listener) final; - void uiManagerShouldRemoveEventListener(const std::shared_ptr &listener) final; - void uiManagerDidFinishReactCommit(const ShadowTree &shadowTree) override; - void uiManagerDidPromoteReactRevision(const ShadowTree &shadowTree) override; - void uiManagerDidStartSurface(const ShadowTree &shadowTree) override; + void uiManagerShouldAddEventListener( + std::shared_ptr listener) final; + void uiManagerShouldRemoveEventListener( + const std::shared_ptr& listener) final; + void uiManagerDidFinishReactCommit(const ShadowTree& shadowTree) override; + void uiManagerDidPromoteReactRevision(const ShadowTree& shadowTree) override; + void uiManagerDidStartSurface(const ShadowTree& shadowTree) override; #pragma mark - ContextContainer std::shared_ptr getContextContainer() const; @@ -115,15 +125,17 @@ 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 uiManagerShouldAddOnSurfaceStartCallback(OnSurfaceStartCallback &&callback) override; + void uiManagerShouldAddOnSurfaceStartCallback( + OnSurfaceStartCallback&& callback) override; private: friend class SurfaceHandler; - SchedulerDelegate *delegate_; + SchedulerDelegate* delegate_; // Invalidation token captured by-value into lambdas deferred via // runtimeScheduler_->scheduleRenderingUpdate. Set to true on delegate // change or Scheduler destruction so a lambda that outlives its captured @@ -155,7 +167,7 @@ class Scheduler final : public UIManagerDelegate { */ std::shared_ptr contextContainer_; - RuntimeScheduler *runtimeScheduler_{nullptr}; + RuntimeScheduler* runtimeScheduler_{nullptr}; std::shared_ptr viewTransitionModule_; diff --git a/packages/react-native/ReactCommon/react/renderer/scheduler/SchedulerDelegate.h b/packages/react-native/ReactCommon/react/renderer/scheduler/SchedulerDelegate.h index 06d9773e4ba5..1e74b2d87b42 100644 --- a/packages/react-native/ReactCommon/react/renderer/scheduler/SchedulerDelegate.h +++ b/packages/react-native/ReactCommon/react/renderer/scheduler/SchedulerDelegate.h @@ -25,7 +25,9 @@ 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 @@ -36,7 +38,8 @@ 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 at the end of the event loop if there were commits to the JS @@ -47,28 +50,41 @@ class SchedulerDelegate { /* * 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; // View transition bitmap snapshot capture and application. - virtual void schedulerDidCaptureViewSnapshot(Tag tag, SurfaceId surfaceId) = 0; - virtual void schedulerDidSetViewSnapshot(Tag sourceTag, Tag targetTag, SurfaceId surfaceId) = 0; + virtual void schedulerDidCaptureViewSnapshot( + Tag tag, + SurfaceId surfaceId) = 0; + virtual void schedulerDidSetViewSnapshot( + Tag sourceTag, + Tag targetTag, + SurfaceId surfaceId) = 0; virtual void schedulerDidClearPendingSnapshots() = 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 93cfb22fef84..de17c0e60bc8 100644 --- a/packages/react-native/ReactCommon/react/renderer/scheduler/SurfaceHandler.h +++ b/packages/react-native/ReactCommon/react/renderer/scheduler/SurfaceHandler.h @@ -62,24 +62,25 @@ 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; /* * Not moveable or copyable */ - SurfaceHandler(SurfaceHandler &&other) noexcept = delete; - SurfaceHandler(const SurfaceHandler &SurfaceHandler) noexcept = delete; - SurfaceHandler &operator=(SurfaceHandler &&other) noexcept = delete; - SurfaceHandler &operator=(const SurfaceHandler &other) noexcept = delete; + SurfaceHandler(SurfaceHandler&& other) noexcept = delete; + SurfaceHandler(const SurfaceHandler& SurfaceHandler) noexcept = delete; + SurfaceHandler& operator=(SurfaceHandler&& other) noexcept = delete; + 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. @@ -112,7 +113,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; /* @@ -120,7 +121,8 @@ 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 @@ -128,12 +130,16 @@ 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. @@ -147,7 +153,7 @@ 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; @@ -184,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 75ef5692b2a1..e8709a7cd7b7 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,25 +56,29 @@ 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 71cda6395482..47cb304eb849 100644 --- a/packages/react-native/ReactCommon/react/renderer/telemetry/SurfaceTelemetry.h +++ b/packages/react-native/ReactCommon/react/renderer/telemetry/SurfaceTelemetry.h @@ -42,7 +42,9 @@ 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 40639078a933..a6a293f78e36 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 dd8a74b79e0b..5ef1901ef078 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 47474ed06248..2f4b85c09c2e 100644 --- a/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/TextLayoutManagerExtended.h +++ b/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/TextLayoutManagerExtended.h @@ -19,21 +19,27 @@ namespace facebook::react { template -concept TextLayoutManagerWithPreparedTextLayout = requires( - TextLayoutManagerT textLayoutManager, - AttributedString attributedString, - ParagraphAttributes paragraphAttributes, - TextLayoutContext layoutContext, - LayoutConstraints layoutConstraints, - typename TextLayoutManagerT::PreparedTextLayout preparedTextLayout) { - sizeof(typename TextLayoutManagerT::PreparedTextLayout); - { - textLayoutManager.prepareLayout(attributedString, paragraphAttributes, layoutContext, layoutConstraints) - } -> std::same_as; - { - textLayoutManager.measurePreparedLayout(preparedTextLayout, layoutContext, layoutConstraints) - } -> std::same_as; -}; +concept TextLayoutManagerWithPreparedTextLayout = + requires( + TextLayoutManagerT textLayoutManager, + AttributedString attributedString, + ParagraphAttributes paragraphAttributes, + TextLayoutContext layoutContext, + LayoutConstraints layoutConstraints, + typename TextLayoutManagerT::PreparedTextLayout preparedTextLayout) { + sizeof(typename TextLayoutManagerT::PreparedTextLayout); + { + textLayoutManager.prepareLayout( + attributedString, + paragraphAttributes, + layoutContext, + layoutConstraints) + } -> std::same_as; + { + textLayoutManager.measurePreparedLayout( + preparedTextLayout, layoutContext, layoutConstraints) + } -> std::same_as; + }; namespace detail { template @@ -55,64 +61,70 @@ struct PreparedTextLayoutT { template class TextLayoutManagerExtended { public: - static constexpr bool supportsLineMeasurement() - { + static constexpr bool supportsLineMeasurement() { return requires(TextLayoutManagerT textLayoutManager) { - { - textLayoutManager.measureLines(AttributedStringBox{}, ParagraphAttributes{}, Size{}) - } -> std::same_as; - }; + { + textLayoutManager.measureLines( + AttributedStringBox{}, ParagraphAttributes{}, Size{}) + } -> std::same_as; + }; } - static constexpr bool supportsPreparedTextLayout() - { + static constexpr bool supportsPreparedTextLayout() { return TextLayoutManagerWithPreparedTextLayout; } - using PreparedTextLayout = typename PreparedTextLayoutT::type; + using PreparedTextLayout = + typename PreparedTextLayoutT::type; - TextLayoutManagerExtended(const TextLayoutManagerT &textLayoutManager) : textLayoutManager_(textLayoutManager) {} + TextLayoutManagerExtended(const TextLayoutManagerT& textLayoutManager) + : textLayoutManager_(textLayoutManager) {} LinesMeasurements measureLines( - const AttributedStringBox &attributedStringBox, - const ParagraphAttributes ¶graphAttributes, - const Size &size) - { + const AttributedStringBox& attributedStringBox, + const ParagraphAttributes& paragraphAttributes, + 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"; } PreparedTextLayout prepareLayout( - const AttributedString &attributedString, - const ParagraphAttributes ¶graphAttributes, - const TextLayoutContext &layoutContext, - const LayoutConstraints &layoutConstraints) const - { + const AttributedString& attributedString, + const ParagraphAttributes& paragraphAttributes, + const TextLayoutContext& layoutContext, + const LayoutConstraints& layoutConstraints) const { if constexpr (supportsPreparedTextLayout()) { - 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 PreparedTextLayout &layout, - const TextLayoutContext &layoutContext, - const LayoutConstraints &layoutConstraints) const - { + const PreparedTextLayout& layout, + const TextLayoutContext& layoutContext, + const LayoutConstraints& layoutConstraints) const { if constexpr (supportsPreparedTextLayout()) { - 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 MeasuredPreparedTextLayout { 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 e302e5f7dded..7da310e7d7e9 100644 --- a/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/TextMeasureCache.h +++ b/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/TextMeasureCache.h @@ -24,14 +24,19 @@ 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; } @@ -67,8 +72,9 @@ class TextMeasureCacheKey final { ParagraphAttributes paragraphAttributes{}; LayoutConstraints layoutConstraints{}; // The measured size depends on the pixel scale factor because layout metrics - // are rounded to the pixel grid. Two otherwise-identical measures at different - // densities are not interchangeable, so the scale factor is part of the key. + // are rounded to the pixel grid. Two otherwise-identical measures at + // different densities are not interchangeable, so the scale factor is part of + // the key. Float pointScaleFactor{}; }; @@ -107,16 +113,23 @@ constexpr auto kSimpleThreadSafeCacheSizeCap = size_t{1024}; * Thread-safe, evicting hash table designed to store text measurement * information. */ -using TextMeasureCache = SimpleThreadSafeCache; +using TextMeasureCache = SimpleThreadSafeCache< + TextMeasureCacheKey, + TextMeasurement, + kSimpleThreadSafeCacheSizeCap>; /* * Thread-safe, evicting hash table designed to store line measurement * information. */ -using LineMeasureCache = SimpleThreadSafeCache; - -inline bool areTextAttributesEquivalentLayoutWise(const TextAttributes &lhs, const TextAttributes &rhs) -{ +using LineMeasureCache = SimpleThreadSafeCache< + LineMeasureCacheKey, + LinesMeasurements, + kSimpleThreadSafeCacheSizeCap>; + +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). @@ -138,13 +151,15 @@ inline bool areTextAttributesEquivalentLayoutWise(const TextAttributes &lhs, con 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) && floatEquality(lhs.maxFontSizeMultiplier, rhs.maxFontSizeMultiplier); } -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( @@ -164,45 +179,52 @@ inline size_t textAttributesHashLayoutWise(const TextAttributes &textAttributes) } 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; @@ -210,7 +232,8 @@ inline bool areAttributedStringsEquivalentLayoutWise(const AttributedString &lhs 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; } } @@ -218,10 +241,11 @@ inline bool areAttributedStringsEquivalentLayoutWise(const AttributedString &lhs 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; @@ -229,7 +253,8 @@ inline bool areAttributedStringsEquivalentDisplayWise(const AttributedString &lh 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; } } @@ -237,45 +262,56 @@ inline bool areAttributedStringsEquivalentDisplayWise(const AttributedString &lh 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 && floatEquality(lhs.pointScaleFactor, rhs.pointScaleFactor); } -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 && floatEquality(lhs.pointScaleFactor, rhs.pointScaleFactor); } @@ -285,8 +321,7 @@ 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, @@ -297,17 +332,17 @@ struct hash { 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, diff --git a/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/TextMeasurementRounding.h b/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/TextMeasurementRounding.h index fcf158fdf16e..bb7507c7589c 100644 --- a/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/TextMeasurementRounding.h +++ b/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/TextMeasurementRounding.h @@ -31,12 +31,15 @@ namespace facebook::react { * only by RCTTextLayoutManager.mm, and the `internal_` prefix keeps it out of * the public C++ API snapshot. */ -inline Size internal_roundTextMeasurementToPixelGrid(Size size, Float pointScaleFactor) -{ +inline Size internal_roundTextMeasurementToPixelGrid( + Size size, + Float pointScaleFactor) { constexpr auto kEpsilon = static_cast(0.001); return Size{ - .width = std::ceil((size.width + kEpsilon) * pointScaleFactor) / pointScaleFactor, - .height = std::ceil((size.height + kEpsilon) * pointScaleFactor) / pointScaleFactor, + .width = std::ceil((size.width + kEpsilon) * pointScaleFactor) / + pointScaleFactor, + .height = std::ceil((size.height + kEpsilon) * pointScaleFactor) / + pointScaleFactor, }; } 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 db78f56d578f..e3cfc765694f 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,7 +13,8 @@ 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.h b/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/platform/android/react/renderer/textlayoutmanager/TextLayoutManager.h index 0b00c4c7f3d9..cbb76320e001 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 @@ -29,30 +29,32 @@ class TextLayoutManager; */ class TextLayoutManager { public: - using PreparedTextLayout = SafeReleaseJniRef>; + using PreparedTextLayout = + 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 ¶graphAttributes, - const TextLayoutContext &layoutContext, - const LayoutConstraints &layoutConstraints) const; + const AttributedStringBox& attributedStringBox, + const ParagraphAttributes& paragraphAttributes, + const TextLayoutContext& layoutContext, + const LayoutConstraints& layoutConstraints) const; /** * Measures an AttributedString on the platform, as identified by some @@ -60,42 +62,46 @@ class TextLayoutManager { */ TextMeasurement measureCachedSpannableById( int64_t cacheId, - const ParagraphAttributes ¶graphAttributes, - const TextLayoutContext &layoutContext, - const LayoutConstraints &layoutConstraints) const; + const ParagraphAttributes& paragraphAttributes, + const TextLayoutContext& layoutContext, + const LayoutConstraints& layoutConstraints) const; /* * Measures lines of `attributedString` using native text rendering * infrastructure. */ LinesMeasurements measureLines( - const AttributedStringBox &attributedStringBox, - const ParagraphAttributes ¶graphAttributes, - const Size &size) const; + const AttributedStringBox& attributedStringBox, + const ParagraphAttributes& paragraphAttributes, + const Size& size) const; /** * Create a platform representation of fully laid out text, to later be * reused. */ PreparedTextLayout prepareLayout( - const AttributedString &attributedString, - const ParagraphAttributes ¶graphAttributes, - const TextLayoutContext &layoutContext, - const LayoutConstraints &layoutConstraints) const; + const AttributedString& attributedString, + const ParagraphAttributes& paragraphAttributes, + const TextLayoutContext& layoutContext, + const LayoutConstraints& layoutConstraints) const; /** * Derive text and attachment measurements from a PreparedTextLayout. */ TextMeasurement measurePreparedLayout( - const PreparedTextLayout &layout, - const TextLayoutContext &layoutContext, - const LayoutConstraints &layoutConstraints) const; + const PreparedTextLayout& layout, + const TextLayoutContext& layoutContext, + const LayoutConstraints& layoutConstraints) const; private: std::shared_ptr contextContainer_; TextMeasureCache textMeasureCache_; LineMeasureCache lineMeasureCache_; - SimpleThreadSafeCache preparedTextCache_; + SimpleThreadSafeCache< + PreparedTextCacheKey, + PreparedTextLayout, + -1 /* Set dynamically*/> + preparedTextCache_; }; } // namespace facebook::react 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 63f2c1afcbc9..4c69793c228a 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,29 +25,30 @@ 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 ¶graphAttributes, - const TextLayoutContext &layoutContext, - const LayoutConstraints &layoutConstraints) const; + const AttributedStringBox& attributedStringBox, + const ParagraphAttributes& paragraphAttributes, + 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/TextLayoutManager.h b/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/platform/ios/react/renderer/textlayoutmanager/TextLayoutManager.h index ce564b01254f..2e3b262c72b9 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,37 +23,38 @@ 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 ¶graphAttributes, - const TextLayoutContext &layoutContext, - const LayoutConstraints &layoutConstraints) const; + const AttributedStringBox& attributedStringBox, + const ParagraphAttributes& paragraphAttributes, + const TextLayoutContext& layoutContext, + const LayoutConstraints& layoutConstraints) const; /* * Measures lines of `attributedString` using native text rendering * infrastructure. */ LinesMeasurements measureLines( - const AttributedStringBox &attributedStringBox, - const ParagraphAttributes ¶graphAttributes, - const Size &size) const; + const AttributedStringBox& attributedStringBox, + const ParagraphAttributes& paragraphAttributes, + 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 f71565b9149b..cd596e920ca2 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/LayoutEventEmitter.h b/packages/react-native/ReactCommon/react/renderer/uimanager/LayoutEventEmitter.h index 4506cfabc8de..7d39ec6442fa 100644 --- a/packages/react-native/ReactCommon/react/renderer/uimanager/LayoutEventEmitter.h +++ b/packages/react-native/ReactCommon/react/renderer/uimanager/LayoutEventEmitter.h @@ -19,13 +19,16 @@ namespace facebook::react { */ class LayoutEventEmitter final : public UIManagerCommitHook { public: - 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 {} void shadowTreeDidCommit( - const ShadowTree &shadowTree, - const RootShadowNode::Shared &rootShadowNode, - const std::vector &affectedLayoutableNodes) noexcept override; + const ShadowTree& shadowTree, + const RootShadowNode::Shared& rootShadowNode, + const std::vector& + affectedLayoutableNodes) noexcept override; }; } // 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 e39dcf5f21db..aa2700c0b881 100644 --- a/packages/react-native/ReactCommon/react/renderer/uimanager/PointerEventsProcessor.h +++ b/packages/react-native/ReactCommon/react/renderer/uimanager/PointerEventsProcessor.h @@ -34,44 +34,55 @@ 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, EventTarget *target); + static std::shared_ptr getShadowNodeFromEventTarget( + jsi::Runtime& runtime, + 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); - - void setPointerCapture(PointerIdentifier pointerId, const std::shared_ptr &shadowNode); - void releasePointerCapture(PointerIdentifier pointerId, const ShadowNode *shadowNode); - bool hasPointerCapture(PointerIdentifier pointerId, const ShadowNode *shadowNode); + 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); 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_; @@ -89,10 +100,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 712a3cdfffc2..336b9dbdd748 100644 --- a/packages/react-native/ReactCommon/react/renderer/uimanager/PointerHoverTracker.h +++ b/packages/react-native/ReactCommon/react/renderer/uimanager/PointerHoverTracker.h @@ -23,12 +23,15 @@ 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 @@ -36,7 +39,9 @@ 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(); @@ -54,7 +59,9 @@ 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 a3d3b67f6f4f..5d9b6400971f 100644 --- a/packages/react-native/ReactCommon/react/renderer/uimanager/SurfaceRegistryBinding.h +++ b/packages/react-native/ReactCommon/react/renderer/uimanager/SurfaceRegistryBinding.h @@ -7,6 +7,7 @@ #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 f7452c8defe6..d81d8f2f4867 100644 --- a/packages/react-native/ReactCommon/react/renderer/uimanager/UIManager.h +++ b/packages/react-native/ReactCommon/react/renderer/uimanager/UIManager.h @@ -41,31 +41,35 @@ 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::shared_ptr animationBackend); + void unstable_setAnimationBackend( + std::shared_ptr animationBackend); std::weak_ptr unstable_getAnimationBackend(); /** @@ -73,17 +77,18 @@ class UIManager final : public ShadowTreeDelegate { */ void stopSurfaceForAnimationDelegate(SurfaceId surfaceId) const; - void setNativeAnimatedDelegate(std::weak_ptr delegate); + void setNativeAnimatedDelegate( + std::weak_ptr delegate); /** * Sets and gets UIManager's ViewTransition API delegate. */ - void setViewTransitionDelegate(UIManagerViewTransitionDelegate *delegate); - UIManagerViewTransitionDelegate *getViewTransitionDelegate() const; + void setViewTransitionDelegate(UIManagerViewTransitionDelegate* delegate); + UIManagerViewTransitionDelegate* getViewTransitionDelegate() const; void animationTick() const; - void synchronouslyUpdateViewOnUIThread(Tag tag, const folly::dynamic &props); + void synchronouslyUpdateViewOnUIThread(Tag tag, const folly::dynamic& props); /* * Provides access to a UIManagerBinding. @@ -92,38 +97,44 @@ 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, + ShadowTree::Unique&& shadowTree, std::string moduleName, 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, std::string moduleName, folly::dynamic props, DisplayMode displayMode) - const noexcept; + void setSurfaceProps( + SurfaceId surfaceId, + std::string moduleName, + folly::dynamic props, + DisplayMode displayMode) const noexcept; ShadowTree::Unique stopSurface(SurfaceId surfaceId) const; @@ -134,48 +145,54 @@ 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; - void shadowTreeDidFinishReactCommit(const ShadowTree &shadowTree) const override; + void shadowTreeDidFinishReactCommit( + const ShadowTree& shadowTree) const override; - void shadowTreeDidPromoteReactRevision(const ShadowTree &shadowTree) const override; + void shadowTreeDidPromoteReactRevision( + const ShadowTree& shadowTree) const override; void shadowTreeDidCommit( - const ShadowTree &shadowTree, - const RootShadowNode::Shared &rootShadowNode, - const std::vector &affectedLayoutableNodes) const noexcept override; + const ShadowTree& shadowTree, + const RootShadowNode::Shared& rootShadowNode, + const std::vector& affectedLayoutableNodes) + const noexcept 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 std::shared_ptr>> &children, + const ShadowNode& shadowNode, + const std::shared_ptr< + const std::vector>>& 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 std::shared_ptr>> &rootChildren, + const std::shared_ptr>>& + 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 @@ -183,24 +200,28 @@ 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,13 +229,14 @@ 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 - ContextContainer std::shared_ptr getContextContainer() const; @@ -223,10 +245,12 @@ class UIManager final : public ShadowTreeDelegate { void addEventListener(std::shared_ptr listener); - void removeEventListener(const std::shared_ptr &listener); + void removeEventListener( + const std::shared_ptr& listener); #pragma mark - Add on surface start callback - void addOnSurfaceStartCallback(UIManagerDelegate::OnSurfaceStartCallback &&callback); + void addOnSurfaceStartCallback( + UIManagerDelegate::OnSurfaceStartCallback&& callback); private: friend class UIManagerBinding; @@ -238,34 +262,35 @@ 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_; - UIManagerViewTransitionDelegate *viewTransitionDelegate_{nullptr}; + UIManagerViewTransitionDelegate* viewTransitionDelegate_{nullptr}; const RuntimeExecutor runtimeExecutor_{}; ShadowTreeRegistry shadowTreeRegistry_{}; 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::shared_ptr animationBackend_; }; diff --git a/packages/react-native/ReactCommon/react/renderer/uimanager/UIManagerAnimationBackend.h b/packages/react-native/ReactCommon/react/renderer/uimanager/UIManagerAnimationBackend.h index 27c39b18e5e0..9669e5708e0b 100644 --- a/packages/react-native/ReactCommon/react/renderer/uimanager/UIManagerAnimationBackend.h +++ b/packages/react-native/ReactCommon/react/renderer/uimanager/UIManagerAnimationBackend.h @@ -27,12 +27,12 @@ class UIManagerAnimationBackend { virtual ~UIManagerAnimationBackend() = default; virtual void onAnimationFrame(AnimationTimestamp timestamp) = 0; - virtual CallbackId start(const Callback &callback) = 0; + virtual CallbackId start(const Callback& callback) = 0; virtual void stop(CallbackId callbackId) = 0; virtual void clearRegistry(SurfaceId surfaceId) = 0; virtual void clearRegistryOnSurfaceStop(SurfaceId surfaceId) = 0; virtual void trigger() = 0; - virtual void pushAnimationMutations(const Callback &callback) = 0; + virtual void pushAnimationMutations(const Callback& callback) = 0; virtual void registerJSInvoker(std::shared_ptr jsInvoker) = 0; }; diff --git a/packages/react-native/ReactCommon/react/renderer/uimanager/UIManagerAnimationDelegate.h b/packages/react-native/ReactCommon/react/renderer/uimanager/UIManagerAnimationDelegate.h index ac310eb4ad96..09c2d0661b5b 100644 --- a/packages/react-native/ReactCommon/react/renderer/uimanager/UIManagerAnimationDelegate.h +++ b/packages/react-native/ReactCommon/react/renderer/uimanager/UIManagerAnimationDelegate.h @@ -23,17 +23,18 @@ 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 0d1910b442b6..db33a51429bd 100644 --- a/packages/react-native/ReactCommon/react/renderer/uimanager/UIManagerBinding.h +++ b/packages/react-native/ReactCommon/react/renderer/uimanager/UIManagerBinding.h @@ -26,13 +26,15 @@ 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); @@ -43,11 +45,11 @@ class UIManagerBinding : public jsi::HostObject { * Thread synchronization must be enforced externally. */ void dispatchEvent( - jsi::Runtime &runtime, - EventTarget *eventTarget, - const std::string &type, + jsi::Runtime& runtime, + EventTarget* eventTarget, + const std::string& type, ReactEventPriority priority, - const EventPayload &payload, + const EventPayload& payload, HighResTimeStamp eventTimestamp) const; /* @@ -62,10 +64,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: /* @@ -73,11 +75,11 @@ class UIManagerBinding : public jsi::HostObject { * UIManagerBinding::dispatchEvent. */ void dispatchEventToJS( - jsi::Runtime &runtime, - EventTarget *eventTarget, - const std::string &type, + jsi::Runtime& runtime, + EventTarget* eventTarget, + const std::string& type, ReactEventPriority priority, - const EventPayload &payload, + const EventPayload& payload, HighResTimeStamp eventTimestamp) const; std::shared_ptr uiManager_; diff --git a/packages/react-native/ReactCommon/react/renderer/uimanager/UIManagerCommitHook.h b/packages/react-native/ReactCommon/react/renderer/uimanager/UIManagerCommitHook.h index 30f5d0e6d61e..523ec225e8c3 100644 --- a/packages/react-native/ReactCommon/react/renderer/uimanager/UIManagerCommitHook.h +++ b/packages/react-native/ReactCommon/react/renderer/uimanager/UIManagerCommitHook.h @@ -24,8 +24,9 @@ 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 +34,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,10 +47,9 @@ 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; @@ -61,11 +61,10 @@ class UIManagerCommitHook { * from `ShadowTreeDelegate`. */ virtual void shadowTreeDidCommit( - const ShadowTree & /*shadowTree*/, - const RootShadowNode::Shared & /*rootShadowNode*/, - const std::vector & /*affectedLayoutableNodes*/) noexcept - { - } + const ShadowTree& /*shadowTree*/, + const RootShadowNode::Shared& /*rootShadowNode*/, + const std::vector< + const LayoutableShadowNode*>& /*affectedLayoutableNodes*/) noexcept {} virtual ~UIManagerCommitHook() noexcept = default; }; diff --git a/packages/react-native/ReactCommon/react/renderer/uimanager/UIManagerDelegate.h b/packages/react-native/ReactCommon/react/renderer/uimanager/UIManagerDelegate.h index ef4dd73de763..d932cab61b25 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,58 +48,71 @@ 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; /* * Called after a new React revision of the shadow tree is committed. */ - virtual void uiManagerDidFinishReactCommit(const ShadowTree &shadowTree) = 0; + virtual void uiManagerDidFinishReactCommit(const ShadowTree& shadowTree) = 0; /* * Called after a React revision of the shadow tree is promoted to be merged. */ - virtual void uiManagerDidPromoteReactRevision(const ShadowTree &shadowTree) = 0; + virtual void uiManagerDidPromoteReactRevision( + const ShadowTree& shadowTree) = 0; - using OnSurfaceStartCallback = std::function; - virtual void uiManagerShouldAddOnSurfaceStartCallback(OnSurfaceStartCallback &&callback) = 0; + using OnSurfaceStartCallback = + std::function; + virtual void uiManagerShouldAddOnSurfaceStartCallback( + OnSurfaceStartCallback&& callback) = 0; // View transition bitmap snapshot capture and application. - virtual void uiManagerDidCaptureViewSnapshot(Tag tag, SurfaceId surfaceId) = 0; - virtual void uiManagerDidSetViewSnapshot(Tag sourceTag, Tag targetTag, SurfaceId surfaceId) = 0; + virtual void uiManagerDidCaptureViewSnapshot( + Tag tag, + SurfaceId surfaceId) = 0; + virtual void uiManagerDidSetViewSnapshot( + Tag sourceTag, + Tag targetTag, + SurfaceId surfaceId) = 0; virtual void uiManagerDidClearPendingSnapshots() = 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 763efb8b3535..1a014411d859 100644 --- a/packages/react-native/ReactCommon/react/renderer/uimanager/UIManagerMountHook.h +++ b/packages/react-native/ReactCommon/react/renderer/uimanager/UIManagerMountHook.h @@ -25,11 +25,12 @@ 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/UIManagerViewTransitionDelegate.h b/packages/react-native/ReactCommon/react/renderer/uimanager/UIManagerViewTransitionDelegate.h index 3fa4c0e1261b..2b1b7d8a9037 100644 --- a/packages/react-native/ReactCommon/react/renderer/uimanager/UIManagerViewTransitionDelegate.h +++ b/packages/react-native/ReactCommon/react/renderer/uimanager/UIManagerViewTransitionDelegate.h @@ -18,16 +18,20 @@ class UIManagerViewTransitionDelegate { public: virtual ~UIManagerViewTransitionDelegate() = default; - virtual void - applyViewTransitionName(const ShadowNode &shadowNode, const std::string &name, const std::string &className) - { - } + virtual void applyViewTransitionName( + const ShadowNode& shadowNode, + const std::string& name, + const std::string& className) {} - virtual void createViewTransitionInstance(const std::string & /*name*/, Tag /*pseudoElementTag*/) {} + virtual void createViewTransitionInstance( + const std::string& /*name*/, + Tag /*pseudoElementTag*/) {} - virtual void cancelViewTransitionName(const ShadowNode &shadowNode, const std::string &name) {} + virtual void cancelViewTransitionName( + const ShadowNode& shadowNode, + const std::string& name) {} - virtual void restoreViewTransitionName(const ShadowNode &shadowNode) {} + virtual void restoreViewTransitionName(const ShadowNode& shadowNode) {} /* * Start a view transition. mutationCallback and onReadyCallback MUST be @@ -37,9 +41,7 @@ class UIManagerViewTransitionDelegate { virtual void startViewTransition( std::function mutationCallback, std::function onReadyCallback, - std::function onCompleteCallback) - { - } + std::function onCompleteCallback) {} virtual void startViewTransitionReadyFinished() {} @@ -54,19 +56,18 @@ class UIManagerViewTransitionDelegate { }; virtual std::optional getViewTransitionInstance( - const std::string &name, - const std::string &pseudo) - { + const std::string& name, + const std::string& pseudo) { return std::nullopt; } // Similar to UIManager::findShadowNodeByTag, but searches all direct children // of the root node (where pseudo-element nodes live) rather than just the - // first child. Pseudo-element nodes are appended as additional children of the - // root node, rather than inserted into the main React tree, to avoid + // first child. Pseudo-element nodes are appended as additional children of + // the root node, rather than inserted into the main React tree, to avoid // disrupting the user-created component tree. - virtual std::shared_ptr findPseudoElementShadowNodeByTag(Tag /*tag*/) const - { + virtual std::shared_ptr findPseudoElementShadowNodeByTag( + Tag /*tag*/) const { return nullptr; } 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 c7ab5af7fac2..e7d891134a1a 100644 --- a/packages/react-native/ReactCommon/react/renderer/uimanager/consistency/LazyShadowTreeRevisionConsistencyManager.h +++ b/packages/react-native/ReactCommon/react/renderer/uimanager/consistency/LazyShadowTreeRevisionConsistencyManager.h @@ -22,16 +22,20 @@ 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); - std::shared_ptr updateCurrentRevision(SurfaceId surfaceId); + std::shared_ptr updateCurrentRevision( + SurfaceId surfaceId); #pragma mark - ShadowTreeRevisionProvider - std::shared_ptr getCurrentRevision(SurfaceId surfaceId) override; + std::shared_ptr getCurrentRevision( + SurfaceId surfaceId) override; #pragma mark - ShadowTreeRevisionConsistencyManager @@ -40,8 +44,9 @@ class LazyShadowTreeRevisionConsistencyManager : public ShadowTreeRevisionConsis 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 ae798d078ebf..c77174cf4a87 100644 --- a/packages/react-native/ReactCommon/react/renderer/uimanager/primitives.h +++ b/packages/react-native/ReactCommon/react/renderer/uimanager/primitives.h @@ -16,32 +16,35 @@ namespace facebook::react { -using BackgroundExecutor = std::function &&callback)>; +using BackgroundExecutor = + std::function&& callback)>; struct ShadowNodeListWrapper : public jsi::NativeState { - ShadowNodeListWrapper(std::shared_ptr>> shadowNodeList) - : shadowNodeList(std::move(shadowNodeList)) - { - } + ShadowNodeListWrapper( + std::shared_ptr>> + 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 // https://itanium-cxx-abi.github.io/cxx-abi/abi.html#vague-vtable) ~ShadowNodeListWrapper() override; - std::shared_ptr>> shadowNodeList; + std::shared_ptr>> + shadowNodeList; }; 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,22 +54,22 @@ inline static jsi::Value valueFromShadowNode( // TODO: once we no longer need to mutate the return value (appendChildToSet) // make this a SharedListOfShared -inline static std::shared_ptr>> shadowNodeListFromValue( - jsi::Runtime &runtime, - const jsi::Value &value) -{ +inline static std::shared_ptr>> +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 { @@ -76,15 +79,17 @@ inline static std::shared_ptr>> sh ; } } else { - return object.getNativeState(runtime)->shadowNodeList; + return object.getNativeState(runtime) + ->shadowNodeList; } } inline static jsi::Value valueFromShadowNodeList( - jsi::Runtime &runtime, - std::shared_ptr>> shadowNodeList) -{ - auto wrapper = std::make_shared(std::move(shadowNodeList)); + jsi::Runtime& runtime, + std::shared_ptr>> + 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); @@ -92,11 +97,13 @@ inline static jsi::Value valueFromShadowNodeList( return obj; } -inline static std::shared_ptr>> shadowNodeListFromWeakList( - const std::shared_ptr>> &weakShadowNodeList) -{ - auto result = std::make_shared>>(); - for (const auto &weakShadowNode : *weakShadowNodeList) { +inline static std::shared_ptr>> +shadowNodeListFromWeakList( + const std::shared_ptr>>& + weakShadowNodeList) { + auto result = + std::make_shared>>(); + for (const auto& weakShadowNode : *weakShadowNodeList) { auto sharedShadowNode = weakShadowNode.lock(); if (!sharedShadowNode) { return nullptr; @@ -106,40 +113,40 @@ inline static std::shared_ptr>> sh return result; } -inline static std::shared_ptr>> weakShadowNodeListFromValue( - jsi::Runtime &runtime, - const jsi::Value &value) -{ +inline static std::shared_ptr>> +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) { @@ -155,13 +162,15 @@ 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/renderer/viewtransition/ViewTransitionModule.h b/packages/react-native/ReactCommon/react/renderer/viewtransition/ViewTransitionModule.h index ea3583794881..10629e5a7da4 100644 --- a/packages/react-native/ReactCommon/react/renderer/viewtransition/ViewTransitionModule.h +++ b/packages/react-native/ReactCommon/react/renderer/viewtransition/ViewTransitionModule.h @@ -28,25 +28,33 @@ class ViewTransitionModule : public UIManagerViewTransitionDelegate, public: ~ViewTransitionModule() override; - void initialize(UIManager *uiManager, std::weak_ptr weakThis); + void initialize( + UIManager* uiManager, + std::weak_ptr weakThis); #pragma mark - UIManagerViewTransitionDelegate - // will be called when a view will transition. if a view already has a view-transition-name, it may not be called - // again until it's removed - void applyViewTransitionName(const ShadowNode &shadowNode, const std::string &name, const std::string &className) - override; + // will be called when a view will transition. if a view already has a + // view-transition-name, it may not be called again until it's removed + void applyViewTransitionName( + const ShadowNode& shadowNode, + const std::string& name, + const std::string& className) override; // creates a pseudo-element shadow node for a given transition name using the // captured old layout metrics - void createViewTransitionInstance(const std::string &name, Tag pseudoElementTag) override; + void createViewTransitionInstance( + const std::string& name, + Tag pseudoElementTag) override; - // if a viewTransitionName is cancelled, the element doesn't have view-transition-name and browser won't be taking - // snapshot - void cancelViewTransitionName(const ShadowNode &shadowNode, const std::string &name) override; + // if a viewTransitionName is cancelled, the element doesn't have + // view-transition-name and browser won't be taking snapshot + void cancelViewTransitionName( + const ShadowNode& shadowNode, + const std::string& name) override; // restore cancellation - void restoreViewTransitionName(const ShadowNode &shadowNode) override; + void restoreViewTransitionName(const ShadowNode& shadowNode) override; void startViewTransition( std::function mutationCallback, @@ -57,18 +65,21 @@ class ViewTransitionModule : public UIManagerViewTransitionDelegate, void startViewTransitionEnd() override; - std::optional getViewTransitionInstance(const std::string &name, const std::string &pseudo) - override; + std::optional getViewTransitionInstance( + const std::string& name, + const std::string& pseudo) override; #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 ShadowTreeCommitOptions &commitOptions) noexcept override; + const ShadowTree& shadowTree, + const RootShadowNode::Shared& oldRootShadowNode, + const RootShadowNode::Unshared& newRootShadowNode, + const ShadowTreeCommitOptions& commitOptions) noexcept override; #pragma mark - MountingOverrideDelegate @@ -76,10 +87,11 @@ class ViewTransitionModule : public UIManagerViewTransitionDelegate, std::optional pullTransaction( SurfaceId surfaceId, MountingTransaction::Number number, - const TransactionTelemetry &telemetry, + const TransactionTelemetry& telemetry, ShadowViewMutationList mutations) const override; - std::shared_ptr findPseudoElementShadowNodeByTag(Tag tag) const override; + std::shared_ptr findPseudoElementShadowNodeByTag( + Tag tag) const override; void suspendOnActiveViewTransition() override; @@ -108,8 +120,8 @@ class ViewTransitionModule : public UIManagerViewTransitionDelegate, // registry of layout of old/new views std::unordered_map oldLayout_{}; std::unordered_map newLayout_{}; - // tag -> (names, transitionId) registry, populated during applyViewTransitionName - // Note that tag and name are not 1:1 mapping + // tag -> (names, transitionId) registry, populated during + // applyViewTransitionName Note that tag and name are not 1:1 mapping // - In some nested composition 2 names are mappped to the same tag // - tags of old and new views are mapped to the same name(s) struct NameRegistryEntry { @@ -119,11 +131,15 @@ class ViewTransitionModule : public UIManagerViewTransitionDelegate, std::unordered_map nameRegistry_{}; // used for cancel/restore viewTransitionName - std::unordered_map> cancelledNameRegistry_{}; + std::unordered_map> + cancelledNameRegistry_{}; - // pseudo-element nodes keyed by transition name, appended to root children via UIManagerCommitHook - // TODO: T262559264 pseudo elements should be cleaned up as soon as transition animation ends - std::unordered_map> oldPseudoElementNodes_{}; + // pseudo-element nodes keyed by transition name, appended to root children + // via UIManagerCommitHook + // TODO: T262559264 pseudo elements should be cleaned up as soon as transition + // animation ends + std::unordered_map> + oldPseudoElementNodes_{}; struct InactivePseudoElement { std::shared_ptr node; @@ -135,14 +151,16 @@ class ViewTransitionModule : public UIManagerViewTransitionDelegate, // pseudo-element nodes created for entering nodes, to be copied into // oldPseudoElementNodes_ during the next applyViewTransitionName call. // Mutable because pullTransaction (const) needs to erase unmounted entries. - mutable std::unordered_map> + mutable std::unordered_map< + std::string, + std::unordered_map> oldPseudoElementNodesRepository_{}; - LayoutMetrics captureLayoutMetricsFromRoot(const ShadowNode &shadowNode); + LayoutMetrics captureLayoutMetricsFromRoot(const ShadowNode& shadowNode); void applySnapshotsOnPseudoElementShadowNodes(); - UIManager *uiManager_{nullptr}; + UIManager* uiManager_{nullptr}; bool transitionStarted_{false}; @@ -163,7 +181,8 @@ class ViewTransitionModule : public UIManagerViewTransitionDelegate, // Tracks animation IDs that must complete before onCompleteCallback_ fires. // Animations are registered via waitForTransitionAnimation (called from JS - // after connectAnimatedNodeToView) and removed via transitionAnimationFinished. + // after connectAnimatedNodeToView) and removed via + // transitionAnimationFinished. std::unordered_set pendingAnimationIds_{}; std::function onCompleteCallback_{nullptr}; }; diff --git a/packages/react-native/ReactCommon/react/runtime/BindingsInstaller.h b/packages/react-native/ReactCommon/react/runtime/BindingsInstaller.h index fb4226f50699..2934685f0a38 100644 --- a/packages/react-native/ReactCommon/react/runtime/BindingsInstaller.h +++ b/packages/react-native/ReactCommon/react/runtime/BindingsInstaller.h @@ -13,8 +13,7 @@ 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 57dc1999b6f3..d707f2f48606 100644 --- a/packages/react-native/ReactCommon/react/runtime/BridgelessNativeMethodCallInvoker.h +++ b/packages/react-native/ReactCommon/react/runtime/BridgelessNativeMethodCallInvoker.h @@ -15,9 +15,13 @@ 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 274015587fde..6606e492ec5f 100644 --- a/packages/react-native/ReactCommon/react/runtime/BufferedRuntimeExecutor.h +++ b/packages/react-native/ReactCommon/react/runtime/BufferedRuntimeExecutor.h @@ -17,14 +17,13 @@ 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_; @@ -33,7 +32,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 b850d0fac316..444a28724537 100644 --- a/packages/react-native/ReactCommon/react/runtime/ReactInstance.h +++ b/packages/react-native/ReactCommon/react/runtime/ReactInstance.h @@ -22,18 +22,18 @@ 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); - ReactInstance(const ReactInstance &) = delete; - ReactInstance(ReactInstance &&) = delete; - ReactInstance &operator=(const ReactInstance &) = delete; - ReactInstance &operator=(ReactInstance &&) = delete; + jsinspector_modern::HostTarget* parentInspectorTarget = nullptr); + ReactInstance(const ReactInstance&) = delete; + ReactInstance(ReactInstance&&) = delete; + ReactInstance& operator=(const ReactInstance&) = delete; + ReactInstance& operator=(ReactInstance&&) = delete; ~ReactInstance() noexcept override; RuntimeExecutor getUnbufferedRuntimeExecutor() noexcept; @@ -47,17 +47,22 @@ 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); @@ -67,20 +72,21 @@ 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 9da5669d7fc7..473c97e9ebc0 100644 --- a/packages/react-native/ReactCommon/react/runtime/TimerManager.h +++ b/packages/react-native/ReactCommon/react/runtime/TimerManager.h @@ -17,7 +17,12 @@ 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. @@ -28,12 +33,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()); } @@ -45,37 +50,38 @@ struct TimerCallback { class TimerManager { public: - explicit TimerManager(std::unique_ptr platformTimerRegistry) noexcept; - TimerManager(const TimerManager &) = delete; - TimerManager(TimerManager &&) = delete; - TimerManager &operator=(const TimerManager &) = delete; - TimerManager &operator=(TimerManager &&) = delete; + explicit TimerManager( + std::unique_ptr platformTimerRegistry) noexcept; + TimerManager(const TimerManager&) = delete; + TimerManager(TimerManager&&) = delete; + TimerManager& operator=(const TimerManager&) = delete; + TimerManager& operator=(TimerManager&&) = delete; ~TimerManager() noexcept; void setRuntimeExecutor(RuntimeExecutor runtimeExecutor) noexcept; void callTimer(TimerHandle handle); - void attachGlobals(jsi::Runtime &runtime); + void attachGlobals(jsi::Runtime& runtime); void quit(); private: 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 bdbce1930162..d7758a45bf22 100644 --- a/packages/react-native/ReactCommon/react/runtime/nativeviewconfig/LegacyUIManagerConstantsProviderBinding.h +++ b/packages/react-native/ReactCommon/react/runtime/nativeviewconfig/LegacyUIManagerConstantsProviderBinding.h @@ -16,9 +16,12 @@ 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); + jsi::Runtime& runtime, + const std::string& name, + std::function&& provider); +void install( + 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 c7bc46026c5f..250f89f01068 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,24 +13,25 @@ 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/RCTHost.h b/packages/react-native/ReactCommon/react/runtime/platform/ios/ReactCommon/RCTHost.h index d845c8e46904..768eef6d7022 100644 --- a/packages/react-native/ReactCommon/react/runtime/platform/ios/ReactCommon/RCTHost.h +++ b/packages/react-native/ReactCommon/react/runtime/platform/ios/ReactCommon/RCTHost.h @@ -61,8 +61,7 @@ typedef NSURL *_Nullable (^RCTHostBundleURLProvider)(void); @end // `RCTHostRuntimeDelegate` has been merged into `RCTHostDelegate` in 0.84 -[[deprecated("Use 'RCTHostDelegate' instead")]] -@protocol RCTHostRuntimeDelegate +[[deprecated("Use 'RCTHostDelegate' instead")]] @protocol RCTHostRuntimeDelegate - (void)host:(RCTHost *)host didInitializeRuntime:(facebook::jsi::Runtime &)runtime 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 e0da9c1fd6a4..5732d3e41afa 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,8 +15,9 @@ 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 8711745df841..2af5dcc0c6c5 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 @@ -17,7 +17,7 @@ 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 #endif // RCT_REMOVE_LEGACY_COMPONENT_INTEROP diff --git a/packages/react-native/ReactCommon/react/test_utils/Entropy.h b/packages/react-native/ReactCommon/react/test_utils/Entropy.h index e4c9f524508e..a858bada731a 100644 --- a/packages/react-native/ReactCommon/react/test_utils/Entropy.h +++ b/packages/react-native/ReactCommon/react/test_utils/Entropy.h @@ -24,8 +24,7 @@ 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_); @@ -34,14 +33,12 @@ 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_; } @@ -50,41 +47,39 @@ 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); } @@ -93,8 +88,7 @@ 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_); } @@ -103,15 +97,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)); @@ -121,7 +115,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 88e6c8bc5fcc..7455d120fe76 100644 --- a/packages/react-native/ReactCommon/react/test_utils/MockClock.h +++ b/packages/react-native/ReactCommon/react/test_utils/MockClock.h @@ -11,16 +11,15 @@ 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 09b27b02f386..61e977467ba1 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 199dd5441511..79ca15d2a655 100644 --- a/packages/react-native/ReactCommon/react/test_utils/ios/RCTSwizzleHelpers.h +++ b/packages/react-native/ReactCommon/react/test_utils/ios/RCTSwizzleHelpers.h @@ -11,6 +11,9 @@ 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/shadowTreeGeneration.h b/packages/react-native/ReactCommon/react/test_utils/shadowTreeGeneration.h index 6627592789c9..7ac52510c776 100644 --- a/packages/react-native/ReactCommon/react/test_utils/shadowTreeGeneration.h +++ b/packages/react-native/ReactCommon/react/test_utils/shadowTreeGeneration.h @@ -20,8 +20,7 @@ namespace facebook::react { -static Tag generateReactTag() -{ +static Tag generateReactTag() { static Tag tag = 1000; return tag++; } @@ -34,11 +33,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); @@ -56,21 +55,24 @@ 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; } @@ -82,58 +84,62 @@ static ShadowTreeEdge findShadowNodeWithIndex(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 std::vector> cloneSharedShadowNodeList( - const std::vector> &list) -{ + const std::vector>& list) { auto result = std::vector>{}; 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)}); + 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)) { @@ -145,11 +151,13 @@ 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 @@ -164,17 +172,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 = ""; @@ -204,8 +212,9 @@ 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()) { @@ -213,9 +222,11 @@ static inline std::shared_ptr messWithYogaStyles(const Entropy &entr } 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 @@ -223,7 +234,7 @@ static inline std::shared_ptr messWithYogaStyles(const Entropy &entr // 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); } @@ -234,49 +245,55 @@ static inline std::shared_ptr messWithYogaStyles(const Entropy &entr 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); @@ -284,15 +301,18 @@ static inline std::shared_ptr generateShadowNodeTree( auto chunks = entropy.distribute(items, deviation); auto children = std::vector>{}; - 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)}, + std::make_shared< + const std::vector>>(children)}, family); } diff --git a/packages/react-native/ReactCommon/react/timing/primitives.h b/packages/react-native/ReactCommon/react/timing/primitives.h index 440e227a3340..f5b36dfbafeb 100644 --- a/packages/react-native/ReactCommon/react/timing/primitives.h +++ b/packages/react-native/ReactCommon/react/timing/primitives.h @@ -27,165 +27,157 @@ 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_; }; @@ -196,153 +188,147 @@ 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 __APPLE__ - static double getMachTimebaseConversionFactor() - { + static double getMachTimebaseConversionFactor() { mach_timebase_info_data_t info; mach_timebase_info(&info); return static_cast(info.numer) / info.denom; } - static std::chrono::steady_clock::time_point machAbsoluteTimeToSteadyClockTimePoint() - { + static std::chrono::steady_clock::time_point + machAbsoluteTimeToSteadyClockTimePoint() { static double conversionFactor = getMachTimebaseConversionFactor(); uint64_t machTime = mach_absolute_time(); - auto nanoseconds = static_cast(static_cast(machTime) * conversionFactor); - return std::chrono::steady_clock::time_point(std::chrono::nanoseconds(nanoseconds)); + auto nanoseconds = + static_cast(static_cast(machTime) * conversionFactor); + return std::chrono::steady_clock::time_point( + std::chrono::nanoseconds(nanoseconds)); } #endif #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(); + static std::chrono::steady_clock::time_point chronoNow() { + auto& timeStampProvider = getTimeStampProvider(); if (timeStampProvider != nullptr) { return timeStampProvider(); } @@ -353,8 +339,7 @@ class HighResTimeStamp { #endif } #else - inline static std::chrono::steady_clock::time_point chronoNow() - { + inline static std::chrono::steady_clock::time_point chronoNow() { #ifdef __APPLE__ return machAbsoluteTimeToSteadyClockTimePoint(); #else @@ -364,18 +349,21 @@ class HighResTimeStamp { #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/Base64.h b/packages/react-native/ReactCommon/react/utils/Base64.h index ec879c2b62b3..b2af2cf1f3ae 100644 --- a/packages/react-native/ReactCommon/react/utils/Base64.h +++ b/packages/react-native/ReactCommon/react/utils/Base64.h @@ -15,17 +15,19 @@ namespace facebook::react { 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; } @@ -57,8 +59,7 @@ 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]; @@ -83,14 +84,12 @@ 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/react/utils/ContextContainer.h b/packages/react-native/ReactCommon/react/utils/ContextContainer.h index 890cff25ca73..41bcdebdfbd4 100644 --- a/packages/react-native/ReactCommon/react/utils/ContextContainer.h +++ b/packages/react-native/ReactCommon/react/utils/ContextContainer.h @@ -37,8 +37,7 @@ 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)}); @@ -48,8 +47,7 @@ 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); @@ -60,11 +58,10 @@ 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 +73,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,8 +88,7 @@ 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); @@ -100,7 +96,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 f53ada84bc2f..75c6ec808972 100644 --- a/packages/react-native/ReactCommon/react/utils/FloatComparison.h +++ b/packages/react-native/ReactCommon/react/utils/FloatComparison.h @@ -14,9 +14,10 @@ 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/MoveWrapper.h b/packages/react-native/ReactCommon/react/utils/MoveWrapper.h index 22a9a0f238f4..51e6696befb9 100644 --- a/packages/react-native/ReactCommon/react/utils/MoveWrapper.h +++ b/packages/react-native/ReactCommon/react/utils/MoveWrapper.h @@ -78,42 +78,37 @@ 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; @@ -123,8 +118,7 @@ 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/react/utils/OnScopeExit.h b/packages/react-native/ReactCommon/react/utils/OnScopeExit.h index 633471daf826..73db32e11554 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 675cdc06ed9f..4415fec8be50 100644 --- a/packages/react-native/ReactCommon/react/utils/PackTraits.h +++ b/packages/react-native/ReactCommon/react/utils/PackTraits.h @@ -12,16 +12,15 @@ 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 d226bcb5ccb1..6e0e5bc9d77d 100644 --- a/packages/react-native/ReactCommon/react/utils/RunLoopObserver.h +++ b/packages/react-native/ReactCommon/react/utils/RunLoopObserver.h @@ -61,12 +61,15 @@ 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. @@ -78,7 +81,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. @@ -115,7 +118,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 04ea9e7f05ab..b94b9eac24b7 100644 --- a/packages/react-native/ReactCommon/react/utils/SharedFunction.h +++ b/packages/react-native/ReactCommon/react/utils/SharedFunction.h @@ -29,28 +29,27 @@ 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 e5c8994b1b87..0ad4eda51894 100644 --- a/packages/react-native/ReactCommon/react/utils/SimpleThreadSafeCache.h +++ b/packages/react-native/ReactCommon/react/utils/SimpleThreadSafeCache.h @@ -15,7 +15,9 @@ namespace facebook::react { template -concept CacheGeneratorFunction = std::invocable && std::same_as, ValueT>; +concept CacheGeneratorFunction = std::invocable && + std::same_as < std::invoke_result_t, +ValueT > ; /* * Simple thread-safe LRU cache. @@ -35,8 +37,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; } @@ -46,9 +48,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); } @@ -58,8 +60,7 @@ 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,8 +76,9 @@ 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 d7ebf2b0e82c..1d23018435a3 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,23 +45,28 @@ 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; } @@ -73,8 +78,7 @@ 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( @@ -84,9 +88,10 @@ DestinationTimePointT clockCast(SourceTimePointT timePoint) /* * 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 94508ae7ed41..106d14f8c425 100644 --- a/packages/react-native/ReactCommon/react/utils/TemplateStringLiteral.h +++ b/packages/react-native/ReactCommon/react/utils/TemplateStringLiteral.h @@ -19,13 +19,12 @@ 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 6b5a5efbfd12..4a945d968f70 100644 --- a/packages/react-native/ReactCommon/react/utils/fnv1a.h +++ b/packages/react-native/ReactCommon/react/utils/fnv1a.h @@ -24,27 +24,25 @@ 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 e6ffd2983f78..936df84b12e0 100644 --- a/packages/react-native/ReactCommon/react/utils/hash_combine.h +++ b/packages/react-native/ReactCommon/react/utils/hash_combine.h @@ -13,20 +13,21 @@ namespace facebook::react { template -concept Hashable = !std::is_same_v && (requires(T a) { - { std::hash{}(a) } -> std::convertible_to; -}); +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 ff1ea60733e7..b577d5596007 100644 --- a/packages/react-native/ReactCommon/react/utils/iequals.h +++ b/packages/react-native/ReactCommon/react/utils/iequals.h @@ -15,8 +15,7 @@ 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 d907339b42b0..2459b8917dbc 100644 --- a/packages/react-native/ReactCommon/react/utils/jsi-utils.h +++ b/packages/react-native/ReactCommon/react/utils/jsi-utils.h @@ -23,6 +23,9 @@ 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.h b/packages/react-native/ReactCommon/react/utils/platform/android/react/utils/LowPriorityExecutor.h index 160efadb16a7..c09398d28e33 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 d70ae6edca2e..eca44655e048 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,8 +11,7 @@ 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 3517cac75101..49c69ee48d5e 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 766d8d8791ea..27212d006dc1 100644 --- a/packages/react-native/ReactCommon/react/utils/toLower.h +++ b/packages/react-native/ReactCommon/react/utils/toLower.h @@ -12,8 +12,7 @@ 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 2b68a2377c9f..6d8d19d2b345 100644 --- a/packages/react-native/ReactCommon/react/utils/to_underlying.h +++ b/packages/react-native/ReactCommon/react/utils/to_underlying.h @@ -15,8 +15,7 @@ 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.h b/packages/react-native/ReactCommon/reactperflogger/fusebox/FuseboxTracer.h index 17fb757772b2..0c415154e7a7 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,12 +37,16 @@ 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); - - static FuseboxTracer &getFuseboxTracer(); + 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(); private: FuseboxTracer() {} diff --git a/packages/react-native/ReactCommon/reactperflogger/reactperflogger/BridgeNativeModulePerfLogger.h b/packages/react-native/ReactCommon/reactperflogger/reactperflogger/BridgeNativeModulePerfLogger.h index 1d024ab0d34e..16b42625299f 100644 --- a/packages/react-native/ReactCommon/reactperflogger/reactperflogger/BridgeNativeModulePerfLogger.h +++ b/packages/react-native/ReactCommon/reactperflogger/reactperflogger/BridgeNativeModulePerfLogger.h @@ -10,57 +10,71 @@ #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 @@ -69,10 +83,25 @@ 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 a470efc8c7a2..da0936a4a059 100644 --- a/packages/react-native/ReactCommon/reactperflogger/reactperflogger/FuseboxPerfettoDataSource.h +++ b/packages/react-native/ReactCommon/reactperflogger/reactperflogger/FuseboxPerfettoDataSource.h @@ -19,28 +19,30 @@ 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 025450d1bdaf..265bd63607bf 100644 --- a/packages/react-native/ReactCommon/reactperflogger/reactperflogger/HermesPerfettoDataSource.h +++ b/packages/react-native/ReactCommon/reactperflogger/reactperflogger/HermesPerfettoDataSource.h @@ -13,28 +13,30 @@ 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 ac1c27553c89..861778fa24ca 100644 --- a/packages/react-native/ReactCommon/reactperflogger/reactperflogger/NativeModulePerfLogger.h +++ b/packages/react-native/ReactCommon/reactperflogger/reactperflogger/NativeModulePerfLogger.h @@ -38,22 +38,24 @@ 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 @@ -61,10 +63,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 @@ -72,28 +74,58 @@ 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. @@ -105,12 +137,26 @@ 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 43c08152f979..c46ff051c536 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 06acd9a3ae03..133f95a0bc71 100644 --- a/packages/react-native/ReactCommon/reactperflogger/reactperflogger/ReactPerfettoCategories.h +++ b/packages/react-native/ReactCommon/reactperflogger/reactperflogger/ReactPerfettoCategories.h @@ -13,6 +13,7 @@ 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 9acf97f9b3c7..73c7619e7706 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 999e38c31344..f8f69b54343e 100644 --- a/packages/react-native/ReactCommon/runtimeexecutor/ReactCommon/RuntimeExecutor.h +++ b/packages/react-native/ReactCommon/runtimeexecutor/ReactCommon/RuntimeExecutor.h @@ -19,6 +19,7 @@ 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 fd74c21261b5..0baee4e2841a 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 17d78acf2a86..12ab4d958e7a 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/YGMacros.h b/packages/react-native/ReactCommon/yoga/yoga/YGMacros.h index ab9b2627a452..64b7fd4d07ee 100644 --- a/packages/react-native/ReactCommon/yoga/yoga/YGMacros.h +++ b/packages/react-native/ReactCommon/yoga/yoga/YGMacros.h @@ -55,42 +55,42 @@ #endif #ifdef __cplusplus -#define YG_DEFINE_ENUM_FLAG_OPERATORS(name) \ - extern "C++" { \ - constexpr name operator~(name a) { \ - return static_cast( \ - ~static_cast::type>(a)); \ - } \ - constexpr name operator|(name a, name b) { \ - return static_cast( \ - static_cast::type>(a) | \ - static_cast::type>(b)); \ - } \ - constexpr name operator&(name a, name b) { \ - return static_cast( \ - static_cast::type>(a) & \ - static_cast::type>(b)); \ - } \ - constexpr name operator^(name a, name b) { \ - return static_cast( \ - static_cast::type>(a) ^ \ - static_cast::type>(b)); \ - } \ - inline name& operator|=(name& a, name b) { \ - return reinterpret_cast( \ - reinterpret_cast::type&>(a) |= \ - static_cast::type>(b)); \ - } \ - inline name& operator&=(name& a, name b) { \ - return reinterpret_cast( \ - reinterpret_cast::type&>(a) &= \ - static_cast::type>(b)); \ - } \ - inline name& operator^=(name& a, name b) { \ - return reinterpret_cast( \ - reinterpret_cast::type&>(a) ^= \ - static_cast::type>(b)); \ - } \ +#define YG_DEFINE_ENUM_FLAG_OPERATORS(name) \ + extern "C++" { \ + constexpr name operator~(name a) \ + { \ + return static_cast(~static_cast::type>(a)); \ + } \ + constexpr name operator|(name a, name b) \ + { \ + return static_cast( \ + static_cast::type>(a) | static_cast::type>(b)); \ + } \ + constexpr name operator&(name a, name b) \ + { \ + return static_cast( \ + static_cast::type>(a) & static_cast::type>(b)); \ + } \ + constexpr name operator^(name a, name b) \ + { \ + return static_cast( \ + static_cast::type>(a) ^ static_cast::type>(b)); \ + } \ + inline name &operator|=(name &a, name b) \ + { \ + return reinterpret_cast( \ + reinterpret_cast::type &>(a) |= static_cast::type>(b)); \ + } \ + inline name &operator&=(name &a, name b) \ + { \ + return reinterpret_cast( \ + reinterpret_cast::type &>(a) &= static_cast::type>(b)); \ + } \ + inline name &operator^=(name &a, name b) \ + { \ + return reinterpret_cast( \ + reinterpret_cast::type &>(a) ^= static_cast::type>(b)); \ + } \ } #else #define YG_DEFINE_ENUM_FLAG_OPERATORS(name) @@ -98,4 +98,4 @@ #define YG_ENUM_DECL(NAME, ...) \ typedef YG_ENUM_BEGIN(NAME){__VA_ARGS__} YG_ENUM_END(NAME); \ - YG_EXPORT const char* NAME##ToString(NAME); + YG_EXPORT const char *NAME##ToString(NAME); diff --git a/packages/react-native/ReactCxxPlatform/react/coremodules/AppStateModule.h b/packages/react-native/ReactCxxPlatform/react/coremodules/AppStateModule.h index 089cd19c497f..c682ec2439e1 100644 --- a/packages/react-native/ReactCxxPlatform/react/coremodules/AppStateModule.h +++ b/packages/react-native/ReactCxxPlatform/react/coremodules/AppStateModule.h @@ -16,7 +16,8 @@ namespace facebook::react { using AppStateConstants = NativeAppStateAppStateConstants; template <> -struct Bridging : NativeAppStateAppStateConstantsBridging {}; +struct Bridging + : NativeAppStateAppStateConstantsBridging {}; using AppState = NativeAppStateAppState; @@ -25,14 +26,18 @@ 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 c750cf971521..63b50871e9cd 100644 --- a/packages/react-native/ReactCxxPlatform/react/coremodules/DeviceInfoModule.h +++ b/packages/react-native/ReactCxxPlatform/react/coremodules/DeviceInfoModule.h @@ -12,9 +12,15 @@ namespace facebook::react { -using DisplayMetrics = NativeDeviceInfoDisplayMetrics; +using DisplayMetrics = + NativeDeviceInfoDisplayMetrics; -using DisplayMetricsAndroid = NativeDeviceInfoDisplayMetricsAndroid; +using DisplayMetricsAndroid = NativeDeviceInfoDisplayMetricsAndroid< + double, + double, + double, + double, + double>; using DimensionsPayload = NativeDeviceInfoDimensionsPayload< std::optional, @@ -22,26 +28,33 @@ using DimensionsPayload = NativeDeviceInfoDimensionsPayload< std::optional, std::optional>; -using DeviceInfoConstants = - NativeDeviceInfoDeviceInfoConstants, std::optional>; +using DeviceInfoConstants = NativeDeviceInfoDeviceInfoConstants< + DimensionsPayload, + std::optional, + 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 ea4c9bc27ac6..04470366940c 100644 --- a/packages/react-native/ReactCxxPlatform/react/coremodules/PlatformConstantsModule.h +++ b/packages/react-native/ReactCxxPlatform/react/coremodules/PlatformConstantsModule.h @@ -13,44 +13,49 @@ namespace facebook::react { using ReactNativeVersionAndroid = - NativePlatformConstantsAndroidReactNativeVersionAndroid>; + NativePlatformConstantsAndroidReactNativeVersionAndroid< + int, + int, + int, + std::optional>; template <> struct Bridging - : 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>; + : NativePlatformConstantsAndroidReactNativeVersionAndroidBridging< + ReactNativeVersionAndroid> {}; + +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 {}; + : NativePlatformConstantsAndroidPlatformConstantsAndroidBridging< + PlatformConstantsAndroid> {}; // 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 0cedcb18373f..ac60020f83e6 100644 --- a/packages/react-native/ReactCxxPlatform/react/devsupport/DevLoadingViewModule.h +++ b/packages/react-native/ReactCxxPlatform/react/devsupport/DevLoadingViewModule.h @@ -15,19 +15,22 @@ 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, std::optional dismissButton); - 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 fa0f5844d51d..68071ba2834f 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,8 +42,7 @@ 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 a9ec5cd41978..907df8efa3b8 100644 --- a/packages/react-native/ReactCxxPlatform/react/devsupport/DevSettingsModule.h +++ b/packages/react-native/ReactCxxPlatform/react/devsupport/DevSettingsModule.h @@ -24,33 +24,33 @@ class DevSettingsModule : public NativeDevSettingsCxxSpec { 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 958cc1901990..daf8ecfc0b1d 100644 --- a/packages/react-native/ReactCxxPlatform/react/devsupport/IDevUIDelegate.h +++ b/packages/react-native/ReactCxxPlatform/react/devsupport/IDevUIDelegate.h @@ -20,11 +20,15 @@ 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 0ee88e327ee2..1ace8f9d6527 100644 --- a/packages/react-native/ReactCxxPlatform/react/devsupport/LogBoxModule.h +++ b/packages/react-native/ReactCxxPlatform/react/devsupport/LogBoxModule.h @@ -13,12 +13,14 @@ 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 7e1596c0f2ba..5551b40c8049 100644 --- a/packages/react-native/ReactCxxPlatform/react/devsupport/PackagerConnection.h +++ b/packages/react-native/ReactCxxPlatform/react/devsupport/PackagerConnection.h @@ -24,13 +24,13 @@ class PackagerConnection { PackagerConnection( WebSocketClientFactory webSocketClientFactory, std::string packagerConnectionUrl, - LiveReloadCallback &&liveReloadCallback, - ShowDevMenuCallback &&showDevMenuCallback); + 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: void attemptConnection(); diff --git a/packages/react-native/ReactCxxPlatform/react/devsupport/SourceCodeModule.h b/packages/react-native/ReactCxxPlatform/react/devsupport/SourceCodeModule.h index 7924c5ad1b29..a19f8800c2df 100644 --- a/packages/react-native/ReactCxxPlatform/react/devsupport/SourceCodeModule.h +++ b/packages/react-native/ReactCxxPlatform/react/devsupport/SourceCodeModule.h @@ -16,16 +16,17 @@ namespace facebook::react { using SourceCodeConstants = NativeSourceCodeSourceCodeConstants; template <> -struct Bridging : NativeSourceCodeSourceCodeConstantsBridging {}; +struct Bridging + : NativeSourceCodeSourceCodeConstantsBridging {}; class SourceCodeModule : public NativeSourceCodeCxxSpec { public: - explicit SourceCodeModule(std::shared_ptr jsInvoker, std::string sourceURL = "") - : NativeSourceCodeCxxSpec(jsInvoker), sourceURL_(std::move(sourceURL)) - { - } + explicit SourceCodeModule( + std::shared_ptr jsInvoker, + std::string sourceURL = "") + : NativeSourceCodeCxxSpec(jsInvoker), sourceURL_(std::move(sourceURL)) {} - SourceCodeConstants getConstants(jsi::Runtime &rt); + SourceCodeConstants getConstants(jsi::Runtime& rt); private: std::string sourceURL_; diff --git a/packages/react-native/ReactCxxPlatform/react/devsupport/inspector/Inspector.h b/packages/react-native/ReactCxxPlatform/react/devsupport/inspector/Inspector.h index c110ad6aea4c..22fb9bffe4c8 100644 --- a/packages/react-native/ReactCxxPlatform/react/devsupport/inspector/Inspector.h +++ b/packages/react-native/ReactCxxPlatform/react/devsupport/inspector/Inspector.h @@ -20,11 +20,13 @@ 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, @@ -32,23 +34,24 @@ class Inspector : public InspectorThread, public std::enable_shared_from_this 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_; @@ -58,7 +61,8 @@ class Inspector : public InspectorThread, public std::enable_shared_from_this 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 e91d5be9f601..871e82eb1753 100644 --- a/packages/react-native/ReactCxxPlatform/react/devsupport/inspector/InspectorPackagerConnectionDelegate.h +++ b/packages/react-native/ReactCxxPlatform/react/devsupport/inspector/InspectorPackagerConnectionDelegate.h @@ -19,19 +19,20 @@ 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; @@ -47,12 +48,13 @@ class InspectorPackagerConnectionDelegate final : public jsinspector_modern::Ins 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 1dbee83051d8..e6b25fe8fbcc 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 045e279b08f8..5cd56007f88b 100644 --- a/packages/react-native/ReactCxxPlatform/react/http/IHttpClient.h +++ b/packages/react-native/ReactCxxPlatform/react/http/IHttpClient.h @@ -40,9 +40,13 @@ 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}; @@ -67,11 +71,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 86aff58f4d35..9424fb76ab00 100644 --- a/packages/react-native/ReactCxxPlatform/react/http/IWebSocketClient.h +++ b/packages/react-native/ReactCxxPlatform/react/http/IWebSocketClient.h @@ -15,21 +15,23 @@ 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; }; @@ -38,7 +40,8 @@ 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 7c12c2acbd28..452f9a8f664e 100644 --- a/packages/react-native/ReactCxxPlatform/react/http/platform/cxx/WebSocketClient.h +++ b/packages/react-native/ReactCxxPlatform/react/http/platform/cxx/WebSocketClient.h @@ -18,20 +18,22 @@ 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 8362646682f3..c1a4bcec7693 100644 --- a/packages/react-native/ReactCxxPlatform/react/io/IImageLoader.h +++ b/packages/react-native/ReactCxxPlatform/react/io/IImageLoader.h @@ -12,7 +12,8 @@ namespace facebook::react { -using IImageLoaderOnLoadCallback = std::function; +using IImageLoaderOnLoadCallback = std::function< + void(double imageWidth, double imageHeight, const char* errorMessage)>; class IImageLoader { public: @@ -24,9 +25,11 @@ 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 0966a70af3ba..209564efc45b 100644 --- a/packages/react-native/ReactCxxPlatform/react/io/ImageLoaderModule.h +++ b/packages/react-native/ReactCxxPlatform/react/io/ImageLoaderModule.h @@ -21,27 +21,34 @@ 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 0d67e3b302de..e2e09005a7b0 100644 --- a/packages/react-native/ReactCxxPlatform/react/io/NetworkingModule.h +++ b/packages/react-native/ReactCxxPlatform/react/io/NetworkingModule.h @@ -17,26 +17,41 @@ 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), }; } @@ -46,10 +61,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); @@ -65,32 +80,35 @@ 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); @@ -98,10 +116,13 @@ class NetworkingModule : public NativeNetworkingAndroidCxxSpec 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, @@ -109,9 +130,15 @@ class NetworkingModule : public NativeNetworkingAndroidCxxSpec 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 8b4588a1e87f..ec3273cce080 100644 --- a/packages/react-native/ReactCxxPlatform/react/io/ResourceLoader.h +++ b/packages/react-native/ReactCxxPlatform/react/io/ResourceLoader.h @@ -16,16 +16,19 @@ class JSBigString; 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::unique_ptr 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::unique_ptr 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::unique_ptr getResourceFileContents(const std::string &path); + static bool isResourceDirectory(const std::string& path); + static bool isResourceFile(const std::string& path); + static std::unique_ptr 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 8ade7372dfcd..f12ca1af328b 100644 --- a/packages/react-native/ReactCxxPlatform/react/io/WebSocketModule.h +++ b/packages/react-native/ReactCxxPlatform/react/io/WebSocketModule.h @@ -21,31 +21,40 @@ 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 8df2d98ca9e1..234cbd43393d 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 b449ca254059..8db809186f31 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 d887dd168ba3..8820d17cd937 100644 --- a/packages/react-native/ReactCxxPlatform/react/logging/DefaultLogger.h +++ b/packages/react-native/ReactCxxPlatform/react/logging/DefaultLogger.h @@ -12,7 +12,8 @@ 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 d512d2b006d7..d2d88fc8cb26 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.h b/packages/react-native/ReactCxxPlatform/react/logging/NativeExceptionsManager.h index 9e8d49ac8c2f..bf708bc0585d 100644 --- a/packages/react-native/ReactCxxPlatform/react/logging/NativeExceptionsManager.h +++ b/packages/react-native/ReactCxxPlatform/react/logging/NativeExceptionsManager.h @@ -27,7 +27,8 @@ using StackFrame = NativeExceptionsManagerStackFrame< std::optional>; template <> -struct Bridging : NativeExceptionsManagerStackFrameBridging {}; +struct Bridging + : NativeExceptionsManagerStackFrameBridging {}; // extraData is `?Object` on the JS side and callers routinely populate it with // non-string values (e.g. jsBuild as a number, nested Error-decorated objects @@ -45,29 +46,42 @@ 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 5b038a00c2c7..94e2dfe720a0 100644 --- a/packages/react-native/ReactCxxPlatform/react/nativemodule/JavaScriptModule.h +++ b/packages/react-native/ReactCxxPlatform/react/nativemodule/JavaScriptModule.h @@ -13,7 +13,9 @@ namespace facebook::react { -using JavaScriptModuleCallback = - std::function; +using JavaScriptModuleCallback = std::function; } // namespace facebook::react diff --git a/packages/react-native/ReactCxxPlatform/react/nativemodule/TurboModuleProvider.h b/packages/react-native/ReactCxxPlatform/react/nativemodule/TurboModuleProvider.h index b10c248aab89..84175f2d8417 100644 --- a/packages/react-native/ReactCxxPlatform/react/nativemodule/TurboModuleProvider.h +++ b/packages/react-native/ReactCxxPlatform/react/nativemodule/TurboModuleProvider.h @@ -17,8 +17,9 @@ namespace facebook::react { class CallInvoker; class TurboModule; -using TurboModuleProvider = - std::function(const std::string &name, const std::shared_ptr &jsInvoker)>; +using TurboModuleProvider = std::function( + const std::string& name, + const std::shared_ptr& jsInvoker)>; using TurboModuleProviders = std::vector; diff --git a/packages/react-native/ReactCxxPlatform/react/profiling/FrameStats.h b/packages/react-native/ReactCxxPlatform/react/profiling/FrameStats.h index ec2d5340c3c8..3c527f606bf9 100644 --- a/packages/react-native/ReactCxxPlatform/react/profiling/FrameStats.h +++ b/packages/react-native/ReactCxxPlatform/react/profiling/FrameStats.h @@ -25,8 +25,7 @@ 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() / @@ -37,8 +36,7 @@ class FrameStatsBlock { public: FrameStatsBlock() : startTimeStamp_(getTimeStampMs()) {} - ~FrameStatsBlock() - { + ~FrameStatsBlock() { logFrameStats(startTimeStamp_, getTimeStampMs() - startTimeStamp_); } diff --git a/packages/react-native/ReactCxxPlatform/react/profiling/RuntimeHeapInfoCollector.h b/packages/react-native/ReactCxxPlatform/react/profiling/RuntimeHeapInfoCollector.h index 120c394fa774..a941b55eff09 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 1e2ba3669df7..ac2878a1c3b3 100644 --- a/packages/react-native/ReactCxxPlatform/react/profiling/TimeSeries.h +++ b/packages/react-native/ReactCxxPlatform/react/profiling/TimeSeries.h @@ -20,18 +20,15 @@ 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; } }; @@ -42,10 +39,9 @@ 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); @@ -54,31 +50,26 @@ 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]; } @@ -90,7 +81,8 @@ 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; @@ -109,8 +101,10 @@ 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_; @@ -121,11 +115,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 ea7fe39a9563..f1b1ca9aa141 100644 --- a/packages/react-native/ReactCxxPlatform/react/profiling/perfetto.h +++ b/packages/react-native/ReactCxxPlatform/react/profiling/perfetto.h @@ -24,8 +24,7 @@ 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 40ec4d9e99d4..22f84d654428 100644 --- a/packages/react-native/ReactCxxPlatform/react/profiling/tracy_noop.h +++ b/packages/react-native/ReactCxxPlatform/react/profiling/tracy_noop.h @@ -26,11 +26,16 @@ 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 089b64d5731c..757fbc4924f1 100644 --- a/packages/react-native/ReactCxxPlatform/react/renderer/scheduler/SchedulerDelegateImpl.h +++ b/packages/react-native/ReactCxxPlatform/react/renderer/scheduler/SchedulerDelegateImpl.h @@ -16,44 +16,59 @@ 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; void setUIManager(std::shared_ptr uiManager) noexcept; 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 schedulerShouldMergeReactRevision(SurfaceId surfaceId) 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; void schedulerDidCaptureViewSnapshot(Tag tag, SurfaceId surfaceId) override; - void schedulerDidSetViewSnapshot(Tag sourceTag, Tag targetTag, SurfaceId surfaceId) override; + void schedulerDidSetViewSnapshot( + Tag sourceTag, + Tag targetTag, + SurfaceId surfaceId) override; void schedulerDidClearPendingSnapshots() override; diff --git a/packages/react-native/ReactCxxPlatform/react/renderer/uimanager/IMountingManager.h b/packages/react-native/ReactCxxPlatform/react/renderer/uimanager/IMountingManager.h index b68da46f54a0..1e7483cbfd44 100644 --- a/packages/react-native/ReactCxxPlatform/react/renderer/uimanager/IMountingManager.h +++ b/packages/react-native/ReactCxxPlatform/react/renderer/uimanager/IMountingManager.h @@ -18,11 +18,13 @@ 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: @@ -30,24 +32,31 @@ 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() {} @@ -59,32 +68,37 @@ class IMountingManager { virtual void accessibleClickAction(Tag /* viewTag */) {} - virtual void accessibleScrollInDirection(Tag /* viewTag */, int /* direction */) {} + 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 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/PlatformTimerRegistryImpl.h b/packages/react-native/ReactCxxPlatform/react/runtime/PlatformTimerRegistryImpl.h index 8cf292f47be5..e6bebefc6b20 100644 --- a/packages/react-native/ReactCxxPlatform/react/runtime/PlatformTimerRegistryImpl.h +++ b/packages/react-native/ReactCxxPlatform/react/runtime/PlatformTimerRegistryImpl.h @@ -19,10 +19,11 @@ namespace facebook::react { class PlatformTimerRegistryImpl : public PlatformTimerRegistry { public: PlatformTimerRegistryImpl() noexcept = default; - PlatformTimerRegistryImpl(const PlatformTimerRegistryImpl &) = delete; - PlatformTimerRegistryImpl(PlatformTimerRegistryImpl &&) = delete; - PlatformTimerRegistryImpl &operator=(const PlatformTimerRegistryImpl &) = delete; - PlatformTimerRegistryImpl &operator=(PlatformTimerRegistryImpl &&) = delete; + PlatformTimerRegistryImpl(const PlatformTimerRegistryImpl&) = delete; + PlatformTimerRegistryImpl(PlatformTimerRegistryImpl&&) = delete; + PlatformTimerRegistryImpl& operator=(const PlatformTimerRegistryImpl&) = + delete; + PlatformTimerRegistryImpl& operator=(PlatformTimerRegistryImpl&&) = delete; ~PlatformTimerRegistryImpl() noexcept override = default; void createTimer(uint32_t timerId, double delayMs) override; @@ -47,7 +48,10 @@ 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/runtime/ReactCxxTurboModuleProvider.h b/packages/react-native/ReactCxxPlatform/react/runtime/ReactCxxTurboModuleProvider.h index cb2c6e7edcd4..6e02dbd788c2 100644 --- a/packages/react-native/ReactCxxPlatform/react/runtime/ReactCxxTurboModuleProvider.h +++ b/packages/react-native/ReactCxxPlatform/react/runtime/ReactCxxTurboModuleProvider.h @@ -27,7 +27,8 @@ class ReactCxxTurboModuleProvider final { TurboModuleProviders turboModuleProviders, std::shared_ptr jsInvoker, JsErrorHandler::OnJsError onJsError, - std::shared_ptr animatedNodesManagerProvider = nullptr, + std::shared_ptr + animatedNodesManagerProvider = nullptr, std::shared_ptr devServerHelper = nullptr, std::shared_ptr devUIDelegate = nullptr, std::shared_ptr logBoxSurfaceDelegate = nullptr, @@ -36,13 +37,14 @@ class ReactCxxTurboModuleProvider final { std::function liveReloadCallback = nullptr, std::shared_ptr sourceURL = nullptr); - std::shared_ptr operator()(const std::string &name) const; + std::shared_ptr operator()(const std::string& name) const; private: TurboModuleProviders turboModuleProviders_; std::shared_ptr jsInvoker_; JsErrorHandler::OnJsError onJsError_; - std::shared_ptr animatedNodesManagerProvider_; + std::shared_ptr + animatedNodesManagerProvider_; std::shared_ptr devServerHelper_; std::shared_ptr devUIDelegate_; std::shared_ptr logBoxSurfaceDelegate_; diff --git a/packages/react-native/ReactCxxPlatform/react/runtime/ReactHost.h b/packages/react-native/ReactCxxPlatform/react/runtime/ReactHost.h index 9ff4a1d68941..8c49f6de875f 100644 --- a/packages/react-native/ReactCxxPlatform/react/runtime/ReactHost.h +++ b/packages/react-native/ReactCxxPlatform/react/runtime/ReactHost.h @@ -51,30 +51,33 @@ class ReactHost { std::shared_ptr devUIDelegate = nullptr, TurboModuleProviders turboModuleProviders = {}, std::shared_ptr logBoxSurfaceDelegate = nullptr, - std::shared_ptr animatedNodesManagerProvider = nullptr, + std::shared_ptr + animatedNodesManagerProvider = nullptr, ReactInstance::BindingsInstallFunc bindingsInstallFunc = nullptr, std::shared_ptr animationChoreographer = 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; @@ -84,13 +87,14 @@ 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(); @@ -98,7 +102,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_; @@ -114,7 +118,8 @@ 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/ReactInstanceConfig.h b/packages/react-native/ReactCxxPlatform/react/runtime/ReactInstanceConfig.h index 559a928f4ed3..4cea917440e9 100644 --- a/packages/react-native/ReactCxxPlatform/react/runtime/ReactInstanceConfig.h +++ b/packages/react-native/ReactCxxPlatform/react/runtime/ReactInstanceConfig.h @@ -33,7 +33,8 @@ struct ReactInstanceConfig { // When unset, a default thread-based PlatformTimerRegistryImpl is used. This // is a seam for tests (e.g. Fantom) to inject a deterministic, mockable timer // registry. - std::function()> platformTimerRegistryFactory{nullptr}; + std::function()> + platformTimerRegistryFactory{nullptr}; }; } // namespace facebook::react diff --git a/packages/react-native/ReactCxxPlatform/react/threading/MessageQueueThreadImpl.h b/packages/react-native/ReactCxxPlatform/react/threading/MessageQueueThreadImpl.h index 68b9dff74b7a..2e95efdbd09e 100644 --- a/packages/react-native/ReactCxxPlatform/react/threading/MessageQueueThreadImpl.h +++ b/packages/react-native/ReactCxxPlatform/react/threading/MessageQueueThreadImpl.h @@ -13,7 +13,8 @@ namespace facebook::react { -using MessageQueueThreadFactory = std::function()>; +using MessageQueueThreadFactory = + std::function()>; constexpr char MessageQueueThreadFactoryKey[] = "MessageQueueThreadFactoryKey"; @@ -24,19 +25,20 @@ 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 2dd86991b9e5..010c141646b2 100644 --- a/packages/react-native/ReactCxxPlatform/react/threading/TaskDispatchThread.h +++ b/packages/react-native/ReactCxxPlatform/react/threading/TaskDispatchThread.h @@ -26,7 +26,9 @@ class TaskDispatchThread { using TaskFn = std::function; using TimePoint = std::chrono::time_point; - TaskDispatchThread(std::string_view threadName = "", int priorityOffset = 0) noexcept; + TaskDispatchThread( + std::string_view threadName = "", + int priorityOffset = 0) noexcept; ~TaskDispatchThread() noexcept; @@ -37,10 +39,13 @@ 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; @@ -50,10 +55,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 69cafe56323e..b50ac8170fda 100644 --- a/packages/react-native/ReactCxxPlatform/react/utils/PlatformRunLoopObserver.h +++ b/packages/react-native/ReactCxxPlatform/react/utils/PlatformRunLoopObserver.h @@ -17,24 +17,22 @@ 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 f7b0f241e998..1f565b1ccb47 100644 --- a/packages/react-native/ReactCxxPlatform/react/utils/RunLoopObserverManager.h +++ b/packages/react-native/ReactCxxPlatform/react/utils/RunLoopObserverManager.h @@ -15,11 +15,12 @@ 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.h b/packages/rn-tester/NativeCxxModuleExample/NativeCxxModuleExample.h index 8c70ad71be50..45df1daf2726 100644 --- a/packages/rn-tester/NativeCxxModuleExample/NativeCxxModuleExample.h +++ b/packages/rn-tester/NativeCxxModuleExample/NativeCxxModuleExample.h @@ -23,28 +23,35 @@ namespace facebook::react { #pragma mark - Structs -using ConstantsStruct = NativeCxxModuleExampleConstantsStruct; +using ConstantsStruct = + NativeCxxModuleExampleConstantsStruct; template <> -struct Bridging : NativeCxxModuleExampleConstantsStructBridging {}; +struct Bridging + : NativeCxxModuleExampleConstantsStructBridging {}; -using ObjectStruct = NativeCxxModuleExampleObjectStruct>; +using ObjectStruct = NativeCxxModuleExampleObjectStruct< + int32_t, + std::string, + std::optional>; 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; @@ -55,8 +62,7 @@ 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)); } }; @@ -67,8 +73,7 @@ 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_; } @@ -91,104 +96,131 @@ 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::optional>; +using MenuItem = NativeCxxModuleExampleMenuItem< + std::string, + AsyncCallback, + std::optional>; template <> struct Bridging : NativeCxxModuleExampleMenuItemBridging {}; #pragma mark - RCTDeviceEventEmitter events -using CustomDeviceEvent = NativeCxxModuleExampleCustomDeviceEvent>; +using CustomDeviceEvent = NativeCxxModuleExampleCustomDeviceEvent< + std::string, + int32_t, + std::optional>; 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); - jsi::ArrayBuffer getArrayBuffer(jsi::Runtime &rt, jsi::ArrayBuffer arg); + jsi::ArrayBuffer getArrayBuffer(jsi::Runtime& rt, jsi::ArrayBuffer arg); - jsi::ArrayBuffer createNativeBuffer(jsi::Runtime &rt, int32_t arg); + jsi::ArrayBuffer createNativeBuffer(jsi::Runtime& rt, int32_t arg); - AsyncPromise processAsyncBuffer(jsi::Runtime &rt, jsi::ArrayBuffer arg); + AsyncPromise processAsyncBuffer( + jsi::Runtime& rt, + jsi::ArrayBuffer arg); - AsyncPromise getAsyncBuffer(jsi::Runtime &rt, int32_t arg); + AsyncPromise getAsyncBuffer(jsi::Runtime& rt, int32_t 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/RCTTest/RCTTestPlugins.h b/packages/rn-tester/RCTTest/RCTTestPlugins.h index 755019513d4a..e202d02f8fe7 100644 --- a/packages/rn-tester/RCTTest/RCTTestPlugins.h +++ b/packages/rn-tester/RCTTest/RCTTestPlugins.h @@ -26,7 +26,7 @@ extern "C" { #endif // RCTTurboModuleManagerDelegate should call this to resolve module classes. -Class RCTTestClassProvider(const char *name); +Class RCTTestClassProvider(const char* name); // Lookup functions Class RCTTestModuleCls(void) __attribute__((used)); diff --git a/private/react-native-fantom/tester/src/AppSettings.h b/private/react-native-fantom/tester/src/AppSettings.h index 0b5c7e2fb434..c6cf0ee15bf8 100644 --- a/private/react-native-fantom/tester/src/AppSettings.h +++ b/private/react-native-fantom/tester/src/AppSettings.h @@ -30,7 +30,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 695e8041efb3..5dd09a2fbd31 100644 --- a/private/react-native-fantom/tester/src/FantomImageLoader.h +++ b/private/react-native-fantom/tester/src/FantomImageLoader.h @@ -22,14 +22,16 @@ 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/FantomTimerRegistry.h b/private/react-native-fantom/tester/src/FantomTimerRegistry.h index 849708c98ee9..0d1dc325a8c9 100644 --- a/private/react-native-fantom/tester/src/FantomTimerRegistry.h +++ b/private/react-native-fantom/tester/src/FantomTimerRegistry.h @@ -41,10 +41,10 @@ namespace facebook::react { class FantomTimerRegistry : public PlatformTimerRegistry { public: FantomTimerRegistry() noexcept = default; - FantomTimerRegistry(const FantomTimerRegistry &) = delete; - FantomTimerRegistry(FantomTimerRegistry &&) = delete; - FantomTimerRegistry &operator=(const FantomTimerRegistry &) = delete; - FantomTimerRegistry &operator=(FantomTimerRegistry &&) = delete; + FantomTimerRegistry(const FantomTimerRegistry&) = delete; + FantomTimerRegistry(FantomTimerRegistry&&) = delete; + FantomTimerRegistry& operator=(const FantomTimerRegistry&) = delete; + FantomTimerRegistry& operator=(FantomTimerRegistry&&) = delete; ~FantomTimerRegistry() noexcept override = default; // PlatformTimerRegistry diff --git a/private/react-native-fantom/tester/src/NativeFantom.h b/private/react-native-fantom/tester/src/NativeFantom.h index 2522e7c2bf48..f864a94d91bc 100644 --- a/private/react-native-fantom/tester/src/NativeFantom.h +++ b/private/react-native-fantom/tester/src/NativeFantom.h @@ -21,20 +21,21 @@ namespace facebook::react { class TesterAppDelegate; -using NativeFantomGetRenderedOutputRenderFormatOptions = NativeFantomRenderFormatOptions< - // includeRoot - bool, - // includeLayoutMetrics - bool>; +using NativeFantomGetRenderedOutputRenderFormatOptions = + NativeFantomRenderFormatOptions< + // includeRoot + bool, + // includeLayoutMetrics + bool>; template <> struct Bridging - : NativeFantomRenderFormatOptionsBridging {}; + : NativeFantomRenderFormatOptionsBridging< + NativeFantomGetRenderedOutputRenderFormatOptions> {}; 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; @@ -53,16 +54,17 @@ 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 @@ -71,83 +73,107 @@ using NativeFantomSetImageResponseImageResponse = NativeFantomImageResponse< std::optional>; // errorMessage template <> struct Bridging - : NativeFantomImageResponseBridging {}; + : NativeFantomImageResponseBridging< + NativeFantomSetImageResponseImageResponse> {}; 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 setTimerMockEnabled(jsi::Runtime &runtime, bool enabled); - void advanceTimers(jsi::Runtime &runtime, double deltaMs); - void runAllTimers(jsi::Runtime &runtime); - double getPendingTimerCount(jsi::Runtime &runtime); + void setTimerMockEnabled(jsi::Runtime& runtime, bool enabled); + void advanceTimers(jsi::Runtime& runtime, double deltaMs); + void runAllTimers(jsi::Runtime& runtime); + double getPendingTimerCount(jsi::Runtime& runtime); - 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/TesterAnimationChoreographer.h b/private/react-native-fantom/tester/src/TesterAnimationChoreographer.h index c45a84867bcd..b4b24866fe8e 100644 --- a/private/react-native-fantom/tester/src/TesterAnimationChoreographer.h +++ b/private/react-native-fantom/tester/src/TesterAnimationChoreographer.h @@ -21,16 +21,14 @@ class TesterAnimationChoreographer : public AnimationChoreographer { void pause() override; void runUITick(AnimationTimestamp timestamp); - AnimationTimestamp now() const override - { + AnimationTimestamp now() const override { if (clockProvider_) { return clockProvider_(); } return AnimationChoreographer::now(); } - void setClockProvider(std::function clockProvider) - { + void setClockProvider(std::function clockProvider) { clockProvider_ = std::move(clockProvider); } diff --git a/private/react-native-fantom/tester/src/TesterAppDelegate.h b/private/react-native-fantom/tester/src/TesterAppDelegate.h index 3f5fc28babff..8c09ff3a9fb1 100644 --- a/private/react-native-fantom/tester/src/TesterAppDelegate.h +++ b/private/react-native-fantom/tester/src/TesterAppDelegate.h @@ -30,25 +30,29 @@ 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; // Loads the bundle, registering the Metro runtime and warm-up modules. // Does not run any tests. - void loadScript(const std::string &bundlePath, const std::string &sourcePath); + void loadScript(const std::string& bundlePath, const std::string& sourcePath); // Loads the bundle and then invokes `$$RunTests$$` to run the tests. - void loadScriptAndRunTests(const std::string &bundlePath, const std::string &sourcePath); + void loadScriptAndRunTests( + const std::string& bundlePath, + const std::string& sourcePath); // Evaluates a single JS snippet in the already-loaded runtime, in global // scope, and flushes the message queue. Used by interactive (REPL) mode. - void evaluateInteractiveChunk(const std::string &source, const std::string &sourceURL); + void evaluateInteractiveChunk( + const std::string& source, + const std::string& sourceURL); // Reads length-prefixed JS snippets from stdin and evaluates each one until // stdin is closed. Each frame is `\n` followed by exactly @@ -59,7 +63,7 @@ class TesterAppDelegate { void openDebugger() const; void startSurface( - jsi::Runtime &runtime, + jsi::Runtime& runtime, float widthDp, float heightDp, SurfaceId surfaceId, @@ -67,7 +71,11 @@ 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); @@ -105,11 +113,11 @@ class TesterAppDelegate { // Non-owning pointer to the JS runtime, captured after the script is loaded. // Used to evaluate snippets directly (outside the run loop) in REPL mode. - jsi::Runtime *runtime_{nullptr}; + jsi::Runtime* runtime_{nullptr}; // Owned by the TimerManager (inside the ReactInstance); this is a non-owning // pointer used to drive the deterministic timer mock from JS. - FantomTimerRegistry *timerRegistry_{nullptr}; + FantomTimerRegistry* timerRegistry_{nullptr}; }; } // namespace facebook::react diff --git a/private/react-native-fantom/tester/src/TesterMountingManager.h b/private/react-native-fantom/tester/src/TesterMountingManager.h index cdfdf96d584d..2d8f908e5d9c 100644 --- a/private/react-native-fantom/tester/src/TesterMountingManager.h +++ b/private/react-native-fantom/tester/src/TesterMountingManager.h @@ -21,16 +21,23 @@ 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; @@ -41,20 +48,17 @@ 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 7d627a3cae47..68939024da4a 100644 --- a/private/react-native-fantom/tester/src/render/RenderOutput.h +++ b/private/react-native-fantom/tester/src/render/RenderOutput.h @@ -15,21 +15,26 @@ 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); // If true, the next call to render() will re-render the entire tree. std::unordered_set treesMutated_{}; diff --git a/private/react-native-fantom/tester/src/stubs/StubClock.h b/private/react-native-fantom/tester/src/stubs/StubClock.h index b766700e70ae..a3c2ff43e338 100644 --- a/private/react-native-fantom/tester/src/stubs/StubClock.h +++ b/private/react-native-fantom/tester/src/stubs/StubClock.h @@ -13,13 +13,11 @@ 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; } @@ -27,6 +25,7 @@ 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 f7b4a5861e73..7ea4a1647ee9 100644 --- a/private/react-native-fantom/tester/src/stubs/StubComponentRegistryFactory.h +++ b/private/react-native-fantom/tester/src/stubs/StubComponentRegistryFactory.h @@ -19,22 +19,30 @@ 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()); + 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>()); 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 ef6dbfe1c610..2750bde819cb 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,20 +27,19 @@ 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 83da413309d6..175eaa309f57 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 f89ef0a18717..6e94d24a0c8f 100644 --- a/private/react-native-fantom/tester/src/stubs/StubWebSocketClient.h +++ b/private/react-native-fantom/tester/src/stubs/StubWebSocketClient.h @@ -15,20 +15,23 @@ 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 {} }; diff --git a/scripts/cxx-api/tests/snapshots/should_deduplicate_base_classes/test.h b/scripts/cxx-api/tests/snapshots/should_deduplicate_base_classes/test.h index ce614aa70fea..2c8d0a7ea4ca 100644 --- a/scripts/cxx-api/tests/snapshots/should_deduplicate_base_classes/test.h +++ b/scripts/cxx-api/tests/snapshots/should_deduplicate_base_classes/test.h @@ -22,7 +22,7 @@ template struct is_special : public false_type {}; template -struct is_special : public true_type {}; +struct is_special : public true_type {}; // Duplicate base class via Doxygen merging template-substituted bases. struct BaseA {}; diff --git a/scripts/cxx-api/tests/snapshots/should_handle_class_public_method_arguments/test.h b/scripts/cxx-api/tests/snapshots/should_handle_class_public_method_arguments/test.h index fd2831d0dcf0..d44632a44f19 100644 --- a/scripts/cxx-api/tests/snapshots/should_handle_class_public_method_arguments/test.h +++ b/scripts/cxx-api/tests/snapshots/should_handle_class_public_method_arguments/test.h @@ -14,14 +14,16 @@ class Clss { void fn0(int32_t arg1); void fn1(int32_t arg1, int32_t arg2); void fn2(std::function arg1); - void fn3(std::function arg1, std::function arg2); + void fn3( + std::function arg1, + std::function arg2); void fn4(std::map m); void fn5(std::unordered_map> m); void fn6(std::tuple t); void fn7(std::vector>> v); void fn8(std::map> m); void fn9(int (*callback)(int, int)); - void fn10(void (*handler)(const char *, size_t)); + void fn10(void (*handler)(const char*, size_t)); void fn11(int (*(*fp)(int))(double)); void fn12(int x = 5, std::string s = "default"); void fn13(std::function f = nullptr); diff --git a/scripts/cxx-api/tests/snapshots/should_handle_concept/test.h b/scripts/cxx-api/tests/snapshots/should_handle_concept/test.h index e63f8a450baf..6f1ed6d333f8 100644 --- a/scripts/cxx-api/tests/snapshots/should_handle_concept/test.h +++ b/scripts/cxx-api/tests/snapshots/should_handle_concept/test.h @@ -15,8 +15,10 @@ namespace test { class CSSSyntaxParser; template -concept CSSParserSink = requires(CSSSyntaxParser &parser) { - { T::consume(parser) } -> std::convertible_to; -}; +concept CSSParserSink = requires(CSSSyntaxParser& parser) { + { + T::consume(parser) + } -> std::convertible_to; + }; } // namespace test diff --git a/scripts/cxx-api/tests/snapshots/should_handle_concept_indent/test.h b/scripts/cxx-api/tests/snapshots/should_handle_concept_indent/test.h index 738b9408491c..b28cf2b3e1a0 100644 --- a/scripts/cxx-api/tests/snapshots/should_handle_concept_indent/test.h +++ b/scripts/cxx-api/tests/snapshots/should_handle_concept_indent/test.h @@ -22,8 +22,8 @@ concept CSSParserSink = requires(CSSSyntaxParser &parser) { // clang-format on template -concept CSSUniqueComponentValueVisitors = - CSSSyntaxVisitorReturn && (CSSComponentValueVisitor && ...) && +concept CSSUniqueComponentValueVisitors = CSSSyntaxVisitorReturn && + (CSSComponentValueVisitor && ...) && ((CSSFunctionVisitor ? 1 : 0) + ... + 0) <= 1 && ((CSSPreservedTokenVisitor ? 1 : 0) + ... + 0) <= 1 && ((CSSSimpleBlockVisitor ? 1 : 0) + ... + 0) <= 1; diff --git a/scripts/cxx-api/tests/snapshots/should_handle_constexpr_constructor/test.h b/scripts/cxx-api/tests/snapshots/should_handle_constexpr_constructor/test.h index 4694db51244a..11c04bd513b3 100644 --- a/scripts/cxx-api/tests/snapshots/should_handle_constexpr_constructor/test.h +++ b/scripts/cxx-api/tests/snapshots/should_handle_constexpr_constructor/test.h @@ -12,8 +12,8 @@ namespace test { class Clss { public: constexpr Clss() = default; - constexpr Clss(const Clss &) = default; - constexpr Clss(Clss &&) = default; + constexpr Clss(const Clss&) = default; + constexpr Clss(Clss&&) = default; explicit constexpr Clss(int value); }; diff --git a/scripts/cxx-api/tests/snapshots/should_handle_constructor_inheritance/test.h b/scripts/cxx-api/tests/snapshots/should_handle_constructor_inheritance/test.h index 0fe9fbb67495..312f1f87a385 100644 --- a/scripts/cxx-api/tests/snapshots/should_handle_constructor_inheritance/test.h +++ b/scripts/cxx-api/tests/snapshots/should_handle_constructor_inheritance/test.h @@ -13,7 +13,7 @@ class Base { public: Base() = default; Base(int test); - Base(const Base &other); + Base(const Base& other); }; class Derived : public Base { diff --git a/scripts/cxx-api/tests/snapshots/should_handle_function_pointer_variable/test.h b/scripts/cxx-api/tests/snapshots/should_handle_function_pointer_variable/test.h index 59aabf212ffc..cff2d0e2e7ea 100644 --- a/scripts/cxx-api/tests/snapshots/should_handle_function_pointer_variable/test.h +++ b/scripts/cxx-api/tests/snapshots/should_handle_function_pointer_variable/test.h @@ -12,7 +12,7 @@ namespace test { struct FunctionPointers { void (*simple)(int); int (*withReturn)(double, float); - void *(*returnsPointer)(const char *); + void* (*returnsPointer)(const char*); }; } // namespace test diff --git a/scripts/cxx-api/tests/snapshots/should_handle_multiple_inherited_constructors/test.h b/scripts/cxx-api/tests/snapshots/should_handle_multiple_inherited_constructors/test.h index 2d19852e49cc..26d7fcb9da60 100644 --- a/scripts/cxx-api/tests/snapshots/should_handle_multiple_inherited_constructors/test.h +++ b/scripts/cxx-api/tests/snapshots/should_handle_multiple_inherited_constructors/test.h @@ -18,17 +18,24 @@ class ShadowNode { class ConcreteViewShadowNode : public ShadowNode { public: - ConcreteViewShadowNode(const ShadowNode &source, const Fragment &fragment); - ConcreteViewShadowNode(const Fragment &fragment, const Shared &family, Traits traits); + ConcreteViewShadowNode(const ShadowNode& source, const Fragment& fragment); + ConcreteViewShadowNode( + const Fragment& fragment, + const Shared& family, + Traits traits); }; class BaseTextShadowNode : public ShadowNode { public: - BaseTextShadowNode(const ShadowNode &source, const Fragment &fragment); - BaseTextShadowNode(const Fragment &fragment, const Shared &family, Traits traits); + BaseTextShadowNode(const ShadowNode& source, const Fragment& fragment); + BaseTextShadowNode( + const Fragment& fragment, + const Shared& family, + Traits traits); }; -class ParagraphShadowNode : public ConcreteViewShadowNode, public BaseTextShadowNode { +class ParagraphShadowNode : public ConcreteViewShadowNode, + public BaseTextShadowNode { public: using BaseTextShadowNode::BaseTextShadowNode; using ConcreteViewShadowNode::ConcreteViewShadowNode; diff --git a/scripts/cxx-api/tests/snapshots/should_handle_mutable_const_pointer_ordering/test.h b/scripts/cxx-api/tests/snapshots/should_handle_mutable_const_pointer_ordering/test.h index 06b03e665c32..505dd77431a5 100644 --- a/scripts/cxx-api/tests/snapshots/should_handle_mutable_const_pointer_ordering/test.h +++ b/scripts/cxx-api/tests/snapshots/should_handle_mutable_const_pointer_ordering/test.h @@ -11,9 +11,9 @@ namespace test { class Cache { public: - mutable int *mutablePtr; - const int *constPtr; - mutable const int *mutableConstPtr; + mutable int* mutablePtr; + const int* constPtr; + mutable const int* mutableConstPtr; }; } // namespace test diff --git a/scripts/cxx-api/tests/snapshots/should_handle_pointer_to_member_function_param/test.h b/scripts/cxx-api/tests/snapshots/should_handle_pointer_to_member_function_param/test.h index 8aaea82b5a17..531e241e1134 100644 --- a/scripts/cxx-api/tests/snapshots/should_handle_pointer_to_member_function_param/test.h +++ b/scripts/cxx-api/tests/snapshots/should_handle_pointer_to_member_function_param/test.h @@ -16,6 +16,9 @@ struct dynamic {}; namespace test { 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); } // namespace test diff --git a/scripts/cxx-api/tests/snapshots/should_handle_pointer_to_member_function_param_with_ref_qualifier/test.h b/scripts/cxx-api/tests/snapshots/should_handle_pointer_to_member_function_param_with_ref_qualifier/test.h index fcdb31e047a7..43f1e0a1197b 100644 --- a/scripts/cxx-api/tests/snapshots/should_handle_pointer_to_member_function_param_with_ref_qualifier/test.h +++ b/scripts/cxx-api/tests/snapshots/should_handle_pointer_to_member_function_param_with_ref_qualifier/test.h @@ -16,8 +16,14 @@ struct dynamic {}; namespace test { 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); } // namespace test diff --git a/scripts/cxx-api/tests/snapshots/should_handle_pure_virtual_trailing_return/test.h b/scripts/cxx-api/tests/snapshots/should_handle_pure_virtual_trailing_return/test.h index b2e9e2382da8..6bb69913ec51 100644 --- a/scripts/cxx-api/tests/snapshots/should_handle_pure_virtual_trailing_return/test.h +++ b/scripts/cxx-api/tests/snapshots/should_handle_pure_virtual_trailing_return/test.h @@ -16,7 +16,7 @@ struct Method {}; class Base { public: virtual auto getMethods() -> std::vector = 0; - virtual auto getName() -> const char * = 0; + virtual auto getName() -> const char* = 0; }; } // namespace test diff --git a/scripts/cxx-api/tests/snapshots/should_handle_template_specialization_self_reference/test.h b/scripts/cxx-api/tests/snapshots/should_handle_template_specialization_self_reference/test.h index 577107df3498..5b975251ec4c 100644 --- a/scripts/cxx-api/tests/snapshots/should_handle_template_specialization_self_reference/test.h +++ b/scripts/cxx-api/tests/snapshots/should_handle_template_specialization_self_reference/test.h @@ -15,12 +15,11 @@ class Callback; template class Callback { public: - Callback(const Callback &) = delete; - Callback &operator=(const Callback &) = delete; + Callback(const Callback&) = delete; + Callback& operator=(const Callback&) = delete; - Callback(Callback &&other) noexcept {} - Callback &operator=(Callback &&other) noexcept - { + Callback(Callback&& other) noexcept {} + Callback& operator=(Callback&& other) noexcept { return *this; } diff --git a/scripts/cxx-api/tests/snapshots/should_handle_union_empty/test.h b/scripts/cxx-api/tests/snapshots/should_handle_union_empty/test.h index 79558b91d4b2..fc449af6bd3d 100644 --- a/scripts/cxx-api/tests/snapshots/should_handle_union_empty/test.h +++ b/scripts/cxx-api/tests/snapshots/should_handle_union_empty/test.h @@ -9,7 +9,6 @@ namespace test { -union EmptyUnion { -}; +union EmptyUnion {}; } // namespace test diff --git a/scripts/cxx-api/tests/snapshots/should_handle_unnamed_template_param_with_default_value/test.h b/scripts/cxx-api/tests/snapshots/should_handle_unnamed_template_param_with_default_value/test.h index c11aa19d3911..3ebe83378bd2 100644 --- a/scripts/cxx-api/tests/snapshots/should_handle_unnamed_template_param_with_default_value/test.h +++ b/scripts/cxx-api/tests/snapshots/should_handle_unnamed_template_param_with_default_value/test.h @@ -20,11 +20,11 @@ struct Value { template < typename T, typename = std::enable_if_t< - std::is_base_of::value || std::is_base_of::value || std::is_base_of::value || + std::is_base_of::value || + std::is_base_of::value || + std::is_base_of::value || std::is_base_of::value>> - /* implicit */ Value(T &&other) - { - } + /* implicit */ Value(T&& other) {} }; } // namespace test diff --git a/scripts/cxx-api/tests/snapshots/should_inline_private_type_aliases/test.h b/scripts/cxx-api/tests/snapshots/should_inline_private_type_aliases/test.h index 7fe2583c9b79..6076ce7fac6a 100644 --- a/scripts/cxx-api/tests/snapshots/should_inline_private_type_aliases/test.h +++ b/scripts/cxx-api/tests/snapshots/should_inline_private_type_aliases/test.h @@ -16,7 +16,7 @@ class Clss { typedef void (*MyFunction)(MyType); public: - void test1(std::function &&function); + void test1(std::function&& function); void test2(MyType val) const; void test3(MyFunction val) const; }; diff --git a/scripts/cxx-api/tests/snapshots/should_normalize_template_specialization_angle_brackets/test.h b/scripts/cxx-api/tests/snapshots/should_normalize_template_specialization_angle_brackets/test.h index f7eba86e456a..08c67e43bd15 100644 --- a/scripts/cxx-api/tests/snapshots/should_normalize_template_specialization_angle_brackets/test.h +++ b/scripts/cxx-api/tests/snapshots/should_normalize_template_specialization_angle_brackets/test.h @@ -8,21 +8,22 @@ 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, CSSValueParser &parser) - -> std::optional - { + static constexpr auto consumeFunctionBlock( + const CSSFunctionBlock& func, + CSSValueParser& parser) -> std::optional { if (!iequals(func.name, "matrix")) { return {}; } CSSMatrix matrix{}; for (int i = 0; i < 6; i++) { - auto value = parser.parseNextValue(i == 0 ? CSSDelimiter::None : CSSDelimiter::Comma); + auto value = parser.parseNextValue( + i == 0 ? CSSDelimiter::None : CSSDelimiter::Comma); if (std::holds_alternative(value)) { return {}; } @@ -37,8 +38,10 @@ struct CSSDataTypeParser { template class ConcreteComponentDescriptor {}; -class AndroidSwitchComponentDescriptor : public ConcreteComponentDescriptor { +class AndroidSwitchComponentDescriptor + : public ConcreteComponentDescriptor { public: - AndroidSwitchComponentDescriptor(const ComponentDescriptorParameters ¶meters); - void adopt(ShadowNode &shadowNode) const; + AndroidSwitchComponentDescriptor( + const ComponentDescriptorParameters& parameters); + void adopt(ShadowNode& shadowNode) const; }; diff --git a/scripts/cxx-api/tests/snapshots/should_not_qualify_function_pointer_param_args_to_outer_class/test.h b/scripts/cxx-api/tests/snapshots/should_not_qualify_function_pointer_param_args_to_outer_class/test.h index 5ffb6c927c00..0b0c7299f77f 100644 --- a/scripts/cxx-api/tests/snapshots/should_not_qualify_function_pointer_param_args_to_outer_class/test.h +++ b/scripts/cxx-api/tests/snapshots/should_not_qualify_function_pointer_param_args_to_outer_class/test.h @@ -12,7 +12,9 @@ namespace test { class Runtime { public: int data; - virtual void getStringData(void *ctx, void (*cb)(void *ctx, bool ascii, const void *data, size_t num)); + virtual void getStringData( + void* ctx, + void (*cb)(void* ctx, bool ascii, const void* data, size_t num)); }; } // namespace test diff --git a/scripts/cxx-api/tests/snapshots/should_not_requalify_friend_type/test.h b/scripts/cxx-api/tests/snapshots/should_not_requalify_friend_type/test.h index 92b43f109907..4c7bec4583cb 100644 --- a/scripts/cxx-api/tests/snapshots/should_not_requalify_friend_type/test.h +++ b/scripts/cxx-api/tests/snapshots/should_not_requalify_friend_type/test.h @@ -14,7 +14,7 @@ struct ShadowNode {}; struct ComponentDescriptor { friend ShadowNode; - virtual void adopt(ShadowNode &shadowNode) const = 0; + virtual void adopt(ShadowNode& shadowNode) const = 0; }; } // namespace test diff --git a/scripts/cxx-api/tests/snapshots/should_not_requalify_globally_qualified_type/test.h b/scripts/cxx-api/tests/snapshots/should_not_requalify_globally_qualified_type/test.h index eacc32296189..268aea082470 100644 --- a/scripts/cxx-api/tests/snapshots/should_not_requalify_globally_qualified_type/test.h +++ b/scripts/cxx-api/tests/snapshots/should_not_requalify_globally_qualified_type/test.h @@ -20,8 +20,8 @@ struct MyType { namespace other { struct Consumer { - void process(const ::test::inner::MyType ¶m); - void processPtr(::test::inner::MyType *param); + void process(const ::test::inner::MyType& param); + void processPtr(::test::inner::MyType* param); ::test::inner::MyType create(); }; diff --git a/scripts/cxx-api/tests/snapshots/should_not_scope_friend_class_under_compound/test.h b/scripts/cxx-api/tests/snapshots/should_not_scope_friend_class_under_compound/test.h index 54b18e301072..fcfd4c30bebd 100644 --- a/scripts/cxx-api/tests/snapshots/should_not_scope_friend_class_under_compound/test.h +++ b/scripts/cxx-api/tests/snapshots/should_not_scope_friend_class_under_compound/test.h @@ -13,7 +13,7 @@ class ProviderRegistry; class Registry { public: - Registry(const ProviderRegistry &provider); + Registry(const ProviderRegistry& provider); bool hasItem(int handle) const; private: diff --git a/scripts/cxx-api/tests/snapshots/should_qualify_function_args/test.h b/scripts/cxx-api/tests/snapshots/should_qualify_function_args/test.h index 96b6acc6abb8..c9f5a72d7dec 100644 --- a/scripts/cxx-api/tests/snapshots/should_qualify_function_args/test.h +++ b/scripts/cxx-api/tests/snapshots/should_qualify_function_args/test.h @@ -13,7 +13,7 @@ struct Param {}; struct Container { void doSomething(Param p); - void doConst(const Param &p); + void doConst(const Param& p); void doMultiple(Param a, Param b, int x); }; diff --git a/scripts/cxx-api/tests/snapshots/should_qualify_function_template_specialization/test.h b/scripts/cxx-api/tests/snapshots/should_qualify_function_template_specialization/test.h index d2c2a63bc3da..8ca85ef277d6 100644 --- a/scripts/cxx-api/tests/snapshots/should_qualify_function_template_specialization/test.h +++ b/scripts/cxx-api/tests/snapshots/should_qualify_function_template_specialization/test.h @@ -18,9 +18,9 @@ template <> MyType convert(MyType value); template -void process(T *ptr); +void process(T* ptr); template <> -void process(MyType *ptr); +void process(MyType* ptr); } // namespace test diff --git a/scripts/cxx-api/tests/snapshots/should_qualify_nested_template_type_with_underscore/test.h b/scripts/cxx-api/tests/snapshots/should_qualify_nested_template_type_with_underscore/test.h index c1aff3db23f8..0dcb5e2571e8 100644 --- a/scripts/cxx-api/tests/snapshots/should_qualify_nested_template_type_with_underscore/test.h +++ b/scripts/cxx-api/tests/snapshots/should_qualify_nested_template_type_with_underscore/test.h @@ -15,13 +15,14 @@ namespace detail { 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 template -typename detail::is_dynamic::type &jsArgAsDynamic(T &&args, size_t n); +typename detail::is_dynamic::type& jsArgAsDynamic(T&& args, size_t n); } // namespace react diff --git a/scripts/cxx-api/tests/snapshots/should_qualify_nested_template_with_decorators/test.h b/scripts/cxx-api/tests/snapshots/should_qualify_nested_template_with_decorators/test.h index 5207aa305b18..a3c6151d5e22 100644 --- a/scripts/cxx-api/tests/snapshots/should_qualify_nested_template_with_decorators/test.h +++ b/scripts/cxx-api/tests/snapshots/should_qualify_nested_template_with_decorators/test.h @@ -22,10 +22,10 @@ class Container { }; template <> -class Container *> { +class Container*> { public: - void set(const Outer *value); - const Outer *get(); + void set(const Outer* value); + const Outer* get(); }; } // namespace test diff --git a/scripts/cxx-api/tests/snapshots/should_qualify_ptr_const_args/test.h b/scripts/cxx-api/tests/snapshots/should_qualify_ptr_const_args/test.h index 47211e25d134..0fb20e4d9996 100644 --- a/scripts/cxx-api/tests/snapshots/should_qualify_ptr_const_args/test.h +++ b/scripts/cxx-api/tests/snapshots/should_qualify_ptr_const_args/test.h @@ -11,6 +11,6 @@ namespace test { struct Node; -void doSomething(const Node *const node, int x); +void doSomething(const Node* const node, int x); } // namespace test diff --git a/scripts/cxx-api/tests/snapshots/should_qualify_template_specialization_pointer_args/test.h b/scripts/cxx-api/tests/snapshots/should_qualify_template_specialization_pointer_args/test.h index bfef20f5123f..2c54caa933a2 100644 --- a/scripts/cxx-api/tests/snapshots/should_qualify_template_specialization_pointer_args/test.h +++ b/scripts/cxx-api/tests/snapshots/should_qualify_template_specialization_pointer_args/test.h @@ -19,10 +19,10 @@ class Wrapper { }; template <> -class Wrapper { +class Wrapper { public: - void set(MyType *value); - MyType *get(); + void set(MyType* value); + MyType* get(); }; } // namespace test diff --git a/scripts/cxx-api/tests/snapshots/should_qualify_type_alias_in_template_specialization/test.h b/scripts/cxx-api/tests/snapshots/should_qualify_type_alias_in_template_specialization/test.h index 6438e7c3960f..9e089677c28d 100644 --- a/scripts/cxx-api/tests/snapshots/should_qualify_type_alias_in_template_specialization/test.h +++ b/scripts/cxx-api/tests/snapshots/should_qualify_type_alias_in_template_specialization/test.h @@ -18,9 +18,9 @@ template <> MyType convert(MyType value); template -void process(T *ptr); +void process(T* ptr); template <> -void process(MyType *ptr); +void process(MyType* ptr); } // namespace test diff --git a/scripts/cxx-api/tests/snapshots/should_qualify_variable_inline_function_type/test.h b/scripts/cxx-api/tests/snapshots/should_qualify_variable_inline_function_type/test.h index 1c726e151ae4..ac81c1822354 100644 --- a/scripts/cxx-api/tests/snapshots/should_qualify_variable_inline_function_type/test.h +++ b/scripts/cxx-api/tests/snapshots/should_qualify_variable_inline_function_type/test.h @@ -17,9 +17,9 @@ struct Result {}; struct Container { std::function simpleCallback; std::function processor; - std::function multiRef; + std::function multiRef; void (*fnPtr)(Param, int); - Result (*fnPtrReturn)(const Param &); + Result (*fnPtrReturn)(const Param&); }; } // namespace test diff --git a/scripts/cxx-api/tests/snapshots/should_qualify_variable_template_specialization/test.h b/scripts/cxx-api/tests/snapshots/should_qualify_variable_template_specialization/test.h index 54e6183e060d..68f1fb587063 100644 --- a/scripts/cxx-api/tests/snapshots/should_qualify_variable_template_specialization/test.h +++ b/scripts/cxx-api/tests/snapshots/should_qualify_variable_template_specialization/test.h @@ -18,9 +18,9 @@ template <> inline constexpr MyType default_value = MyType{}; template -inline T *null_ptr = nullptr; +inline T* null_ptr = nullptr; template <> -inline MyType *null_ptr = nullptr; +inline MyType* null_ptr = nullptr; } // namespace test