Add support for display: contents style (#1726)

Summary:
X-link: https://github.com/facebook/react-native/pull/47035

This PR adds support for `display: contents` style by effectively skipping nodes with `display: contents` set during layout.

This required changes in the logic related to children traversal - before this PR a node would be always laid out in the context of its direct parent. After this PR that assumption is no longer true - `display: contents` allows nodes to be skipped, i.e.:

```html
<div id="node1">
  <div id="node2" style="display: contents;">
    <div id="node3" />
  </div>
</div>
```

`node3` will be laid out as if it were a child of `node1`.

Because of this, iterating over direct children of a node is no longer correct to achieve the correct layout. This PR introduces `LayoutableChildren::Iterator` which can traverse the subtree of a given node in a way that nodes with `display: contents` are replaced with their concrete children.

A tree like this:
```mermaid
flowchart TD
    A((A))
    B((B))
    C((C))
    D((D))
    E((E))
    F((F))
    G((G))
    H((H))
    I((I))
    J((J))

    A --> B
    A --> C
    B --> D
    B --> E
    C --> F
    D --> G
    F --> H
    G --> I
    H --> J

    style B fill:https://github.com/facebook/yoga/issues/050
    style C fill:https://github.com/facebook/yoga/issues/050
    style D fill:https://github.com/facebook/yoga/issues/050
    style H fill:https://github.com/facebook/yoga/issues/050
    style I fill:https://github.com/facebook/yoga/issues/050
```

would be laid out as if the green nodes (ones with `display: contents`) did not exist. It also changes the logic where children were accessed by index to use the iterator instead as random access would be non-trivial to implement and it's not really necessary - the iteration was always sequential and indices were only used as boundaries.

There's one place where knowledge of layoutable children is required to calculate the gap. An optimization for this is for a node to keep a counter of how many `display: contents` nodes are its children. If there are none, a short path of just returning the size of the children vector can be taken, otherwise it needs to iterate over layoutable children and count them, since the structure may be complex.

One more major change this PR introduces is `cleanupContentsNodesRecursively`. Since nodes with `display: contents` would be entirely skipped during the layout pass, they would keep previous metrics, would be kept as dirty, and, in the case of nested `contents` nodes, would not be cloned, breaking `doesOwn` relation. All of this is handled in the new method which clones `contents` nodes recursively, sets empty layout, and marks them as clean and having a new layout so that it can be used on the React Native side.

Relies on https://github.com/facebook/yoga/pull/1725

Changelog: [Internal]

Pull Request resolved: https://github.com/facebook/yoga/pull/1726

Test Plan: Added tests for `display: contents` based on existing tests for `display: none` and ensured that all the tests were passing.

Reviewed By: joevilches

Differential Revision: D64404340

Pulled By: NickGerleman

fbshipit-source-id: f6f6e9a6fad82873f18c8a0ead58aad897df5d09
This commit is contained in:
Jakub Piasecki
2024-10-18 22:05:41 -07:00
committed by Facebook GitHub Bot
parent 568718242d
commit 68bb2343d2
26 changed files with 2590 additions and 44 deletions

View File

@@ -0,0 +1,150 @@
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <cstdint>
#include <vector>
#include <yoga/enums/Display.h>
namespace facebook::yoga {
class Node;
template <typename T>
class LayoutableChildren {
public:
using Backtrack = std::vector<std::pair<const T*, size_t>>;
struct Iterator {
using iterator_category = std::input_iterator_tag;
using difference_type = std::ptrdiff_t;
using value_type = T*;
using pointer = T*;
using reference = T*;
Iterator() = default;
Iterator(const T* node, size_t childIndex)
: node_(node), childIndex_(childIndex) {}
Iterator(const T* node, size_t childIndex, Backtrack&& backtrack)
: node_(node),
childIndex_(childIndex),
backtrack_(std::move(backtrack)) {}
T* operator*() const {
return node_->getChild(childIndex_);
}
Iterator& operator++() {
next();
currentNodeIndex_++;
return *this;
}
Iterator operator++(int) {
Iterator tmp = *this;
++(*this);
return tmp;
}
size_t index() const {
return currentNodeIndex_;
}
friend bool operator==(const Iterator& a, const Iterator& b) {
return a.node_ == b.node_ && a.childIndex_ == b.childIndex_;
}
friend bool operator!=(const Iterator& a, const Iterator& b) {
return a.node_ != b.node_ || a.childIndex_ != b.childIndex_;
}
private:
void next() {
if (childIndex_ + 1 >= node_->getChildCount()) {
// if the current node has no more children, try to backtrack and
// visit its successor
if (backtrack_.empty()) {
// if there are no nodes to backtrack to, the last node has been
// visited
*this = Iterator{};
} else {
// pop and restore the latest backtrack entry
const auto back = backtrack_.back();
backtrack_.pop_back();
node_ = back.first;
childIndex_ = back.second;
// go to the next node
next();
}
} else {
// current node has more children to visit, go to next
++childIndex_;
// skip all display: contents nodes, possibly going deeper into the
// tree
skipContentsNodes();
}
}
void skipContentsNodes() {
// get the node that would be returned from the iterator
auto currentNode = node_->getChild(childIndex_);
while (currentNode->style().display() == Display::Contents &&
currentNode->getChildCount() > 0) {
// if it has display: contents set, it shouldn't be returned but its
// children should in its place push the current node and child index
// so that the current state can be restored when backtracking
backtrack_.push_back({node_, childIndex_});
// traverse the child
node_ = currentNode;
childIndex_ = 0;
// repeat until a node without display: contents is found in the
// subtree or a leaf is reached
currentNode = currentNode->getChild(childIndex_);
}
// if no node without display: contents was found, try to backtrack
if (currentNode->style().display() == Display::Contents) {
next();
}
}
const T* node_{nullptr};
size_t childIndex_{0};
size_t currentNodeIndex_{0};
Backtrack backtrack_;
friend LayoutableChildren;
};
explicit LayoutableChildren(const T* node) : node_(node) {
static_assert(std::input_iterator<LayoutableChildren<T>::Iterator>);
static_assert(
std::is_base_of<Node, T>::value,
"Type parameter of LayoutableChildren must derive from yoga::Node");
}
Iterator begin() const {
if (node_->getChildCount() > 0) {
auto result = Iterator(node_, 0);
result.skipContentsNodes();
return result;
} else {
return Iterator{};
}
}
Iterator end() const {
return Iterator{};
}
private:
const T* node_;
};
} // namespace facebook::yoga

View File

@@ -41,6 +41,7 @@ Node::Node(Node&& node) noexcept
style_(std::move(node.style_)),
layout_(node.layout_),
lineIndex_(node.lineIndex_),
contentsChildrenCount_(node.contentsChildrenCount_),
owner_(node.owner_),
children_(std::move(node.children_)),
config_(node.config_),
@@ -116,14 +117,37 @@ void Node::setMeasureFunc(YGMeasureFunc measureFunc) {
}
void Node::replaceChild(Node* child, size_t index) {
auto previousChild = children_[index];
if (previousChild->style().display() == Display::Contents &&
child->style().display() != Display::Contents) {
contentsChildrenCount_--;
} else if (
previousChild->style().display() != Display::Contents &&
child->style().display() == Display::Contents) {
contentsChildrenCount_++;
}
children_[index] = child;
}
void Node::replaceChild(Node* oldChild, Node* newChild) {
if (oldChild->style().display() == Display::Contents &&
newChild->style().display() != Display::Contents) {
contentsChildrenCount_--;
} else if (
oldChild->style().display() != Display::Contents &&
newChild->style().display() == Display::Contents) {
contentsChildrenCount_++;
}
std::replace(children_.begin(), children_.end(), oldChild, newChild);
}
void Node::insertChild(Node* child, size_t index) {
if (child->style().display() == Display::Contents) {
contentsChildrenCount_++;
}
children_.insert(children_.begin() + static_cast<ptrdiff_t>(index), child);
}
@@ -160,6 +184,10 @@ void Node::setDirty(bool isDirty) {
bool Node::removeChild(Node* child) {
auto p = std::find(children_.begin(), children_.end(), child);
if (p != children_.end()) {
if (child->style().display() == Display::Contents) {
contentsChildrenCount_--;
}
children_.erase(p);
return true;
}
@@ -167,6 +195,10 @@ bool Node::removeChild(Node* child) {
}
void Node::removeChild(size_t index) {
if (children_[index]->style().display() == Display::Contents) {
contentsChildrenCount_--;
}
children_.erase(children_.begin() + static_cast<ptrdiff_t>(index));
}

View File

@@ -12,6 +12,7 @@
#include <vector>
#include <yoga/Yoga.h>
#include <yoga/node/LayoutableChildren.h>
#include <yoga/config/Config.h>
#include <yoga/enums/Dimension.h>
@@ -31,6 +32,7 @@ namespace facebook::yoga {
class YG_EXPORT Node : public ::YGNode {
public:
using LayoutableChildren = yoga::LayoutableChildren<Node>;
Node();
explicit Node(const Config* config);
@@ -144,6 +146,24 @@ class YG_EXPORT Node : public ::YGNode {
return children_.size();
}
LayoutableChildren getLayoutChildren() const {
return LayoutableChildren(this);
}
size_t getLayoutChildCount() const {
if (contentsChildrenCount_ == 0) {
return children_.size();
} else {
size_t count = 0;
for (auto iter = getLayoutChildren().begin();
iter != getLayoutChildren().end();
iter++) {
count++;
}
return count;
}
}
const Config* getConfig() const {
return config_;
}
@@ -298,6 +318,7 @@ class YG_EXPORT Node : public ::YGNode {
Style style_;
LayoutResults layout_;
size_t lineIndex_ = 0;
size_t contentsChildrenCount_ = 0;
Node* owner_ = nullptr;
std::vector<Node*> children_;
const Config* config_;