HTMLOptionsCollection.cpp 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. /*
  2. * Copyright (c) 2022, the SerenityOS developers.
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibWeb/DOM/DOMException.h>
  7. #include <LibWeb/HTML/HTMLOptGroupElement.h>
  8. #include <LibWeb/HTML/HTMLOptionElement.h>
  9. #include <LibWeb/HTML/HTMLOptionsCollection.h>
  10. #include <LibWeb/HTML/HTMLSelectElement.h>
  11. namespace Web::HTML {
  12. HTMLOptionsCollection::HTMLOptionsCollection(DOM::ParentNode& root, Function<bool(DOM::Element const&)> filter)
  13. : DOM::HTMLCollection(root, move(filter))
  14. {
  15. }
  16. // https://html.spec.whatwg.org/multipage/common-dom-interfaces.html#dom-htmloptionscollection-add
  17. DOM::ExceptionOr<void> HTMLOptionsCollection::add(HTMLOptionOrOptGroupElement element, Optional<HTMLElementOrElementIndex> before)
  18. {
  19. auto resolved_element = element.visit([](auto const& e) -> NonnullRefPtr<HTMLElement> { return e; });
  20. RefPtr<DOM::Node> before_element;
  21. if (before.has_value() && before->has<NonnullRefPtr<HTMLElement>>())
  22. before_element = before->get<NonnullRefPtr<HTMLElement>>();
  23. // 1. If element is an ancestor of the select element on which the HTMLOptionsCollection is rooted, then throw a "HierarchyRequestError" DOMException.
  24. if (resolved_element->is_ancestor_of(root()))
  25. return DOM::HierarchyRequestError::create("The provided element is an ancestor of the root select element.");
  26. // 2. If before is an element, but that element isn't a descendant of the select element on which the HTMLOptionsCollection is rooted, then throw a "NotFoundError" DOMException.
  27. if (before_element && !before_element->is_descendant_of(root()))
  28. return DOM::NotFoundError::create("The 'before' element is not a descendant of the root select element.");
  29. // 3. If element and before are the same element, then return.
  30. if (before_element && (resolved_element.ptr() == before_element.ptr()))
  31. return {};
  32. // 4. If before is a node, then let reference be that node. Otherwise, if before is an integer, and there is a beforeth node in the collection, let reference be that node. Otherwise, let reference be null.
  33. RefPtr<DOM::Node> reference;
  34. if (before_element)
  35. reference = move(before_element);
  36. else if (before.has_value() && before->has<i32>())
  37. reference = item(before->get<i32>());
  38. // 5. If reference is not null, let parent be the parent node of reference. Otherwise, let parent be the select element on which the HTMLOptionsCollection is rooted.
  39. DOM::Node* parent = reference ? reference->parent() : root().ptr();
  40. // 6. Pre-insert element into parent node before reference.
  41. (void)TRY(parent->pre_insert(resolved_element, reference));
  42. return {};
  43. }
  44. }