LibWeb: Add select and option collection set length

This commit is contained in:
Bastiaan van der Plaat 2024-04-08 21:50:35 +02:00 committed by Andreas Kling
parent 4e5ce7b63e
commit 5c277144d8
Notes: sideshowbarker 2024-07-16 23:17:55 +09:00
8 changed files with 95 additions and 5 deletions

View file

@ -5,10 +5,12 @@
*/
#include <LibWeb/Bindings/Intrinsics.h>
#include <LibWeb/DOM/ElementFactory.h>
#include <LibWeb/HTML/HTMLOptGroupElement.h>
#include <LibWeb/HTML/HTMLOptionElement.h>
#include <LibWeb/HTML/HTMLOptionsCollection.h>
#include <LibWeb/HTML/HTMLSelectElement.h>
#include <LibWeb/Namespace.h>
#include <LibWeb/WebIDL/DOMException.h>
namespace Web::HTML {
@ -33,6 +35,41 @@ void HTMLOptionsCollection::initialize(JS::Realm& realm)
WEB_SET_PROTOTYPE_FOR_INTERFACE(HTMLOptionsCollection);
}
// https://html.spec.whatwg.org/multipage/common-dom-interfaces.html#dom-htmloptionscollection-length
WebIDL::ExceptionOr<void> HTMLOptionsCollection::set_length(WebIDL::UnsignedLong value)
{
// 1. Let current be the number of nodes represented by the collection.
auto current = static_cast<WebIDL::UnsignedLong>(length());
// 2. If the given value is greater than current, then:
if (value > current) {
// 2.1. If the given value is greater than 100,000, then return.
if (value > 100'000)
return {};
// 2.2. Let n be value current.
auto n = value - current;
// 2.3. Append n new option elements with no attributes and no child nodes to the select element on which this is rooted.
// Mutation events must be fired as if a DocumentFragment containing the new option elements had been inserted.
auto root_element = root();
for (WebIDL::UnsignedLong i = 0; i < n; i++)
TRY(root_element->append_child(TRY(DOM::create_element(root_element->document(), HTML::TagNames::option, Namespace::HTML))));
}
// 3. If the given value is less than current, then:
if (value < current) {
// 3.1. Let n be current value.
auto n = current - value;
// 3.2. Remove the last n nodes in the collection from their parent nodes.
for (WebIDL::UnsignedLong i = current - 1; i >= current - n; i--)
this->item(i)->remove();
}
return {};
}
// https://html.spec.whatwg.org/multipage/common-dom-interfaces.html#dom-htmloptionscollection-add
WebIDL::ExceptionOr<void> HTMLOptionsCollection::add(HTMLOptionOrOptGroupElement element, Optional<HTMLElementOrElementIndex> before)
{