From c09ac536c5c7630888eee4376a33492a93bae541 Mon Sep 17 00:00:00 2001 From: Tobias Christiansen Date: Sat, 17 Apr 2021 23:05:56 +0200 Subject: [PATCH] LibWeb: Add capabilities to find the index of a child in its parent. For Elements depending on the index they are inside their parent. Most notably the
    element. Also added a typed version to only count children of a certain type. This patch is work towards #2059 --- Userland/Libraries/LibWeb/TreeNode.h | 33 ++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/Userland/Libraries/LibWeb/TreeNode.h b/Userland/Libraries/LibWeb/TreeNode.h index 77b4139db4..ec6ea07d70 100644 --- a/Userland/Libraries/LibWeb/TreeNode.h +++ b/Userland/Libraries/LibWeb/TreeNode.h @@ -97,6 +97,39 @@ public: return const_cast(this)->child_at_index(index); } + Optional index_of_child(const T& search_child) + { + VERIFY(search_child.parent() == this); + size_t index = 0; + auto* child = first_child(); + VERIFY(child); + + do { + if (child == &search_child) + return index; + index++; + } while (child && (child = child->next_sibling())); + return {}; + } + + template + Optional index_of_child(const T& search_child) + { + VERIFY(search_child.parent() == this); + size_t index = 0; + auto* child = first_child(); + VERIFY(child); + + do { + if (!is(child)) + continue; + if (child == &search_child) + return index; + index++; + } while (child && (child = child->next_sibling())); + return {}; + } + bool is_ancestor_of(const TreeNode&) const; bool is_inclusive_ancestor_of(const TreeNode&) const; bool is_descendant_of(const TreeNode&) const;