script: Expose a constructor on HTMLCollection that takes a static function (#34667)

Expose a new constructor on `HTMLCollection`, `new_with_filter_fn`, that
filters elements using a simple static function -- a common pattern.
This allows more easily creating this `HTMLCollection` without having to
create a new data structure. Since the constructor takes a static
function, no data should be captured preventing garbage collection
issues.

Signed-off-by: Martin Robinson <mrobinson@igalia.com>
This commit is contained in:
Martin Robinson 2024-12-18 09:03:50 +01:00 committed by GitHub
parent d54b68bc96
commit 9d986a8ab3
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
7 changed files with 90 additions and 135 deletions

View file

@ -16,7 +16,7 @@ use crate::dom::bindings::root::{DomRoot, LayoutDom};
use crate::dom::bindings::str::DOMString;
use crate::dom::document::Document;
use crate::dom::element::{Element, LayoutElementHelpers};
use crate::dom::htmlcollection::{CollectionFilter, HTMLCollection};
use crate::dom::htmlcollection::HTMLCollection;
use crate::dom::htmlelement::HTMLElement;
use crate::dom::htmltablerowelement::HTMLTableRowElement;
use crate::dom::node::{window_from_node, Node};
@ -61,19 +61,17 @@ impl HTMLTableSectionElement {
}
}
#[derive(JSTraceable)]
struct RowsFilter;
impl CollectionFilter for RowsFilter {
fn filter(&self, elem: &Element, root: &Node) -> bool {
elem.is::<HTMLTableRowElement>() &&
elem.upcast::<Node>().GetParentNode().as_deref() == Some(root)
}
}
impl HTMLTableSectionElementMethods<crate::DomTypeHolder> for HTMLTableSectionElement {
// https://html.spec.whatwg.org/multipage/#dom-tbody-rows
fn Rows(&self) -> DomRoot<HTMLCollection> {
HTMLCollection::create(&window_from_node(self), self.upcast(), Box::new(RowsFilter))
HTMLCollection::new_with_filter_fn(
&window_from_node(self),
self.upcast(),
|element, root| {
element.is::<HTMLTableRowElement>() &&
element.upcast::<Node>().GetParentNode().as_deref() == Some(root)
},
)
}
// https://html.spec.whatwg.org/multipage/#dom-tbody-insertrow