From 708263790a9da79af87dc2356060bc20d8b0fd91 Mon Sep 17 00:00:00 2001 From: Shannon Booth Date: Fri, 25 Aug 2023 12:16:44 +1200 Subject: [PATCH] LibWeb: Implement LiveNodeList::first_matching This function returns the first element which matches both the filter for the LiveNodeList collection itself, and a further filter that is supplied as an argument to this function. --- .../Libraries/LibWeb/DOM/LiveNodeList.cpp | 23 +++++++++++++++++++ Userland/Libraries/LibWeb/DOM/LiveNodeList.h | 2 ++ 2 files changed, 25 insertions(+) diff --git a/Userland/Libraries/LibWeb/DOM/LiveNodeList.cpp b/Userland/Libraries/LibWeb/DOM/LiveNodeList.cpp index e3743ff454..677178d98a 100644 --- a/Userland/Libraries/LibWeb/DOM/LiveNodeList.cpp +++ b/Userland/Libraries/LibWeb/DOM/LiveNodeList.cpp @@ -52,6 +52,29 @@ JS::MarkedVector LiveNodeList::collection() const return nodes; } +Node* LiveNodeList::first_matching(Function const& filter) const +{ + Node* matched_node = nullptr; + if (m_scope == Scope::Descendants) { + m_root->for_each_in_subtree([&](auto& node) { + if (m_filter(node) && filter(node)) { + matched_node = const_cast(&node); + return IterationDecision::Break; + } + return IterationDecision::Continue; + }); + } else { + m_root->for_each_child([&](auto& node) { + if (m_filter(node) && filter(node)) { + matched_node = const_cast(&node); + return IterationDecision::Break; + } + return IterationDecision::Continue; + }); + } + return matched_node; +} + // https://dom.spec.whatwg.org/#dom-nodelist-length u32 LiveNodeList::length() const { diff --git a/Userland/Libraries/LibWeb/DOM/LiveNodeList.h b/Userland/Libraries/LibWeb/DOM/LiveNodeList.h index 80b97d66b5..b99fcadde0 100644 --- a/Userland/Libraries/LibWeb/DOM/LiveNodeList.h +++ b/Userland/Libraries/LibWeb/DOM/LiveNodeList.h @@ -34,6 +34,8 @@ public: protected: LiveNodeList(JS::Realm&, Node& root, Scope, Function filter); + Node* first_matching(Function const& filter) const; + private: virtual void visit_edges(Cell::Visitor&) override;