use dom_struct::dom_struct;
use servo_atoms::Atom;
use crate::dom::bindings::codegen::Bindings::HTMLCollectionBinding::HTMLCollectionMethods;
use crate::dom::bindings::codegen::Bindings::HTMLFormControlsCollectionBinding::HTMLFormControlsCollectionMethods;
use crate::dom::bindings::codegen::Bindings::NodeBinding::{GetRootNodeOptions, NodeMethods};
use crate::dom::bindings::codegen::UnionTypes::RadioNodeListOrElement;
use crate::dom::bindings::inheritance::Castable;
use crate::dom::bindings::reflector::{reflect_dom_object, DomObject};
use crate::dom::bindings::root::{Dom, DomRoot};
use crate::dom::bindings::str::DOMString;
use crate::dom::element::Element;
use crate::dom::htmlcollection::{CollectionFilter, HTMLCollection};
use crate::dom::htmlformelement::HTMLFormElement;
use crate::dom::node::Node;
use crate::dom::radionodelist::RadioNodeList;
use crate::dom::window::Window;
#[dom_struct]
pub struct HTMLFormControlsCollection {
collection: HTMLCollection,
form: Dom<HTMLFormElement>,
}
impl HTMLFormControlsCollection {
fn new_inherited(
form: &HTMLFormElement,
filter: Box<dyn CollectionFilter + 'static>,
) -> HTMLFormControlsCollection {
let root_of_form = form
.upcast::<Node>()
.GetRootNode(&GetRootNodeOptions::empty());
HTMLFormControlsCollection {
collection: HTMLCollection::new_inherited(&root_of_form, filter),
form: Dom::from_ref(form),
}
}
pub fn new(
window: &Window,
form: &HTMLFormElement,
filter: Box<dyn CollectionFilter + 'static>,
) -> DomRoot<HTMLFormControlsCollection> {
reflect_dom_object(
Box::new(HTMLFormControlsCollection::new_inherited(form, filter)),
window,
)
}
}
impl HTMLFormControlsCollectionMethods for HTMLFormControlsCollection {
fn Length(&self) -> u32 {
self.collection.Length()
}
fn NamedItem(&self, name: DOMString) -> Option<RadioNodeListOrElement> {
if name.is_empty() {
return None;
}
let name = Atom::from(name);
let mut filter_map = self.collection.elements_iter().filter_map(|elem| {
if elem.get_name().is_some_and(|n| n == name) ||
elem.get_id().is_some_and(|i| i == name)
{
Some(elem)
} else {
None
}
});
if let Some(elem) = filter_map.next() {
let mut peekable = filter_map.peekable();
if peekable.peek().is_none() {
Some(RadioNodeListOrElement::Element(elem))
} else {
let global = self.global();
let window = global.as_window();
Some(RadioNodeListOrElement::RadioNodeList(
RadioNodeList::new_controls_except_image_inputs(window, &self.form, &name),
))
}
} else {
None
}
}
fn NamedGetter(&self, name: DOMString) -> Option<RadioNodeListOrElement> {
self.NamedItem(name)
}
fn SupportedPropertyNames(&self) -> Vec<DOMString> {
self.collection.SupportedPropertyNames()
}
fn IndexedGetter(&self, index: u32) -> Option<DomRoot<Element>> {
self.collection.IndexedGetter(index)
}
}