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`.
This commit is contained in:
Shannon Booth 2024-04-01 15:08:22 +02:00 committed by Andreas Kling
parent b6501adef8
commit cdd0038c9e
Notes: sideshowbarker 2024-07-16 17:05:37 +09:00
2 changed files with 26 additions and 18 deletions

View file

@ -50,26 +50,32 @@ void HTMLCollection::visit_edges(Cell::Visitor& visitor)
visitor.visit(element);
}
void HTMLCollection::update_cache_if_needed() const
{
// 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
{
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();
}
update_cache_if_needed();
JS::MarkedVector<JS::NonnullGCPtr<Element>> elements(heap());
for (auto& element : m_cached_elements)
elements.append(element);

View file

@ -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;