Skip to content

Commit

Permalink
C++ Cleanup 3/N: Reorganize YGNode (facebook#39170)
Browse files Browse the repository at this point in the history
Summary:
Pull Request resolved: facebook#39170

## This diff

This diff adds a top level `node` directory for code related to Yoga nodes and data structures on them (inc moving `YGLayout` to `LayoutResults`).

The public API for config handles is `YGNodeRef`, which is forward declared to be a pointer to a struct named `YGNode`. The existing `YGNode` is split into `yoga::Node`, as the private C++ implementation, inheriting from `YGNode`, a marker type represented as an empty struct. The public API continues to accept `YGNodeRef`, which continues to be `YGNode *`, but it must be cast to its concrete internal representation at the API boundary before doing work on it.

This change ends up needing to touch quite a bit, due to the amount of code that mixed and matched private and public APIs. Don't be scared though, because these changes are very mechanical, and Phabricator's line-count is 3x the actual amount due to mirrors and dirsyncs.

## This stack

The organization of the C++ internals of Yoga are in need of attention.
1. Some of the C++ internals are namespaced, but others not.
2. Some of the namespaces include `detail`, but are meant to be used outside of the translation unit (FB Clang Tidy rules warn on any usage of these)
2. Most of the files are in a flat hierarchy, except for event tracing in its own folder
3. Some files and functions begin with YG, others don’t
4. Some functions are uppercase, others are not
5. Almost all of the interesting logic is in Yoga.cpp, and the file is too large to reason about
6. There are multiple grab bag files where folks put random functions they need in (Utils, BitUtils, Yoga-Internal.h)
7. There is no clear indication from file structure or type naming what is private vs not
8. Handles like `YGNodeRef` and `YGConfigRef` can be used to access internals just by importing headers

This stack does some much needed spring cleaning:
1. All non-public headers and C++ implementation details are in separate folders from the root level `yoga`. This will give us room to split up logic and add more files without too large a flat hierarchy
3. All private C++ internals are under the `facebook::yoga` namespace. Details namespaces are only ever used within the same header, as they are intended
4. Utils files are split
5. Most C++ internals drop the YG prefix
6. Most C++ internal function names are all lower camel case
7. We start to split up Yoga.cpp
8. Every header beginning with YG or at the top-level directory is public and C only, with the exception of Yoga-Internal.h which has non-public functions for bindings
9. It is not possible to use private APIs without static casting handles to internal classes

This will give us more leeway to continue splitting monolithic files, and consistent guidelines for style in new files as well.

These changes should not be breaking to any project using only public Yoga headers. This includes every usage of Yoga in fbsource except for RN Fabric which is currently tied to internals. This refactor should make that boundary clearer.

Changelog: [Internal]

Differential Revision: D48712710

fbshipit-source-id: 83afd055eb02daf5fa64e23da496648987dce04f
  • Loading branch information
NickGerleman authored and facebook-github-bot committed Aug 28, 2023
1 parent 5026f3b commit 9e6be00
Show file tree
Hide file tree
Showing 21 changed files with 419 additions and 359 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@

// TODO: Reconcile missing layoutContext functionality from callbacks in the C
// API and use that
#include <yoga/YGNode.h>
#include <yoga/node/Node.h>

using namespace facebook;
using namespace facebook::yoga;
Expand Down Expand Up @@ -688,7 +688,7 @@ static void jni_YGNodeSetHasMeasureFuncJNI(
jobject /*obj*/,
jlong nativePointer,
jboolean hasMeasureFunc) {
_jlong2YGNodeRef(nativePointer)
static_cast<yoga::Node*>(_jlong2YGNodeRef(nativePointer))
->setMeasureFunc(hasMeasureFunc ? YGJNIMeasureFunc : nullptr);
}

Expand All @@ -715,7 +715,7 @@ static void jni_YGNodeSetHasBaselineFuncJNI(
jobject /*obj*/,
jlong nativePointer,
jboolean hasBaselineFunc) {
_jlong2YGNodeRef(nativePointer)
static_cast<yoga::Node*>(_jlong2YGNodeRef(nativePointer))
->setBaselineFunc(hasBaselineFunc ? YGJNIBaselineFunc : nullptr);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,12 @@
#include "jni.h"

class PtrJNodeMapVanilla {
std::map<YGNodeRef, size_t> ptrsToIdxs_;
jobjectArray javaNodes_;
std::map<YGNodeConstRef, size_t> ptrsToIdxs_{};
jobjectArray javaNodes_{};

public:
PtrJNodeMapVanilla() : ptrsToIdxs_{}, javaNodes_{} {}
PtrJNodeMapVanilla() = default;

PtrJNodeMapVanilla(jlongArray javaNativePointers, jobjectArray javaNodes)
: javaNodes_{javaNodes} {
using namespace facebook::yoga::vanillajni;
Expand All @@ -30,11 +31,11 @@ class PtrJNodeMapVanilla {
javaNativePointers, 0, nativePointersSize, nativePointers.data());

for (size_t i = 0; i < nativePointersSize; ++i) {
ptrsToIdxs_[(YGNodeRef) nativePointers[i]] = i;
ptrsToIdxs_[(YGNodeConstRef) nativePointers[i]] = i;
}
}

facebook::yoga::vanillajni::ScopedLocalRef<jobject> ref(YGNodeRef node) {
facebook::yoga::vanillajni::ScopedLocalRef<jobject> ref(YGNodeConstRef node) {
using namespace facebook::yoga::vanillajni;

JNIEnv* env = getCurrentEnv();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ YogaLayoutableShadowNode::YogaLayoutableShadowNode(
yogaNode_.setContext(this);

// Newly created node must be `dirty` just because it is new.
// This is not a default for `YGNode`.
// This is not a default for `yoga::Node`.
yogaNode_.setDirty(true);

if (getTraits().check(ShadowNodeTraits::Trait::MeasurableYogaNode)) {
Expand All @@ -106,7 +106,7 @@ YogaLayoutableShadowNode::YogaLayoutableShadowNode(
yogaConfig_(FabricDefaultYogaLog),
yogaNode_(static_cast<YogaLayoutableShadowNode const &>(sourceShadowNode)
.yogaNode_) {
// Note, cloned `YGNode` instance (copied using copy-constructor) inherits
// Note, cloned `yoga::Node` instance (copied using copy-constructor) inherits
// dirty flag, measure function, and other properties being set originally in
// the `YogaLayoutableShadowNode` constructor above.

Expand Down Expand Up @@ -321,7 +321,8 @@ bool YogaLayoutableShadowNode::doesOwn(
void YogaLayoutableShadowNode::updateYogaChildrenOwnersIfNeeded() {
for (auto &childYogaNode : yogaNode_.getChildren()) {
if (childYogaNode->getOwner() == &yogaNode_) {
childYogaNode->setOwner(reinterpret_cast<YGNodeRef>(0xBADC0FFEE0DDF00D));
childYogaNode->setOwner(
reinterpret_cast<yoga::Node *>(0xBADC0FFEE0DDF00D));
}
}
}
Expand All @@ -336,7 +337,9 @@ void YogaLayoutableShadowNode::updateYogaChildren() {
bool isClean = !yogaNode_.isDirty() &&
getChildren().size() == yogaNode_.getChildren().size();

auto oldYogaChildren = isClean ? yogaNode_.getChildren() : YGVector{};
auto oldYogaChildren =
isClean ? yogaNode_.getChildren() : std::vector<yoga::Node *>{};

yogaNode_.setChildren({});
yogaLayoutableChildren_.clear();

Expand Down Expand Up @@ -829,9 +832,9 @@ YGSize YogaLayoutableShadowNode::yogaNodeMeasureCallbackConnector(
}

YogaLayoutableShadowNode &YogaLayoutableShadowNode::shadowNodeFromContext(
YGNode *yogaNode) {
YGNodeRef yogaNode) {
return traitCast<YogaLayoutableShadowNode &>(
*static_cast<ShadowNode *>(yogaNode->getContext()));
*static_cast<ShadowNode *>(YGNodeGetContext(yogaNode)));
}

yoga::Config &YogaLayoutableShadowNode::initializeYogaConfig(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
#include <memory>
#include <vector>

#include <yoga/YGNode.h>
#include <yoga/node/Node.h>

#include <react/debug/react_native_assert.h>
#include <react/renderer/components/view/YogaStylableProps.h>
Expand Down Expand Up @@ -100,7 +100,7 @@ class YogaLayoutableShadowNode : public LayoutableShadowNode {
* Yoga node as `mutable` here to avoid `static_cast`ing the pointer to this
* all the time.
*/
mutable YGNode yogaNode_;
mutable yoga::Node yogaNode_;

private:
/*
Expand Down Expand Up @@ -156,17 +156,17 @@ class YogaLayoutableShadowNode : public LayoutableShadowNode {
static yoga::Config &initializeYogaConfig(
yoga::Config &config,
YGConfigRef previousConfig = nullptr);
static YGNode *yogaNodeCloneCallbackConnector(
YGNode *oldYogaNode,
YGNode *parentYogaNode,
static YGNodeRef yogaNodeCloneCallbackConnector(
YGNodeRef oldYogaNode,
YGNodeRef parentYogaNode,
int childIndex);
static YGSize yogaNodeMeasureCallbackConnector(
YGNode *yogaNode,
YGNodeRef yogaNode,
float width,
YGMeasureMode widthMode,
float height,
YGMeasureMode heightMode);
static YogaLayoutableShadowNode &shadowNodeFromContext(YGNode *yogaNode);
static YogaLayoutableShadowNode &shadowNodeFromContext(YGNodeRef yogaNode);

#pragma mark - RTL Legacy Autoflip

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
#include <react/renderer/core/propsConversions.h>
#include <react/renderer/debug/debugStringConvertibleUtils.h>
#include <react/utils/CoreFeatures.h>
#include <yoga/YGNode.h>
#include <yoga/Yoga.h>

#include "conversions.h"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@
#include <react/renderer/graphics/Transform.h>
#include <stdlib.h>
#include <yoga/YGEnums.h>
#include <yoga/YGNode.h>
#include <yoga/Yoga.h>
#include <yoga/node/Node.h>
#include <cmath>
#include <optional>

Expand Down Expand Up @@ -113,7 +113,7 @@ inline std::optional<Float> optionalFloatFromYogaValue(
}
}

inline LayoutMetrics layoutMetricsFromYogaNode(YGNode &yogaNode) {
inline LayoutMetrics layoutMetricsFromYogaNode(yoga::Node &yogaNode) {
auto layoutMetrics = LayoutMetrics{};

layoutMetrics.frame = Rect{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ class ShadowNodeTraits {
// Any Yoga node (not only Leaf ones) can have this trait.
DirtyYogaNode = 1 << 7,

// Inherits `YogaLayoutableShadowNode` and enforces that the `YGNode` is a
// Inherits `YogaLayoutableShadowNode` and enforces that the yoga node is a
// leaf.
LeafYogaNode = 1 << 8,

Expand Down
4 changes: 2 additions & 2 deletions packages/react-native/ReactCommon/yoga/yoga/Utils.h
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

#pragma once

#include "YGNode.h"
#include <yoga/node/Node.h>
#include <yoga/Yoga-internal.h>
#include <yoga/style/CompactValue.h>

Expand Down Expand Up @@ -43,7 +43,7 @@ struct YGCollectFlexItemsRowValues {
float totalFlexGrowFactors;
float totalFlexShrinkScaledFactors;
uint32_t endOfLineIndex;
std::vector<YGNodeRef> relativeChildren;
std::vector<facebook::yoga::Node*> relativeChildren;
float remainingFreeSpace;
// The size of the mainDim for the row after considering size, padding, margin
// and border of flex items. This is used to calculate maxLineDim after going
Expand Down
44 changes: 22 additions & 22 deletions packages/react-native/ReactCommon/yoga/yoga/YGNodePrint.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,8 @@
#include <yoga/YGEnums.h>

#include "YGNodePrint.h"
#include "YGNode.h"
#include <yoga/Yoga-internal.h>
#include "Utils.h"
#include <yoga/Utils.h>

namespace facebook::yoga {
typedef std::string string;
Expand Down Expand Up @@ -92,7 +91,7 @@ static void appendEdges(
const string& key,
const Style::Edges& edges) {
if (areFourValuesEqual(edges)) {
auto edgeValue = YGNode::computeEdgeValueForColumn(
auto edgeValue = yoga::Node::computeEdgeValueForColumn(
edges, YGEdgeLeft, CompactValue::ofZero());
appendNumberIfNotZero(base, key, edgeValue);
} else {
Expand All @@ -110,16 +109,16 @@ static void appendEdgeIfNotUndefined(
const YGEdge edge) {
// TODO: this doesn't take RTL / YGEdgeStart / YGEdgeEnd into account
auto value = (edge == YGEdgeLeft || edge == YGEdgeRight)
? YGNode::computeEdgeValueForRow(
? yoga::Node::computeEdgeValueForRow(
edges, edge, edge, CompactValue::ofUndefined())
: YGNode::computeEdgeValueForColumn(
: yoga::Node::computeEdgeValueForColumn(
edges, edge, CompactValue::ofUndefined());
appendNumberIfNotUndefined(base, str, value);
}

void YGNodeToString(
std::string& str,
YGNodeRef node,
yoga::Node* node,
YGPrintOptions options,
uint32_t level) {
indent(str, level);
Expand All @@ -141,27 +140,27 @@ void YGNodeToString(
if (options & YGPrintOptionsStyle) {
appendFormattedString(str, "style=\"");
const auto& style = node->getStyle();
if (style.flexDirection() != YGNode().getStyle().flexDirection()) {
if (style.flexDirection() != yoga::Node{}.getStyle().flexDirection()) {
appendFormattedString(
str,
"flex-direction: %s; ",
YGFlexDirectionToString(style.flexDirection()));
}
if (style.justifyContent() != YGNode().getStyle().justifyContent()) {
if (style.justifyContent() != yoga::Node{}.getStyle().justifyContent()) {
appendFormattedString(
str,
"justify-content: %s; ",
YGJustifyToString(style.justifyContent()));
}
if (style.alignItems() != YGNode().getStyle().alignItems()) {
if (style.alignItems() != yoga::Node{}.getStyle().alignItems()) {
appendFormattedString(
str, "align-items: %s; ", YGAlignToString(style.alignItems()));
}
if (style.alignContent() != YGNode().getStyle().alignContent()) {
if (style.alignContent() != yoga::Node{}.getStyle().alignContent()) {
appendFormattedString(
str, "align-content: %s; ", YGAlignToString(style.alignContent()));
}
if (style.alignSelf() != YGNode().getStyle().alignSelf()) {
if (style.alignSelf() != yoga::Node{}.getStyle().alignSelf()) {
appendFormattedString(
str, "align-self: %s; ", YGAlignToString(style.alignSelf()));
}
Expand All @@ -170,33 +169,34 @@ void YGNodeToString(
appendNumberIfNotAuto(str, "flex-basis", style.flexBasis());
appendFloatOptionalIfDefined(str, "flex", style.flex());

if (style.flexWrap() != YGNode().getStyle().flexWrap()) {
if (style.flexWrap() != yoga::Node{}.getStyle().flexWrap()) {
appendFormattedString(
str, "flex-wrap: %s; ", YGWrapToString(style.flexWrap()));
}

if (style.overflow() != YGNode().getStyle().overflow()) {
if (style.overflow() != yoga::Node{}.getStyle().overflow()) {
appendFormattedString(
str, "overflow: %s; ", YGOverflowToString(style.overflow()));
}

if (style.display() != YGNode().getStyle().display()) {
if (style.display() != yoga::Node{}.getStyle().display()) {
appendFormattedString(
str, "display: %s; ", YGDisplayToString(style.display()));
}
appendEdges(str, "margin", style.margin());
appendEdges(str, "padding", style.padding());
appendEdges(str, "border", style.border());

if (YGNode::computeColumnGap(style.gap(), CompactValue::ofUndefined()) !=
YGNode::computeColumnGap(
YGNode().getStyle().gap(), CompactValue::ofUndefined())) {
if (yoga::Node::computeColumnGap(
style.gap(), CompactValue::ofUndefined()) !=
yoga::Node::computeColumnGap(
yoga::Node{}.getStyle().gap(), CompactValue::ofUndefined())) {
appendNumberIfNotUndefined(
str, "column-gap", style.gap()[YGGutterColumn]);
}
if (YGNode::computeRowGap(style.gap(), CompactValue::ofUndefined()) !=
YGNode::computeRowGap(
YGNode().getStyle().gap(), CompactValue::ofUndefined())) {
if (yoga::Node::computeRowGap(style.gap(), CompactValue::ofUndefined()) !=
yoga::Node::computeRowGap(
yoga::Node{}.getStyle().gap(), CompactValue::ofUndefined())) {
appendNumberIfNotUndefined(str, "row-gap", style.gap()[YGGutterRow]);
}

Expand All @@ -211,7 +211,7 @@ void YGNodeToString(
appendNumberIfNotAuto(
str, "min-height", style.minDimensions()[YGDimensionHeight]);

if (style.positionType() != YGNode().getStyle().positionType()) {
if (style.positionType() != yoga::Node{}.getStyle().positionType()) {
appendFormattedString(
str, "position: %s; ", YGPositionTypeToString(style.positionType()));
}
Expand All @@ -232,7 +232,7 @@ void YGNodeToString(
if (options & YGPrintOptionsChildren && childCount > 0) {
for (uint32_t i = 0; i < childCount; i++) {
appendFormattedString(str, "\n");
YGNodeToString(str, YGNodeGetChild(node, i), options, level + 1);
YGNodeToString(str, node->getChild(i), options, level + 1);
}
appendFormattedString(str, "\n");
indent(str, level);
Expand Down
3 changes: 2 additions & 1 deletion packages/react-native/ReactCommon/yoga/yoga/YGNodePrint.h
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,13 @@
#include <string>

#include <yoga/Yoga.h>
#include <yoga/node/Node.h>

namespace facebook::yoga {

void YGNodeToString(
std::string& str,
YGNodeRef node,
yoga::Node* node,
YGPrintOptions options,
uint32_t level);

Expand Down
2 changes: 0 additions & 2 deletions packages/react-native/ReactCommon/yoga/yoga/Yoga-internal.h
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,6 @@

#include <yoga/style/CompactValue.h>

using YGVector = std::vector<YGNodeRef>;

YG_EXTERN_C_BEGIN

void YGNodeCalculateLayoutWithContext(
Expand Down
Loading

0 comments on commit 9e6be00

Please sign in to comment.