Selaa lähdekoodia

LibWeb: Factor out a method to update the cached elements

This is useful for any function which is needing to read the from the
cache, instead of onl using `collect_matching_elements`.
Shannon Booth 1 vuosi sitten
vanhempi
commit
cdd0038c9e

+ 23 - 17
Userland/Libraries/LibWeb/DOM/HTMLCollection.cpp

@@ -50,26 +50,32 @@ void HTMLCollection::visit_edges(Cell::Visitor& visitor)
         visitor.visit(element);
 }
 
-JS::MarkedVector<JS::NonnullGCPtr<Element>> HTMLCollection::collect_matching_elements() const
+void HTMLCollection::update_cache_if_needed() const
 {
-    if (m_cached_dom_tree_version != root()->document().dom_tree_version()) {
-        m_cached_elements.clear();
-        if (m_scope == Scope::Descendants) {
-            m_root->for_each_in_subtree_of_type<Element>([&](auto& element) {
-                if (m_filter(element))
-                    m_cached_elements.append(element);
-                return IterationDecision::Continue;
-            });
-        } else {
-            m_root->for_each_child_of_type<Element>([&](auto& element) {
-                if (m_filter(element))
-                    m_cached_elements.append(element);
-                return IterationDecision::Continue;
-            });
-        }
-        m_cached_dom_tree_version = root()->document().dom_tree_version();
+    // Nothing to do, the DOM hasn't updated since we last built the cache.
+    if (m_cached_dom_tree_version == root()->document().dom_tree_version())
+        return;
+
+    m_cached_elements.clear();
+    if (m_scope == Scope::Descendants) {
+        m_root->for_each_in_subtree_of_type<Element>([&](auto& element) {
+            if (m_filter(element))
+                m_cached_elements.append(element);
+            return IterationDecision::Continue;
+        });
+    } else {
+        m_root->for_each_child_of_type<Element>([&](auto& element) {
+            if (m_filter(element))
+                m_cached_elements.append(element);
+            return IterationDecision::Continue;
+        });
     }
+    m_cached_dom_tree_version = root()->document().dom_tree_version();
+}
 
+JS::MarkedVector<JS::NonnullGCPtr<Element>> HTMLCollection::collect_matching_elements() const
+{
+    update_cache_if_needed();
     JS::MarkedVector<JS::NonnullGCPtr<Element>> elements(heap());
     for (auto& element : m_cached_elements)
         elements.append(element);

+ 2 - 0
Userland/Libraries/LibWeb/DOM/HTMLCollection.h

@@ -56,6 +56,8 @@ protected:
 private:
     virtual void visit_edges(Cell::Visitor&) override;
 
+    void update_cache_if_needed() const;
+
     mutable u64 m_cached_dom_tree_version { 0 };
     mutable Vector<JS::NonnullGCPtr<Element>> m_cached_elements;