From 8f512439572c954f1349d1184a39d0518b4e15e4 Mon Sep 17 00:00:00 2001 From: Valentin Shergin Date: Tue, 9 Oct 2018 16:25:13 -0700 Subject: [PATCH] Fabric: Enabling clang-format for the rest of Fabric Summary: This is the second and the final part of adopting clang-format. Reviewed By: mdvacca Differential Revision: D10229624 fbshipit-source-id: d97670b716800ea2488b84bd0aacaf54d8bd2e31 --- ReactCommon/.clang-format | 2 +- .../fabric/components/view/primitives.h | 1 - .../fabric/components/view/propsConversions.h | 275 ++++++++++++------ .../componentdescriptor/ComponentDescriptor.h | 28 +- .../ConcreteComponentDescriptor.h | 75 +++-- ReactCommon/fabric/core/conversions.h | 18 +- .../fabric/core/layout/LayoutConstraints.h | 4 +- .../fabric/core/layout/LayoutContext.h | 2 +- .../fabric/core/layout/LayoutMetrics.h | 40 ++- .../fabric/core/layout/LayoutPrimitives.h | 19 +- .../core/layout/LayoutableShadowNode.cpp | 14 +- .../fabric/core/layout/LayoutableShadowNode.h | 32 +- .../fabric/core/primitives/ReactPrimitives.h | 3 +- .../fabric/core/primitives/Sealable.cpp | 6 +- ReactCommon/fabric/core/primitives/Sealable.h | 37 +-- ReactCommon/fabric/core/propsConversions.h | 48 +-- .../core/shadownode/ConcreteShadowNode.h | 35 ++- .../fabric/core/shadownode/LocalData.h | 7 +- ReactCommon/fabric/core/shadownode/Props.cpp | 13 +- ReactCommon/fabric/core/shadownode/Props.h | 9 +- .../fabric/core/shadownode/ShadowNode.cpp | 79 ++--- .../fabric/core/shadownode/ShadowNode.h | 39 ++- .../core/shadownode/ShadowNodeFragment.h | 2 +- .../core/tests/ComponentDescriptorTest.cpp | 45 ++- .../fabric/core/tests/PrimitivesTest.cpp | 3 +- .../fabric/core/tests/ShadowNodeTest.cpp | 115 +++++--- ReactCommon/fabric/core/tests/TestComponent.h | 24 +- .../fabric/debug/DebugStringConvertible.cpp | 33 ++- .../fabric/debug/DebugStringConvertible.h | 27 +- .../debug/DebugStringConvertibleItem.cpp | 20 +- .../fabric/debug/DebugStringConvertibleItem.h | 17 +- .../debug/debugStringConvertibleUtils.h | 47 ++- .../tests/DebugStringConvertibleTest.cpp | 49 ++-- ReactCommon/fabric/events/BatchedEventQueue.h | 5 +- ReactCommon/fabric/events/EventBeat.h | 11 +- .../fabric/events/EventBeatBasedExecutor.cpp | 20 +- .../fabric/events/EventBeatBasedExecutor.h | 10 +- ReactCommon/fabric/events/EventDispatcher.cpp | 26 +- ReactCommon/fabric/events/EventDispatcher.h | 19 +- ReactCommon/fabric/events/EventEmitter.cpp | 29 +- ReactCommon/fabric/events/EventEmitter.h | 47 ++- ReactCommon/fabric/events/EventQueue.cpp | 17 +- ReactCommon/fabric/events/EventQueue.h | 11 +- ReactCommon/fabric/events/RawEvent.cpp | 13 +- ReactCommon/fabric/events/RawEvent.h | 12 +- .../fabric/events/UnbatchedEventQueue.h | 6 +- ReactCommon/fabric/events/primitives.h | 21 +- .../imagemanager/platform/ios/ImageManager.mm | 4 +- .../platform/ios/RCTImageManager.mm | 40 +-- .../SampleComponentDescriptorFactor.cpp | 5 +- .../platform/android/TextLayoutManager.cpp | 44 ++- .../platform/android/TextLayoutManager.h | 19 +- .../platform/ios/RCTAttributedTextUtils.h | 8 +- .../platform/ios/RCTAttributedTextUtils.mm | 171 ++++++----- .../platform/ios/RCTFontUtils.mm | 97 +++--- .../platform/ios/RCTTextLayoutManager.h | 29 +- .../platform/ios/RCTTextLayoutManager.mm | 120 ++++---- .../ios/RCTTextPrimitivesConversions.h | 70 +++-- .../platform/ios/TextLayoutManager.h | 13 +- .../platform/ios/TextLayoutManager.mm | 15 +- .../uimanager/ComponentDescriptorFactory.h | 7 +- .../uimanager/ComponentDescriptorRegistry.cpp | 16 +- .../uimanager/ComponentDescriptorRegistry.h | 20 +- .../fabric/uimanager/ContextContainer.h | 24 +- .../fabric/uimanager/Differentiator.cpp | 173 ++++++----- ReactCommon/fabric/uimanager/Differentiator.h | 5 +- .../fabric/uimanager/FabricUIManager.cpp | 187 ++++++------ .../fabric/uimanager/FabricUIManager.h | 85 ++++-- ReactCommon/fabric/uimanager/Scheduler.cpp | 89 +++--- ReactCommon/fabric/uimanager/Scheduler.h | 50 ++-- .../fabric/uimanager/SchedulerDelegate.h | 10 +- ReactCommon/fabric/uimanager/ShadowTree.cpp | 130 ++++----- ReactCommon/fabric/uimanager/ShadowTree.h | 44 ++- .../fabric/uimanager/ShadowTreeDelegate.h | 7 +- ReactCommon/fabric/uimanager/ShadowView.cpp | 39 ++- .../fabric/uimanager/ShadowViewMutation.cpp | 76 ++--- .../fabric/uimanager/ShadowViewMutation.h | 40 +-- .../fabric/uimanager/UIManagerDelegate.h | 12 +- 78 files changed, 1719 insertions(+), 1345 deletions(-) diff --git a/ReactCommon/.clang-format b/ReactCommon/.clang-format index 550292f9506..34fb029ee3c 100644 --- a/ReactCommon/.clang-format +++ b/ReactCommon/.clang-format @@ -35,7 +35,7 @@ BreakBeforeTernaryOperators: true BreakConstructorInitializersBeforeComma: false BreakAfterJavaFieldAnnotations: false BreakStringLiterals: false -ColumnLimit: 80 +ColumnLimit: 80 CommentPragmas: '^ IWYU pragma:' ConstructorInitializerAllOnOneLineOrOnePerLine: true ConstructorInitializerIndentWidth: 4 diff --git a/ReactCommon/fabric/components/view/primitives.h b/ReactCommon/fabric/components/view/primitives.h index cde0b247938..4f3a00dd550 100644 --- a/ReactCommon/fabric/components/view/primitives.h +++ b/ReactCommon/fabric/components/view/primitives.h @@ -7,7 +7,6 @@ #pragma once -#include #include #include #include diff --git a/ReactCommon/fabric/components/view/propsConversions.h b/ReactCommon/fabric/components/view/propsConversions.h index 45ed01f0f04..4ef72d1d3be 100644 --- a/ReactCommon/fabric/components/view/propsConversions.h +++ b/ReactCommon/fabric/components/view/propsConversions.h @@ -14,98 +14,200 @@ namespace facebook { namespace react { static inline std::array convertRawProp( - const RawProps &rawProps, - const std::string &widthName, - const std::string &heightName, - const std::array &sourceValue, - const std::array &defaultValue -) { + const RawProps &rawProps, + const std::string &widthName, + const std::string &heightName, + const std::array &sourceValue, + const std::array &defaultValue) { auto dimentions = defaultValue; - dimentions[YGDimensionWidth] = convertRawProp(rawProps, widthName, sourceValue[YGDimensionWidth], defaultValue[YGDimensionWidth]); - dimentions[YGDimensionHeight] = convertRawProp(rawProps, heightName, sourceValue[YGDimensionHeight], defaultValue[YGDimensionWidth]); + dimentions[YGDimensionWidth] = convertRawProp( + rawProps, + widthName, + sourceValue[YGDimensionWidth], + defaultValue[YGDimensionWidth]); + dimentions[YGDimensionHeight] = convertRawProp( + rawProps, + heightName, + sourceValue[YGDimensionHeight], + defaultValue[YGDimensionWidth]); return dimentions; } static inline std::array convertRawProp( - const RawProps &rawProps, - const std::string &prefix, - const std::string &suffix, - const std::array &sourceValue, - const std::array &defaultValue -) { + const RawProps &rawProps, + const std::string &prefix, + const std::string &suffix, + const std::array &sourceValue, + const std::array &defaultValue) { auto result = defaultValue; - result[YGEdgeLeft] = convertRawProp(rawProps, prefix + "Left" + suffix, sourceValue[YGEdgeLeft], defaultValue[YGEdgeLeft]); - result[YGEdgeTop] = convertRawProp(rawProps, prefix + "Top" + suffix, sourceValue[YGEdgeTop], defaultValue[YGEdgeTop]); - result[YGEdgeRight] = convertRawProp(rawProps, prefix + "Right" + suffix, sourceValue[YGEdgeRight], defaultValue[YGEdgeRight]); - result[YGEdgeBottom] = convertRawProp(rawProps, prefix + "Bottom" + suffix, sourceValue[YGEdgeBottom], defaultValue[YGEdgeBottom]); - result[YGEdgeStart] = convertRawProp(rawProps, prefix + "Start" + suffix, sourceValue[YGEdgeStart], defaultValue[YGEdgeStart]); - result[YGEdgeEnd] = convertRawProp(rawProps, prefix + "End" + suffix, sourceValue[YGEdgeEnd], defaultValue[YGEdgeEnd]); - result[YGEdgeHorizontal] = convertRawProp(rawProps, prefix + "Horizontal" + suffix, sourceValue[YGEdgeHorizontal], defaultValue[YGEdgeHorizontal]); - result[YGEdgeVertical] = convertRawProp(rawProps, prefix + "Vertical" + suffix, sourceValue[YGEdgeVertical], defaultValue[YGEdgeVertical]); - result[YGEdgeAll] = convertRawProp(rawProps, prefix + suffix, sourceValue[YGEdgeAll], defaultValue[YGEdgeAll]); + result[YGEdgeLeft] = convertRawProp( + rawProps, + prefix + "Left" + suffix, + sourceValue[YGEdgeLeft], + defaultValue[YGEdgeLeft]); + result[YGEdgeTop] = convertRawProp( + rawProps, + prefix + "Top" + suffix, + sourceValue[YGEdgeTop], + defaultValue[YGEdgeTop]); + result[YGEdgeRight] = convertRawProp( + rawProps, + prefix + "Right" + suffix, + sourceValue[YGEdgeRight], + defaultValue[YGEdgeRight]); + result[YGEdgeBottom] = convertRawProp( + rawProps, + prefix + "Bottom" + suffix, + sourceValue[YGEdgeBottom], + defaultValue[YGEdgeBottom]); + result[YGEdgeStart] = convertRawProp( + rawProps, + prefix + "Start" + suffix, + sourceValue[YGEdgeStart], + defaultValue[YGEdgeStart]); + result[YGEdgeEnd] = convertRawProp( + rawProps, + prefix + "End" + suffix, + sourceValue[YGEdgeEnd], + defaultValue[YGEdgeEnd]); + result[YGEdgeHorizontal] = convertRawProp( + rawProps, + prefix + "Horizontal" + suffix, + sourceValue[YGEdgeHorizontal], + defaultValue[YGEdgeHorizontal]); + result[YGEdgeVertical] = convertRawProp( + rawProps, + prefix + "Vertical" + suffix, + sourceValue[YGEdgeVertical], + defaultValue[YGEdgeVertical]); + result[YGEdgeAll] = convertRawProp( + rawProps, + prefix + suffix, + sourceValue[YGEdgeAll], + defaultValue[YGEdgeAll]); return result; } static inline std::array convertRawProp( - const RawProps &rawProps, - const std::array &sourceValue, - const std::array &defaultValue -) { + const RawProps &rawProps, + const std::array &sourceValue, + const std::array &defaultValue) { auto result = defaultValue; - result[YGEdgeLeft] = convertRawProp(rawProps, "left", sourceValue[YGEdgeLeft], defaultValue[YGEdgeLeft]); - result[YGEdgeTop] = convertRawProp(rawProps, "top", sourceValue[YGEdgeTop], defaultValue[YGEdgeTop]); - result[YGEdgeRight] = convertRawProp(rawProps, "right", sourceValue[YGEdgeRight], defaultValue[YGEdgeRight]); - result[YGEdgeBottom] = convertRawProp(rawProps, "bottom", sourceValue[YGEdgeBottom], defaultValue[YGEdgeBottom]); - result[YGEdgeStart] = convertRawProp(rawProps, "start", sourceValue[YGEdgeStart], defaultValue[YGEdgeStart]); - result[YGEdgeEnd] = convertRawProp(rawProps, "end", sourceValue[YGEdgeEnd], defaultValue[YGEdgeEnd]); + result[YGEdgeLeft] = convertRawProp( + rawProps, "left", sourceValue[YGEdgeLeft], defaultValue[YGEdgeLeft]); + result[YGEdgeTop] = convertRawProp( + rawProps, "top", sourceValue[YGEdgeTop], defaultValue[YGEdgeTop]); + result[YGEdgeRight] = convertRawProp( + rawProps, "right", sourceValue[YGEdgeRight], defaultValue[YGEdgeRight]); + result[YGEdgeBottom] = convertRawProp( + rawProps, + "bottom", + sourceValue[YGEdgeBottom], + defaultValue[YGEdgeBottom]); + result[YGEdgeStart] = convertRawProp( + rawProps, "start", sourceValue[YGEdgeStart], defaultValue[YGEdgeStart]); + result[YGEdgeEnd] = convertRawProp( + rawProps, "end", sourceValue[YGEdgeEnd], defaultValue[YGEdgeEnd]); return result; } -static inline YGStyle convertRawProp(const RawProps &rawProps, const YGStyle &sourceValue) { - auto yogaStyle = YGStyle {}; - yogaStyle.direction = convertRawProp(rawProps, "direction", sourceValue.direction, yogaStyle.direction); - yogaStyle.flexDirection = convertRawProp(rawProps, "flexDirection", sourceValue.flexDirection, yogaStyle.flexDirection); - yogaStyle.justifyContent = convertRawProp(rawProps, "justifyContent", sourceValue.justifyContent, yogaStyle.justifyContent); - yogaStyle.alignContent = convertRawProp(rawProps, "alignContent", sourceValue.alignContent, yogaStyle.alignContent); - yogaStyle.alignItems = convertRawProp(rawProps, "alignItems", sourceValue.alignItems, yogaStyle.alignItems); - yogaStyle.alignSelf = convertRawProp(rawProps, "alignSelf", sourceValue.alignSelf, yogaStyle.alignSelf); - yogaStyle.positionType = convertRawProp(rawProps, "position", sourceValue.positionType, yogaStyle.positionType); - yogaStyle.flexWrap = convertRawProp(rawProps, "flexWrap", sourceValue.flexWrap, yogaStyle.flexWrap); - yogaStyle.overflow = convertRawProp(rawProps, "overflow", sourceValue.overflow, yogaStyle.overflow); - yogaStyle.display = convertRawProp(rawProps, "display", sourceValue.display, yogaStyle.display); - yogaStyle.flex = convertRawProp(rawProps, "flex", sourceValue.flex, yogaStyle.flex); - yogaStyle.flexGrow = convertRawProp(rawProps, "flexGrow", sourceValue.flexGrow, yogaStyle.flexGrow); - yogaStyle.flexShrink = convertRawProp(rawProps, "flexShrink", sourceValue.flexShrink, yogaStyle.flexShrink); - yogaStyle.flexBasis = convertRawProp(rawProps, "flexBasis", sourceValue.flexBasis, yogaStyle.flexBasis); - yogaStyle.margin = convertRawProp(rawProps, "margin", "", sourceValue.margin, yogaStyle.margin); - yogaStyle.position = convertRawProp(rawProps, sourceValue.position, yogaStyle.position); - yogaStyle.padding = convertRawProp(rawProps, "padding", "", sourceValue.padding, yogaStyle.padding); - yogaStyle.border = convertRawProp(rawProps, "border", "Width", sourceValue.border, yogaStyle.border); - yogaStyle.dimensions = convertRawProp(rawProps, "width", "height", sourceValue.dimensions, yogaStyle.dimensions); - yogaStyle.minDimensions = convertRawProp(rawProps, "minWidth", "minHeight", sourceValue.minDimensions, yogaStyle.minDimensions); - yogaStyle.maxDimensions = convertRawProp(rawProps, "maxWidth", "maxHeight", sourceValue.maxDimensions, yogaStyle.maxDimensions); - yogaStyle.aspectRatio = convertRawProp(rawProps, "aspectRatio", sourceValue.aspectRatio, yogaStyle.aspectRatio); +static inline YGStyle convertRawProp( + const RawProps &rawProps, + const YGStyle &sourceValue) { + auto yogaStyle = YGStyle{}; + yogaStyle.direction = convertRawProp( + rawProps, "direction", sourceValue.direction, yogaStyle.direction); + yogaStyle.flexDirection = convertRawProp( + rawProps, + "flexDirection", + sourceValue.flexDirection, + yogaStyle.flexDirection); + yogaStyle.justifyContent = convertRawProp( + rawProps, + "justifyContent", + sourceValue.justifyContent, + yogaStyle.justifyContent); + yogaStyle.alignContent = convertRawProp( + rawProps, + "alignContent", + sourceValue.alignContent, + yogaStyle.alignContent); + yogaStyle.alignItems = convertRawProp( + rawProps, "alignItems", sourceValue.alignItems, yogaStyle.alignItems); + yogaStyle.alignSelf = convertRawProp( + rawProps, "alignSelf", sourceValue.alignSelf, yogaStyle.alignSelf); + yogaStyle.positionType = convertRawProp( + rawProps, "position", sourceValue.positionType, yogaStyle.positionType); + yogaStyle.flexWrap = convertRawProp( + rawProps, "flexWrap", sourceValue.flexWrap, yogaStyle.flexWrap); + yogaStyle.overflow = convertRawProp( + rawProps, "overflow", sourceValue.overflow, yogaStyle.overflow); + yogaStyle.display = convertRawProp( + rawProps, "display", sourceValue.display, yogaStyle.display); + yogaStyle.flex = + convertRawProp(rawProps, "flex", sourceValue.flex, yogaStyle.flex); + yogaStyle.flexGrow = convertRawProp( + rawProps, "flexGrow", sourceValue.flexGrow, yogaStyle.flexGrow); + yogaStyle.flexShrink = convertRawProp( + rawProps, "flexShrink", sourceValue.flexShrink, yogaStyle.flexShrink); + yogaStyle.flexBasis = convertRawProp( + rawProps, "flexBasis", sourceValue.flexBasis, yogaStyle.flexBasis); + yogaStyle.margin = convertRawProp( + rawProps, "margin", "", sourceValue.margin, yogaStyle.margin); + yogaStyle.position = + convertRawProp(rawProps, sourceValue.position, yogaStyle.position); + yogaStyle.padding = convertRawProp( + rawProps, "padding", "", sourceValue.padding, yogaStyle.padding); + yogaStyle.border = convertRawProp( + rawProps, "border", "Width", sourceValue.border, yogaStyle.border); + yogaStyle.dimensions = convertRawProp( + rawProps, + "width", + "height", + sourceValue.dimensions, + yogaStyle.dimensions); + yogaStyle.minDimensions = convertRawProp( + rawProps, + "minWidth", + "minHeight", + sourceValue.minDimensions, + yogaStyle.minDimensions); + yogaStyle.maxDimensions = convertRawProp( + rawProps, + "maxWidth", + "maxHeight", + sourceValue.maxDimensions, + yogaStyle.maxDimensions); + yogaStyle.aspectRatio = convertRawProp( + rawProps, "aspectRatio", sourceValue.aspectRatio, yogaStyle.aspectRatio); return yogaStyle; } template static inline CascadedRectangleCorners convertRawProp( - const RawProps &rawProps, - const std::string &prefix, - const std::string &suffix, - const CascadedRectangleCorners &sourceValue -) { + const RawProps &rawProps, + const std::string &prefix, + const std::string &suffix, + const CascadedRectangleCorners &sourceValue) { CascadedRectangleCorners result; - result.topLeft = convertRawProp(rawProps, prefix + "TopLeft" + suffix, sourceValue.topLeft); - result.topRight = convertRawProp(rawProps, prefix + "TopRight" + suffix, sourceValue.topRight); - result.bottomLeft = convertRawProp(rawProps, prefix + "BottomLeft" + suffix, sourceValue.bottomLeft); - result.bottomRight = convertRawProp(rawProps, prefix + "BottomRight" + suffix, sourceValue.bottomRight); + result.topLeft = convertRawProp( + rawProps, prefix + "TopLeft" + suffix, sourceValue.topLeft); + result.topRight = convertRawProp( + rawProps, prefix + "TopRight" + suffix, sourceValue.topRight); + result.bottomLeft = convertRawProp( + rawProps, prefix + "BottomLeft" + suffix, sourceValue.bottomLeft); + result.bottomRight = convertRawProp( + rawProps, prefix + "BottomRight" + suffix, sourceValue.bottomRight); - result.topStart = convertRawProp(rawProps, prefix + "TopStart" + suffix, sourceValue.topStart); - result.topEnd = convertRawProp(rawProps, prefix + "TopEnd" + suffix, sourceValue.topEnd); - result.bottomStart = convertRawProp(rawProps, prefix + "BottomStart" + suffix, sourceValue.bottomStart); - result.bottomEnd = convertRawProp(rawProps, prefix + "BottomEnd" + suffix, sourceValue.bottomEnd); + result.topStart = convertRawProp( + rawProps, prefix + "TopStart" + suffix, sourceValue.topStart); + result.topEnd = + convertRawProp(rawProps, prefix + "TopEnd" + suffix, sourceValue.topEnd); + result.bottomStart = convertRawProp( + rawProps, prefix + "BottomStart" + suffix, sourceValue.bottomStart); + result.bottomEnd = convertRawProp( + rawProps, prefix + "BottomEnd" + suffix, sourceValue.bottomEnd); result.all = convertRawProp(rawProps, prefix + suffix, sourceValue.all); @@ -114,22 +216,29 @@ static inline CascadedRectangleCorners convertRawProp( template static inline CascadedRectangleEdges convertRawProp( - const RawProps &rawProps, - const std::string &prefix, - const std::string &suffix, - const CascadedRectangleEdges &sourceValue -) { + const RawProps &rawProps, + const std::string &prefix, + const std::string &suffix, + const CascadedRectangleEdges &sourceValue) { CascadedRectangleEdges result; - result.left = convertRawProp(rawProps, prefix + "Left" + suffix, sourceValue.left); - result.right = convertRawProp(rawProps, prefix + "Right" + suffix, sourceValue.right); - result.top = convertRawProp(rawProps, prefix + "Top" + suffix, sourceValue.top); - result.bottom = convertRawProp(rawProps, prefix + "Bottom" + suffix, sourceValue.bottom); + result.left = + convertRawProp(rawProps, prefix + "Left" + suffix, sourceValue.left); + result.right = + convertRawProp(rawProps, prefix + "Right" + suffix, sourceValue.right); + result.top = + convertRawProp(rawProps, prefix + "Top" + suffix, sourceValue.top); + result.bottom = + convertRawProp(rawProps, prefix + "Bottom" + suffix, sourceValue.bottom); - result.start = convertRawProp(rawProps, prefix + "Start" + suffix, sourceValue.start); - result.end = convertRawProp(rawProps, prefix + "End" + suffix, sourceValue.end); - result.horizontal = convertRawProp(rawProps, prefix + "Horizontal" + suffix, sourceValue.horizontal); - result.vertical = convertRawProp(rawProps, prefix + "Vertical" + suffix, sourceValue.vertical); + result.start = + convertRawProp(rawProps, prefix + "Start" + suffix, sourceValue.start); + result.end = + convertRawProp(rawProps, prefix + "End" + suffix, sourceValue.end); + result.horizontal = convertRawProp( + rawProps, prefix + "Horizontal" + suffix, sourceValue.horizontal); + result.vertical = convertRawProp( + rawProps, prefix + "Vertical" + suffix, sourceValue.vertical); result.all = convertRawProp(rawProps, prefix + suffix, sourceValue.all); diff --git a/ReactCommon/fabric/core/componentdescriptor/ComponentDescriptor.h b/ReactCommon/fabric/core/componentdescriptor/ComponentDescriptor.h index bdc2d57fd9e..91dd70326fb 100644 --- a/ReactCommon/fabric/core/componentdescriptor/ComponentDescriptor.h +++ b/ReactCommon/fabric/core/componentdescriptor/ComponentDescriptor.h @@ -7,8 +7,8 @@ #pragma once -#include #include +#include namespace facebook { namespace react { @@ -24,8 +24,7 @@ using SharedComponentDescriptor = std::shared_ptr; * `ShadowNode`s (such as creating, cloning, props and children managing). */ class ComponentDescriptor { -public: - + public: virtual ~ComponentDescriptor() = default; /* @@ -45,24 +44,21 @@ public: * Creates a new `ShadowNode` of a particular type. */ virtual SharedShadowNode createShadowNode( - const ShadowNodeFragment &fragment - ) const = 0; + const ShadowNodeFragment &fragment) const = 0; /* * Clones a `ShadowNode` with optionally new `props` and/or `children`. */ virtual UnsharedShadowNode 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 SharedShadowNode &parentShadowNode, - const SharedShadowNode &childShadowNode - ) const = 0; + const SharedShadowNode &parentShadowNode, + const SharedShadowNode &childShadowNode) const = 0; /* * Creates a new `Props` of a particular type with all values copied from @@ -71,18 +67,16 @@ public: * will be used. */ virtual SharedProps cloneProps( - const SharedProps &props, - const RawProps &rawProps - ) const = 0; + const SharedProps &props, + const RawProps &rawProps) const = 0; /* * Creates a new `EventEmitter` object compatible with particular type of * shadow nodes. */ virtual SharedEventEmitter createEventEmitter( - SharedEventTarget eventTarget, - const Tag &tag - ) const = 0; + SharedEventTarget eventTarget, + const Tag &tag) const = 0; }; } // namespace react diff --git a/ReactCommon/fabric/core/componentdescriptor/ConcreteComponentDescriptor.h b/ReactCommon/fabric/core/componentdescriptor/ConcreteComponentDescriptor.h index 439e2c9f0f6..8d313183265 100644 --- a/ReactCommon/fabric/core/componentdescriptor/ConcreteComponentDescriptor.h +++ b/ReactCommon/fabric/core/componentdescriptor/ConcreteComponentDescriptor.h @@ -7,8 +7,8 @@ #pragma once -#include #include +#include #include #include @@ -25,18 +25,21 @@ namespace react { * if necessary. */ template -class ConcreteComponentDescriptor: public ComponentDescriptor { - static_assert(std::is_base_of::value, "ShadowNodeT must be a descendant of ShadowNode"); +class ConcreteComponentDescriptor : public ComponentDescriptor { + static_assert( + std::is_base_of::value, + "ShadowNodeT must be a descendant of ShadowNode"); using SharedShadowNodeT = std::shared_ptr; 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; -public: - ConcreteComponentDescriptor(SharedEventDispatcher eventDispatcher): - eventDispatcher_(eventDispatcher) {} + public: + ConcreteComponentDescriptor(SharedEventDispatcher eventDispatcher) + : eventDispatcher_(eventDispatcher) {} ComponentHandle getComponentHandle() const override { return ShadowNodeT::Handle(); @@ -47,15 +50,13 @@ public: } SharedShadowNode createShadowNode( - const ShadowNodeFragment &fragment - ) const override { + const ShadowNodeFragment &fragment) const override { assert(std::dynamic_pointer_cast(fragment.props)); - assert(std::dynamic_pointer_cast(fragment.eventEmitter)); + assert(std::dynamic_pointer_cast( + fragment.eventEmitter)); - auto shadowNode = std::make_shared( - fragment, - getCloneFunction() - ); + auto shadowNode = + std::make_shared(fragment, getCloneFunction()); adopt(shadowNode); @@ -63,57 +64,53 @@ public: } UnsharedShadowNode cloneShadowNode( - const ShadowNode &sourceShadowNode, - const ShadowNodeFragment &fragment - ) const override { - auto shadowNode = std::make_shared( - sourceShadowNode, - fragment - ); + const ShadowNode &sourceShadowNode, + const ShadowNodeFragment &fragment) const override { + auto shadowNode = std::make_shared(sourceShadowNode, fragment); adopt(shadowNode); return shadowNode; } void appendChild( - const SharedShadowNode &parentShadowNode, - const SharedShadowNode &childShadowNode - ) const override { - auto concreteParentShadowNode = std::static_pointer_cast(parentShadowNode); - auto concreteNonConstParentShadowNode = std::const_pointer_cast(concreteParentShadowNode); + const SharedShadowNode &parentShadowNode, + const SharedShadowNode &childShadowNode) const override { + auto concreteParentShadowNode = + std::static_pointer_cast(parentShadowNode); + auto concreteNonConstParentShadowNode = + std::const_pointer_cast(concreteParentShadowNode); concreteNonConstParentShadowNode->appendChild(childShadowNode); } virtual SharedProps cloneProps( - const SharedProps &props, - const RawProps &rawProps - ) const override { + const SharedProps &props, + const RawProps &rawProps) const override { return ShadowNodeT::Props(rawProps, props); }; virtual SharedEventEmitter createEventEmitter( - SharedEventTarget eventTarget, - const Tag &tag - ) const override { - return std::make_shared(std::move(eventTarget), tag, eventDispatcher_); + SharedEventTarget eventTarget, + const Tag &tag) const override { + return std::make_shared( + std::move(eventTarget), tag, eventDispatcher_); } -protected: - + protected: virtual void adopt(UnsharedShadowNode shadowNode) const { // Default implementation does nothing. assert(shadowNode->getComponentHandle() == getComponentHandle()); } -private: - - mutable SharedEventDispatcher eventDispatcher_ {nullptr}; + private: + mutable SharedEventDispatcher eventDispatcher_{nullptr}; mutable ShadowNodeCloneFunction cloneFunction_; ShadowNodeCloneFunction getCloneFunction() const { if (!cloneFunction_) { - cloneFunction_ = [this](const ShadowNode &shadowNode, const ShadowNodeFragment &fragment) { + cloneFunction_ = [this]( + const ShadowNode &shadowNode, + const ShadowNodeFragment &fragment) { return this->cloneShadowNode(shadowNode, fragment); }; } diff --git a/ReactCommon/fabric/core/conversions.h b/ReactCommon/fabric/core/conversions.h index 7799cec13a0..9a9c4495e25 100644 --- a/ReactCommon/fabric/core/conversions.h +++ b/ReactCommon/fabric/core/conversions.h @@ -14,17 +14,23 @@ namespace react { inline std::string toString(const LayoutDirection &layoutDirection) { switch (layoutDirection) { - case LayoutDirection::Undefined: return "undefined"; - case LayoutDirection::LeftToRight: return "ltr"; - case LayoutDirection::RightToLeft: return "rtl"; + case LayoutDirection::Undefined: + return "undefined"; + case LayoutDirection::LeftToRight: + return "ltr"; + case LayoutDirection::RightToLeft: + return "rtl"; } } inline std::string toString(const DisplayType &displayType) { switch (displayType) { - case DisplayType::None: return "none"; - case DisplayType::Flex: return "flex"; - case DisplayType::Inline: return "inline"; + case DisplayType::None: + return "none"; + case DisplayType::Flex: + return "flex"; + case DisplayType::Inline: + return "inline"; } } diff --git a/ReactCommon/fabric/core/layout/LayoutConstraints.h b/ReactCommon/fabric/core/layout/LayoutConstraints.h index 2d53f369961..f930173630d 100644 --- a/ReactCommon/fabric/core/layout/LayoutConstraints.h +++ b/ReactCommon/fabric/core/layout/LayoutConstraints.h @@ -17,8 +17,8 @@ namespace react { * Unified layout constraints for measuring. */ struct LayoutConstraints { - Size minimumSize {0, 0}; - Size maximumSize {kFloatUndefined, kFloatUndefined}; + Size minimumSize{0, 0}; + Size maximumSize{kFloatUndefined, kFloatUndefined}; LayoutDirection layoutDirection; }; diff --git a/ReactCommon/fabric/core/layout/LayoutContext.h b/ReactCommon/fabric/core/layout/LayoutContext.h index bb4791d39af..80988f0986c 100644 --- a/ReactCommon/fabric/core/layout/LayoutContext.h +++ b/ReactCommon/fabric/core/layout/LayoutContext.h @@ -20,7 +20,7 @@ struct LayoutContext { /* * Compound absolute position of the node relative to the root node. */ - Point absolutePosition {0, 0}; + Point absolutePosition{0, 0}; /* * Reflects the scale factor needed to convert from the logical coordinate diff --git a/ReactCommon/fabric/core/layout/LayoutMetrics.h b/ReactCommon/fabric/core/layout/LayoutMetrics.h index 9e519221c23..92c31e833a5 100644 --- a/ReactCommon/fabric/core/layout/LayoutMetrics.h +++ b/ReactCommon/fabric/core/layout/LayoutMetrics.h @@ -18,23 +18,34 @@ namespace react { */ struct LayoutMetrics { Rect frame; - EdgeInsets contentInsets {0}; - EdgeInsets borderWidth {0}; - DisplayType displayType {DisplayType::Flex}; - LayoutDirection layoutDirection {LayoutDirection::Undefined}; - Float pointScaleFactor {1.0}; + EdgeInsets contentInsets{0}; + EdgeInsets borderWidth{0}; + DisplayType displayType{DisplayType::Flex}; + LayoutDirection layoutDirection{LayoutDirection::Undefined}; + Float pointScaleFactor{1.0}; Rect getContentFrame() const { - return Rect { - Point {contentInsets.left, contentInsets.top}, - Size {frame.size.width - contentInsets.left - contentInsets.right, frame.size.height - contentInsets.top - contentInsets.bottom} - }; + return Rect{ + Point{contentInsets.left, contentInsets.top}, + Size{frame.size.width - contentInsets.left - contentInsets.right, + frame.size.height - contentInsets.top - contentInsets.bottom}}; } bool operator==(const LayoutMetrics &rhs) const { - return - std::tie(this->frame, this->contentInsets, this->borderWidth, this->displayType, this->layoutDirection, this->pointScaleFactor) == - std::tie(rhs.frame, rhs.contentInsets, rhs.borderWidth, rhs.displayType, rhs.layoutDirection, this->pointScaleFactor); + return std::tie( + this->frame, + this->contentInsets, + this->borderWidth, + this->displayType, + this->layoutDirection, + this->pointScaleFactor) == + std::tie( + rhs.frame, + rhs.contentInsets, + rhs.borderWidth, + rhs.displayType, + rhs.layoutDirection, + this->pointScaleFactor); } bool operator!=(const LayoutMetrics &rhs) const { @@ -43,9 +54,10 @@ struct LayoutMetrics { }; /* - * Represents some undefined, not-yet-computed or meaningless value of `LayoutMetrics` type. + * Represents some undefined, not-yet-computed or meaningless value of + * `LayoutMetrics` type. */ -static const LayoutMetrics EmptyLayoutMetrics = {.frame = { .size = {-1, -1}}}; +static const LayoutMetrics EmptyLayoutMetrics = {.frame = {.size = {-1, -1}}}; } // namespace react } // namespace facebook diff --git a/ReactCommon/fabric/core/layout/LayoutPrimitives.h b/ReactCommon/fabric/core/layout/LayoutPrimitives.h index fc74187e823..6c6f524aec1 100644 --- a/ReactCommon/fabric/core/layout/LayoutPrimitives.h +++ b/ReactCommon/fabric/core/layout/LayoutPrimitives.h @@ -35,14 +35,11 @@ enum class LayoutDirection { } // namespace react } // namespace facebook -namespace std -{ - template <> - struct hash - { - size_t operator()(const facebook::react::LayoutDirection& v) const - { - return hash()(static_cast(v)); - } - }; -} +namespace std { +template <> +struct hash { + size_t operator()(const facebook::react::LayoutDirection &v) const { + return hash()(static_cast(v)); + } +}; +} // namespace std diff --git a/ReactCommon/fabric/core/layout/LayoutableShadowNode.cpp b/ReactCommon/fabric/core/layout/LayoutableShadowNode.cpp index a25ecf8741e..f12e1175df3 100644 --- a/ReactCommon/fabric/core/layout/LayoutableShadowNode.cpp +++ b/ReactCommon/fabric/core/layout/LayoutableShadowNode.cpp @@ -96,10 +96,11 @@ void LayoutableShadowNode::layoutChildren(LayoutContext layoutContext) { #if RN_DEBUG_STRING_CONVERTIBLE SharedDebugStringConvertibleList LayoutableShadowNode::getDebugProps() const { - auto list = SharedDebugStringConvertibleList {}; + auto list = SharedDebugStringConvertibleList{}; if (getHasNewLayout()) { - list.push_back(std::make_shared("hasNewLayout")); + list.push_back( + std::make_shared("hasNewLayout")); } if (!getIsLayoutClean()) { @@ -109,14 +110,17 @@ SharedDebugStringConvertibleList LayoutableShadowNode::getDebugProps() const { auto layoutMetrics = getLayoutMetrics(); auto defaultLayoutMetrics = LayoutMetrics(); - list.push_back(std::make_shared("frame", toString(layoutMetrics.frame))); + list.push_back(std::make_shared( + "frame", toString(layoutMetrics.frame))); if (layoutMetrics.borderWidth != defaultLayoutMetrics.borderWidth) { - list.push_back(std::make_shared("borderWidth", toString(layoutMetrics.borderWidth))); + list.push_back(std::make_shared( + "borderWidth", toString(layoutMetrics.borderWidth))); } if (layoutMetrics.contentInsets != defaultLayoutMetrics.contentInsets) { - list.push_back(std::make_shared("contentInsets", toString(layoutMetrics.contentInsets))); + list.push_back(std::make_shared( + "contentInsets", toString(layoutMetrics.contentInsets))); } if (layoutMetrics.displayType == DisplayType::None) { diff --git a/ReactCommon/fabric/core/layout/LayoutableShadowNode.h b/ReactCommon/fabric/core/layout/LayoutableShadowNode.h index 516b50e6881..a419be119cf 100644 --- a/ReactCommon/fabric/core/layout/LayoutableShadowNode.h +++ b/ReactCommon/fabric/core/layout/LayoutableShadowNode.h @@ -9,8 +9,8 @@ #include #include -#include #include +#include #include #include @@ -26,11 +26,8 @@ struct LayoutContext; * Describes all sufficient layout API (in approach-agnostic way) * which makes a concurrent layout possible. */ -class LayoutableShadowNode: - public virtual Sealable { - -public: - +class LayoutableShadowNode : public virtual Sealable { + public: /* * Measures the node (and node content, propbably recursivly) with * given constrains and relying on possible layout. @@ -42,8 +39,9 @@ public: * Computes layout recusively. * Additional environmental constraints might be provided via `layoutContext` * argument. - * Default implementation basically calls `layoutChildren()` and then `layout()` - * (recursively), and provides some obvious performance optimization. + * Default implementation basically calls `layoutChildren()` and then + * `layout()` (recursively), and provides some obvious performance + * optimization. */ virtual void layout(LayoutContext layoutContext); @@ -59,8 +57,7 @@ public: */ virtual bool isLayoutOnly() const; -protected: - + protected: /* * Clean or Dirty layout state: * Indicates whether all nodes (and possibly their subtrees) along the path @@ -92,13 +89,16 @@ protected: /* * Returns layoutable children to interate on. */ - virtual std::vector getLayoutableChildNodes() const = 0; + virtual std::vector getLayoutableChildNodes() + const = 0; /* * In case layout algorithm needs to mutate this (probably sealed) node, * it has to clone and replace it in the hierarchy before to do so. */ - virtual LayoutableShadowNode *cloneAndReplaceChild(LayoutableShadowNode *child, int suggestedIndex = -1) = 0; + virtual LayoutableShadowNode *cloneAndReplaceChild( + LayoutableShadowNode *child, + int suggestedIndex = -1) = 0; /* * Sets layout metrics for the shadow node. @@ -112,10 +112,10 @@ protected: SharedDebugStringConvertibleList getDebugProps() const; #endif -private: - LayoutMetrics layoutMetrics_ {}; - bool hasNewLayout_ {false}; - bool isLayoutClean_ {false}; + private: + LayoutMetrics layoutMetrics_{}; + bool hasNewLayout_{false}; + bool isLayoutClean_{false}; }; } // namespace react diff --git a/ReactCommon/fabric/core/primitives/ReactPrimitives.h b/ReactCommon/fabric/core/primitives/ReactPrimitives.h index 72ecba50c6e..296266e1bef 100644 --- a/ReactCommon/fabric/core/primitives/ReactPrimitives.h +++ b/ReactCommon/fabric/core/primitives/ReactPrimitives.h @@ -20,7 +20,8 @@ namespace react { * `Tag` and `InstanceHandle` are used to address React Native components. */ using Tag = int32_t; -using InstanceHandle = struct InstanceHandleDummyStruct {} *; +using InstanceHandle = struct InstanceHandleDummyStruct { +} *; /* * An id of a running Surface instance that is used to refer to the instance. diff --git a/ReactCommon/fabric/core/primitives/Sealable.cpp b/ReactCommon/fabric/core/primitives/Sealable.cpp index 2de864f9c5a..cd1c2b02984 100644 --- a/ReactCommon/fabric/core/primitives/Sealable.cpp +++ b/ReactCommon/fabric/core/primitives/Sealable.cpp @@ -26,11 +26,11 @@ namespace react { #ifndef NDEBUG -Sealable::Sealable(): sealed_(false) {} +Sealable::Sealable() : sealed_(false) {} -Sealable::Sealable(const Sealable &other): sealed_(false) {}; +Sealable::Sealable(const Sealable &other) : sealed_(false){}; -Sealable::Sealable(Sealable &&other) noexcept: sealed_(false) {}; +Sealable::Sealable(Sealable &&other) noexcept : sealed_(false){}; Sealable::~Sealable() noexcept {}; diff --git a/ReactCommon/fabric/core/primitives/Sealable.h b/ReactCommon/fabric/core/primitives/Sealable.h index 4077531fb57..b11afecbf9f 100644 --- a/ReactCommon/fabric/core/primitives/Sealable.h +++ b/ReactCommon/fabric/core/primitives/Sealable.h @@ -13,7 +13,8 @@ namespace facebook { namespace react { /* - * Represents an object which can be *sealed* (imperatively marked as immutable). + * Represents an object which can be *sealed* (imperatively marked as + * immutable). * * The `sealed` flag is tight to a particular instance of the class and resets * to `false` for all newly created (by copy-constructor, assignment operator @@ -21,22 +22,22 @@ namespace react { * * Why do we need this? In Fabric, some objects are semi-immutable * even if they are explicitly marked as `const`. It means that in some special - * cases those objects can be const-casted-away and then mutated. That comes from - * the fact that we share some object's life-cycle responsibilities with React - * and the immutability is guaranteed by some logic splitted between native and - * JavaScript worlds (which makes it impossible to fully use immutability - * enforcement at a language level). - * To detect possible errors as early as possible we additionally mark objects - * as *sealed* after some stages and then enforce this at run-time. + * cases those objects can be const-casted-away and then mutated. That comes + * from the fact that we share some object's life-cycle responsibilities with + * React and the immutability is guaranteed by some logic splitted between + * native and JavaScript worlds (which makes it impossible to fully use + * immutability enforcement at a language level). To detect possible errors as + * early as possible we additionally mark objects as *sealed* after some stages + * and then enforce this at run-time. * * How to use: * 1. Inherit your class from `Sealable`. * 2. Call `ensureUnsealed()` in all cases where the object might be mutated: * a. At the beginning of all *always* mutating `non-const` methods; - * b. Right before the place where actual mutation happens in all *possible* - * mutating `non-const` methods; - * c. Right after performing `const_cast`. (Optionally. This is not strictly - * necessary but might help detect problems earlier.) + * b. Right before the place where actual mutation happens in all + * *possible* mutating `non-const` methods; c. Right after performing + * `const_cast`. (Optionally. This is not strictly necessary but might help + * detect problems earlier.) * 3. Call `seal()` at some point from which any modifications * must be prevented. */ @@ -44,16 +45,18 @@ namespace react { #ifdef NDEBUG class Sealable { -public: + public: inline void seal() const {} - inline bool getSealed() const { return true; } + inline bool getSealed() const { + return true; + } inline void ensureUnsealed() const {} }; #else class Sealable { -public: + public: Sealable(); Sealable(const Sealable &other); Sealable(Sealable &&other) noexcept; @@ -78,8 +81,8 @@ public: */ void ensureUnsealed() const; -private: - mutable std::atomic sealed_ {false}; + private: + mutable std::atomic sealed_{false}; }; #endif diff --git a/ReactCommon/fabric/core/propsConversions.h b/ReactCommon/fabric/core/propsConversions.h index 9999c3fd6b7..c0e9b85c99c 100644 --- a/ReactCommon/fabric/core/propsConversions.h +++ b/ReactCommon/fabric/core/propsConversions.h @@ -7,24 +7,32 @@ #pragma once -#include -#include #include #include #include +#include +#include namespace facebook { namespace react { -inline void fromDynamic(const folly::dynamic &value, bool &result) { result = value.getBool(); } +inline void fromDynamic(const folly::dynamic &value, bool &result) { + result = value.getBool(); +} inline void fromDynamic(const folly::dynamic &value, int &result) { - // All numbers from JS are treated as double, and JS cannot represent int64 in practice. - // So this always converts the value to int64 instead. + // All numbers from JS are treated as double, and JS cannot represent int64 in + // practice. So this always converts the value to int64 instead. result = value.asInt(); } -inline void fromDynamic(const folly::dynamic &value, float &result) { result = (float)value.asDouble(); } -inline void fromDynamic(const folly::dynamic &value, double &result) { result = value.asDouble(); } -inline void fromDynamic(const folly::dynamic &value, std::string &result) { result = value.getString(); } +inline void fromDynamic(const folly::dynamic &value, float &result) { + result = (float)value.asDouble(); +} +inline void fromDynamic(const folly::dynamic &value, double &result) { + result = value.asDouble(); +} +inline void fromDynamic(const folly::dynamic &value, std::string &result) { + result = value.getString(); +} template inline void fromDynamic(const folly::dynamic &value, std::vector &result) { @@ -45,11 +53,10 @@ inline void fromDynamic(const folly::dynamic &value, std::vector &result) { template inline T convertRawProp( - const RawProps &rawProps, - const std::string &name, - const T &sourceValue, - const T &defaultValue = T() -) { + const RawProps &rawProps, + const std::string &name, + const T &sourceValue, + const T &defaultValue = T()) { const auto &iterator = rawProps.find(name); if (iterator == rawProps.end()) { return sourceValue; @@ -57,7 +64,8 @@ inline T convertRawProp( const auto &value = iterator->second; - // Special case: `null` always means `the prop was removed, use default value`. + // Special case: `null` always means `the prop was removed, use default + // value`. if (value.isNull()) { return defaultValue; } @@ -69,11 +77,10 @@ inline T convertRawProp( template inline static folly::Optional convertRawProp( - const RawProps &rawProps, - const std::string &name, - const folly::Optional &sourceValue, - const folly::Optional &defaultValue = {} -) { + const RawProps &rawProps, + const std::string &name, + const folly::Optional &sourceValue, + const folly::Optional &defaultValue = {}) { const auto &iterator = rawProps.find(name); if (iterator == rawProps.end()) { return sourceValue; @@ -81,7 +88,8 @@ inline static folly::Optional convertRawProp( const auto &value = iterator->second; - // Special case: `null` always means `the prop was removed, use default value`. + // Special case: `null` always means `the prop was removed, use default + // value`. if (value.isNull()) { return defaultValue; } diff --git a/ReactCommon/fabric/core/shadownode/ConcreteShadowNode.h b/ReactCommon/fabric/core/shadownode/ConcreteShadowNode.h index 25e9a821ce4..cd99d629fa5 100644 --- a/ReactCommon/fabric/core/shadownode/ConcreteShadowNode.h +++ b/ReactCommon/fabric/core/shadownode/ConcreteShadowNode.h @@ -20,14 +20,15 @@ namespace react { * with many handy features. */ template < - const char *concreteComponentName, - typename PropsT, - typename EventEmitterT = EventEmitter -> -class ConcreteShadowNode: public ShadowNode { - static_assert(std::is_base_of::value, "PropsT must be a descendant of Props"); + const char *concreteComponentName, + typename PropsT, + typename EventEmitterT = EventEmitter> +class ConcreteShadowNode : public ShadowNode { + static_assert( + std::is_base_of::value, + "PropsT must be a descendant of Props"); -public: + public: using ShadowNode::ShadowNode; using ConcreteProps = PropsT; @@ -44,12 +45,18 @@ public: return ComponentHandle(concreteComponentName); } - static SharedConcreteProps Props(const RawProps &rawProps, const SharedProps &baseProps = nullptr) { - return std::make_shared(baseProps ? *std::static_pointer_cast(baseProps) : PropsT(), rawProps); + static SharedConcreteProps Props( + const RawProps &rawProps, + const SharedProps &baseProps = nullptr) { + return std::make_shared( + baseProps ? *std::static_pointer_cast(baseProps) + : PropsT(), + rawProps); } static SharedConcreteProps defaultSharedProps() { - static const SharedConcreteProps defaultSharedProps = std::make_shared(); + static const SharedConcreteProps defaultSharedProps = + std::make_shared(); return defaultSharedProps; } @@ -69,13 +76,15 @@ public: /* * Returns subset of children that are inherited from `SpecificShadowNodeT`. */ - template + template std::vector getChildrenSlice() const { std::vector children; for (const auto &childShadowNode : getChildren()) { - auto specificChildShadowNode = dynamic_cast(childShadowNode.get()); + auto specificChildShadowNode = + dynamic_cast(childShadowNode.get()); if (specificChildShadowNode) { - children.push_back(const_cast(specificChildShadowNode)); + children.push_back( + const_cast(specificChildShadowNode)); } } return children; diff --git a/ReactCommon/fabric/core/shadownode/LocalData.h b/ReactCommon/fabric/core/shadownode/LocalData.h index 71560fb77d9..9fe47c774b5 100644 --- a/ReactCommon/fabric/core/shadownode/LocalData.h +++ b/ReactCommon/fabric/core/shadownode/LocalData.h @@ -26,11 +26,8 @@ using SharedLocalData = std::shared_ptr; * All `LocalData` objects *must* be immutable (sealed) when they became * a part of the shadow tree. */ -class LocalData: - public Sealable, - public DebugStringConvertible { - -public: +class LocalData : public Sealable, public DebugStringConvertible { + public: virtual ~LocalData() = default; virtual folly::dynamic getDynamic() const { diff --git a/ReactCommon/fabric/core/shadownode/Props.cpp b/ReactCommon/fabric/core/shadownode/Props.cpp index c50cde97afc..c6ca7d20c30 100644 --- a/ReactCommon/fabric/core/shadownode/Props.cpp +++ b/ReactCommon/fabric/core/shadownode/Props.cpp @@ -13,12 +13,13 @@ namespace facebook { namespace react { -Props::Props(const Props &sourceProps, const RawProps &rawProps): - nativeId(convertRawProp(rawProps, "nativeID", sourceProps.nativeId)) - #ifdef ANDROID - ,rawProps(rawProps) - #endif - {}; +Props::Props(const Props &sourceProps, const RawProps &rawProps) + : nativeId(convertRawProp(rawProps, "nativeID", sourceProps.nativeId)) +#ifdef ANDROID + , + rawProps(rawProps) +#endif + {}; } // namespace react } // namespace facebook diff --git a/ReactCommon/fabric/core/shadownode/Props.h b/ReactCommon/fabric/core/shadownode/Props.h index f072f7a3a33..ace5e4dfe99 100644 --- a/ReactCommon/fabric/core/shadownode/Props.h +++ b/ReactCommon/fabric/core/shadownode/Props.h @@ -9,8 +9,8 @@ #include -#include #include +#include #include namespace facebook { @@ -23,11 +23,8 @@ using SharedProps = std::shared_ptr; /* * Represents the most generic props object. */ -class Props: - public virtual Sealable, - public virtual DebugStringConvertible { - -public: +class Props : public virtual Sealable, public virtual DebugStringConvertible { + public: Props() = default; Props(const Props &sourceProps, const RawProps &rawProps); virtual ~Props() = default; diff --git a/ReactCommon/fabric/core/shadownode/ShadowNode.cpp b/ReactCommon/fabric/core/shadownode/ShadowNode.cpp index 853cfc20cc0..3ea2d8193f3 100644 --- a/ReactCommon/fabric/core/shadownode/ShadowNode.cpp +++ b/ReactCommon/fabric/core/shadownode/ShadowNode.cpp @@ -17,43 +17,40 @@ namespace facebook { namespace react { SharedShadowNodeSharedList ShadowNode::emptySharedShadowNodeSharedList() { - static const auto emptySharedShadowNodeSharedList = std::make_shared(); + static const auto emptySharedShadowNodeSharedList = + std::make_shared(); return emptySharedShadowNodeSharedList; } #pragma mark - Constructors ShadowNode::ShadowNode( - const ShadowNodeFragment &fragment, - const ShadowNodeCloneFunction &cloneFunction -): - tag_(fragment.tag), - rootTag_(fragment.rootTag), - props_(fragment.props), - eventEmitter_(fragment.eventEmitter), - children_(fragment.children ?: emptySharedShadowNodeSharedList()), - cloneFunction_(cloneFunction), - childrenAreShared_(true), - revision_(1) { - + const ShadowNodeFragment &fragment, + const ShadowNodeCloneFunction &cloneFunction) + : tag_(fragment.tag), + rootTag_(fragment.rootTag), + props_(fragment.props), + eventEmitter_(fragment.eventEmitter), + children_(fragment.children ?: emptySharedShadowNodeSharedList()), + cloneFunction_(cloneFunction), + childrenAreShared_(true), + revision_(1) { assert(props_); assert(children_); } ShadowNode::ShadowNode( - const ShadowNode &sourceShadowNode, - const ShadowNodeFragment &fragment -): - tag_(fragment.tag ?: sourceShadowNode.tag_), - rootTag_(fragment.rootTag ?: sourceShadowNode.rootTag_), - props_(fragment.props ?: sourceShadowNode.props_), - eventEmitter_(fragment.eventEmitter ?: sourceShadowNode.eventEmitter_), - children_(fragment.children ?: sourceShadowNode.children_), - localData_(fragment.localData ?: sourceShadowNode.localData_), - cloneFunction_(sourceShadowNode.cloneFunction_), - childrenAreShared_(true), - revision_(sourceShadowNode.revision_ + 1) { - + const ShadowNode &sourceShadowNode, + const ShadowNodeFragment &fragment) + : tag_(fragment.tag ?: sourceShadowNode.tag_), + rootTag_(fragment.rootTag ?: sourceShadowNode.rootTag_), + props_(fragment.props ?: sourceShadowNode.props_), + eventEmitter_(fragment.eventEmitter ?: sourceShadowNode.eventEmitter_), + children_(fragment.children ?: sourceShadowNode.children_), + localData_(fragment.localData ?: sourceShadowNode.localData_), + cloneFunction_(sourceShadowNode.cloneFunction_), + childrenAreShared_(true), + revision_(sourceShadowNode.revision_ + 1) { assert(props_); assert(children_); } @@ -109,16 +106,21 @@ void ShadowNode::appendChild(const SharedShadowNode &child) { ensureUnsealed(); cloneChildrenIfShared(); - auto nonConstChildren = std::const_pointer_cast(children_); + auto nonConstChildren = + std::const_pointer_cast(children_); nonConstChildren->push_back(child); } -void ShadowNode::replaceChild(const SharedShadowNode &oldChild, const SharedShadowNode &newChild, int suggestedIndex) { +void ShadowNode::replaceChild( + const SharedShadowNode &oldChild, + const SharedShadowNode &newChild, + int suggestedIndex) { ensureUnsealed(); cloneChildrenIfShared(); - auto nonConstChildren = std::const_pointer_cast(children_); + auto nonConstChildren = + std::const_pointer_cast(children_); if (suggestedIndex != -1 && suggestedIndex < nonConstChildren->size()) { if (nonConstChildren->at(suggestedIndex) == oldChild) { @@ -127,7 +129,8 @@ void ShadowNode::replaceChild(const SharedShadowNode &oldChild, const SharedShad } } - std::replace(nonConstChildren->begin(), nonConstChildren->end(), oldChild, newChild); + std::replace( + nonConstChildren->begin(), nonConstChildren->end(), oldChild, newChild); } void ShadowNode::setLocalData(const SharedLocalData &localData) { @@ -151,14 +154,16 @@ std::string ShadowNode::getDebugName() const { } std::string ShadowNode::getDebugValue() const { - return "r" + folly::to(revision_) + (getSealed() ? "/sealed" : ""); + return "r" + folly::to(revision_) + + (getSealed() ? "/sealed" : ""); } SharedDebugStringConvertibleList ShadowNode::getDebugChildren() const { - auto debugChildren = SharedDebugStringConvertibleList {}; + auto debugChildren = SharedDebugStringConvertibleList{}; for (auto child : *children_) { - auto debugChild = std::dynamic_pointer_cast(child); + auto debugChild = + std::dynamic_pointer_cast(child); if (debugChild) { debugChildren.push_back(debugChild); } @@ -168,11 +173,9 @@ SharedDebugStringConvertibleList ShadowNode::getDebugChildren() const { } SharedDebugStringConvertibleList ShadowNode::getDebugProps() const { - return - props_->getDebugProps() + - SharedDebugStringConvertibleList { - debugStringConvertibleItem("tag", folly::to(tag_)) - }; + return props_->getDebugProps() + + SharedDebugStringConvertibleList{ + debugStringConvertibleItem("tag", folly::to(tag_))}; } #endif diff --git a/ReactCommon/fabric/core/shadownode/ShadowNode.h b/ReactCommon/fabric/core/shadownode/ShadowNode.h index a93cd0b4321..cb50219d70f 100644 --- a/ReactCommon/fabric/core/shadownode/ShadowNode.h +++ b/ReactCommon/fabric/core/shadownode/ShadowNode.h @@ -7,16 +7,16 @@ #pragma once -#include #include +#include #include #include #include #include #include -#include #include +#include namespace facebook { namespace react { @@ -32,16 +32,13 @@ using SharedShadowNodeSharedList = std::shared_ptr; using SharedShadowNodeUnsharedList = std::shared_ptr; using ShadowNodeCloneFunction = std::function; + const ShadowNode &sourceShadowNode, + const ShadowNodeFragment &fragment)>; -class ShadowNode: - public virtual Sealable, - public virtual DebugStringConvertible, - public std::enable_shared_from_this { - -public: +class ShadowNode : public virtual Sealable, + public virtual DebugStringConvertible, + public std::enable_shared_from_this { + public: static SharedShadowNodeSharedList emptySharedShadowNodeSharedList(); #pragma mark - Constructors @@ -50,18 +47,16 @@ public: * Creates a Shadow Node based on fields specified in a `fragment`. */ ShadowNode( - const ShadowNodeFragment &fragment, - const ShadowNodeCloneFunction &cloneFunction - ); + const ShadowNodeFragment &fragment, + const ShadowNodeCloneFunction &cloneFunction); /* * Creates a Shadow Node via cloning given `sourceShadowNode` and * applying fields from given `fragment`. */ ShadowNode( - const ShadowNode &sourceShadowNode, - const ShadowNodeFragment &fragment - ); + const ShadowNode &sourceShadowNode, + const ShadowNodeFragment &fragment); virtual ~ShadowNode() = default; @@ -94,7 +89,10 @@ public: #pragma mark - Mutating Methods void appendChild(const SharedShadowNode &child); - void replaceChild(const SharedShadowNode &oldChild, const SharedShadowNode &newChild, int suggestedIndex = -1); + void replaceChild( + const SharedShadowNode &oldChild, + const SharedShadowNode &newChild, + int suggestedIndex = -1); void clearSourceNode(); /* @@ -112,7 +110,7 @@ public: SharedDebugStringConvertibleList getDebugProps() const override; #endif -protected: + protected: Tag tag_; Tag rootTag_; SharedProps props_; @@ -120,8 +118,7 @@ protected: SharedShadowNodeSharedList children_; SharedLocalData localData_; -private: - + private: /* * Clones the list of children (and creates a new `shared_ptr` to it) if * `childrenAreShared_` flag is `true`. diff --git a/ReactCommon/fabric/core/shadownode/ShadowNodeFragment.h b/ReactCommon/fabric/core/shadownode/ShadowNodeFragment.h index 7a21cd68123..28fe77f1f8d 100644 --- a/ReactCommon/fabric/core/shadownode/ShadowNodeFragment.h +++ b/ReactCommon/fabric/core/shadownode/ShadowNodeFragment.h @@ -31,7 +31,7 @@ struct ShadowNodeFragment { const SharedShadowNodeSharedList &children = nullSharedChildren(); const SharedLocalData &localData = nullLocalData(); -private: + private: static SharedProps &nullSharedProps(); static SharedEventEmitter &nullSharedEventEmitter(); static SharedShadowNodeSharedList &nullSharedChildren(); diff --git a/ReactCommon/fabric/core/tests/ComponentDescriptorTest.cpp b/ReactCommon/fabric/core/tests/ComponentDescriptorTest.cpp index 33c4639f069..8dcd11fccfd 100644 --- a/ReactCommon/fabric/core/tests/ComponentDescriptorTest.cpp +++ b/ReactCommon/fabric/core/tests/ComponentDescriptorTest.cpp @@ -12,19 +12,26 @@ using namespace facebook::react; TEST(ComponentDescriptorTest, createShadowNode) { - SharedComponentDescriptor descriptor = std::make_shared(nullptr); + SharedComponentDescriptor descriptor = + std::make_shared(nullptr); ASSERT_EQ(descriptor->getComponentHandle(), TestShadowNode::Handle()); - ASSERT_STREQ(descriptor->getComponentName().c_str(), TestShadowNode::Name().c_str()); + ASSERT_STREQ( + descriptor->getComponentName().c_str(), TestShadowNode::Name().c_str()); ASSERT_STREQ(descriptor->getComponentName().c_str(), "Test"); RawProps raw; raw["nativeID"] = "abc"; SharedProps props = descriptor->cloneProps(nullptr, raw); - SharedShadowNode node = descriptor->createShadowNode(ShadowNodeFragment {.tag = 9, .rootTag = 1, .props = props, .eventEmitter = descriptor->createEventEmitter(0, 9)}); + SharedShadowNode node = descriptor->createShadowNode( + ShadowNodeFragment{.tag = 9, + .rootTag = 1, + .props = props, + .eventEmitter = descriptor->createEventEmitter(0, 9)}); ASSERT_EQ(node->getComponentHandle(), TestShadowNode::Handle()); - ASSERT_STREQ(node->getComponentName().c_str(), TestShadowNode::Name().c_str()); + ASSERT_STREQ( + node->getComponentName().c_str(), TestShadowNode::Name().c_str()); ASSERT_STREQ(node->getComponentName().c_str(), "Test"); ASSERT_EQ(node->getTag(), 9); ASSERT_EQ(node->getRootTag(), 1); @@ -32,12 +39,17 @@ TEST(ComponentDescriptorTest, createShadowNode) { } TEST(ComponentDescriptorTest, cloneShadowNode) { - SharedComponentDescriptor descriptor = std::make_shared(nullptr); + SharedComponentDescriptor descriptor = + std::make_shared(nullptr); RawProps raw; raw["nativeID"] = "abc"; SharedProps props = descriptor->cloneProps(nullptr, raw); - SharedShadowNode node = descriptor->createShadowNode(ShadowNodeFragment {.tag = 9, .rootTag = 1, .props = props, .eventEmitter = descriptor->createEventEmitter(0, 9)}); + SharedShadowNode node = descriptor->createShadowNode( + ShadowNodeFragment{.tag = 9, + .rootTag = 1, + .props = props, + .eventEmitter = descriptor->createEventEmitter(0, 9)}); SharedShadowNode cloned = descriptor->cloneShadowNode(*node, {}); ASSERT_STREQ(cloned->getComponentName().c_str(), "Test"); @@ -47,14 +59,27 @@ TEST(ComponentDescriptorTest, cloneShadowNode) { } TEST(ComponentDescriptorTest, appendChild) { - SharedComponentDescriptor descriptor = std::make_shared(nullptr); + SharedComponentDescriptor descriptor = + std::make_shared(nullptr); RawProps raw; raw["nativeID"] = "abc"; SharedProps props = descriptor->cloneProps(nullptr, raw); - SharedShadowNode node1 = descriptor->createShadowNode(ShadowNodeFragment {.tag = 1, .rootTag = 1, .props = props, .eventEmitter = descriptor->createEventEmitter(0, 1)}); - SharedShadowNode node2 = descriptor->createShadowNode(ShadowNodeFragment {.tag = 2, .rootTag = 1, .props = props, .eventEmitter = descriptor->createEventEmitter(0, 2)}); - SharedShadowNode node3 = descriptor->createShadowNode(ShadowNodeFragment {.tag = 3, .rootTag = 1, .props = props, .eventEmitter = descriptor->createEventEmitter(0, 3)}); + SharedShadowNode node1 = descriptor->createShadowNode( + ShadowNodeFragment{.tag = 1, + .rootTag = 1, + .props = props, + .eventEmitter = descriptor->createEventEmitter(0, 1)}); + SharedShadowNode node2 = descriptor->createShadowNode( + ShadowNodeFragment{.tag = 2, + .rootTag = 1, + .props = props, + .eventEmitter = descriptor->createEventEmitter(0, 2)}); + SharedShadowNode node3 = descriptor->createShadowNode( + ShadowNodeFragment{.tag = 3, + .rootTag = 1, + .props = props, + .eventEmitter = descriptor->createEventEmitter(0, 3)}); descriptor->appendChild(node1, node2); descriptor->appendChild(node1, node3); diff --git a/ReactCommon/fabric/core/tests/PrimitivesTest.cpp b/ReactCommon/fabric/core/tests/PrimitivesTest.cpp index bf9f8a371c3..fa0495f686e 100644 --- a/ReactCommon/fabric/core/tests/PrimitivesTest.cpp +++ b/ReactCommon/fabric/core/tests/PrimitivesTest.cpp @@ -30,7 +30,8 @@ TEST(SealableTest, handleAssignmentsCorrectly) { Sealable other2; EXPECT_THROW(obj = other2, std::runtime_error); - // It doesn't matter if the other object is also sealed, it's still not allowed. + // It doesn't matter if the other object is also sealed, it's still not + // allowed. other2.seal(); EXPECT_THROW(obj = other2, std::runtime_error); diff --git a/ReactCommon/fabric/core/tests/ShadowNodeTest.cpp b/ReactCommon/fabric/core/tests/ShadowNodeTest.cpp index c4c742fbee3..8caeff77742 100644 --- a/ReactCommon/fabric/core/tests/ShadowNodeTest.cpp +++ b/ReactCommon/fabric/core/tests/ShadowNodeTest.cpp @@ -29,14 +29,12 @@ TEST(ShadowNodeTest, handleProps) { TEST(ShadowNodeTest, handleShadowNodeCreation) { auto node = std::make_shared( - ShadowNodeFragment { - .tag = 9, - .rootTag = 1, - .props = std::make_shared(), - .children = ShadowNode::emptySharedShadowNodeSharedList() - }, - nullptr - ); + ShadowNodeFragment{ + .tag = 9, + .rootTag = 1, + .props = std::make_shared(), + .children = ShadowNode::emptySharedShadowNodeSharedList()}, + nullptr); ASSERT_FALSE(node->getSealed()); ASSERT_STREQ(node->getComponentName().c_str(), "Test"); @@ -54,15 +52,13 @@ TEST(ShadowNodeTest, handleShadowNodeCreation) { TEST(ShadowNodeTest, handleShadowNodeSimpleCloning) { auto node = std::make_shared( - ShadowNodeFragment { - .tag = 9, - .rootTag = 1, - .props = std::make_shared(), - .children = ShadowNode::emptySharedShadowNodeSharedList() - }, - nullptr - ); - auto node2 = std::make_shared(*node, ShadowNodeFragment {}); + ShadowNodeFragment{ + .tag = 9, + .rootTag = 1, + .props = std::make_shared(), + .children = ShadowNode::emptySharedShadowNodeSharedList()}, + nullptr); + auto node2 = std::make_shared(*node, ShadowNodeFragment{}); ASSERT_STREQ(node->getComponentName().c_str(), "Test"); ASSERT_EQ(node->getTag(), 9); @@ -72,9 +68,27 @@ TEST(ShadowNodeTest, handleShadowNodeSimpleCloning) { TEST(ShadowNodeTest, handleShadowNodeMutation) { auto props = std::make_shared(); - auto node1 = std::make_shared(ShadowNodeFragment {.tag = 1, .rootTag = 1, .props = std::make_shared(), .children = ShadowNode::emptySharedShadowNodeSharedList()}, nullptr); - auto node2 = std::make_shared(ShadowNodeFragment {.tag = 2, .rootTag = 1, .props = std::make_shared(), .children = ShadowNode::emptySharedShadowNodeSharedList()}, nullptr); - auto node3 = std::make_shared(ShadowNodeFragment {.tag = 3, .rootTag = 1, .props = std::make_shared(), .children = ShadowNode::emptySharedShadowNodeSharedList()}, nullptr); + auto node1 = std::make_shared( + ShadowNodeFragment{ + .tag = 1, + .rootTag = 1, + .props = std::make_shared(), + .children = ShadowNode::emptySharedShadowNodeSharedList()}, + nullptr); + auto node2 = std::make_shared( + ShadowNodeFragment{ + .tag = 2, + .rootTag = 1, + .props = std::make_shared(), + .children = ShadowNode::emptySharedShadowNodeSharedList()}, + nullptr); + auto node3 = std::make_shared( + ShadowNodeFragment{ + .tag = 3, + .rootTag = 1, + .props = std::make_shared(), + .children = ShadowNode::emptySharedShadowNodeSharedList()}, + nullptr); node1->appendChild(node2); node1->appendChild(node3); @@ -83,7 +97,7 @@ TEST(ShadowNodeTest, handleShadowNodeMutation) { ASSERT_EQ(node1Children.at(0), node2); ASSERT_EQ(node1Children.at(1), node3); - auto node4 = std::make_shared(*node2, ShadowNodeFragment {}); + auto node4 = std::make_shared(*node2, ShadowNodeFragment{}); node1->replaceChild(node2, node4); node1Children = node1->getChildren(); ASSERT_EQ(node1Children.size(), 2); @@ -99,31 +113,32 @@ TEST(ShadowNodeTest, handleShadowNodeMutation) { // No more mutation after sealing. EXPECT_THROW(node4->setLocalData(nullptr), std::runtime_error); - auto node5 = std::make_shared(*node4, ShadowNodeFragment {}); + auto node5 = std::make_shared(*node4, ShadowNodeFragment{}); node5->setLocalData(nullptr); ASSERT_EQ(node5->getLocalData(), nullptr); } TEST(ShadowNodeTest, handleCloneFunction) { - auto firstNode = std::make_shared(ShadowNodeFragment {.tag = 9, .rootTag = 1, .props = std::make_shared(), .children = ShadowNode::emptySharedShadowNodeSharedList()}, nullptr); + auto firstNode = std::make_shared( + ShadowNodeFragment{ + .tag = 9, + .rootTag = 1, + .props = std::make_shared(), + .children = ShadowNode::emptySharedShadowNodeSharedList()}, + nullptr); // The shadow node is not clonable if `cloneFunction` is not provided, ASSERT_DEATH_IF_SUPPORTED(firstNode->clone({}), "cloneFunction_"); auto secondNode = std::make_shared( - ShadowNodeFragment { - .tag = 9, - .rootTag = 1, - .props = std::make_shared(), - .children = ShadowNode::emptySharedShadowNodeSharedList() - }, - [](const ShadowNode &shadowNode, const ShadowNodeFragment &fragment) { - return std::make_shared( - shadowNode, - fragment - ); - } - ); + ShadowNodeFragment{ + .tag = 9, + .rootTag = 1, + .props = std::make_shared(), + .children = ShadowNode::emptySharedShadowNodeSharedList()}, + [](const ShadowNode &shadowNode, const ShadowNodeFragment &fragment) { + return std::make_shared(shadowNode, fragment); + }); auto secondNodeClone = secondNode->clone({}); @@ -131,7 +146,9 @@ TEST(ShadowNodeTest, handleCloneFunction) { ASSERT_NE(secondNode, secondNodeClone); // `secondNodeClone` is an instance of `TestShadowNode`. - ASSERT_NE(std::dynamic_pointer_cast(secondNodeClone), nullptr); + ASSERT_NE( + std::dynamic_pointer_cast(secondNodeClone), + nullptr); // Both nodes have same content. ASSERT_EQ(secondNode->getTag(), secondNodeClone->getTag()); @@ -149,9 +166,27 @@ TEST(ShadowNodeTest, handleLocalData) { auto localDataOver9000 = std::make_shared(); localDataOver9000->setNumber(9001); auto props = std::make_shared(); - auto firstNode = std::make_shared(ShadowNodeFragment {.tag = 9, .rootTag = 1, .props = props, .children = ShadowNode::emptySharedShadowNodeSharedList()}, nullptr); - auto secondNode = std::make_shared(ShadowNodeFragment {.tag = 9, .rootTag = 1, .props = props, .children = ShadowNode::emptySharedShadowNodeSharedList()}, nullptr); - auto thirdNode = std::make_shared(ShadowNodeFragment {.tag = 9, .rootTag = 1, .props = props, .children = ShadowNode::emptySharedShadowNodeSharedList()}, nullptr); + auto firstNode = std::make_shared( + ShadowNodeFragment{ + .tag = 9, + .rootTag = 1, + .props = props, + .children = ShadowNode::emptySharedShadowNodeSharedList()}, + nullptr); + auto secondNode = std::make_shared( + ShadowNodeFragment{ + .tag = 9, + .rootTag = 1, + .props = props, + .children = ShadowNode::emptySharedShadowNodeSharedList()}, + nullptr); + auto thirdNode = std::make_shared( + ShadowNodeFragment{ + .tag = 9, + .rootTag = 1, + .props = props, + .children = ShadowNode::emptySharedShadowNodeSharedList()}, + nullptr); firstNode->setLocalData(localData42); secondNode->setLocalData(localData42); diff --git a/ReactCommon/fabric/core/tests/TestComponent.h b/ReactCommon/fabric/core/tests/TestComponent.h index 8b1bdd5ec0e..c25e7864466 100644 --- a/ReactCommon/fabric/core/tests/TestComponent.h +++ b/ReactCommon/fabric/core/tests/TestComponent.h @@ -18,12 +18,12 @@ using namespace facebook::react; /** - * This defines a set of TestComponent classes: Props, ShadowNode, ComponentDescriptor. - * To be used for testing purpose. + * This defines a set of TestComponent classes: Props, ShadowNode, + * ComponentDescriptor. To be used for testing purpose. */ -class TestLocalData: public LocalData { -public: +class TestLocalData : public LocalData { + public: void setNumber(const int &number) { number_ = number; } @@ -32,28 +32,28 @@ public: return number_; } -private: - int number_ {0}; + private: + int number_{0}; }; static const char TestComponentName[] = "Test"; class TestProps : public Props { -public: + public: using Props::Props; - TestProps(): - Props(Props(), {{"nativeID", "testNativeID"}}) {} + TestProps() : Props(Props(), {{"nativeID", "testNativeID"}}) {} }; using SharedTestProps = std::shared_ptr; class TestShadowNode; using SharedTestShadowNode = std::shared_ptr; class TestShadowNode : public ConcreteShadowNode { -public: + public: using ConcreteShadowNode::ConcreteShadowNode; }; -class TestComponentDescriptor: public ConcreteComponentDescriptor { -public: +class TestComponentDescriptor + : public ConcreteComponentDescriptor { + public: using ConcreteComponentDescriptor::ConcreteComponentDescriptor; }; diff --git a/ReactCommon/fabric/debug/DebugStringConvertible.cpp b/ReactCommon/fabric/debug/DebugStringConvertible.cpp index 3deadc22608..20c182c4833 100644 --- a/ReactCommon/fabric/debug/DebugStringConvertible.cpp +++ b/ReactCommon/fabric/debug/DebugStringConvertible.cpp @@ -12,7 +12,9 @@ namespace react { #if RN_DEBUG_STRING_CONVERTIBLE -std::string DebugStringConvertible::getDebugChildrenDescription(DebugStringConvertibleOptions options, int depth) const { +std::string DebugStringConvertible::getDebugChildrenDescription( + DebugStringConvertibleOptions options, + int depth) const { if (depth >= options.maximumDepth) { return ""; } @@ -30,7 +32,9 @@ std::string DebugStringConvertible::getDebugChildrenDescription(DebugStringConve return childrenString; } -std::string DebugStringConvertible::getDebugPropsDescription(DebugStringConvertibleOptions options, int depth) const { +std::string DebugStringConvertible::getDebugPropsDescription( + DebugStringConvertibleOptions options, + int depth) const { if (depth >= options.maximumDepth) { return ""; } @@ -45,8 +49,10 @@ std::string DebugStringConvertible::getDebugPropsDescription(DebugStringConverti auto name = prop->getDebugName(); auto value = prop->getDebugValue(); auto children = prop->getDebugPropsDescription(options, depth + 1); - 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()) { @@ -57,19 +63,23 @@ std::string DebugStringConvertible::getDebugPropsDescription(DebugStringConverti return propsString; } -std::string DebugStringConvertible::getDebugDescription(DebugStringConvertibleOptions options, int depth) const { +std::string DebugStringConvertible::getDebugDescription( + DebugStringConvertibleOptions options, + int depth) const { auto nameString = getDebugName(); auto valueString = getDebugValue(); auto childrenString = getDebugChildrenDescription(options, depth); auto propsString = getDebugPropsDescription(options, depth); - auto leading = options.format ? std::string(depth * 2, ' ') : std::string {""}; - auto trailing = options.format ? std::string {"\n"} : std::string {""}; + auto leading = options.format ? std::string(depth * 2, ' ') : std::string{""}; + auto trailing = options.format ? std::string{"\n"} : std::string{""}; return leading + "<" + nameString + - (valueString.empty() ? "" : "=" + valueString) + - (propsString.empty() ? "" : " " + propsString) + - (childrenString.empty() ? "/>" + trailing : ">" + trailing + childrenString + leading + "" + trailing); + (valueString.empty() ? "" : "=" + valueString) + + (propsString.empty() ? "" : " " + propsString) + + (childrenString.empty() ? "/>" + trailing + : ">" + trailing + childrenString + leading + + "" + trailing); } std::string DebugStringConvertible::getDebugName() const { @@ -80,7 +90,8 @@ std::string DebugStringConvertible::getDebugValue() const { return ""; } -SharedDebugStringConvertibleList DebugStringConvertible::getDebugChildren() const { +SharedDebugStringConvertibleList DebugStringConvertible::getDebugChildren() + const { return SharedDebugStringConvertibleList(); } diff --git a/ReactCommon/fabric/debug/DebugStringConvertible.h b/ReactCommon/fabric/debug/DebugStringConvertible.h index dffd501986e..65010551250 100644 --- a/ReactCommon/fabric/debug/DebugStringConvertible.h +++ b/ReactCommon/fabric/debug/DebugStringConvertible.h @@ -7,8 +7,8 @@ #pragma once -#include #include +#include #include namespace facebook { @@ -22,12 +22,14 @@ namespace 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}; - int maximumDepth {INT_MAX}; + bool format{true}; + int maximumDepth{INT_MAX}; }; // Abstract class describes conformance to DebugStringConvertible concept @@ -35,8 +37,7 @@ struct DebugStringConvertibleOptions { // Use this as a base class for providing a debugging textual representation // of your class. class DebugStringConvertible { - -public: + public: virtual ~DebugStringConvertible() = default; // Returns a name of the object. @@ -60,12 +61,18 @@ public: // 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 = {}, int depth = 0) const; + virtual std::string getDebugDescription( + DebugStringConvertibleOptions options = {}, + int depth = 0) const; // Do same as `getDebugDescription` but return only *children* and // *properties* parts (which are used in `getDebugDescription`). - virtual std::string getDebugPropsDescription(DebugStringConvertibleOptions options = {}, int depth = 0) const; - virtual std::string getDebugChildrenDescription(DebugStringConvertibleOptions options = {}, int depth = 0) const; + virtual std::string getDebugPropsDescription( + DebugStringConvertibleOptions options = {}, + int depth = 0) const; + virtual std::string getDebugChildrenDescription( + DebugStringConvertibleOptions options = {}, + int depth = 0) const; }; #else diff --git a/ReactCommon/fabric/debug/DebugStringConvertibleItem.cpp b/ReactCommon/fabric/debug/DebugStringConvertibleItem.cpp index 9b686eefbe2..93961d06110 100644 --- a/ReactCommon/fabric/debug/DebugStringConvertibleItem.cpp +++ b/ReactCommon/fabric/debug/DebugStringConvertibleItem.cpp @@ -13,15 +13,11 @@ namespace react { #if RN_DEBUG_STRING_CONVERTIBLE DebugStringConvertibleItem::DebugStringConvertibleItem( - const std::string &name, - const std::string &value, - const SharedDebugStringConvertibleList &props, - const SharedDebugStringConvertibleList &children -): - name_(name), - value_(value), - props_(props), - children_(children) {} + const std::string &name, + const std::string &value, + const SharedDebugStringConvertibleList &props, + const SharedDebugStringConvertibleList &children) + : name_(name), value_(value), props_(props), children_(children) {} std::string DebugStringConvertibleItem::getDebugName() const { return name_; @@ -31,11 +27,13 @@ std::string DebugStringConvertibleItem::getDebugValue() const { return value_; } -SharedDebugStringConvertibleList DebugStringConvertibleItem::getDebugProps() const { +SharedDebugStringConvertibleList DebugStringConvertibleItem::getDebugProps() + const { return props_; } -SharedDebugStringConvertibleList DebugStringConvertibleItem::getDebugChildren() const { +SharedDebugStringConvertibleList DebugStringConvertibleItem::getDebugChildren() + const { return children_; } diff --git a/ReactCommon/fabric/debug/DebugStringConvertibleItem.h b/ReactCommon/fabric/debug/DebugStringConvertibleItem.h index 6680683d364..edb01c4ea1d 100644 --- a/ReactCommon/fabric/debug/DebugStringConvertibleItem.h +++ b/ReactCommon/fabric/debug/DebugStringConvertibleItem.h @@ -19,26 +19,23 @@ namespace react { // Trivial implementation of `DebugStringConvertible` abstract class // with a stored output; useful for assembling `DebugStringConvertible` values // in custom implementations of `getDebugChildren` and `getDebugProps`. -class DebugStringConvertibleItem: - public DebugStringConvertible { - -public: +class DebugStringConvertibleItem : public DebugStringConvertible { + public: DebugStringConvertibleItem() = default; DebugStringConvertibleItem(const DebugStringConvertibleItem &item) = default; DebugStringConvertibleItem( - const std::string &name = "", - const std::string &value = "", - const SharedDebugStringConvertibleList &props = {}, - const SharedDebugStringConvertibleList &children = {} - ); + const std::string &name = "", + const std::string &value = "", + const SharedDebugStringConvertibleList &props = {}, + const SharedDebugStringConvertibleList &children = {}); std::string getDebugName() const override; std::string getDebugValue() const override; SharedDebugStringConvertibleList getDebugChildren() const override; SharedDebugStringConvertibleList getDebugProps() const override; -private: + private: std::string name_; std::string value_; SharedDebugStringConvertibleList props_; diff --git a/ReactCommon/fabric/debug/debugStringConvertibleUtils.h b/ReactCommon/fabric/debug/debugStringConvertibleUtils.h index d82f079175c..928f267f649 100644 --- a/ReactCommon/fabric/debug/debugStringConvertibleUtils.h +++ b/ReactCommon/fabric/debug/debugStringConvertibleUtils.h @@ -7,9 +7,9 @@ #pragma once -#include #include #include +#include #include #include @@ -22,14 +22,25 @@ namespace react { #if RN_DEBUG_STRING_CONVERTIBLE -inline std::string toString(const std::string &value) { return value; } -inline std::string toString(const int &value) { return folly::to(value); } -inline std::string toString(const bool &value) { return folly::to(value); } -inline std::string toString(const float &value) { return folly::to(value); } -inline std::string toString(const double &value) { return folly::to(value); } +inline std::string toString(const std::string &value) { + return value; +} +inline std::string toString(const int &value) { + return folly::to(value); +} +inline std::string toString(const bool &value) { + return folly::to(value); +} +inline std::string toString(const float &value) { + return folly::to(value); +} +inline std::string toString(const double &value) { + return folly::to(value); +} template -inline SharedDebugStringConvertible debugStringConvertibleItem(std::string name, T value, T defaultValue = {}) { +inline SharedDebugStringConvertible +debugStringConvertibleItem(std::string name, T value, T defaultValue = {}) { if (value == defaultValue) { return nullptr; } @@ -38,23 +49,33 @@ inline SharedDebugStringConvertible debugStringConvertibleItem(std::string name, } template -inline SharedDebugStringConvertible debugStringConvertibleItem(std::string name, folly::Optional value, T defaultValue = {}) { +inline SharedDebugStringConvertible debugStringConvertibleItem( + std::string name, + folly::Optional value, + T defaultValue = {}) { if (!value.hasValue()) { 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) { - auto result = SharedDebugStringConvertibleList {}; +inline SharedDebugStringConvertibleList operator+( + 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(std::string name, DebugStringConvertible value, std::string defaultValue) { - return debugStringConvertibleItem(name, value.getDebugDescription(), defaultValue); +inline SharedDebugStringConvertible debugStringConvertibleItem( + std::string name, + DebugStringConvertible value, + std::string defaultValue) { + return debugStringConvertibleItem( + name, value.getDebugDescription(), defaultValue); } #endif diff --git a/ReactCommon/fabric/debug/tests/DebugStringConvertibleTest.cpp b/ReactCommon/fabric/debug/tests/DebugStringConvertibleTest.cpp index eb963368888..b8175c3a147 100644 --- a/ReactCommon/fabric/debug/tests/DebugStringConvertibleTest.cpp +++ b/ReactCommon/fabric/debug/tests/DebugStringConvertibleTest.cpp @@ -14,7 +14,8 @@ using namespace facebook::react; TEST(DebugStringConvertibleTest, handleSimpleNode) { SharedDebugStringConvertibleList empty; - auto item = std::make_shared("View", "hello", empty, empty); + auto item = std::make_shared( + "View", "hello", empty, empty); ASSERT_STREQ(item->getDebugName().c_str(), "View"); ASSERT_STREQ(item->getDebugValue().c_str(), "hello"); @@ -24,9 +25,9 @@ TEST(DebugStringConvertibleTest, handleSimpleNode) { TEST(DebugStringConvertibleTest, handleSimpleNodeWithProps) { SharedDebugStringConvertibleList empty; SharedDebugStringConvertibleList props = { - std::make_shared("x", "1", empty, empty) - }; - auto item = std::make_shared("View", "hello", props, empty); + std::make_shared("x", "1", empty, empty)}; + auto item = std::make_shared( + "View", "hello", props, empty); ASSERT_STREQ(item->getDebugName().c_str(), "View"); ASSERT_STREQ(item->getDebugValue().c_str(), "hello"); @@ -36,42 +37,48 @@ TEST(DebugStringConvertibleTest, handleSimpleNodeWithProps) { TEST(DebugStringConvertibleTest, handleSimpleNodeWithChildren) { SharedDebugStringConvertibleList empty; SharedDebugStringConvertibleList children = { - std::make_shared("Child", "a", empty, empty) - }; - auto item = std::make_shared("View", "hello", empty, children); + std::make_shared("Child", "a", empty, empty)}; + auto item = std::make_shared( + "View", "hello", empty, children); ASSERT_STREQ(item->getDebugName().c_str(), "View"); ASSERT_STREQ(item->getDebugValue().c_str(), "hello"); - ASSERT_STREQ(item->getDebugDescription().c_str(), "\n \n\n"); + ASSERT_STREQ( + item->getDebugDescription().c_str(), + "\n \n\n"); } TEST(DebugStringConvertibleTest, handleNestedNode) { SharedDebugStringConvertibleList empty; SharedDebugStringConvertibleList props = { - std::make_shared("x", "1", empty, empty) - }; + std::make_shared("x", "1", empty, empty)}; SharedDebugStringConvertibleList children = { - std::make_shared("Child", "a", props, empty) - }; - auto item = std::make_shared("View", "hello", props, children); + std::make_shared("Child", "a", props, empty)}; + auto item = std::make_shared( + "View", "hello", props, children); ASSERT_STREQ(item->getDebugName().c_str(), "View"); ASSERT_STREQ(item->getDebugValue().c_str(), "hello"); - ASSERT_STREQ(item->getDebugDescription().c_str(), "\n \n\n"); + ASSERT_STREQ( + item->getDebugDescription().c_str(), + "\n \n\n"); } TEST(DebugStringConvertibleTest, handleNodeWithComplexProps) { SharedDebugStringConvertibleList empty; SharedDebugStringConvertibleList subProps = { - std::make_shared("height", "100", empty, empty), - std::make_shared("width", "200", empty, empty) - }; + std::make_shared( + "height", "100", empty, empty), + std::make_shared( + "width", "200", empty, empty)}; SharedDebugStringConvertibleList props = { - std::make_shared("x", "1", subProps, empty) - }; - auto item = std::make_shared("View", "hello", props, empty); + std::make_shared("x", "1", subProps, empty)}; + auto item = std::make_shared( + "View", "hello", props, empty); ASSERT_STREQ(item->getDebugName().c_str(), "View"); ASSERT_STREQ(item->getDebugValue().c_str(), "hello"); - ASSERT_STREQ(item->getDebugDescription().c_str(), "\n"); + ASSERT_STREQ( + item->getDebugDescription().c_str(), + "\n"); } diff --git a/ReactCommon/fabric/events/BatchedEventQueue.h b/ReactCommon/fabric/events/BatchedEventQueue.h index 4f0778dfdf6..da6fbf3b010 100644 --- a/ReactCommon/fabric/events/BatchedEventQueue.h +++ b/ReactCommon/fabric/events/BatchedEventQueue.h @@ -16,9 +16,8 @@ namespace react { * Event Queue that dispatches event in batches synchronizing them with * an Event Beat. */ -class BatchedEventQueue final: public EventQueue { - -public: +class BatchedEventQueue final : public EventQueue { + public: using EventQueue::EventQueue; void enqueueEvent(const RawEvent &rawEvent) const override; diff --git a/ReactCommon/fabric/events/EventBeat.h b/ReactCommon/fabric/events/EventBeat.h index 14eababdd24..7a991a69ea8 100644 --- a/ReactCommon/fabric/events/EventBeat.h +++ b/ReactCommon/fabric/events/EventBeat.h @@ -15,12 +15,11 @@ namespace facebook { namespace react { /* - * Event Beat serves two interleaving purposes: synchronization of event queues and - * ensuring that event dispatching happens on propper threads. + * Event Beat serves two interleaving purposes: synchronization of event queues + * and ensuring that event dispatching happens on propper threads. */ class EventBeat { - -public: + public: virtual ~EventBeat() = default; using BeatCallback = std::function; @@ -58,7 +57,7 @@ public: */ void setFailCallback(const FailCallback &failCallback); -protected: + protected: /* * Should be used by sublasses to send a beat. * Receiver might ignore the call if a beat was not requested. @@ -67,7 +66,7 @@ protected: BeatCallback beatCallback_; FailCallback failCallback_; - mutable std::atomic isRequested_ {false}; + mutable std::atomic isRequested_{false}; }; using EventBeatFactory = std::function()>; diff --git a/ReactCommon/fabric/events/EventBeatBasedExecutor.cpp b/ReactCommon/fabric/events/EventBeatBasedExecutor.cpp index eaef666cfc5..d31f620de2a 100644 --- a/ReactCommon/fabric/events/EventBeatBasedExecutor.cpp +++ b/ReactCommon/fabric/events/EventBeatBasedExecutor.cpp @@ -16,11 +16,13 @@ namespace react { using Mode = EventBeatBasedExecutor::Mode; -EventBeatBasedExecutor::EventBeatBasedExecutor(std::unique_ptr eventBeat): - eventBeat_(std::move(eventBeat)) { - - eventBeat_->setBeatCallback(std::bind(&EventBeatBasedExecutor::onBeat, this, true)); - eventBeat_->setFailCallback(std::bind(&EventBeatBasedExecutor::onBeat, this, false)); +EventBeatBasedExecutor::EventBeatBasedExecutor( + std::unique_ptr eventBeat) + : eventBeat_(std::move(eventBeat)) { + eventBeat_->setBeatCallback( + std::bind(&EventBeatBasedExecutor::onBeat, this, true)); + eventBeat_->setFailCallback( + std::bind(&EventBeatBasedExecutor::onBeat, this, false)); } void EventBeatBasedExecutor::operator()(Routine routine, Mode mode) const { @@ -32,12 +34,8 @@ void EventBeatBasedExecutor::operator()(Routine routine, Mode mode) const { std::mutex mutex; mutex.lock(); - execute({ - .routine = std::move(routine), - .callback = [&mutex]() { - mutex.unlock(); - } - }); + execute({.routine = std::move(routine), + .callback = [&mutex]() { mutex.unlock(); }}); mutex.lock(); } diff --git a/ReactCommon/fabric/events/EventBeatBasedExecutor.h b/ReactCommon/fabric/events/EventBeatBasedExecutor.h index 52e69026e5c..80a616891d5 100644 --- a/ReactCommon/fabric/events/EventBeatBasedExecutor.h +++ b/ReactCommon/fabric/events/EventBeatBasedExecutor.h @@ -20,8 +20,7 @@ namespace react { * General purpose executor that uses EventBeat to ensure proper threading. */ class EventBeatBasedExecutor { - -public: + public: using Routine = std::function; using Callback = std::function; @@ -30,10 +29,7 @@ public: Callback callback; }; - enum class Mode { - Synchronous, - Asynchronous - }; + enum class Mode { Synchronous, Asynchronous }; EventBeatBasedExecutor(std::unique_ptr eventBeat); @@ -42,7 +38,7 @@ public: */ void operator()(Routine routine, Mode mode = Mode::Asynchronous) const; -private: + private: void onBeat(bool success = true) const; void execute(Task task) const; diff --git a/ReactCommon/fabric/events/EventDispatcher.cpp b/ReactCommon/fabric/events/EventDispatcher.cpp index 08374f7f632..737b8a7a91d 100644 --- a/ReactCommon/fabric/events/EventDispatcher.cpp +++ b/ReactCommon/fabric/events/EventDispatcher.cpp @@ -7,8 +7,8 @@ #include "EventDispatcher.h" -#include "UnbatchedEventQueue.h" #include "BatchedEventQueue.h" +#include "UnbatchedEventQueue.h" #define REACT_FABRIC_SYNC_EVENT_DISPATCHING_DISABLED @@ -16,31 +16,33 @@ namespace facebook { namespace react { EventDispatcher::EventDispatcher( - const EventPipe &eventPipe, - const EventBeatFactory &synchonousEventBeatFactory, - const EventBeatFactory &asynchonousEventBeatFactory -) { + const EventPipe &eventPipe, + const EventBeatFactory &synchonousEventBeatFactory, + const EventBeatFactory &asynchonousEventBeatFactory) { // Synchronous/Unbatched eventQueues_[(int)EventPriority::SynchronousUnbatched] = - std::make_unique(eventPipe, synchonousEventBeatFactory()); + std::make_unique( + eventPipe, synchonousEventBeatFactory()); // Synchronous/Batched eventQueues_[(int)EventPriority::SynchronousBatched] = - std::make_unique(eventPipe, synchonousEventBeatFactory()); + std::make_unique( + eventPipe, synchonousEventBeatFactory()); // Asynchronous/Unbatched eventQueues_[(int)EventPriority::AsynchronousUnbatched] = - std::make_unique(eventPipe, asynchonousEventBeatFactory()); + std::make_unique( + eventPipe, asynchonousEventBeatFactory()); // Asynchronous/Batched eventQueues_[(int)EventPriority::AsynchronousBatched] = - std::make_unique(eventPipe, asynchonousEventBeatFactory()); + std::make_unique( + eventPipe, asynchonousEventBeatFactory()); } void EventDispatcher::dispatchEvent( - const RawEvent &rawEvent, - EventPriority priority -) const { + const RawEvent &rawEvent, + EventPriority priority) const { #ifdef REACT_FABRIC_SYNC_EVENT_DISPATCHING_DISABLED // Synchronous dispatch works, but JavaScript interop layer does not have // proper synchonization yet and it crashes. diff --git a/ReactCommon/fabric/events/EventDispatcher.h b/ReactCommon/fabric/events/EventDispatcher.h index 9f409f3b649..4a89c9d2234 100644 --- a/ReactCommon/fabric/events/EventDispatcher.h +++ b/ReactCommon/fabric/events/EventDispatcher.h @@ -10,8 +10,8 @@ #include #include -#include #include +#include namespace facebook { namespace react { @@ -25,23 +25,18 @@ using WeakEventDispatcher = std::weak_ptr; * Particular `EventEmitter` clases use this for sending events. */ class EventDispatcher { - -public: + public: EventDispatcher( - const EventPipe &eventPipe, - const EventBeatFactory &synchonousEventBeatFactory, - const EventBeatFactory &asynchonousEventBeatFactory - ); + const EventPipe &eventPipe, + const EventBeatFactory &synchonousEventBeatFactory, + const EventBeatFactory &asynchonousEventBeatFactory); /* * Dispatches a raw event with given priority using event-delivery pipe. */ - void dispatchEvent( - const RawEvent &rawEvent, - EventPriority priority - ) const; + void dispatchEvent(const RawEvent &rawEvent, EventPriority priority) const; -private: + private: std::array, 4> eventQueues_; }; diff --git a/ReactCommon/fabric/events/EventEmitter.cpp b/ReactCommon/fabric/events/EventEmitter.cpp index 339031db4fa..271845db2bc 100644 --- a/ReactCommon/fabric/events/EventEmitter.cpp +++ b/ReactCommon/fabric/events/EventEmitter.cpp @@ -34,19 +34,17 @@ std::recursive_mutex &EventEmitter::DispatchMutex() { } EventEmitter::EventEmitter( - SharedEventTarget eventTarget, - Tag tag, - WeakEventDispatcher eventDispatcher -): - eventTarget_(std::move(eventTarget)), - tag_(tag), - eventDispatcher_(std::move(eventDispatcher)) {} + SharedEventTarget eventTarget, + Tag tag, + WeakEventDispatcher eventDispatcher) + : eventTarget_(std::move(eventTarget)), + tag_(tag), + eventDispatcher_(std::move(eventDispatcher)) {} void EventEmitter::dispatchEvent( - const std::string &type, - const folly::dynamic &payload, - const EventPriority &priority -) const { + const std::string &type, + const folly::dynamic &payload, + const EventPriority &priority) const { auto eventDispatcher = eventDispatcher_.lock(); if (!eventDispatcher) { return; @@ -58,13 +56,8 @@ void EventEmitter::dispatchEvent( extendedPayload.merge_patch(payload); eventDispatcher->dispatchEvent( - RawEvent( - normalizeEventType(type), - extendedPayload, - eventTarget_ - ), - priority - ); + RawEvent(normalizeEventType(type), extendedPayload, eventTarget_), + priority); } void EventEmitter::setEnabled(bool enabled) const { diff --git a/ReactCommon/fabric/events/EventEmitter.h b/ReactCommon/fabric/events/EventEmitter.h index c9a25da7d34..5126a40f023 100644 --- a/ReactCommon/fabric/events/EventEmitter.h +++ b/ReactCommon/fabric/events/EventEmitter.h @@ -9,9 +9,9 @@ #include #include -#include #include #include +#include namespace facebook { namespace react { @@ -23,32 +23,32 @@ using SharedEventEmitter = std::shared_ptr; /* * Base class for all particular typed event handlers. * Stores a pointer to `EventTarget` identifying a particular component and - * a weak pointer to `EventDispatcher` which is responsible for delivering the event. + * a weak pointer to `EventDispatcher` which is responsible for delivering the + * event. * - * Note: Retaining an `EventTarget` does *not* guarantee that actual event target - * exists and/or valid in JavaScript realm. The `EventTarget` retains an `EventTargetWrapper` - * which wraps JavaScript object in `unsafe-unretained` manner. Retaining - * the `EventTarget` *does* indicate that we can use that to get an actual - * JavaScript object from that in the future *ensuring safety beforehand somehow*; - * JSI maintains `WeakObject` object as long as we retain the `EventTarget`. - * All `EventTarget` instances must be deallocated before stopping JavaScript machine. + * Note: Retaining an `EventTarget` does *not* guarantee that actual event + * target exists and/or valid in JavaScript realm. The `EventTarget` retains an + * `EventTargetWrapper` which wraps JavaScript object in `unsafe-unretained` + * manner. Retaining the `EventTarget` *does* indicate that we can use that to + * get an actual JavaScript object from that in the future *ensuring safety + * beforehand somehow*; JSI maintains `WeakObject` object as long as we retain + * the `EventTarget`. All `EventTarget` instances must be deallocated before + * stopping JavaScript machine. */ class EventEmitter { - /* * We have to repeat `Tag` type definition here because `events` module does * not depend on `core` module (and should not). */ using Tag = int32_t; -public: + public: static std::recursive_mutex &DispatchMutex(); EventEmitter( - SharedEventTarget eventTarget, - Tag tag, - WeakEventDispatcher eventDispatcher - ); + SharedEventTarget eventTarget, + Tag tag, + WeakEventDispatcher eventDispatcher); virtual ~EventEmitter() = default; @@ -61,11 +61,11 @@ public: void setEnabled(bool enabled) const; bool getEnabled() const; - protected: - + protected: #ifdef ANDROID -// We need this temporarily due to lack of Java-counterparts for particular subclasses. -public: + // We need this temporarily due to lack of Java-counterparts for particular + // subclasses. + public: #endif /* @@ -73,12 +73,11 @@ public: * Is used by particular subclasses only. */ void dispatchEvent( - const std::string &type, - const folly::dynamic &payload = folly::dynamic::object(), - const EventPriority &priority = EventPriority::AsynchronousBatched - ) const; + const std::string &type, + const folly::dynamic &payload = folly::dynamic::object(), + const EventPriority &priority = EventPriority::AsynchronousBatched) const; -private: + private: mutable SharedEventTarget eventTarget_; Tag tag_; WeakEventDispatcher eventDispatcher_; diff --git a/ReactCommon/fabric/events/EventQueue.cpp b/ReactCommon/fabric/events/EventQueue.cpp index 85c34d01373..e34bfd92560 100644 --- a/ReactCommon/fabric/events/EventQueue.cpp +++ b/ReactCommon/fabric/events/EventQueue.cpp @@ -12,11 +12,12 @@ namespace facebook { namespace react { -EventQueue::EventQueue(EventPipe eventPipe, std::unique_ptr eventBeat): - eventPipe_(std::move(eventPipe)), - eventBeat_(std::move(eventBeat)) { - eventBeat_->setBeatCallback(std::bind(&EventQueue::onBeat, this)); - } +EventQueue::EventQueue( + EventPipe eventPipe, + std::unique_ptr eventBeat) + : eventPipe_(std::move(eventPipe)), eventBeat_(std::move(eventBeat)) { + eventBeat_->setBeatCallback(std::bind(&EventQueue::onBeat, this)); +} void EventQueue::enqueueEvent(const RawEvent &rawEvent) const { std::lock_guard lock(queueMutex_); @@ -41,11 +42,7 @@ void EventQueue::onBeat() const { std::lock_guard lock(EventEmitter::DispatchMutex()); for (const auto &event : queue) { - eventPipe_( - event.eventTarget.lock().get(), - event.type, - event.payload - ); + eventPipe_(event.eventTarget.lock().get(), event.type, event.payload); } } } diff --git a/ReactCommon/fabric/events/EventQueue.h b/ReactCommon/fabric/events/EventQueue.h index c10a989d71f..152937c8337 100644 --- a/ReactCommon/fabric/events/EventQueue.h +++ b/ReactCommon/fabric/events/EventQueue.h @@ -12,8 +12,8 @@ #include #include -#include #include +#include namespace facebook { namespace react { @@ -23,8 +23,7 @@ namespace react { * using given Event Pipe. */ class EventQueue { - -public: + public: EventQueue(EventPipe eventPipe, std::unique_ptr eventBeat); virtual ~EventQueue() = default; @@ -34,13 +33,13 @@ public: */ virtual void enqueueEvent(const RawEvent &rawEvent) const; -protected: - + protected: void onBeat() const; const EventPipe eventPipe_; const std::unique_ptr eventBeat_; - mutable std::vector queue_; // Thread-safe, protected by `queueMutex_`. + mutable std::vector + queue_; // Thread-safe, protected by `queueMutex_`. mutable std::mutex queueMutex_; }; diff --git a/ReactCommon/fabric/events/RawEvent.cpp b/ReactCommon/fabric/events/RawEvent.cpp index 7dd65f00fcf..e73d06dcdc8 100644 --- a/ReactCommon/fabric/events/RawEvent.cpp +++ b/ReactCommon/fabric/events/RawEvent.cpp @@ -11,13 +11,12 @@ namespace facebook { namespace react { RawEvent::RawEvent( - std::string type, - folly::dynamic payload, - WeakEventTarget eventTarget -): - type(std::move(type)), - payload(std::move(payload)), - eventTarget(std::move(eventTarget)) {} + std::string type, + folly::dynamic payload, + WeakEventTarget eventTarget) + : type(std::move(type)), + payload(std::move(payload)), + eventTarget(std::move(eventTarget)) {} } // namespace react } // namespace facebook diff --git a/ReactCommon/fabric/events/RawEvent.h b/ReactCommon/fabric/events/RawEvent.h index 67d85c6f494..ecb022af6e4 100644 --- a/ReactCommon/fabric/events/RawEvent.h +++ b/ReactCommon/fabric/events/RawEvent.h @@ -8,8 +8,8 @@ #include -#include #include +#include namespace facebook { namespace react { @@ -18,13 +18,11 @@ namespace react { * Represents ready-to-dispatch event object. */ class RawEvent { - -public: + public: RawEvent( - std::string type, - folly::dynamic payload, - WeakEventTarget eventTarget - ); + std::string type, + folly::dynamic payload, + WeakEventTarget eventTarget); const std::string type; const folly::dynamic payload; diff --git a/ReactCommon/fabric/events/UnbatchedEventQueue.h b/ReactCommon/fabric/events/UnbatchedEventQueue.h index f1e08949c66..06c4a14de50 100644 --- a/ReactCommon/fabric/events/UnbatchedEventQueue.h +++ b/ReactCommon/fabric/events/UnbatchedEventQueue.h @@ -16,14 +16,12 @@ namespace react { * Event Queue that dispatches events as granular as possible without waiting * for the next beat. */ -class UnbatchedEventQueue final: public EventQueue { - -public: +class UnbatchedEventQueue final : public EventQueue { + public: using EventQueue::EventQueue; void enqueueEvent(const RawEvent &rawEvent) const override; }; - } // namespace react } // namespace facebook diff --git a/ReactCommon/fabric/events/primitives.h b/ReactCommon/fabric/events/primitives.h index c13a6a8fe77..9428f446e2f 100644 --- a/ReactCommon/fabric/events/primitives.h +++ b/ReactCommon/fabric/events/primitives.h @@ -12,7 +12,7 @@ namespace facebook { namespace react { -enum class EventPriority: int { +enum class EventPriority : int { SynchronousUnbatched, SynchronousBatched, AsynchronousUnbatched, @@ -25,24 +25,31 @@ enum class EventPriority: int { }; /* - * We need this types only to ensure type-safety when we deal with them. Conceptually, - * they are opaque pointers to some types that derived from those classes. + * We need this types only to ensure type-safety when we deal with them. + * Conceptually, they are opaque pointers to some types that derived from those + * classes. * * `EventHandler` is managed as a `unique_ptr`, so it must have a *virtual* * destructor to allow proper deallocation having only a pointer * to the base (`EventHandler`) class. * - * `EventTarget` is managed as a `shared_ptr`, so it does not need to have a virtual - * destructor because `shared_ptr` stores a pointer to destructor inside. + * `EventTarget` is managed as a `shared_ptr`, so it does not need to have a + * virtual destructor because `shared_ptr` stores a pointer to destructor + * inside. */ -struct EventHandler { virtual ~EventHandler() = default; }; +struct EventHandler { + virtual ~EventHandler() = default; +}; using UniqueEventHandler = std::unique_ptr; struct EventTarget {}; using SharedEventTarget = std::shared_ptr; using WeakEventTarget = std::weak_ptr; -using EventPipe = std::function; +using EventPipe = std::function; } // namespace react } // namespace facebook diff --git a/ReactCommon/fabric/imagemanager/platform/ios/ImageManager.mm b/ReactCommon/fabric/imagemanager/platform/ios/ImageManager.mm index 6b870467773..62255d9bdc0 100644 --- a/ReactCommon/fabric/imagemanager/platform/ios/ImageManager.mm +++ b/ReactCommon/fabric/imagemanager/platform/ios/ImageManager.mm @@ -15,7 +15,9 @@ namespace facebook { namespace react { ImageManager::ImageManager(void *platformSpecificCounterpart) { - self_ = (__bridge_retained void *)[[RCTImageManager alloc] initWithImageLoader:(__bridge RCTImageLoader *)platformSpecificCounterpart]; + self_ = (__bridge_retained void *)[[RCTImageManager alloc] + initWithImageLoader:(__bridge RCTImageLoader *) + platformSpecificCounterpart]; } ImageManager::~ImageManager() { diff --git a/ReactCommon/fabric/imagemanager/platform/ios/RCTImageManager.mm b/ReactCommon/fabric/imagemanager/platform/ios/RCTImageManager.mm index 2b93ed062a5..b3e97541b91 100644 --- a/ReactCommon/fabric/imagemanager/platform/ios/RCTImageManager.mm +++ b/ReactCommon/fabric/imagemanager/platform/ios/RCTImageManager.mm @@ -16,13 +16,11 @@ using namespace facebook::react; -@implementation RCTImageManager -{ +@implementation RCTImageManager { RCTImageLoader *_imageLoader; } -- (instancetype)initWithImageLoader:(RCTImageLoader *)imageLoader -{ +- (instancetype)initWithImageLoader:(RCTImageLoader *)imageLoader { if (self = [super init]) { _imageLoader = imageLoader; } @@ -30,14 +28,14 @@ using namespace facebook::react; return self; } -- (ImageRequest)requestImage:(const ImageSource &)imageSource -{ +- (ImageRequest)requestImage:(const ImageSource &)imageSource { __block auto promise = folly::Promise(); NSURLRequest *request = NSURLRequestFromImageSource(imageSource); auto completionBlock = ^(NSError *error, UIImage *image) { - auto imageResponse = ImageResponse(std::shared_ptr((__bridge_retained void *)image, CFRelease)); + auto imageResponse = ImageResponse( + std::shared_ptr((__bridge_retained void *)image, CFRelease)); promise.setValue(std::move(imageResponse)); }; @@ -48,19 +46,23 @@ using namespace facebook::react; }; RCTImageLoaderCancellationBlock cancellationBlock = - [_imageLoader loadImageWithURLRequest:request - size:CGSizeMake(imageSource.size.width, imageSource.size.height) - scale:imageSource.scale - clipped:YES - resizeMode:RCTResizeModeStretch - progressBlock:nil - partialLoadBlock:nil - completionBlock:completionBlock]; + [_imageLoader loadImageWithURLRequest:request + size:CGSizeMake( + imageSource.size.width, + imageSource.size.height) + scale:imageSource.scale + clipped:YES + resizeMode:RCTResizeModeStretch + progressBlock:nil + partialLoadBlock:nil + completionBlock:completionBlock]; - promise.setInterruptHandler([cancellationBlock, interruptBlock](const folly::exception_wrapper &exceptionWrapper) { - cancellationBlock(); - interruptBlock(exceptionWrapper); - }); + promise.setInterruptHandler( + [cancellationBlock, + interruptBlock](const folly::exception_wrapper &exceptionWrapper) { + cancellationBlock(); + interruptBlock(exceptionWrapper); + }); return ImageRequest(imageSource, promise.getFuture()); } diff --git a/ReactCommon/fabric/sample/SampleComponentDescriptorFactor.cpp b/ReactCommon/fabric/sample/SampleComponentDescriptorFactor.cpp index 550502be41f..e842c98ecd4 100644 --- a/ReactCommon/fabric/sample/SampleComponentDescriptorFactor.cpp +++ b/ReactCommon/fabric/sample/SampleComponentDescriptorFactor.cpp @@ -16,9 +16,8 @@ namespace react { * This is a sample implementation. Each app should provide its own. */ SharedComponentDescriptorRegistry ComponentDescriptorFactory::buildRegistry( - const SharedEventDispatcher &eventDispatcher, - const SharedContextContainer &contextContainer -) { + const SharedEventDispatcher &eventDispatcher, + const SharedContextContainer &contextContainer) { auto registry = std::make_shared(); return registry; } diff --git a/ReactCommon/fabric/textlayoutmanager/platform/android/TextLayoutManager.cpp b/ReactCommon/fabric/textlayoutmanager/platform/android/TextLayoutManager.cpp index 716fc8004e9..e3ae34f373a 100644 --- a/ReactCommon/fabric/textlayoutmanager/platform/android/TextLayoutManager.cpp +++ b/ReactCommon/fabric/textlayoutmanager/platform/android/TextLayoutManager.cpp @@ -15,36 +15,48 @@ using namespace facebook::jni; namespace facebook { namespace react { -TextLayoutManager::~TextLayoutManager() { -} +TextLayoutManager::~TextLayoutManager() {} void *TextLayoutManager::getNativeTextLayoutManager() const { return self_; } Size TextLayoutManager::measure( - Tag reactTag, - AttributedString attributedString, - ParagraphAttributes paragraphAttributes, - LayoutConstraints layoutConstraints -) const { + Tag reactTag, + AttributedString attributedString, + ParagraphAttributes paragraphAttributes, + LayoutConstraints layoutConstraints) const { + const jni::global_ref &fabricUIManager = + contextContainer_->getInstance>( + "FabricUIManager"); - const jni::global_ref & fabricUIManager = contextContainer_->getInstance>("FabricUIManager"); + auto clazz = + jni::findClassStatic("com/facebook/fbreact/fabric/FabricUIManager"); + static auto measure = clazz->getMethod("measure"); - auto clazz = jni::findClassStatic("com/facebook/fbreact/fabric/FabricUIManager"); - static auto measure = - clazz->getMethod("measure"); - - int width = (int) layoutConstraints.maximumSize.width; - int height = (int) layoutConstraints.maximumSize.height; + int width = (int)layoutConstraints.maximumSize.width; + int height = (int)layoutConstraints.maximumSize.height; local_ref componentName = make_jstring("RCTText"); - auto values = measure(fabricUIManager, reactTag, componentName.get(), ReadableNativeMap::newObjectCxxArgs(toDynamic(attributedString)).get(), ReadableNativeMap::newObjectCxxArgs(toDynamic(paragraphAttributes)).get(), width, height); + auto values = measure( + fabricUIManager, + reactTag, + componentName.get(), + ReadableNativeMap::newObjectCxxArgs(toDynamic(attributedString)).get(), + ReadableNativeMap::newObjectCxxArgs(toDynamic(paragraphAttributes)).get(), + width, + height); std::vector indices; indices.resize(values->size()); values->getRegion(0, values->size(), indices.data()); - return {(float) indices[0], (float) indices[1]}; + return {(float)indices[0], (float)indices[1]}; } } // namespace react diff --git a/ReactCommon/fabric/textlayoutmanager/platform/android/TextLayoutManager.h b/ReactCommon/fabric/textlayoutmanager/platform/android/TextLayoutManager.h index 74df2977b6c..aa94601b718 100644 --- a/ReactCommon/fabric/textlayoutmanager/platform/android/TextLayoutManager.h +++ b/ReactCommon/fabric/textlayoutmanager/platform/android/TextLayoutManager.h @@ -25,21 +25,19 @@ using SharedTextLayoutManager = std::shared_ptr; * Cross platform facade for Android-specific TextLayoutManager. */ class TextLayoutManager { - -public: - - TextLayoutManager(const SharedContextContainer &contextContainer) : contextContainer_(contextContainer) {}; + public: + TextLayoutManager(const SharedContextContainer &contextContainer) + : contextContainer_(contextContainer){}; ~TextLayoutManager(); /* * Measures `attributedString` using native text rendering infrastructure. */ Size measure( - Tag reactTag, - AttributedString attributedString, - ParagraphAttributes paragraphAttributes, - LayoutConstraints layoutConstraints - ) const; + Tag reactTag, + AttributedString attributedString, + ParagraphAttributes paragraphAttributes, + LayoutConstraints layoutConstraints) const; /* * Returns an opaque pointer to platform-specific TextLayoutManager. @@ -47,8 +45,7 @@ public: */ void *getNativeTextLayoutManager() const; -private: - + private: void *self_; SharedContextContainer contextContainer_; diff --git a/ReactCommon/fabric/textlayoutmanager/platform/ios/RCTAttributedTextUtils.h b/ReactCommon/fabric/textlayoutmanager/platform/ios/RCTAttributedTextUtils.h index f8297218bcc..6f190e7cade 100644 --- a/ReactCommon/fabric/textlayoutmanager/platform/ios/RCTAttributedTextUtils.h +++ b/ReactCommon/fabric/textlayoutmanager/platform/ios/RCTAttributedTextUtils.h @@ -12,16 +12,18 @@ NS_ASSUME_NONNULL_BEGIN -NSString *const RCTAttributedStringIsHighlightedAttributeName = @"IsHighlighted"; +NSString *const RCTAttributedStringIsHighlightedAttributeName = + @"IsHighlighted"; NSString *const RCTAttributedStringParentShadowNode = @"ParentShadowNode"; /** * Constructs ready-to-render `NSAttributedString` by given `AttributedString`. */ -NSAttributedString *RCTNSAttributedStringFromAttributedString(const facebook::react::AttributedString &attributedString); +NSAttributedString *RCTNSAttributedStringFromAttributedString( + const facebook::react::AttributedString &attributedString); @interface RCTSharedShadowNodeWrapper : NSObject -@property (nonatomic, assign) facebook::react::SharedShadowNode node; +@property(nonatomic, assign) facebook::react::SharedShadowNode node; @end NS_ASSUME_NONNULL_END diff --git a/ReactCommon/fabric/textlayoutmanager/platform/ios/RCTAttributedTextUtils.mm b/ReactCommon/fabric/textlayoutmanager/platform/ios/RCTAttributedTextUtils.mm index 42e90599696..8b21215d7ce 100644 --- a/ReactCommon/fabric/textlayoutmanager/platform/ios/RCTAttributedTextUtils.mm +++ b/ReactCommon/fabric/textlayoutmanager/platform/ios/RCTAttributedTextUtils.mm @@ -15,50 +15,72 @@ @implementation RCTSharedShadowNodeWrapper @end -inline static UIFont *RCTEffectiveFontFromTextAttributes(const TextAttributes &textAttributes) { - NSString *fontFamily = [NSString stringWithCString:textAttributes.fontFamily.c_str() - encoding:NSUTF8StringEncoding]; +inline static UIFont *RCTEffectiveFontFromTextAttributes( + const TextAttributes &textAttributes) { + NSString *fontFamily = + [NSString stringWithCString:textAttributes.fontFamily.c_str() + encoding:NSUTF8StringEncoding]; RCTFontProperties fontProperties; fontProperties.family = fontFamily; fontProperties.size = textAttributes.fontSize; - fontProperties.style = textAttributes.fontStyle.hasValue() ? RCTFontStyleFromFontStyle(textAttributes.fontStyle.value()) : RCTFontStyleUndefined; - fontProperties.variant = textAttributes.fontVariant.hasValue() ? RCTFontVariantFromFontVariant(textAttributes.fontVariant.value()) : RCTFontVariantDefault; - fontProperties.weight = textAttributes.fontWeight.hasValue() ? CGFloat(textAttributes.fontWeight.value()) : NAN; + fontProperties.style = textAttributes.fontStyle.hasValue() + ? RCTFontStyleFromFontStyle(textAttributes.fontStyle.value()) + : RCTFontStyleUndefined; + fontProperties.variant = textAttributes.fontVariant.hasValue() + ? RCTFontVariantFromFontVariant(textAttributes.fontVariant.value()) + : RCTFontVariantDefault; + fontProperties.weight = textAttributes.fontWeight.hasValue() + ? CGFloat(textAttributes.fontWeight.value()) + : NAN; fontProperties.sizeMultiplier = textAttributes.fontSizeMultiplier; return RCTFontWithFontProperties(fontProperties); } -inline static CGFloat RCTEffectiveFontSizeMultiplierFromTextAttributes(const TextAttributes &textAttributes) { - return textAttributes.allowFontScaling.value_or(true) && !isnan(textAttributes.fontSizeMultiplier) ? textAttributes.fontSizeMultiplier : 1.0; +inline static CGFloat RCTEffectiveFontSizeMultiplierFromTextAttributes( + const TextAttributes &textAttributes) { + return textAttributes.allowFontScaling.value_or(true) && + !isnan(textAttributes.fontSizeMultiplier) + ? textAttributes.fontSizeMultiplier + : 1.0; } -inline static UIColor *RCTEffectiveForegroundColorFromTextAttributes(const TextAttributes &textAttributes) { - UIColor *effectiveForegroundColor = RCTUIColorFromSharedColor(textAttributes.foregroundColor) ?: [UIColor blackColor]; +inline static UIColor *RCTEffectiveForegroundColorFromTextAttributes( + const TextAttributes &textAttributes) { + UIColor *effectiveForegroundColor = + RCTUIColorFromSharedColor(textAttributes.foregroundColor) + ?: [UIColor blackColor]; if (!isnan(textAttributes.opacity)) { - effectiveForegroundColor = - [effectiveForegroundColor colorWithAlphaComponent:CGColorGetAlpha(effectiveForegroundColor.CGColor) * textAttributes.opacity]; + effectiveForegroundColor = [effectiveForegroundColor + colorWithAlphaComponent:CGColorGetAlpha( + effectiveForegroundColor.CGColor) * + textAttributes.opacity]; } return effectiveForegroundColor; } -inline static UIColor *RCTEffectiveBackgroundColorFromTextAttributes(const TextAttributes &textAttributes) { - UIColor *effectiveBackgroundColor = RCTUIColorFromSharedColor(textAttributes.backgroundColor); +inline static UIColor *RCTEffectiveBackgroundColorFromTextAttributes( + const TextAttributes &textAttributes) { + UIColor *effectiveBackgroundColor = + RCTUIColorFromSharedColor(textAttributes.backgroundColor); if (effectiveBackgroundColor && !isnan(textAttributes.opacity)) { - effectiveBackgroundColor = - [effectiveBackgroundColor colorWithAlphaComponent:CGColorGetAlpha(effectiveBackgroundColor.CGColor) * textAttributes.opacity]; + effectiveBackgroundColor = [effectiveBackgroundColor + colorWithAlphaComponent:CGColorGetAlpha( + effectiveBackgroundColor.CGColor) * + textAttributes.opacity]; } return effectiveBackgroundColor ?: [UIColor clearColor]; } -static NSDictionary *RCTNSTextAttributesFromTextAttributes(const TextAttributes &textAttributes) { +static NSDictionary * +RCTNSTextAttributesFromTextAttributes(const TextAttributes &textAttributes) { NSMutableDictionary *attributes = - [NSMutableDictionary dictionaryWithCapacity:10]; + [NSMutableDictionary dictionaryWithCapacity:10]; // Font UIFont *font = RCTEffectiveFontFromTextAttributes(textAttributes); @@ -67,14 +89,16 @@ static NSDictionary *RCTNSTextAttributesFromTextAttri } // Colors - UIColor *effectiveForegroundColor = RCTEffectiveForegroundColorFromTextAttributes(textAttributes); + UIColor *effectiveForegroundColor = + RCTEffectiveForegroundColorFromTextAttributes(textAttributes); if (textAttributes.foregroundColor || !isnan(textAttributes.opacity)) { attributes[NSForegroundColorAttributeName] = effectiveForegroundColor; } if (textAttributes.backgroundColor || !isnan(textAttributes.opacity)) { - attributes[NSBackgroundColorAttributeName] = RCTEffectiveBackgroundColorFromTextAttributes(textAttributes); + attributes[NSBackgroundColorAttributeName] = + RCTEffectiveBackgroundColorFromTextAttributes(textAttributes); } // Kerning @@ -86,8 +110,10 @@ static NSDictionary *RCTNSTextAttributesFromTextAttri NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle new]; BOOL isParagraphStyleUsed = NO; if (textAttributes.alignment.hasValue()) { - TextAlignment textAlignment = textAttributes.alignment.value_or(TextAlignment::Natural); - if (textAttributes.layoutDirection.value_or(LayoutDirection::LeftToRight) == LayoutDirection::RightToLeft) { + TextAlignment textAlignment = + textAttributes.alignment.value_or(TextAlignment::Natural); + if (textAttributes.layoutDirection.value_or(LayoutDirection::LeftToRight) == + LayoutDirection::RightToLeft) { if (textAlignment == TextAlignment::Right) { textAlignment = TextAlignment::Left; } else if (textAlignment == TextAlignment::Left) { @@ -96,19 +122,20 @@ static NSDictionary *RCTNSTextAttributesFromTextAttri } paragraphStyle.alignment = - RCTNSTextAlignmentFromTextAlignment(textAlignment); + RCTNSTextAlignmentFromTextAlignment(textAlignment); isParagraphStyleUsed = YES; } if (textAttributes.baseWritingDirection.hasValue()) { paragraphStyle.baseWritingDirection = - RCTNSWritingDirectionFromWritingDirection(textAttributes.baseWritingDirection.value()); + RCTNSWritingDirectionFromWritingDirection( + textAttributes.baseWritingDirection.value()); isParagraphStyleUsed = YES; } if (!isnan(textAttributes.lineHeight)) { - CGFloat lineHeight = - textAttributes.lineHeight * RCTEffectiveFontSizeMultiplierFromTextAttributes(textAttributes); + CGFloat lineHeight = textAttributes.lineHeight * + RCTEffectiveFontSizeMultiplierFromTextAttributes(textAttributes); paragraphStyle.minimumLineHeight = lineHeight; paragraphStyle.maximumLineHeight = lineHeight; isParagraphStyleUsed = YES; @@ -119,21 +146,23 @@ static NSDictionary *RCTNSTextAttributesFromTextAttri } // Decoration - if (textAttributes.textDecorationLineType.value_or(TextDecorationLineType::None) != TextDecorationLineType::None) { + if (textAttributes.textDecorationLineType.value_or( + TextDecorationLineType::None) != TextDecorationLineType::None) { auto textDecorationLineType = textAttributes.textDecorationLineType.value(); - NSUnderlineStyle style = - RCTNSUnderlineStyleFromStyleAndPattern( - textAttributes.textDecorationLineStyle.value_or(TextDecorationLineStyle::Single), - textAttributes.textDecorationLinePattern.value_or(TextDecorationLinePattern::Solid) - ); + NSUnderlineStyle style = RCTNSUnderlineStyleFromStyleAndPattern( + textAttributes.textDecorationLineStyle.value_or( + TextDecorationLineStyle::Single), + textAttributes.textDecorationLinePattern.value_or( + TextDecorationLinePattern::Solid)); - UIColor *textDecorationColor = RCTUIColorFromSharedColor(textAttributes.textDecorationColor); + UIColor *textDecorationColor = + RCTUIColorFromSharedColor(textAttributes.textDecorationColor); // Underline if (textDecorationLineType == TextDecorationLineType::Underline || - textDecorationLineType == TextDecorationLineType::UnderlineStrikethrough) { - + textDecorationLineType == + TextDecorationLineType::UnderlineStrikethrough) { attributes[NSUnderlineStyleAttributeName] = @(style); if (textDecorationColor) { @@ -143,8 +172,8 @@ static NSDictionary *RCTNSTextAttributesFromTextAttri // Strikethrough if (textDecorationLineType == TextDecorationLineType::Strikethrough || - textDecorationLineType == TextDecorationLineType::UnderlineStrikethrough) { - + textDecorationLineType == + TextDecorationLineType::UnderlineStrikethrough) { attributes[NSStrikethroughStyleAttributeName] = @(style); if (textDecorationColor) { @@ -157,9 +186,11 @@ static NSDictionary *RCTNSTextAttributesFromTextAttri if (textAttributes.textShadowOffset.hasValue()) { auto textShadowOffset = textAttributes.textShadowOffset.value(); NSShadow *shadow = [NSShadow new]; - shadow.shadowOffset = CGSize {textShadowOffset.width, textShadowOffset.height}; + shadow.shadowOffset = + CGSize{textShadowOffset.width, textShadowOffset.height}; shadow.shadowBlurRadius = textAttributes.textShadowRadius; - shadow.shadowColor = RCTUIColorFromSharedColor(textAttributes.textShadowColor); + shadow.shadowColor = + RCTUIColorFromSharedColor(textAttributes.textShadowColor); attributes[NSShadowAttributeName] = shadow; } @@ -171,8 +202,10 @@ static NSDictionary *RCTNSTextAttributesFromTextAttri return [attributes copy]; } -NSAttributedString *RCTNSAttributedStringFromAttributedString(const AttributedString &attributedString) { - NSMutableAttributedString *nsAttributedString = [[NSMutableAttributedString alloc] init]; +NSAttributedString *RCTNSAttributedStringFromAttributedString( + const AttributedString &attributedString) { + NSMutableAttributedString *nsAttributedString = + [[NSMutableAttributedString alloc] init]; [nsAttributedString beginEditing]; @@ -180,51 +213,51 @@ NSAttributedString *RCTNSAttributedStringFromAttributedString(const AttributedSt NSAttributedString *nsAttributedStringFragment; auto layoutableShadowNode = - std::dynamic_pointer_cast(fragment.shadowNode); + std::dynamic_pointer_cast( + fragment.shadowNode); if (layoutableShadowNode) { auto layoutMetrics = layoutableShadowNode->getLayoutMetrics(); - CGRect bounds = { - .origin = { - .x = layoutMetrics.frame.origin.x, - .y = layoutMetrics.frame.origin.y - }, - .size = { - .width = layoutMetrics.frame.size.width, - .height = layoutMetrics.frame.size.height - } - }; + CGRect bounds = {.origin = {.x = layoutMetrics.frame.origin.x, + .y = layoutMetrics.frame.origin.y}, + .size = {.width = layoutMetrics.frame.size.width, + .height = layoutMetrics.frame.size.height}}; NSTextAttachment *attachment = [NSTextAttachment new]; attachment.bounds = bounds; - nsAttributedStringFragment = [NSAttributedString attributedStringWithAttachment:attachment]; - } else { - NSString *string = - [NSString stringWithCString:fragment.string.c_str() - encoding:NSUTF8StringEncoding]; - nsAttributedStringFragment = - [[NSAttributedString alloc] initWithString:string - attributes:RCTNSTextAttributesFromTextAttributes(fragment.textAttributes)]; + [NSAttributedString attributedStringWithAttachment:attachment]; + } else { + NSString *string = [NSString stringWithCString:fragment.string.c_str() + encoding:NSUTF8StringEncoding]; + + nsAttributedStringFragment = [[NSAttributedString alloc] + initWithString:string + attributes:RCTNSTextAttributesFromTextAttributes( + fragment.textAttributes)]; } NSMutableAttributedString *nsMutableAttributedStringFragment = - [[NSMutableAttributedString alloc] initWithAttributedString:nsAttributedStringFragment]; + [[NSMutableAttributedString alloc] + initWithAttributedString:nsAttributedStringFragment]; if (fragment.parentShadowNode) { - RCTSharedShadowNodeWrapper *parentShadowNode = [RCTSharedShadowNodeWrapper new]; + RCTSharedShadowNodeWrapper *parentShadowNode = + [RCTSharedShadowNodeWrapper new]; parentShadowNode.node = fragment.parentShadowNode; - - NSDictionary *additionalTextAttributes = @{ - RCTAttributedStringParentShadowNode: parentShadowNode - }; - [nsMutableAttributedStringFragment addAttributes:additionalTextAttributes - range:NSMakeRange(0, nsMutableAttributedStringFragment.length)]; + NSDictionary *additionalTextAttributes = + @{RCTAttributedStringParentShadowNode : parentShadowNode}; + + [nsMutableAttributedStringFragment + addAttributes:additionalTextAttributes + range:NSMakeRange( + 0, nsMutableAttributedStringFragment.length)]; } - [nsAttributedString appendAttributedString:nsMutableAttributedStringFragment]; + [nsAttributedString + appendAttributedString:nsMutableAttributedStringFragment]; } [nsAttributedString endEditing]; diff --git a/ReactCommon/fabric/textlayoutmanager/platform/ios/RCTFontUtils.mm b/ReactCommon/fabric/textlayoutmanager/platform/ios/RCTFontUtils.mm index 5b8cba1644c..3167a5d1268 100644 --- a/ReactCommon/fabric/textlayoutmanager/platform/ios/RCTFontUtils.mm +++ b/ReactCommon/fabric/textlayoutmanager/platform/ios/RCTFontUtils.mm @@ -17,7 +17,7 @@ static RCTFontProperties RCTDefaultFontProperties() { dispatch_once(&onceToken, ^{ defaultFontProperties.size = 14; defaultFontProperties.family = - [UIFont systemFontOfSize:defaultFontProperties.size].familyName; + [UIFont systemFontOfSize:defaultFontProperties.size].familyName; defaultFontProperties.style = RCTFontStyleNormal; defaultFontProperties.variant = RCTFontVariantDefault; defaultFontProperties.sizeMultiplier = 1.0; @@ -26,24 +26,39 @@ static RCTFontProperties RCTDefaultFontProperties() { return defaultFontProperties; } -static RCTFontProperties RCTResolveFontProperties(RCTFontProperties fontProperties) { +static RCTFontProperties RCTResolveFontProperties( + RCTFontProperties fontProperties) { RCTFontProperties defaultFontProperties = RCTDefaultFontProperties(); - fontProperties.family = fontProperties.family.length && ![fontProperties.family isEqualToString:@"System"] ? fontProperties.family : defaultFontProperties.family; - fontProperties.size = !isnan(fontProperties.size) ? fontProperties.size : defaultFontProperties.size; - fontProperties.weight = !isnan(fontProperties.weight) ? fontProperties.weight : defaultFontProperties.weight; - fontProperties.style = fontProperties.style != RCTFontStyleUndefined ? fontProperties.style : defaultFontProperties.style; - fontProperties.variant = fontProperties.variant != RCTFontVariantUndefined ? fontProperties.variant : defaultFontProperties.variant; + fontProperties.family = fontProperties.family.length && + ![fontProperties.family isEqualToString:@"System"] + ? fontProperties.family + : defaultFontProperties.family; + fontProperties.size = !isnan(fontProperties.size) + ? fontProperties.size + : defaultFontProperties.size; + fontProperties.weight = !isnan(fontProperties.weight) + ? fontProperties.weight + : defaultFontProperties.weight; + fontProperties.style = fontProperties.style != RCTFontStyleUndefined + ? fontProperties.style + : defaultFontProperties.style; + fontProperties.variant = fontProperties.variant != RCTFontVariantUndefined + ? fontProperties.variant + : defaultFontProperties.variant; return fontProperties; } static UIFontWeight RCTGetFontWeight(UIFont *font) { - NSDictionary *traits = [font.fontDescriptor objectForKey:UIFontDescriptorTraitsAttribute]; + NSDictionary *traits = + [font.fontDescriptor objectForKey:UIFontDescriptorTraitsAttribute]; return [traits[UIFontWeightTrait] doubleValue]; } static RCTFontStyle RCTGetFontStyle(UIFont *font) { - NSDictionary *traits = [font.fontDescriptor objectForKey:UIFontDescriptorTraitsAttribute]; - UIFontDescriptorSymbolicTraits symbolicTraits = [traits[UIFontSymbolicTrait] unsignedIntValue]; + NSDictionary *traits = + [font.fontDescriptor objectForKey:UIFontDescriptorTraitsAttribute]; + UIFontDescriptorSymbolicTraits symbolicTraits = + [traits[UIFontSymbolicTrait] unsignedIntValue]; if (symbolicTraits & UIFontDescriptorTraitItalic) { return RCTFontStyleItalic; } @@ -61,25 +76,26 @@ static UIFontWeight RCTUIFontWeightFromFloat(CGFloat fontWeight) { // and UIKit uses the same numerical notation, we have to use exact // `UIFontWeight*` constants to make it work properly (because // float values comparison is tricky). - static UIFontWeight weights[] = { - /* ~100 */ UIFontWeightUltraLight, - /* ~200 */ UIFontWeightThin, - /* ~300 */ UIFontWeightLight, - /* ~400 */ UIFontWeightRegular, - /* ~500 */ UIFontWeightMedium, - /* ~600 */ UIFontWeightSemibold, - /* ~700 */ UIFontWeightBold, - /* ~800 */ UIFontWeightHeavy, - /* ~900 */ UIFontWeightBlack - }; + static UIFontWeight weights[] = {/* ~100 */ UIFontWeightUltraLight, + /* ~200 */ UIFontWeightThin, + /* ~300 */ UIFontWeightLight, + /* ~400 */ UIFontWeightRegular, + /* ~500 */ UIFontWeightMedium, + /* ~600 */ UIFontWeightSemibold, + /* ~700 */ UIFontWeightBold, + /* ~800 */ UIFontWeightHeavy, + /* ~900 */ UIFontWeightBlack}; return weights[std::llround((fontWeight / 100) - 1)]; } -static UIFont *RCTDefaultFontWithFontProperties(RCTFontProperties fontProperties) { +static UIFont *RCTDefaultFontWithFontProperties( + RCTFontProperties fontProperties) { static NSCache *fontCache; static std::mutex fontCacheMutex; - NSString *cacheKey = [NSString stringWithFormat:@"%.1f/%.2f", fontProperties.size, fontProperties.weight]; + NSString *cacheKey = [NSString stringWithFormat:@"%.1f/%.2f", + fontProperties.size, + fontProperties.weight]; UIFont *font; { @@ -91,17 +107,21 @@ static UIFont *RCTDefaultFontWithFontProperties(RCTFontProperties fontProperties } if (!font) { - font = [UIFont systemFontOfSize:fontProperties.size - weight:RCTUIFontWeightFromFloat(fontProperties.weight)]; + font = [UIFont + systemFontOfSize:fontProperties.size + weight:RCTUIFontWeightFromFloat(fontProperties.weight)]; if (fontProperties.variant == RCTFontStyleItalic) { UIFontDescriptor *fontDescriptor = [font fontDescriptor]; - UIFontDescriptorSymbolicTraits symbolicTraits = fontDescriptor.symbolicTraits; + UIFontDescriptorSymbolicTraits symbolicTraits = + fontDescriptor.symbolicTraits; symbolicTraits |= UIFontDescriptorTraitItalic; - fontDescriptor = [fontDescriptor fontDescriptorWithSymbolicTraits:symbolicTraits]; - font = [UIFont fontWithDescriptor:fontDescriptor size:fontProperties.size]; + fontDescriptor = + [fontDescriptor fontDescriptorWithSymbolicTraits:symbolicTraits]; + font = + [UIFont fontWithDescriptor:fontDescriptor size:fontProperties.size]; } { @@ -117,7 +137,8 @@ UIFont *RCTFontWithFontProperties(RCTFontProperties fontProperties) { RCTFontProperties defaultFontProperties = RCTDefaultFontProperties(); fontProperties = RCTResolveFontProperties(fontProperties); - CGFloat effectiveFontSize = fontProperties.sizeMultiplier * fontProperties.size; + CGFloat effectiveFontSize = + fontProperties.sizeMultiplier * fontProperties.size; UIFont *font; if ([fontProperties.family isEqualToString:defaultFontProperties.family]) { // Handle system font as special case. This ensures that we preserve @@ -125,7 +146,7 @@ UIFont *RCTFontWithFontProperties(RCTFontProperties fontProperties) { font = RCTDefaultFontWithFontProperties(fontProperties); } else { NSArray *fontNames = - [UIFont fontNamesForFamilyName:fontProperties.family]; + [UIFont fontNamesForFamilyName:fontProperties.family]; if (fontNames.count == 0) { // Gracefully handle being given a font name rather than font family, for @@ -134,7 +155,9 @@ UIFont *RCTFontWithFontProperties(RCTFontProperties fontProperties) { if (!font) { // Failback to system font. - font = [UIFont systemFontOfSize:effectiveFontSize weight:RCTUIFontWeightFromFloat(fontProperties.weight)]; + font = [UIFont + systemFontOfSize:effectiveFontSize + weight:RCTUIFontWeightFromFloat(fontProperties.weight)]; } } else { // Get the closest font that matches the given weight for the fontFamily @@ -147,15 +170,17 @@ UIFont *RCTFontWithFontProperties(RCTFontProperties fontProperties) { } CGFloat testWeight = RCTGetFontWeight(fontMatch); - if (ABS(testWeight - fontProperties.weight) < ABS(closestWeight - fontProperties.weight)) { + if (ABS(testWeight - fontProperties.weight) < + ABS(closestWeight - fontProperties.weight)) { font = fontMatch; closestWeight = testWeight; } } if (!font) { - // If we still don't have a match at least return the first font in the fontFamily - // This is to support built-in font Zapfino and other custom single font families like Impact + // If we still don't have a match at least return the first font in the + // fontFamily This is to support built-in font Zapfino and other custom + // single font families like Impact font = [UIFont fontWithName:fontNames[0] size:effectiveFontSize]; } } @@ -165,7 +190,9 @@ UIFont *RCTFontWithFontProperties(RCTFontProperties fontProperties) { if (fontProperties.variant != RCTFontVariantDefault) { NSArray *fontFeatures = RCTFontFeatures(fontProperties.variant); UIFontDescriptor *fontDescriptor = - [font.fontDescriptor fontDescriptorByAddingAttributes:@{UIFontDescriptorFeatureSettingsAttribute: fontFeatures}]; + [font.fontDescriptor fontDescriptorByAddingAttributes:@{ + UIFontDescriptorFeatureSettingsAttribute : fontFeatures + }]; font = [UIFont fontWithDescriptor:fontDescriptor size:effectiveFontSize]; } diff --git a/ReactCommon/fabric/textlayoutmanager/platform/ios/RCTTextLayoutManager.h b/ReactCommon/fabric/textlayoutmanager/platform/ios/RCTTextLayoutManager.h index 42b11a9effe..d44e05fdd39 100644 --- a/ReactCommon/fabric/textlayoutmanager/platform/ios/RCTTextLayoutManager.h +++ b/ReactCommon/fabric/textlayoutmanager/platform/ios/RCTTextLayoutManager.h @@ -7,10 +7,10 @@ #import -#import -#import #import #import +#import +#import NS_ASSUME_NONNULL_BEGIN @@ -19,18 +19,27 @@ NS_ASSUME_NONNULL_BEGIN */ @interface RCTTextLayoutManager : NSObject -- (facebook::react::Size)measureWithAttributedString:(facebook::react::AttributedString)attributedString - paragraphAttributes:(facebook::react::ParagraphAttributes)paragraphAttributes - layoutConstraints:(facebook::react::LayoutConstraints)layoutConstraints; +- (facebook::react::Size) + measureWithAttributedString: + (facebook::react::AttributedString)attributedString + paragraphAttributes: + (facebook::react::ParagraphAttributes)paragraphAttributes + layoutConstraints: + (facebook::react::LayoutConstraints)layoutConstraints; - (void)drawAttributedString:(facebook::react::AttributedString)attributedString - paragraphAttributes:(facebook::react::ParagraphAttributes)paragraphAttributes + paragraphAttributes: + (facebook::react::ParagraphAttributes)paragraphAttributes frame:(CGRect)frame; -- (facebook::react::SharedShadowNode)getParentShadowNodeWithAttributeString:(facebook::react::AttributedString)attributedString - paragraphAttributes:(facebook::react::ParagraphAttributes)paragraphAttributes - frame:(CGRect)frame - atPoint:(CGPoint)point; +- (facebook::react::SharedShadowNode) + getParentShadowNodeWithAttributeString: + (facebook::react::AttributedString)attributedString + paragraphAttributes: + (facebook::react::ParagraphAttributes) + paragraphAttributes + frame:(CGRect)frame + atPoint:(CGPoint)point; @end diff --git a/ReactCommon/fabric/textlayoutmanager/platform/ios/RCTTextLayoutManager.mm b/ReactCommon/fabric/textlayoutmanager/platform/ios/RCTTextLayoutManager.mm index 4c64fc59829..0f206ceaaba 100644 --- a/ReactCommon/fabric/textlayoutmanager/platform/ios/RCTTextLayoutManager.mm +++ b/ReactCommon/fabric/textlayoutmanager/platform/ios/RCTTextLayoutManager.mm @@ -14,24 +14,31 @@ using namespace facebook::react; @implementation RCTTextLayoutManager -static NSLineBreakMode RCTNSLineBreakModeFromWritingDirection(EllipsizeMode ellipsizeMode) { +static NSLineBreakMode RCTNSLineBreakModeFromWritingDirection( + EllipsizeMode ellipsizeMode) { switch (ellipsizeMode) { - case EllipsizeMode::Clip: return NSLineBreakByClipping; - case EllipsizeMode::Head: return NSLineBreakByTruncatingHead; - case EllipsizeMode::Tail: return NSLineBreakByTruncatingTail; - case EllipsizeMode::Middle: return NSLineBreakByTruncatingMiddle; + case EllipsizeMode::Clip: + return NSLineBreakByClipping; + case EllipsizeMode::Head: + return NSLineBreakByTruncatingHead; + case EllipsizeMode::Tail: + return NSLineBreakByTruncatingTail; + case EllipsizeMode::Middle: + return NSLineBreakByTruncatingMiddle; } } -- (facebook::react::Size)measureWithAttributedString:(AttributedString)attributedString - paragraphAttributes:(ParagraphAttributes)paragraphAttributes - layoutConstraints:(LayoutConstraints)layoutConstraints -{ - CGSize maximumSize = CGSize {layoutConstraints.maximumSize.width, layoutConstraints.maximumSize.height}; +- (facebook::react::Size) + measureWithAttributedString:(AttributedString)attributedString + paragraphAttributes:(ParagraphAttributes)paragraphAttributes + layoutConstraints:(LayoutConstraints)layoutConstraints { + CGSize maximumSize = CGSize{layoutConstraints.maximumSize.width, + layoutConstraints.maximumSize.height}; NSTextStorage *textStorage = - [self _textStorageAndLayoutManagerWithAttributesString:RCTNSAttributedStringFromAttributedString(attributedString) - paragraphAttributes:paragraphAttributes - size:maximumSize]; + [self _textStorageAndLayoutManagerWithAttributesString: + RCTNSAttributedStringFromAttributedString(attributedString) + paragraphAttributes:paragraphAttributes + size:maximumSize]; NSLayoutManager *layoutManager = textStorage.layoutManagers.firstObject; NSTextContainer *textContainer = layoutManager.textContainers.firstObject; @@ -39,52 +46,58 @@ static NSLineBreakMode RCTNSLineBreakModeFromWritingDirection(EllipsizeMode elli CGSize size = [layoutManager usedRectForTextContainer:textContainer].size; - size = (CGSize){ - MIN(size.width, maximumSize.width), - MIN(size.height, maximumSize.height) - }; + size = (CGSize){MIN(size.width, maximumSize.width), + MIN(size.height, maximumSize.height)}; - return facebook::react::Size {size.width, size.height}; + return facebook::react::Size{size.width, size.height}; } - (void)drawAttributedString:(AttributedString)attributedString paragraphAttributes:(ParagraphAttributes)paragraphAttributes - frame:(CGRect)frame -{ + frame:(CGRect)frame { NSTextStorage *textStorage = - [self _textStorageAndLayoutManagerWithAttributesString:RCTNSAttributedStringFromAttributedString(attributedString) - paragraphAttributes:paragraphAttributes - size:frame.size]; - NSLayoutManager *layoutManager = textStorage.layoutManagers.firstObject; - NSTextContainer *textContainer = layoutManager.textContainers.firstObject; + [self _textStorageAndLayoutManagerWithAttributesString: + RCTNSAttributedStringFromAttributedString(attributedString) + paragraphAttributes:paragraphAttributes + size:frame.size]; + NSLayoutManager *layoutManager = textStorage.layoutManagers.firstObject; + NSTextContainer *textContainer = layoutManager.textContainers.firstObject; - NSRange glyphRange = [layoutManager glyphRangeForTextContainer:textContainer]; - [layoutManager drawBackgroundForGlyphRange:glyphRange atPoint:frame.origin]; - [layoutManager drawGlyphsForGlyphRange:glyphRange atPoint:frame.origin]; + NSRange glyphRange = [layoutManager glyphRangeForTextContainer:textContainer]; + [layoutManager drawBackgroundForGlyphRange:glyphRange atPoint:frame.origin]; + [layoutManager drawGlyphsForGlyphRange:glyphRange atPoint:frame.origin]; } -- (NSTextStorage *)_textStorageAndLayoutManagerWithAttributesString:(NSAttributedString *)attributedString - paragraphAttributes:(ParagraphAttributes)paragraphAttributes - size:(CGSize)size -{ +- (NSTextStorage *) + _textStorageAndLayoutManagerWithAttributesString: + (NSAttributedString *)attributedString + paragraphAttributes: + (ParagraphAttributes)paragraphAttributes + size:(CGSize)size { NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize:size]; textContainer.lineFragmentPadding = 0.0; // Note, the default value is 5. - textContainer.lineBreakMode = - paragraphAttributes.maximumNumberOfLines > 0 ? RCTNSLineBreakModeFromWritingDirection(paragraphAttributes.ellipsizeMode) : NSLineBreakByClipping; + textContainer.lineBreakMode = paragraphAttributes.maximumNumberOfLines > 0 + ? RCTNSLineBreakModeFromWritingDirection( + paragraphAttributes.ellipsizeMode) + : NSLineBreakByClipping; textContainer.maximumNumberOfLines = paragraphAttributes.maximumNumberOfLines; NSLayoutManager *layoutManager = [NSLayoutManager new]; [layoutManager addTextContainer:textContainer]; NSTextStorage *textStorage = - [[NSTextStorage alloc] initWithAttributedString:attributedString]; + [[NSTextStorage alloc] initWithAttributedString:attributedString]; [textStorage addLayoutManager:layoutManager]; if (paragraphAttributes.adjustsFontSizeToFit) { - CGFloat minimumFontSize = !isnan(paragraphAttributes.minimumFontSize) ? paragraphAttributes.minimumFontSize : 4.0; - CGFloat maximumFontSize = !isnan(paragraphAttributes.maximumFontSize) ? paragraphAttributes.maximumFontSize : 96.0; + CGFloat minimumFontSize = !isnan(paragraphAttributes.minimumFontSize) + ? paragraphAttributes.minimumFontSize + : 4.0; + CGFloat maximumFontSize = !isnan(paragraphAttributes.maximumFontSize) + ? paragraphAttributes.maximumFontSize + : 96.0; [textStorage scaleFontSizeToFitSize:size minimumFontSize:minimumFontSize maximumFontSize:maximumFontSize]; @@ -93,26 +106,35 @@ static NSLineBreakMode RCTNSLineBreakModeFromWritingDirection(EllipsizeMode elli return textStorage; } -- (SharedShadowNode)getParentShadowNodeWithAttributeString:(AttributedString)attributedString - paragraphAttributes:(ParagraphAttributes)paragraphAttributes - frame:(CGRect)frame - atPoint:(CGPoint)point { +- (SharedShadowNode) + getParentShadowNodeWithAttributeString:(AttributedString)attributedString + paragraphAttributes: + (ParagraphAttributes)paragraphAttributes + frame:(CGRect)frame + atPoint:(CGPoint)point { NSTextStorage *textStorage = - [self _textStorageAndLayoutManagerWithAttributesString:RCTNSAttributedStringFromAttributedString(attributedString) - paragraphAttributes:paragraphAttributes - size:frame.size]; + [self _textStorageAndLayoutManagerWithAttributesString: + RCTNSAttributedStringFromAttributedString(attributedString) + paragraphAttributes:paragraphAttributes + size:frame.size]; NSLayoutManager *layoutManager = textStorage.layoutManagers.firstObject; NSTextContainer *textContainer = layoutManager.textContainers.firstObject; CGFloat fraction; - NSUInteger characterIndex = [layoutManager characterIndexForPoint:point - inTextContainer:textContainer - fractionOfDistanceBetweenInsertionPoints:&fraction]; + NSUInteger characterIndex = + [layoutManager characterIndexForPoint:point + inTextContainer:textContainer + fractionOfDistanceBetweenInsertionPoints:&fraction]; // If the point is not before (fraction == 0.0) the first character and not // after (fraction == 1.0) the last character, then the attribute is valid. - if (textStorage.length > 0 && (fraction > 0 || characterIndex > 0) && (fraction < 1 || characterIndex < textStorage.length - 1)) { - RCTSharedShadowNodeWrapper *parentShadowNode = (RCTSharedShadowNodeWrapper *)[textStorage attribute:RCTAttributedStringParentShadowNode atIndex:characterIndex effectiveRange:NULL]; + if (textStorage.length > 0 && (fraction > 0 || characterIndex > 0) && + (fraction < 1 || characterIndex < textStorage.length - 1)) { + RCTSharedShadowNodeWrapper *parentShadowNode = + (RCTSharedShadowNodeWrapper *)[textStorage + attribute:RCTAttributedStringParentShadowNode + atIndex:characterIndex + effectiveRange:NULL]; return parentShadowNode.node; } diff --git a/ReactCommon/fabric/textlayoutmanager/platform/ios/RCTTextPrimitivesConversions.h b/ReactCommon/fabric/textlayoutmanager/platform/ios/RCTTextPrimitivesConversions.h index b5e0fc4222e..2ac7a295d6d 100644 --- a/ReactCommon/fabric/textlayoutmanager/platform/ios/RCTTextPrimitivesConversions.h +++ b/ReactCommon/fabric/textlayoutmanager/platform/ios/RCTTextPrimitivesConversions.h @@ -12,59 +12,83 @@ using namespace facebook::react; -inline static NSTextAlignment RCTNSTextAlignmentFromTextAlignment(TextAlignment textAlignment) { +inline static NSTextAlignment RCTNSTextAlignmentFromTextAlignment( + TextAlignment textAlignment) { switch (textAlignment) { - case TextAlignment::Natural: return NSTextAlignmentNatural; - case TextAlignment::Left: return NSTextAlignmentLeft; - case TextAlignment::Right: return NSTextAlignmentRight; - case TextAlignment::Center: return NSTextAlignmentCenter; - case TextAlignment::Justified: return NSTextAlignmentJustified; + case TextAlignment::Natural: + return NSTextAlignmentNatural; + case TextAlignment::Left: + return NSTextAlignmentLeft; + case TextAlignment::Right: + return NSTextAlignmentRight; + case TextAlignment::Center: + return NSTextAlignmentCenter; + case TextAlignment::Justified: + return NSTextAlignmentJustified; } } -inline static NSWritingDirection RCTNSWritingDirectionFromWritingDirection(WritingDirection writingDirection) { +inline static NSWritingDirection RCTNSWritingDirectionFromWritingDirection( + WritingDirection writingDirection) { switch (writingDirection) { - case WritingDirection::Natural: return NSWritingDirectionNatural; - case WritingDirection::LeftToRight: return NSWritingDirectionLeftToRight; - case WritingDirection::RightToLeft: return NSWritingDirectionRightToLeft; + case WritingDirection::Natural: + return NSWritingDirectionNatural; + case WritingDirection::LeftToRight: + return NSWritingDirectionLeftToRight; + case WritingDirection::RightToLeft: + return NSWritingDirectionRightToLeft; } } inline static RCTFontStyle RCTFontStyleFromFontStyle(FontStyle fontStyle) { switch (fontStyle) { - case FontStyle::Normal: return RCTFontStyleNormal; - case FontStyle::Italic: return RCTFontStyleItalic; - case FontStyle::Oblique: return RCTFontStyleOblique; + case FontStyle::Normal: + return RCTFontStyleNormal; + case FontStyle::Italic: + return RCTFontStyleItalic; + case FontStyle::Oblique: + return RCTFontStyleOblique; } } -inline static RCTFontVariant RCTFontVariantFromFontVariant(FontVariant fontVariant) { +inline static RCTFontVariant RCTFontVariantFromFontVariant( + FontVariant fontVariant) { return (RCTFontVariant)fontVariant; } -inline static NSUnderlineStyle RCTNSUnderlineStyleFromStyleAndPattern(TextDecorationLineStyle textDecorationLineStyle, TextDecorationLinePattern textDecorationLinePattern) { +inline static NSUnderlineStyle RCTNSUnderlineStyleFromStyleAndPattern( + TextDecorationLineStyle textDecorationLineStyle, + TextDecorationLinePattern textDecorationLinePattern) { NSUnderlineStyle style = NSUnderlineStyleNone; switch (textDecorationLineStyle) { case TextDecorationLineStyle::Single: - style = NSUnderlineStyle(style | NSUnderlineStyleSingle); break; + style = NSUnderlineStyle(style | NSUnderlineStyleSingle); + break; case TextDecorationLineStyle::Thick: - style = NSUnderlineStyle(style | NSUnderlineStyleThick); break; + style = NSUnderlineStyle(style | NSUnderlineStyleThick); + break; case TextDecorationLineStyle::Double: - style = NSUnderlineStyle(style | NSUnderlineStyleDouble); break; + style = NSUnderlineStyle(style | NSUnderlineStyleDouble); + break; } switch (textDecorationLinePattern) { case TextDecorationLinePattern::Solid: - style = NSUnderlineStyle(style | NSUnderlinePatternSolid); break; + style = NSUnderlineStyle(style | NSUnderlinePatternSolid); + break; case TextDecorationLinePattern::Dash: - style = NSUnderlineStyle(style | NSUnderlinePatternDash); break; + style = NSUnderlineStyle(style | NSUnderlinePatternDash); + break; case TextDecorationLinePattern::Dot: - style = NSUnderlineStyle(style | NSUnderlinePatternDot); break; + style = NSUnderlineStyle(style | NSUnderlinePatternDot); + break; case TextDecorationLinePattern::DashDot: - style = NSUnderlineStyle(style | NSUnderlinePatternDashDot); break; + style = NSUnderlineStyle(style | NSUnderlinePatternDashDot); + break; case TextDecorationLinePattern::DashDotDot: - style = NSUnderlineStyle(style | NSUnderlinePatternDashDotDot); break; + style = NSUnderlineStyle(style | NSUnderlinePatternDashDotDot); + break; } return style; diff --git a/ReactCommon/fabric/textlayoutmanager/platform/ios/TextLayoutManager.h b/ReactCommon/fabric/textlayoutmanager/platform/ios/TextLayoutManager.h index a20c657722d..dc7baea7516 100644 --- a/ReactCommon/fabric/textlayoutmanager/platform/ios/TextLayoutManager.h +++ b/ReactCommon/fabric/textlayoutmanager/platform/ios/TextLayoutManager.h @@ -25,7 +25,7 @@ using SharedTextLayoutManager = std::shared_ptr; * Cross platform facade for iOS-specific RCTTTextLayoutManager. */ class TextLayoutManager { -public: + public: TextLayoutManager(const SharedContextContainer &contextContainer); ~TextLayoutManager(); @@ -33,11 +33,10 @@ public: * Measures `attributedString` using native text rendering infrastructure. */ Size measure( - Tag reactTag, - AttributedString attributedString, - ParagraphAttributes paragraphAttributes, - LayoutConstraints layoutConstraints - ) const; + Tag reactTag, + AttributedString attributedString, + ParagraphAttributes paragraphAttributes, + LayoutConstraints layoutConstraints) const; /* * Returns an opaque pointer to platform-specific TextLayoutManager. @@ -45,7 +44,7 @@ public: */ void *getNativeTextLayoutManager() const; -private: + private: void *self_; }; diff --git a/ReactCommon/fabric/textlayoutmanager/platform/ios/TextLayoutManager.mm b/ReactCommon/fabric/textlayoutmanager/platform/ios/TextLayoutManager.mm index 2429596a54f..2c082e9e167 100644 --- a/ReactCommon/fabric/textlayoutmanager/platform/ios/TextLayoutManager.mm +++ b/ReactCommon/fabric/textlayoutmanager/platform/ios/TextLayoutManager.mm @@ -12,7 +12,8 @@ namespace facebook { namespace react { -TextLayoutManager::TextLayoutManager(const SharedContextContainer &contextContainer) { +TextLayoutManager::TextLayoutManager( + const SharedContextContainer &contextContainer) { self_ = (__bridge_retained void *)[RCTTextLayoutManager new]; } @@ -26,12 +27,12 @@ void *TextLayoutManager::getNativeTextLayoutManager() const { } Size TextLayoutManager::measure( - Tag reactTag, - AttributedString attributedString, - ParagraphAttributes paragraphAttributes, - LayoutConstraints layoutConstraints -) const { - RCTTextLayoutManager *textLayoutManager = (__bridge RCTTextLayoutManager *)self_; + Tag reactTag, + AttributedString attributedString, + ParagraphAttributes paragraphAttributes, + LayoutConstraints layoutConstraints) const { + RCTTextLayoutManager *textLayoutManager = + (__bridge RCTTextLayoutManager *)self_; return [textLayoutManager measureWithAttributedString:attributedString paragraphAttributes:paragraphAttributes layoutConstraints:layoutConstraints]; diff --git a/ReactCommon/fabric/uimanager/ComponentDescriptorFactory.h b/ReactCommon/fabric/uimanager/ComponentDescriptorFactory.h index 19d88b8cf92..3ef02294c38 100644 --- a/ReactCommon/fabric/uimanager/ComponentDescriptorFactory.h +++ b/ReactCommon/fabric/uimanager/ComponentDescriptorFactory.h @@ -24,9 +24,10 @@ namespace react { * should register its specific set of supported components. */ class ComponentDescriptorFactory { - -public: - static SharedComponentDescriptorRegistry buildRegistry(const SharedEventDispatcher &eventDispatcher, const SharedContextContainer &contextContainer); + public: + static SharedComponentDescriptorRegistry buildRegistry( + const SharedEventDispatcher &eventDispatcher, + const SharedContextContainer &contextContainer); }; } // namespace react diff --git a/ReactCommon/fabric/uimanager/ComponentDescriptorRegistry.cpp b/ReactCommon/fabric/uimanager/ComponentDescriptorRegistry.cpp index 22f291df803..b057f71a803 100644 --- a/ReactCommon/fabric/uimanager/ComponentDescriptorRegistry.cpp +++ b/ReactCommon/fabric/uimanager/ComponentDescriptorRegistry.cpp @@ -8,7 +8,8 @@ namespace facebook { namespace react { -void ComponentDescriptorRegistry::registerComponentDescriptor(SharedComponentDescriptor componentDescriptor) { +void ComponentDescriptorRegistry::registerComponentDescriptor( + SharedComponentDescriptor componentDescriptor) { ComponentHandle componentHandle = componentDescriptor->getComponentHandle(); _registryByHandle[componentHandle] = componentDescriptor; @@ -16,17 +17,20 @@ void ComponentDescriptorRegistry::registerComponentDescriptor(SharedComponentDes _registryByName[componentName] = componentDescriptor; } -const SharedComponentDescriptor ComponentDescriptorRegistry::operator[](const SharedShadowNode &shadowNode) const { +const SharedComponentDescriptor ComponentDescriptorRegistry::operator[]( + const SharedShadowNode &shadowNode) const { ComponentHandle componentHandle = shadowNode->getComponentHandle(); return _registryByHandle.at(componentHandle); } -const SharedComponentDescriptor ComponentDescriptorRegistry::operator[](const ComponentName &componentName) const { +const SharedComponentDescriptor ComponentDescriptorRegistry::operator[]( + const ComponentName &componentName) const { auto it = _registryByName.find(componentName); if (it == _registryByName.end()) { - throw std::invalid_argument(("Unable to find componentDescriptor for " + componentName).c_str()); - } - return it->second; + throw std::invalid_argument( + ("Unable to find componentDescriptor for " + componentName).c_str()); + } + return it->second; } } // namespace react diff --git a/ReactCommon/fabric/uimanager/ComponentDescriptorRegistry.h b/ReactCommon/fabric/uimanager/ComponentDescriptorRegistry.h index 14c17a72fe4..1a45747f4df 100644 --- a/ReactCommon/fabric/uimanager/ComponentDescriptorRegistry.h +++ b/ReactCommon/fabric/uimanager/ComponentDescriptorRegistry.h @@ -14,21 +14,25 @@ namespace react { class ComponentDescriptorRegistry; -using SharedComponentDescriptorRegistry = std::shared_ptr; +using SharedComponentDescriptorRegistry = + std::shared_ptr; /* * Registry of particular `ComponentDescriptor`s. */ class ComponentDescriptorRegistry { + public: + void registerComponentDescriptor( + SharedComponentDescriptor componentDescriptor); -public: - void registerComponentDescriptor(SharedComponentDescriptor componentDescriptor); + const SharedComponentDescriptor operator[]( + const SharedShadowNode &shadowNode) const; + const SharedComponentDescriptor operator[]( + const ComponentName &componentName) const; - const SharedComponentDescriptor operator[](const SharedShadowNode &shadowNode) const; - const SharedComponentDescriptor operator[](const ComponentName &componentName) const; - -private: - std::unordered_map _registryByHandle; + private: + std::unordered_map + _registryByHandle; std::unordered_map _registryByName; }; diff --git a/ReactCommon/fabric/uimanager/ContextContainer.h b/ReactCommon/fabric/uimanager/ContextContainer.h index 0b76b861be9..8c0819c8532 100644 --- a/ReactCommon/fabric/uimanager/ContextContainer.h +++ b/ReactCommon/fabric/uimanager/ContextContainer.h @@ -25,21 +25,18 @@ using SharedContextContainer = std::shared_ptr; * Instance types must be copyable. */ class ContextContainer final { - -public: + public: /* * Registers an instance of the particular type `T` in the container. * If `key` parameter is specified, the instance is registered * by `{type, key}` pair. */ - template + template void registerInstance(const T &instance, const std::string &key = {}) { std::lock_guard lock(mutex_); - instances_.insert({ - {std::type_index(typeid(T)), key}, - std::make_shared(instance) - }); + instances_.insert( + {{std::type_index(typeid(T)), key}, std::make_shared(instance)}); } /* @@ -47,18 +44,19 @@ public: * If `key` parameter is specified, the lookup will be performed * by {type, key} pair. */ - template + template T getInstance(const std::string &key = {}) const { std::lock_guard lock(mutex_); - return *std::static_pointer_cast(instances_.at({std::type_index(typeid(T)), key})); + return *std::static_pointer_cast( + instances_.at({std::type_index(typeid(T)), key})); } -private: + private: std::unordered_map< - std::pair, - std::shared_ptr - > instances_; + std::pair, + std::shared_ptr> + instances_; mutable std::mutex mutex_; }; diff --git a/ReactCommon/fabric/uimanager/Differentiator.cpp b/ReactCommon/fabric/uimanager/Differentiator.cpp index b9b2cadbd93..e3e26739df4 100644 --- a/ReactCommon/fabric/uimanager/Differentiator.cpp +++ b/ReactCommon/fabric/uimanager/Differentiator.cpp @@ -5,23 +5,26 @@ #include "Differentiator.h" -#include "ShadowView.h" #include +#include "ShadowView.h" namespace facebook { namespace react { -static void sliceChildShadowNodeViewPairsRecursively(ShadowViewNodePairList &pairList, Point layoutOffset, const ShadowNode &shadowNode) { +static void sliceChildShadowNodeViewPairsRecursively( + ShadowViewNodePairList &pairList, + Point layoutOffset, + const ShadowNode &shadowNode) { for (const auto &childShadowNode : shadowNode.getChildren()) { auto shadowView = ShadowView(*childShadowNode); - const auto layoutableShadowNode = dynamic_cast(childShadowNode.get()); + const auto layoutableShadowNode = + dynamic_cast(childShadowNode.get()); if (layoutableShadowNode && layoutableShadowNode->isLayoutOnly()) { sliceChildShadowNodeViewPairsRecursively( - pairList, - layoutOffset + shadowView.layoutMetrics.frame.origin, - *childShadowNode - ); + pairList, + layoutOffset + shadowView.layoutMetrics.frame.origin, + *childShadowNode); } else { shadowView.layoutMetrics.frame.origin += layoutOffset; pairList.push_back({shadowView, *childShadowNode}); @@ -29,18 +32,18 @@ static void sliceChildShadowNodeViewPairsRecursively(ShadowViewNodePairList &pai } } -static ShadowViewNodePairList sliceChildShadowNodeViewPairs(const ShadowNode &shadowNode) { +static ShadowViewNodePairList sliceChildShadowNodeViewPairs( + const ShadowNode &shadowNode) { ShadowViewNodePairList pairList; sliceChildShadowNodeViewPairsRecursively(pairList, {0, 0}, shadowNode); return pairList; } static void calculateShadowViewMutations( - ShadowViewMutationList &mutations, - const ShadowView &parentShadowView, - const ShadowViewNodePairList &oldChildPairs, - const ShadowViewNodePairList &newChildPairs -) { + ShadowViewMutationList &mutations, + const ShadowView &parentShadowView, + const ShadowViewNodePairList &oldChildPairs, + const ShadowViewNodePairList &newChildPairs) { // The current version of the algorithm is otimized for simplicity, // not for performance or optimal result. @@ -64,7 +67,8 @@ static void calculateShadowViewMutations( ShadowViewMutationList destructiveDownwardMutations = {}; // Stage 1: Collecting `Update` mutations - for (index = 0; index < oldChildPairs.size() && index < newChildPairs.size(); index++) { + for (index = 0; index < oldChildPairs.size() && index < newChildPairs.size(); + index++) { const auto &oldChildPair = oldChildPairs[index]; const auto &newChildPair = newChildPairs[index]; @@ -74,24 +78,23 @@ static void calculateShadowViewMutations( } if (oldChildPair.shadowView != newChildPair.shadowView) { - updateMutations.push_back( - ShadowViewMutation::UpdateMutation( + updateMutations.push_back(ShadowViewMutation::UpdateMutation( parentShadowView, oldChildPair.shadowView, newChildPair.shadowView, - index - ) - ); + index)); } - const auto oldGrandChildPairs = sliceChildShadowNodeViewPairs(oldChildPair.shadowNode); - const auto newGrandChildPairs = sliceChildShadowNodeViewPairs(newChildPair.shadowNode); + const auto oldGrandChildPairs = + sliceChildShadowNodeViewPairs(oldChildPair.shadowNode); + const auto newGrandChildPairs = + sliceChildShadowNodeViewPairs(newChildPair.shadowNode); calculateShadowViewMutations( - *(newGrandChildPairs.size() ? &downwardMutations : &destructiveDownwardMutations), - oldChildPair.shadowView, - oldGrandChildPairs, - newGrandChildPairs - ); + *(newGrandChildPairs.size() ? &downwardMutations + : &destructiveDownwardMutations), + oldChildPair.shadowView, + oldGrandChildPairs, + newGrandChildPairs); } int lastIndexAfterFirstStage = index; @@ -100,30 +103,21 @@ static void calculateShadowViewMutations( for (; index < newChildPairs.size(); index++) { const auto &newChildPair = newChildPairs[index]; - insertMutations.push_back( - ShadowViewMutation::InsertMutation( - parentShadowView, - newChildPair.shadowView, - index - ) - ); + insertMutations.push_back(ShadowViewMutation::InsertMutation( + parentShadowView, newChildPair.shadowView, index)); insertedPaires.insert({newChildPair.shadowView.tag, newChildPair}); } // Stage 3: Collecting `Delete` and `Remove` mutations - for (index = lastIndexAfterFirstStage; index < oldChildPairs.size(); index++) { + for (index = lastIndexAfterFirstStage; index < oldChildPairs.size(); + index++) { const auto &oldChildPair = oldChildPairs[index]; // Even if the old view was (re)inserted, we have to generate `remove` // mutation. - removeMutations.push_back( - ShadowViewMutation::RemoveMutation( - parentShadowView, - oldChildPair.shadowView, - index - ) - ); + removeMutations.push_back(ShadowViewMutation::RemoveMutation( + parentShadowView, oldChildPair.shadowView, index)); const auto &it = insertedPaires.find(oldChildPair.shadowView.tag); @@ -132,33 +126,31 @@ static void calculateShadowViewMutations( // We have to generate `delete` mutation and apply the algorithm // recursively. deleteMutations.push_back( - ShadowViewMutation::DeleteMutation( - oldChildPair.shadowView - ) - ); + ShadowViewMutation::DeleteMutation(oldChildPair.shadowView)); // We also have to call the algorithm recursively to clean up the entire // subtree starting from the removed view. calculateShadowViewMutations( - destructiveDownwardMutations, - oldChildPair.shadowView, - sliceChildShadowNodeViewPairs(oldChildPair.shadowNode), - {} - ); + destructiveDownwardMutations, + oldChildPair.shadowView, + sliceChildShadowNodeViewPairs(oldChildPair.shadowNode), + {}); } else { // The old view *was* (re)inserted. // We have to call the algorithm recursively if the inserted view // is *not* the same as removed one. const auto &newChildPair = it->second; if (newChildPair.shadowView != oldChildPair.shadowView) { - const auto oldGrandChildPairs = sliceChildShadowNodeViewPairs(oldChildPair.shadowNode); - const auto newGrandChildPairs = sliceChildShadowNodeViewPairs(newChildPair.shadowNode); + const auto oldGrandChildPairs = + sliceChildShadowNodeViewPairs(oldChildPair.shadowNode); + const auto newGrandChildPairs = + sliceChildShadowNodeViewPairs(newChildPair.shadowNode); calculateShadowViewMutations( - *(newGrandChildPairs.size() ? &downwardMutations : &destructiveDownwardMutations), - newChildPair.shadowView, - oldGrandChildPairs, - newGrandChildPairs - ); + *(newGrandChildPairs.size() ? &downwardMutations + : &destructiveDownwardMutations), + newChildPair.shadowView, + oldGrandChildPairs, + newGrandChildPairs); } // In any case we have to remove the view from `insertedPaires` as @@ -170,42 +162,48 @@ static void calculateShadowViewMutations( } // Stage 4: Collecting `Create` mutations - for (index = lastIndexAfterFirstStage; index < newChildPairs.size(); index++) { + for (index = lastIndexAfterFirstStage; index < newChildPairs.size(); + index++) { const auto &newChildPair = newChildPairs[index]; - if (insertedPaires.find(newChildPair.shadowView.tag) == insertedPaires.end()) { + if (insertedPaires.find(newChildPair.shadowView.tag) == + insertedPaires.end()) { // The new view was (re)inserted, so there is no need to create it. continue; } createMutations.push_back( - ShadowViewMutation::CreateMutation( - newChildPair.shadowView - ) - ); + ShadowViewMutation::CreateMutation(newChildPair.shadowView)); calculateShadowViewMutations( - downwardMutations, - newChildPair.shadowView, - {}, - sliceChildShadowNodeViewPairs(newChildPair.shadowNode) - ); + downwardMutations, + newChildPair.shadowView, + {}, + sliceChildShadowNodeViewPairs(newChildPair.shadowNode)); } // All mutations in an optimal order: - mutations.insert(mutations.end(), destructiveDownwardMutations.begin(), destructiveDownwardMutations.end()); - mutations.insert(mutations.end(), updateMutations.begin(), updateMutations.end()); - mutations.insert(mutations.end(), removeMutations.rbegin(), removeMutations.rend()); - mutations.insert(mutations.end(), deleteMutations.begin(), deleteMutations.end()); - mutations.insert(mutations.end(), createMutations.begin(), createMutations.end()); - mutations.insert(mutations.end(), insertMutations.begin(), insertMutations.end()); - mutations.insert(mutations.end(), downwardMutations.begin(), downwardMutations.end()); + mutations.insert( + mutations.end(), + destructiveDownwardMutations.begin(), + destructiveDownwardMutations.end()); + mutations.insert( + mutations.end(), updateMutations.begin(), updateMutations.end()); + mutations.insert( + mutations.end(), removeMutations.rbegin(), removeMutations.rend()); + mutations.insert( + mutations.end(), deleteMutations.begin(), deleteMutations.end()); + mutations.insert( + mutations.end(), createMutations.begin(), createMutations.end()); + mutations.insert( + mutations.end(), insertMutations.begin(), insertMutations.end()); + mutations.insert( + mutations.end(), downwardMutations.begin(), downwardMutations.end()); } ShadowViewMutationList calculateShadowViewMutations( - const ShadowNode &oldRootShadowNode, - const ShadowNode &newRootShadowNode -) { + const ShadowNode &oldRootShadowNode, + const ShadowNode &newRootShadowNode) { // Root shadow nodes must have same tag. assert(oldRootShadowNode.getTag() == newRootShadowNode.getTag()); @@ -215,22 +213,15 @@ ShadowViewMutationList calculateShadowViewMutations( auto newRootShadowView = ShadowView(newRootShadowNode); if (oldRootShadowView != newRootShadowView) { - mutations.push_back( - ShadowViewMutation::UpdateMutation( - ShadowView(), - oldRootShadowView, - newRootShadowView, - -1 - ) - ); + mutations.push_back(ShadowViewMutation::UpdateMutation( + ShadowView(), oldRootShadowView, newRootShadowView, -1)); } calculateShadowViewMutations( - mutations, - ShadowView(oldRootShadowNode), - sliceChildShadowNodeViewPairs(oldRootShadowNode), - sliceChildShadowNodeViewPairs(newRootShadowNode) - ); + mutations, + ShadowView(oldRootShadowNode), + sliceChildShadowNodeViewPairs(oldRootShadowNode), + sliceChildShadowNodeViewPairs(newRootShadowNode)); return mutations; } diff --git a/ReactCommon/fabric/uimanager/Differentiator.h b/ReactCommon/fabric/uimanager/Differentiator.h index ff41a3802f3..384b5570dc0 100644 --- a/ReactCommon/fabric/uimanager/Differentiator.h +++ b/ReactCommon/fabric/uimanager/Differentiator.h @@ -17,9 +17,8 @@ namespace react { * The list of mutations might be and might not be optimal. */ ShadowViewMutationList calculateShadowViewMutations( - const ShadowNode &oldRootShadowNode, - const ShadowNode &newRootShadowNode -); + const ShadowNode &oldRootShadowNode, + const ShadowNode &newRootShadowNode); } // namespace react } // namespace facebook diff --git a/ReactCommon/fabric/uimanager/FabricUIManager.cpp b/ReactCommon/fabric/uimanager/FabricUIManager.cpp index a483b8d82b8..3d92072af7f 100644 --- a/ReactCommon/fabric/uimanager/FabricUIManager.cpp +++ b/ReactCommon/fabric/uimanager/FabricUIManager.cpp @@ -12,9 +12,9 @@ #include #include #include -#include #include #include +#include #include #include @@ -22,7 +22,8 @@ namespace facebook { namespace react { static const RawProps rawPropsFromDynamic(const folly::dynamic object) { - // TODO: Convert this to something smarter, probably returning `std::iterator`. + // TODO: Convert this to something smarter, probably returning + // `std::iterator`. RawProps result; if (object.isNull()) { @@ -44,7 +45,8 @@ static const std::string componentNameByReactViewName(std::string viewName) { // eventually, all names will be unified. std::string rctPrefix("RCT"); - if (std::mismatch(rctPrefix.begin(), rctPrefix.end(), viewName.begin()).first == rctPrefix.end()) { + if (std::mismatch(rctPrefix.begin(), rctPrefix.end(), viewName.begin()) + .first == rctPrefix.end()) { // If `viewName` has "RCT" prefix, remove it. viewName.erase(0, rctPrefix.length()); } @@ -72,13 +74,10 @@ static const std::string componentNameByReactViewName(std::string viewName) { // We need this temporarly for testing purposes until we have proper // implementation of core components. - if ( - viewName == "SinglelineTextInputView" || - viewName == "MultilineTextInputView" || - viewName == "RefreshControl" || - viewName == "SafeAreaView" || - viewName == "ScrollContentView" || - viewName == "AndroidHorizontalScrollContentView" // Android + if (viewName == "SinglelineTextInputView" || + viewName == "MultilineTextInputView" || viewName == "RefreshControl" || + viewName == "SafeAreaView" || viewName == "ScrollContentView" || + viewName == "AndroidHorizontalScrollContentView" // Android ) { return "View"; } @@ -86,32 +85,27 @@ static const std::string componentNameByReactViewName(std::string viewName) { return viewName; } - FabricUIManager::FabricUIManager( +FabricUIManager::FabricUIManager( std::unique_ptr executor, std::function installer, - std::function uninstaller - ): - executor_(std::move(executor)), - installer_(std::move(installer)), - uninstaller_(std::move(uninstaller)) { - - (*executor_)([this] { - installer_(*this); - }); + std::function uninstaller) + : executor_(std::move(executor)), + installer_(std::move(installer)), + uninstaller_(std::move(uninstaller)) { + (*executor_)([this] { installer_(*this); }); } FabricUIManager::~FabricUIManager() { // We move `executor_` and `uninstaller_` inside a lambda to extend their // life-time until the lambda finishes. - auto executor = std::shared_ptr {std::move(executor_)}; + auto executor = std::shared_ptr{std::move(executor_)}; auto uninstaller = std::move(uninstaller_); - (*executor)([uninstaller, executor]() { - uninstaller(); - }); + (*executor)([uninstaller, executor]() { uninstaller(); }); } -void FabricUIManager::setComponentDescriptorRegistry(const SharedComponentDescriptorRegistry &componentDescriptorRegistry) { +void FabricUIManager::setComponentDescriptorRegistry( + const SharedComponentDescriptorRegistry &componentDescriptorRegistry) { componentDescriptorRegistry_ = componentDescriptorRegistry; } @@ -123,63 +117,74 @@ UIManagerDelegate *FabricUIManager::getDelegate() { return delegate_; } -void FabricUIManager::setDispatchEventToEmptyTargetFunction(std::function dispatchEventFunction) { +void FabricUIManager::setDispatchEventToEmptyTargetFunction( + std::function dispatchEventFunction) { dispatchEventToEmptyTargetFunction_ = dispatchEventFunction; } -void FabricUIManager::setDispatchEventToTargetFunction(std::function dispatchEventFunction) { +void FabricUIManager::setDispatchEventToTargetFunction( + std::function dispatchEventFunction) { dispatchEventToTargetFunction_ = dispatchEventFunction; } -void FabricUIManager::setStartSurfaceFunction(std::function startSurfaceFunction) { +void FabricUIManager::setStartSurfaceFunction( + std::function startSurfaceFunction) { startSurfaceFunction_ = startSurfaceFunction; } -void FabricUIManager::setStopSurfaceFunction(std::function stopSurfaceFunction) { +void FabricUIManager::setStopSurfaceFunction( + std::function stopSurfaceFunction) { stopSurfaceFunction_ = stopSurfaceFunction; } -void FabricUIManager::dispatchEventToTarget(const EventTarget *eventTarget, const std::string &type, const folly::dynamic &payload) const { +void FabricUIManager::dispatchEventToTarget( + const EventTarget *eventTarget, + const std::string &type, + const folly::dynamic &payload) const { if (eventTarget) { dispatchEventToTargetFunction_( - *eventHandler_, - *eventTarget, - const_cast(type), - const_cast(payload) - ); + *eventHandler_, + *eventTarget, + const_cast(type), + const_cast(payload)); } else { dispatchEventToEmptyTargetFunction_( - *eventHandler_, - const_cast(type), - const_cast(payload) - ); + *eventHandler_, + const_cast(type), + const_cast(payload)); } } -void FabricUIManager::startSurface(SurfaceId surfaceId, const std::string &moduleName, const folly::dynamic &initialProps) const { +void FabricUIManager::startSurface( + SurfaceId surfaceId, + const std::string &moduleName, + const folly::dynamic &initialProps) const { (*executor_)([this, surfaceId, moduleName, initialProps] { startSurfaceFunction_(surfaceId, moduleName, initialProps); }); } void FabricUIManager::stopSurface(SurfaceId surfaceId) const { - (*executor_)([this, surfaceId] { - stopSurfaceFunction_(surfaceId); - }); + (*executor_)([this, surfaceId] { stopSurfaceFunction_(surfaceId); }); } -SharedShadowNode FabricUIManager::createNode(int tag, std::string viewName, int rootTag, folly::dynamic props, SharedEventTarget eventTarget) const { +SharedShadowNode FabricUIManager::createNode( + int tag, + std::string viewName, + int rootTag, + folly::dynamic props, + SharedEventTarget eventTarget) const { ComponentName componentName = componentNameByReactViewName(viewName); - const SharedComponentDescriptor &componentDescriptor = (*componentDescriptorRegistry_)[componentName]; + const SharedComponentDescriptor &componentDescriptor = + (*componentDescriptorRegistry_)[componentName]; RawProps rawProps = rawPropsFromDynamic(props); - SharedShadowNode shadowNode = - componentDescriptor->createShadowNode({ - .tag = tag, - .rootTag = rootTag, - .eventEmitter = componentDescriptor->createEventEmitter(std::move(eventTarget), tag), - .props = componentDescriptor->cloneProps(nullptr, rawProps) - }); + SharedShadowNode shadowNode = componentDescriptor->createShadowNode( + {.tag = tag, + .rootTag = rootTag, + .eventEmitter = + componentDescriptor->createEventEmitter(std::move(eventTarget), tag), + .props = componentDescriptor->cloneProps(nullptr, rawProps)}); if (delegate_) { delegate_->uiManagerDidCreateShadowNode(shadowNode); @@ -188,83 +193,91 @@ SharedShadowNode FabricUIManager::createNode(int tag, std::string viewName, int return shadowNode; } -SharedShadowNode FabricUIManager::cloneNode(const SharedShadowNode &shadowNode) const { - const SharedComponentDescriptor &componentDescriptor = (*componentDescriptorRegistry_)[shadowNode]; +SharedShadowNode FabricUIManager::cloneNode( + const SharedShadowNode &shadowNode) const { + const SharedComponentDescriptor &componentDescriptor = + (*componentDescriptorRegistry_)[shadowNode]; SharedShadowNode clonedShadowNode = - componentDescriptor->cloneShadowNode(*shadowNode, {}); + componentDescriptor->cloneShadowNode(*shadowNode, {}); return clonedShadowNode; } -SharedShadowNode FabricUIManager::cloneNodeWithNewChildren(const SharedShadowNode &shadowNode) const { +SharedShadowNode FabricUIManager::cloneNodeWithNewChildren( + const SharedShadowNode &shadowNode) const { // Assuming semantic: Cloning with same props but empty children. - const SharedComponentDescriptor &componentDescriptor = (*componentDescriptorRegistry_)[shadowNode]; + const SharedComponentDescriptor &componentDescriptor = + (*componentDescriptorRegistry_)[shadowNode]; - SharedShadowNode clonedShadowNode = - componentDescriptor->cloneShadowNode( - *shadowNode, - { - .children = ShadowNode::emptySharedShadowNodeSharedList() - } - ); + SharedShadowNode clonedShadowNode = componentDescriptor->cloneShadowNode( + *shadowNode, {.children = ShadowNode::emptySharedShadowNodeSharedList()}); return clonedShadowNode; } -SharedShadowNode FabricUIManager::cloneNodeWithNewProps(const SharedShadowNode &shadowNode, folly::dynamic props) const { +SharedShadowNode FabricUIManager::cloneNodeWithNewProps( + const SharedShadowNode &shadowNode, + folly::dynamic props) const { // Assuming semantic: Cloning with same children and specified props. - const SharedComponentDescriptor &componentDescriptor = (*componentDescriptorRegistry_)[shadowNode]; + const SharedComponentDescriptor &componentDescriptor = + (*componentDescriptorRegistry_)[shadowNode]; RawProps rawProps = rawPropsFromDynamic(props); - SharedShadowNode clonedShadowNode = - componentDescriptor->cloneShadowNode( + SharedShadowNode clonedShadowNode = componentDescriptor->cloneShadowNode( *shadowNode, - { - .props = componentDescriptor->cloneProps(shadowNode->getProps(), rawProps) - } - ); + {.props = + componentDescriptor->cloneProps(shadowNode->getProps(), rawProps)}); return clonedShadowNode; } -SharedShadowNode FabricUIManager::cloneNodeWithNewChildrenAndProps(const SharedShadowNode &shadowNode, folly::dynamic props) const { +SharedShadowNode FabricUIManager::cloneNodeWithNewChildrenAndProps( + const SharedShadowNode &shadowNode, + folly::dynamic props) const { // Assuming semantic: Cloning with empty children and specified props. - const SharedComponentDescriptor &componentDescriptor = (*componentDescriptorRegistry_)[shadowNode]; + const SharedComponentDescriptor &componentDescriptor = + (*componentDescriptorRegistry_)[shadowNode]; RawProps rawProps = rawPropsFromDynamic(props); - SharedShadowNode clonedShadowNode = - componentDescriptor->cloneShadowNode( + SharedShadowNode clonedShadowNode = componentDescriptor->cloneShadowNode( *shadowNode, - { - .props = componentDescriptor->cloneProps(shadowNode->getProps(), rawProps), - .children = ShadowNode::emptySharedShadowNodeSharedList() - } - ); + {.props = + componentDescriptor->cloneProps(shadowNode->getProps(), rawProps), + .children = ShadowNode::emptySharedShadowNodeSharedList()}); return clonedShadowNode; } -void FabricUIManager::appendChild(const SharedShadowNode &parentShadowNode, const SharedShadowNode &childShadowNode) const { - const SharedComponentDescriptor &componentDescriptor = (*componentDescriptorRegistry_)[parentShadowNode]; +void FabricUIManager::appendChild( + const SharedShadowNode &parentShadowNode, + const SharedShadowNode &childShadowNode) const { + const SharedComponentDescriptor &componentDescriptor = + (*componentDescriptorRegistry_)[parentShadowNode]; componentDescriptor->appendChild(parentShadowNode, childShadowNode); } -SharedShadowNodeUnsharedList FabricUIManager::createChildSet(int rootTag) const { +SharedShadowNodeUnsharedList FabricUIManager::createChildSet( + int rootTag) const { return std::make_shared(SharedShadowNodeList({})); } -void FabricUIManager::appendChildToSet(const SharedShadowNodeUnsharedList &shadowNodeList, const SharedShadowNode &shadowNode) const { +void FabricUIManager::appendChildToSet( + const SharedShadowNodeUnsharedList &shadowNodeList, + const SharedShadowNode &shadowNode) const { shadowNodeList->push_back(shadowNode); } -void FabricUIManager::completeRoot(int rootTag, const SharedShadowNodeUnsharedList &children) const { +void FabricUIManager::completeRoot( + int rootTag, + const SharedShadowNodeUnsharedList &children) const { if (delegate_) { delegate_->uiManagerDidFinishTransaction(rootTag, children); } } -void FabricUIManager::registerEventHandler(UniqueEventHandler eventHandler) const { +void FabricUIManager::registerEventHandler( + UniqueEventHandler eventHandler) const { // Technically, it should be protected by a mutex but regularly it should // be safe because it used only during initialization process. eventHandler_ = std::move(eventHandler); diff --git a/ReactCommon/fabric/uimanager/FabricUIManager.h b/ReactCommon/fabric/uimanager/FabricUIManager.h index 3481faecce3..00011996849 100644 --- a/ReactCommon/fabric/uimanager/FabricUIManager.h +++ b/ReactCommon/fabric/uimanager/FabricUIManager.h @@ -26,28 +26,37 @@ using UIManager = FabricUIManager; * Particular implementations of those functions should capture references to * the runtime and ensure proper threading. */ -using UIManagerInstaller = void (UIManager &uiManager); -using UIManagerUninstaller = void (); +using UIManagerInstaller = void(UIManager &uiManager); +using UIManagerUninstaller = void(); -using DispatchEventToEmptyTargetFunction = void (const EventHandler &eventHandler, const std::string &type, const folly::dynamic &payload); -using DispatchEventToTargetFunction = void (const EventHandler &eventHandler, const EventTarget &eventTarget, const std::string &type, const folly::dynamic &payload); +using DispatchEventToEmptyTargetFunction = void( + const EventHandler &eventHandler, + const std::string &type, + const folly::dynamic &payload); +using DispatchEventToTargetFunction = void( + const EventHandler &eventHandler, + const EventTarget &eventTarget, + const std::string &type, + const folly::dynamic &payload); -using StartSurface = void (SurfaceId surfaceId, const std::string &moduleName, const folly::dynamic &initalProps); -using StopSurface = void (SurfaceId surfaceId); +using StartSurface = void( + SurfaceId surfaceId, + const std::string &moduleName, + const folly::dynamic &initalProps); +using StopSurface = void(SurfaceId surfaceId); class FabricUIManager { -public: - + public: FabricUIManager( - std::unique_ptr executor, - std::function installer, - std::function uninstaller - ); + std::unique_ptr executor, + std::function installer, + std::function uninstaller); ~FabricUIManager(); #pragma mark - Native-facing Interface - void setComponentDescriptorRegistry(const SharedComponentDescriptorRegistry &componentDescriptorRegistry); + void setComponentDescriptorRegistry( + const SharedComponentDescriptorRegistry &componentDescriptorRegistry); /* * Sets and gets the UIManager's delegate. @@ -62,15 +71,23 @@ public: /* * Registers callback functions. */ - void setDispatchEventToEmptyTargetFunction(std::function dispatchEventFunction); - void setDispatchEventToTargetFunction(std::function dispatchEventFunction); + void setDispatchEventToEmptyTargetFunction( + std::function dispatchEventFunction); + void setDispatchEventToTargetFunction( + std::function dispatchEventFunction); void setStartSurfaceFunction(std::function); void setStopSurfaceFunction(std::function); #pragma mark - Native-facing Interface - void dispatchEventToTarget(const EventTarget *eventTarget, const std::string &type, const folly::dynamic &payload) const; - void startSurface(SurfaceId surfaceId, const std::string &moduleName, const folly::dynamic &initialProps) const; + void dispatchEventToTarget( + const EventTarget *eventTarget, + const std::string &type, + const folly::dynamic &payload) const; + void startSurface( + SurfaceId surfaceId, + const std::string &moduleName, + const folly::dynamic &initialProps) const; void stopSurface(SurfaceId surfaceId) const; #pragma mark - JavaScript/React-facing Interface @@ -79,24 +96,40 @@ public: * All those JavaScript-facing methods call be called from any thread. * `UIManager` guarantees its own thread-safety, but it does *not* guarantee * thread-safety of `ShadowNode`s that it operates on. The caller should - * enforce logical correctness and thread-safety of the unsealed `ShadowNode`s. + * enforce logical correctness and thread-safety of the unsealed + * `ShadowNode`s. */ - SharedShadowNode createNode(Tag reactTag, std::string viewName, Tag rootTag, folly::dynamic props, SharedEventTarget eventTarget) const; + SharedShadowNode createNode( + Tag reactTag, + std::string viewName, + Tag rootTag, + folly::dynamic props, + SharedEventTarget eventTarget) const; SharedShadowNode cloneNode(const SharedShadowNode &node) const; SharedShadowNode cloneNodeWithNewChildren(const SharedShadowNode &node) const; - SharedShadowNode cloneNodeWithNewProps(const SharedShadowNode &node, folly::dynamic props) const; - SharedShadowNode cloneNodeWithNewChildrenAndProps(const SharedShadowNode &node, folly::dynamic newProps) const; - void appendChild(const SharedShadowNode &parentNode, const SharedShadowNode &childNode) const; + SharedShadowNode cloneNodeWithNewProps( + const SharedShadowNode &node, + folly::dynamic props) const; + SharedShadowNode cloneNodeWithNewChildrenAndProps( + const SharedShadowNode &node, + folly::dynamic newProps) const; + void appendChild( + const SharedShadowNode &parentNode, + const SharedShadowNode &childNode) const; SharedShadowNodeUnsharedList createChildSet(Tag rootTag) const; - void appendChildToSet(const SharedShadowNodeUnsharedList &childSet, const SharedShadowNode &childNode) const; - void completeRoot(Tag rootTag, const SharedShadowNodeUnsharedList &childSet) const; + void appendChildToSet( + const SharedShadowNodeUnsharedList &childSet, + const SharedShadowNode &childNode) const; + void completeRoot(Tag rootTag, const SharedShadowNodeUnsharedList &childSet) + const; void registerEventHandler(UniqueEventHandler eventHandler) const; -private: + private: SharedComponentDescriptorRegistry componentDescriptorRegistry_; UIManagerDelegate *delegate_; mutable UniqueEventHandler eventHandler_; - std::function dispatchEventToEmptyTargetFunction_; + std::function + dispatchEventToEmptyTargetFunction_; std::function dispatchEventToTargetFunction_; std::function startSurfaceFunction_; std::function stopSurfaceFunction_; diff --git a/ReactCommon/fabric/uimanager/Scheduler.cpp b/ReactCommon/fabric/uimanager/Scheduler.cpp index 4cbada1e4d0..9439610d59d 100644 --- a/ReactCommon/fabric/uimanager/Scheduler.cpp +++ b/ReactCommon/fabric/uimanager/Scheduler.cpp @@ -15,34 +15,33 @@ namespace facebook { namespace react { -Scheduler::Scheduler(const SharedContextContainer &contextContainer): - contextContainer_(contextContainer) { - - const auto asynchronousEventBeatFactory = contextContainer->getInstance("asynchronous"); - const auto synchronousEventBeatFactory = contextContainer->getInstance("synchronous"); +Scheduler::Scheduler(const SharedContextContainer &contextContainer) + : contextContainer_(contextContainer) { + const auto asynchronousEventBeatFactory = + contextContainer->getInstance("asynchronous"); + const auto synchronousEventBeatFactory = + contextContainer->getInstance("synchronous"); uiManager_ = std::make_shared( - std::make_unique(asynchronousEventBeatFactory()), - contextContainer->getInstance>("uimanager-installer"), - contextContainer->getInstance>("uimanager-uninstaller") - ); + std::make_unique(asynchronousEventBeatFactory()), + contextContainer->getInstance>( + "uimanager-installer"), + contextContainer->getInstance>( + "uimanager-uninstaller")); - auto eventDispatcher = - std::make_shared( + auto eventDispatcher = std::make_shared( std::bind( - &FabricUIManager::dispatchEventToTarget, - uiManager_.get(), - std::placeholders::_1, - std::placeholders::_2, - std::placeholders::_3 - ), + &FabricUIManager::dispatchEventToTarget, + uiManager_.get(), + std::placeholders::_1, + std::placeholders::_2, + std::placeholders::_3), synchronousEventBeatFactory, - asynchronousEventBeatFactory - ); + asynchronousEventBeatFactory); uiManager_->setComponentDescriptorRegistry( - ComponentDescriptorFactory::buildRegistry(eventDispatcher, contextContainer) - ); + ComponentDescriptorFactory::buildRegistry( + eventDispatcher, contextContainer)); uiManager_->setDelegate(this); } @@ -52,15 +51,15 @@ Scheduler::~Scheduler() { } void Scheduler::startSurface( - SurfaceId surfaceId, - const std::string &moduleName, - const folly::dynamic &initialProps, - const LayoutConstraints &layoutConstraints, - const LayoutContext &layoutContext -) const { + SurfaceId surfaceId, + const std::string &moduleName, + const folly::dynamic &initialProps, + const LayoutConstraints &layoutConstraints, + const LayoutContext &layoutContext) const { std::lock_guard lock(mutex_); - auto shadowTree = std::make_unique(surfaceId, layoutConstraints, layoutContext); + auto shadowTree = + std::make_unique(surfaceId, layoutConstraints, layoutContext); shadowTree->setDelegate(this); shadowTreeRegistry_.emplace(surfaceId, std::move(shadowTree)); @@ -80,16 +79,16 @@ void Scheduler::stopSurface(SurfaceId surfaceId) const { const auto &shadowTree = iterator->second; assert(shadowTree); // As part of stopping the Surface, we have to commit an empty tree. - shadowTree->complete(std::const_pointer_cast(ShadowNode::emptySharedShadowNodeSharedList())); + shadowTree->complete(std::const_pointer_cast( + ShadowNode::emptySharedShadowNodeSharedList())); shadowTree->setDelegate(nullptr); shadowTreeRegistry_.erase(iterator); } Size Scheduler::measureSurface( - SurfaceId surfaceId, - const LayoutConstraints &layoutConstraints, - const LayoutContext &layoutContext -) const { + SurfaceId surfaceId, + const LayoutConstraints &layoutConstraints, + const LayoutContext &layoutContext) const { std::lock_guard lock(mutex_); const auto &shadowTree = shadowTreeRegistry_.at(surfaceId); assert(shadowTree); @@ -97,10 +96,9 @@ Size Scheduler::measureSurface( } void Scheduler::constraintSurfaceLayout( - SurfaceId surfaceId, - const LayoutConstraints &layoutConstraints, - const LayoutContext &layoutContext -) const { + SurfaceId surfaceId, + const LayoutConstraints &layoutConstraints, + const LayoutContext &layoutContext) const { std::lock_guard lock(mutex_); const auto &shadowTree = shadowTreeRegistry_.at(surfaceId); assert(shadowTree); @@ -121,15 +119,20 @@ SchedulerDelegate *Scheduler::getDelegate() const { #pragma mark - ShadowTreeDelegate -void Scheduler::shadowTreeDidCommit(const ShadowTree &shadowTree, const ShadowViewMutationList &mutations) const { +void Scheduler::shadowTreeDidCommit( + const ShadowTree &shadowTree, + const ShadowViewMutationList &mutations) const { if (delegate_) { - delegate_->schedulerDidFinishTransaction(shadowTree.getSurfaceId(), mutations); + delegate_->schedulerDidFinishTransaction( + shadowTree.getSurfaceId(), mutations); } } #pragma mark - UIManagerDelegate -void Scheduler::uiManagerDidFinishTransaction(Tag rootTag, const SharedShadowNodeUnsharedList &rootChildNodes) { +void Scheduler::uiManagerDidFinishTransaction( + Tag rootTag, + const SharedShadowNodeUnsharedList &rootChildNodes) { std::lock_guard lock(mutex_); const auto iterator = shadowTreeRegistry_.find(rootTag); @@ -142,9 +145,11 @@ void Scheduler::uiManagerDidFinishTransaction(Tag rootTag, const SharedShadowNod iterator->second->complete(rootChildNodes); } -void Scheduler::uiManagerDidCreateShadowNode(const SharedShadowNode &shadowNode) { +void Scheduler::uiManagerDidCreateShadowNode( + const SharedShadowNode &shadowNode) { if (delegate_) { - delegate_->schedulerDidRequestPreliminaryViewAllocation(shadowNode->getComponentName()); + delegate_->schedulerDidRequestPreliminaryViewAllocation( + shadowNode->getComponentName()); } } diff --git a/ReactCommon/fabric/uimanager/Scheduler.h b/ReactCommon/fabric/uimanager/Scheduler.h index 0fa004369ca..3bd5a4876d8 100644 --- a/ReactCommon/fabric/uimanager/Scheduler.h +++ b/ReactCommon/fabric/uimanager/Scheduler.h @@ -12,9 +12,9 @@ #include #include #include -#include #include #include +#include namespace facebook { namespace react { @@ -24,31 +24,26 @@ class FabricUIManager; /* * Scheduler coordinates Shadow Tree updates and event flows. */ -class Scheduler final: - public UIManagerDelegate, - public ShadowTreeDelegate { - -public: +class Scheduler final : public UIManagerDelegate, public ShadowTreeDelegate { + public: Scheduler(const SharedContextContainer &contextContainer); ~Scheduler(); #pragma mark - Surface Management void startSurface( - SurfaceId surfaceId, - const std::string &moduleName, - const folly::dynamic &initialProps, - const LayoutConstraints &layoutConstraints = {}, - const LayoutContext &layoutContext = {} - ) const; + SurfaceId surfaceId, + const std::string &moduleName, + const folly::dynamic &initialProps, + const LayoutConstraints &layoutConstraints = {}, + const LayoutContext &layoutContext = {}) const; void stopSurface(SurfaceId surfaceId) const; Size measureSurface( - SurfaceId surfaceId, - const LayoutConstraints &layoutConstraints, - const LayoutContext &layoutContext - ) const; + SurfaceId surfaceId, + const LayoutConstraints &layoutConstraints, + const LayoutContext &layoutContext) const; /* * Applies given `layoutConstraints` and `layoutContext` to a Surface. @@ -58,10 +53,9 @@ public: * Can be called from any thread. */ void constraintSurfaceLayout( - SurfaceId surfaceId, - const LayoutConstraints &layoutConstraints, - const LayoutContext &layoutContext - ) const; + SurfaceId surfaceId, + const LayoutConstraints &layoutConstraints, + const LayoutContext &layoutContext) const; #pragma mark - Delegate @@ -75,12 +69,17 @@ public: #pragma mark - UIManagerDelegate - void uiManagerDidFinishTransaction(Tag rootTag, const SharedShadowNodeUnsharedList &rootChildNodes) override; - void uiManagerDidCreateShadowNode(const SharedShadowNode &shadowNode) override; + void uiManagerDidFinishTransaction( + Tag rootTag, + const SharedShadowNodeUnsharedList &rootChildNodes) override; + void uiManagerDidCreateShadowNode( + const SharedShadowNode &shadowNode) override; #pragma mark - ShadowTreeDelegate - void shadowTreeDidCommit(const ShadowTree &shadowTree, const ShadowViewMutationList &mutations) const override; + void shadowTreeDidCommit( + const ShadowTree &shadowTree, + const ShadowViewMutationList &mutations) const override; #pragma mark - Deprecated @@ -89,11 +88,12 @@ public: */ std::shared_ptr getUIManager_DO_NOT_USE(); -private: + private: SchedulerDelegate *delegate_; std::shared_ptr uiManager_; mutable std::mutex mutex_; - mutable std::unordered_map> shadowTreeRegistry_; // Protected by `mutex_`. + mutable std::unordered_map> + shadowTreeRegistry_; // Protected by `mutex_`. SharedEventDispatcher eventDispatcher_; SharedContextContainer contextContainer_; }; diff --git a/ReactCommon/fabric/uimanager/SchedulerDelegate.h b/ReactCommon/fabric/uimanager/SchedulerDelegate.h index 9ea0efd4756..2a50c29061b 100644 --- a/ReactCommon/fabric/uimanager/SchedulerDelegate.h +++ b/ReactCommon/fabric/uimanager/SchedulerDelegate.h @@ -18,19 +18,21 @@ namespace react { * Abstract class for Scheduler's delegate. */ class SchedulerDelegate { - -public: + public: /* * Called right after Scheduler computed (and laid out) a new updated version * of the tree and calculated a set of mutations which are suffisient * to construct a new one. */ - virtual void schedulerDidFinishTransaction(Tag rootTag, const ShadowViewMutationList &mutations) = 0; + virtual void schedulerDidFinishTransaction( + Tag rootTag, + const ShadowViewMutationList &mutations) = 0; /* * Called right after a new ShadowNode was created. */ - virtual void schedulerDidRequestPreliminaryViewAllocation(ComponentName componentName) = 0; + virtual void schedulerDidRequestPreliminaryViewAllocation( + ComponentName componentName) = 0; virtual ~SchedulerDelegate() noexcept = default; }; diff --git a/ReactCommon/fabric/uimanager/ShadowTree.cpp b/ReactCommon/fabric/uimanager/ShadowTree.cpp index 81c4a9ba26e..4207206a739 100644 --- a/ReactCommon/fabric/uimanager/ShadowTree.cpp +++ b/ReactCommon/fabric/uimanager/ShadowTree.cpp @@ -8,41 +8,36 @@ #include #include -#include "ShadowTreeDelegate.h" #include "Differentiator.h" +#include "ShadowTreeDelegate.h" #include "ShadowViewMutation.h" namespace facebook { namespace react { ShadowTree::ShadowTree( - SurfaceId surfaceId, - const LayoutConstraints &layoutConstraints, - const LayoutContext &layoutContext -): - surfaceId_(surfaceId) { - - const auto noopEventEmitter = std::make_shared(nullptr, -1, std::shared_ptr()); + SurfaceId surfaceId, + const LayoutConstraints &layoutConstraints, + const LayoutContext &layoutContext) + : surfaceId_(surfaceId) { + const auto noopEventEmitter = std::make_shared( + nullptr, -1, std::shared_ptr()); const auto props = std::make_shared( - *RootShadowNode::defaultSharedProps(), - layoutConstraints, - layoutContext - ); + *RootShadowNode::defaultSharedProps(), layoutConstraints, layoutContext); rootShadowNode_ = std::make_shared( - ShadowNodeFragment { - .tag = surfaceId, - .rootTag = surfaceId, - .props = props, - .eventEmitter = noopEventEmitter, - }, - nullptr - ); + ShadowNodeFragment{ + .tag = surfaceId, + .rootTag = surfaceId, + .props = props, + .eventEmitter = noopEventEmitter, + }, + nullptr); } ShadowTree::~ShadowTree() { - complete(std::make_shared(SharedShadowNodeList {})); + complete(std::make_shared(SharedShadowNodeList{})); } Tag ShadowTree::getSurfaceId() const { @@ -61,55 +56,56 @@ void ShadowTree::synchronize(std::function function) const { #pragma mark - Layout -Size ShadowTree::measure(const LayoutConstraints &layoutConstraints, const LayoutContext &layoutContext) const { - auto newRootShadowNode = cloneRootShadowNode(getRootShadowNode(), layoutConstraints, layoutContext); +Size ShadowTree::measure( + const LayoutConstraints &layoutConstraints, + const LayoutContext &layoutContext) const { + auto newRootShadowNode = cloneRootShadowNode( + getRootShadowNode(), layoutConstraints, layoutContext); newRootShadowNode->layout(); return newRootShadowNode->getLayoutMetrics().frame.size; } -bool ShadowTree::constraintLayout(const LayoutConstraints &layoutConstraints, const LayoutContext &layoutContext) const { +bool ShadowTree::constraintLayout( + const LayoutConstraints &layoutConstraints, + const LayoutContext &layoutContext) const { auto oldRootShadowNode = getRootShadowNode(); - auto newRootShadowNode = cloneRootShadowNode(oldRootShadowNode, layoutConstraints, layoutContext); + auto newRootShadowNode = + cloneRootShadowNode(oldRootShadowNode, layoutConstraints, layoutContext); return complete(oldRootShadowNode, newRootShadowNode); } #pragma mark - Commiting UnsharedRootShadowNode ShadowTree::cloneRootShadowNode( - const SharedRootShadowNode &oldRootShadowNode, - const LayoutConstraints &layoutConstraints, - const LayoutContext &layoutContext -) const { - auto props = std::make_shared(*oldRootShadowNode->getProps(), layoutConstraints, layoutContext); - auto newRootShadowNode = - std::make_shared(*oldRootShadowNode, ShadowNodeFragment {.props = props}); + const SharedRootShadowNode &oldRootShadowNode, + const LayoutConstraints &layoutConstraints, + const LayoutContext &layoutContext) const { + auto props = std::make_shared( + *oldRootShadowNode->getProps(), layoutConstraints, layoutContext); + auto newRootShadowNode = std::make_shared( + *oldRootShadowNode, ShadowNodeFragment{.props = props}); return newRootShadowNode; } -bool ShadowTree::complete(const SharedShadowNodeUnsharedList &rootChildNodes) const { +bool ShadowTree::complete( + const SharedShadowNodeUnsharedList &rootChildNodes) const { auto oldRootShadowNode = getRootShadowNode(); - auto newRootShadowNode = - std::make_shared( + auto newRootShadowNode = std::make_shared( *oldRootShadowNode, - ShadowNodeFragment { - .children = SharedShadowNodeSharedList(rootChildNodes) - } - ); + ShadowNodeFragment{.children = + SharedShadowNodeSharedList(rootChildNodes)}); return complete(oldRootShadowNode, newRootShadowNode); } bool ShadowTree::complete( - const SharedRootShadowNode &oldRootShadowNode, - const UnsharedRootShadowNode &newRootShadowNode -) const { + const SharedRootShadowNode &oldRootShadowNode, + const UnsharedRootShadowNode &newRootShadowNode) const { newRootShadowNode->layout(); newRootShadowNode->sealRecursive(); - auto mutations = calculateShadowViewMutations( - *oldRootShadowNode, - *newRootShadowNode - ); + auto mutations = + calculateShadowViewMutations(*oldRootShadowNode, *newRootShadowNode); if (!commit(oldRootShadowNode, newRootShadowNode, mutations)) { return false; @@ -125,10 +121,9 @@ bool ShadowTree::complete( } bool ShadowTree::commit( - const SharedRootShadowNode &oldRootShadowNode, - const SharedRootShadowNode &newRootShadowNode, - const ShadowViewMutationList &mutations -) const { + const SharedRootShadowNode &oldRootShadowNode, + const SharedRootShadowNode &newRootShadowNode, + const ShadowViewMutationList &mutations) const { std::lock_guard lock(commitMutex_); if (oldRootShadowNode != rootShadowNode_) { @@ -142,34 +137,38 @@ bool ShadowTree::commit( return true; } -void ShadowTree::emitLayoutEvents(const ShadowViewMutationList &mutations) const { +void ShadowTree::emitLayoutEvents( + const ShadowViewMutationList &mutations) const { for (const auto &mutation : mutations) { // Only `Insert` and `Update` mutations can affect layout metrics. - if ( - mutation.type != ShadowViewMutation::Insert && - mutation.type != ShadowViewMutation::Update - ) { + if (mutation.type != ShadowViewMutation::Insert && + mutation.type != ShadowViewMutation::Update) { continue; } - const auto viewEventEmitter = std::dynamic_pointer_cast(mutation.newChildShadowView.eventEmitter); + const auto viewEventEmitter = + std::dynamic_pointer_cast( + mutation.newChildShadowView.eventEmitter); - // Checking if particular shadow node supports `onLayout` event (part of `ViewEventEmitter`). + // Checking if particular shadow node supports `onLayout` event (part of + // `ViewEventEmitter`). if (!viewEventEmitter) { continue; } - // Checking if the `onLayout` event was requested for the particular Shadow Node. - const auto viewProps = std::dynamic_pointer_cast(mutation.newChildShadowView.props); + // Checking if the `onLayout` event was requested for the particular Shadow + // Node. + const auto viewProps = std::dynamic_pointer_cast( + mutation.newChildShadowView.props); if (viewProps && !viewProps->onLayout) { continue; } - // In case if we have `oldChildShadowView`, checking that layout metrics have changed. - if ( - mutation.type != ShadowViewMutation::Update && - mutation.oldChildShadowView.layoutMetrics == mutation.newChildShadowView.layoutMetrics - ) { + // In case if we have `oldChildShadowView`, checking that layout metrics + // have changed. + if (mutation.type != ShadowViewMutation::Update && + mutation.oldChildShadowView.layoutMetrics == + mutation.newChildShadowView.layoutMetrics) { continue; } @@ -177,7 +176,8 @@ void ShadowTree::emitLayoutEvents(const ShadowViewMutationList &mutations) const } } -void ShadowTree::toggleEventEmitters(const ShadowViewMutationList &mutations) const { +void ShadowTree::toggleEventEmitters( + const ShadowViewMutationList &mutations) const { std::lock_guard lock(EventEmitter::DispatchMutex()); for (const auto &mutation : mutations) { diff --git a/ReactCommon/fabric/uimanager/ShadowTree.h b/ReactCommon/fabric/uimanager/ShadowTree.h index d01a9c7af7f..836f956b62c 100644 --- a/ReactCommon/fabric/uimanager/ShadowTree.h +++ b/ReactCommon/fabric/uimanager/ShadowTree.h @@ -22,17 +22,14 @@ namespace react { * Represents the shadow tree and its lifecycle. */ class ShadowTree final { - -public: - + public: /* * Creates a new shadow tree instance. */ ShadowTree( - SurfaceId surfaceId, - const LayoutConstraints &layoutConstraints, - const LayoutContext &layoutContext - ); + SurfaceId surfaceId, + const LayoutConstraints &layoutConstraints, + const LayoutContext &layoutContext); ~ShadowTree(); @@ -54,10 +51,12 @@ public: #pragma mark - Layout /* - * Measures the shadow tree with given `layoutConstraints` and `layoutContext`. - * Can be called from any thread, side-effect-less. + * Measures the shadow tree with given `layoutConstraints` and + * `layoutContext`. Can be called from any thread, side-effect-less. */ - Size measure(const LayoutConstraints &layoutConstraints, const LayoutContext &layoutContext) const; + Size measure( + const LayoutConstraints &layoutConstraints, + const LayoutContext &layoutContext) const; /* * Applies given `layoutConstraints` and `layoutContext` and commit @@ -65,7 +64,9 @@ public: * Returns `true` if the operation finished successfully. * Can be called from any thread. */ - bool constraintLayout(const LayoutConstraints &layoutConstraints, const LayoutContext &layoutContext) const; + bool constraintLayout( + const LayoutConstraints &layoutConstraints, + const LayoutContext &layoutContext) const; #pragma mark - Application @@ -86,23 +87,20 @@ public: void setDelegate(ShadowTreeDelegate const *delegate); ShadowTreeDelegate const *getDelegate() const; -private: + private: UnsharedRootShadowNode cloneRootShadowNode( - const SharedRootShadowNode &oldRootShadowNode, - const LayoutConstraints &layoutConstraints, - const LayoutContext &layoutContext - ) const; + const SharedRootShadowNode &oldRootShadowNode, + const LayoutConstraints &layoutConstraints, + const LayoutContext &layoutContext) const; bool complete( - const SharedRootShadowNode &oldRootShadowNode, - const UnsharedRootShadowNode &newRootShadowNode - ) const; + const SharedRootShadowNode &oldRootShadowNode, + const UnsharedRootShadowNode &newRootShadowNode) const; bool commit( - const SharedRootShadowNode &oldRootShadowNode, - const SharedRootShadowNode &newRootShadowNode, - const ShadowViewMutationList &mutations - ) const; + const SharedRootShadowNode &oldRootShadowNode, + const SharedRootShadowNode &newRootShadowNode, + const ShadowViewMutationList &mutations) const; void toggleEventEmitters(const ShadowViewMutationList &mutations) const; void emitLayoutEvents(const ShadowViewMutationList &mutations) const; diff --git a/ReactCommon/fabric/uimanager/ShadowTreeDelegate.h b/ReactCommon/fabric/uimanager/ShadowTreeDelegate.h index 8d0f7ddeabd..7dbc96e7325 100644 --- a/ReactCommon/fabric/uimanager/ShadowTreeDelegate.h +++ b/ReactCommon/fabric/uimanager/ShadowTreeDelegate.h @@ -16,12 +16,13 @@ class ShadowTree; * Abstract class for ShadowTree's delegate. */ class ShadowTreeDelegate { - -public: + public: /* * Called right after Shadow Tree commit a new state of the the tree. */ - virtual void shadowTreeDidCommit(const ShadowTree &shadowTree, const ShadowViewMutationList &mutations) const = 0; + virtual void shadowTreeDidCommit( + const ShadowTree &shadowTree, + const ShadowViewMutationList &mutations) const = 0; virtual ~ShadowTreeDelegate() noexcept = default; }; diff --git a/ReactCommon/fabric/uimanager/ShadowView.cpp b/ReactCommon/fabric/uimanager/ShadowView.cpp index 474ff32e79d..8f0c869afd1 100644 --- a/ReactCommon/fabric/uimanager/ShadowView.cpp +++ b/ReactCommon/fabric/uimanager/ShadowView.cpp @@ -11,23 +11,36 @@ namespace facebook { namespace react { static LayoutMetrics layoutMetricsFromShadowNode(const ShadowNode &shadowNode) { - auto layoutableShadowNode = dynamic_cast(&shadowNode); - return layoutableShadowNode ? layoutableShadowNode->getLayoutMetrics() : EmptyLayoutMetrics; + auto layoutableShadowNode = + dynamic_cast(&shadowNode); + return layoutableShadowNode ? layoutableShadowNode->getLayoutMetrics() + : EmptyLayoutMetrics; } -ShadowView::ShadowView(const ShadowNode &shadowNode): - componentName(shadowNode.getComponentName()), - componentHandle(shadowNode.getComponentHandle()), - tag(shadowNode.getTag()), - props(shadowNode.getProps()), - eventEmitter(shadowNode.getEventEmitter()), - layoutMetrics(layoutMetricsFromShadowNode(shadowNode)), - localData(shadowNode.getLocalData()) {} +ShadowView::ShadowView(const ShadowNode &shadowNode) + : componentName(shadowNode.getComponentName()), + componentHandle(shadowNode.getComponentHandle()), + tag(shadowNode.getTag()), + props(shadowNode.getProps()), + eventEmitter(shadowNode.getEventEmitter()), + layoutMetrics(layoutMetricsFromShadowNode(shadowNode)), + localData(shadowNode.getLocalData()) {} bool ShadowView::operator==(const ShadowView &rhs) const { - return - std::tie(this->tag, this->componentName, this->props, this->eventEmitter, this->layoutMetrics, this->localData) == - std::tie(rhs.tag, rhs.componentName, rhs.props, rhs.eventEmitter, rhs.layoutMetrics, rhs.localData); + return std::tie( + this->tag, + this->componentName, + this->props, + this->eventEmitter, + this->layoutMetrics, + this->localData) == + std::tie( + rhs.tag, + rhs.componentName, + rhs.props, + rhs.eventEmitter, + rhs.layoutMetrics, + rhs.localData); } bool ShadowView::operator!=(const ShadowView &rhs) const { diff --git a/ReactCommon/fabric/uimanager/ShadowViewMutation.cpp b/ReactCommon/fabric/uimanager/ShadowViewMutation.cpp index 83ad07dd559..023107a5fa9 100644 --- a/ReactCommon/fabric/uimanager/ShadowViewMutation.cpp +++ b/ReactCommon/fabric/uimanager/ShadowViewMutation.cpp @@ -10,65 +10,45 @@ namespace facebook { namespace react { -ShadowViewMutation ShadowViewMutation::CreateMutation( - ShadowView shadowView -) { - return ShadowViewMutation { - .type = Create, - .newChildShadowView = shadowView, - .index = -1 - }; +ShadowViewMutation ShadowViewMutation::CreateMutation(ShadowView shadowView) { + return ShadowViewMutation{ + .type = Create, .newChildShadowView = shadowView, .index = -1}; } -ShadowViewMutation ShadowViewMutation::DeleteMutation( - ShadowView shadowView -) { - return { - .type = Delete, - .oldChildShadowView = shadowView, - .index = -1 - }; +ShadowViewMutation ShadowViewMutation::DeleteMutation(ShadowView shadowView) { + return {.type = Delete, .oldChildShadowView = shadowView, .index = -1}; } ShadowViewMutation ShadowViewMutation::InsertMutation( - ShadowView parentShadowView, - ShadowView childShadowView, - int index -) { - return { - .type = Insert, - .parentShadowView = parentShadowView, - .newChildShadowView = childShadowView, - .index = index - }; + ShadowView parentShadowView, + ShadowView childShadowView, + int index) { + return {.type = Insert, + .parentShadowView = parentShadowView, + .newChildShadowView = childShadowView, + .index = index}; } ShadowViewMutation ShadowViewMutation::RemoveMutation( - ShadowView parentShadowView, - ShadowView childShadowView, - int index -) { - return { - .type = Remove, - .parentShadowView = parentShadowView, - .oldChildShadowView = childShadowView, - .index = index - }; + ShadowView parentShadowView, + ShadowView childShadowView, + int index) { + return {.type = Remove, + .parentShadowView = parentShadowView, + .oldChildShadowView = childShadowView, + .index = index}; } ShadowViewMutation ShadowViewMutation::UpdateMutation( - ShadowView parentShadowView, - ShadowView oldChildShadowView, - ShadowView newChildShadowView, - int index -) { - return { - .type = Update, - .parentShadowView = parentShadowView, - .oldChildShadowView = oldChildShadowView, - .newChildShadowView = newChildShadowView, - .index = index - }; + ShadowView parentShadowView, + ShadowView oldChildShadowView, + ShadowView newChildShadowView, + int index) { + return {.type = Update, + .parentShadowView = parentShadowView, + .oldChildShadowView = oldChildShadowView, + .newChildShadowView = newChildShadowView, + .index = index}; } } // namespace react diff --git a/ReactCommon/fabric/uimanager/ShadowViewMutation.h b/ReactCommon/fabric/uimanager/ShadowViewMutation.h index b56cb0d6c1e..6619bec6b8f 100644 --- a/ReactCommon/fabric/uimanager/ShadowViewMutation.h +++ b/ReactCommon/fabric/uimanager/ShadowViewMutation.h @@ -21,60 +21,46 @@ namespace react { * Use static methods to instantiate mutations of different types. */ struct ShadowViewMutation final { - #pragma mark - Designated Initializers /* * Creates and returns an `Create` mutation. */ - static ShadowViewMutation CreateMutation( - ShadowView shadowView - ); + static ShadowViewMutation CreateMutation(ShadowView shadowView); /* * Creates and returns an `Delete` mutation. */ - static ShadowViewMutation DeleteMutation( - ShadowView shadowView - ); + static ShadowViewMutation DeleteMutation(ShadowView shadowView); /* * Creates and returns an `Insert` mutation. */ static ShadowViewMutation InsertMutation( - ShadowView parentShadowView, - ShadowView childShadowView, - int index - ); + ShadowView parentShadowView, + ShadowView childShadowView, + int index); /* * Creates and returns a `Remove` mutation. */ static ShadowViewMutation RemoveMutation( - ShadowView parentShadowView, - ShadowView childShadowView, - int index - ); + ShadowView parentShadowView, + ShadowView childShadowView, + int index); /* * Creates and returns an `Update` mutation. */ static ShadowViewMutation UpdateMutation( - ShadowView parentShadowView, - ShadowView oldChildShadowView, - ShadowView newChildShadowView, - int index - ); + ShadowView parentShadowView, + ShadowView oldChildShadowView, + ShadowView newChildShadowView, + int index); #pragma mark - Type - enum Type { - Create, - Delete, - Insert, - Remove, - Update - }; + enum Type { Create, Delete, Insert, Remove, Update }; #pragma mark - Fields diff --git a/ReactCommon/fabric/uimanager/UIManagerDelegate.h b/ReactCommon/fabric/uimanager/UIManagerDelegate.h index 1bd8cb89fc7..0e67113b89f 100644 --- a/ReactCommon/fabric/uimanager/UIManagerDelegate.h +++ b/ReactCommon/fabric/uimanager/UIManagerDelegate.h @@ -7,8 +7,8 @@ #pragma once -#include #include +#include namespace facebook { namespace react { @@ -17,20 +17,22 @@ namespace react { * Abstract class for UIManager's delegate. */ class UIManagerDelegate { - -public: + public: /* * Called right after the new/updated Shadow Node tree is constructed. * The tree is not layed out and not sealed at this time. */ - virtual void uiManagerDidFinishTransaction(Tag rootTag, const SharedShadowNodeUnsharedList &rootChildNodes) = 0; + virtual void uiManagerDidFinishTransaction( + Tag rootTag, + const SharedShadowNodeUnsharedList &rootChildNodes) = 0; /* * Called each time when UIManager constructs a new Shadow Node. Receiver * maight use this to preluminary optimistically allocate a new native view * instances. */ - virtual void uiManagerDidCreateShadowNode(const SharedShadowNode &shadowNode) = 0; + virtual void uiManagerDidCreateShadowNode( + const SharedShadowNode &shadowNode) = 0; virtual ~UIManagerDelegate() noexcept = default; };