LiveNodeList.cpp 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /*
  2. * Copyright (c) 2021, Luke Wilde <lukew@serenityos.org>
  3. * Copyright (c) 2022, Andreas Kling <kling@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <LibJS/Heap/Heap.h>
  8. #include <LibJS/Runtime/Error.h>
  9. #include <LibWeb/DOM/LiveNodeList.h>
  10. #include <LibWeb/DOM/Node.h>
  11. namespace Web::DOM {
  12. WebIDL::ExceptionOr<JS::NonnullGCPtr<NodeList>> LiveNodeList::create(JS::Realm& realm, Node& root, Scope scope, Function<bool(Node const&)> filter)
  13. {
  14. return MUST_OR_THROW_OOM(realm.heap().allocate<LiveNodeList>(realm, realm, root, scope, move(filter)));
  15. }
  16. LiveNodeList::LiveNodeList(JS::Realm& realm, Node& root, Scope scope, Function<bool(Node const&)> filter)
  17. : NodeList(realm)
  18. , m_root(root)
  19. , m_filter(move(filter))
  20. , m_scope(scope)
  21. {
  22. }
  23. LiveNodeList::~LiveNodeList() = default;
  24. void LiveNodeList::visit_edges(Cell::Visitor& visitor)
  25. {
  26. Base::visit_edges(visitor);
  27. visitor.visit(m_root.ptr());
  28. }
  29. JS::MarkedVector<Node*> LiveNodeList::collection() const
  30. {
  31. JS::MarkedVector<Node*> nodes(heap());
  32. if (m_scope == Scope::Descendants) {
  33. m_root->for_each_in_subtree([&](auto& node) {
  34. if (m_filter(node))
  35. nodes.append(const_cast<Node*>(&node));
  36. return IterationDecision::Continue;
  37. });
  38. } else {
  39. m_root->for_each_child([&](auto& node) {
  40. if (m_filter(node))
  41. nodes.append(const_cast<Node*>(&node));
  42. return IterationDecision::Continue;
  43. });
  44. }
  45. return nodes;
  46. }
  47. // https://dom.spec.whatwg.org/#dom-nodelist-length
  48. u32 LiveNodeList::length() const
  49. {
  50. return collection().size();
  51. }
  52. // https://dom.spec.whatwg.org/#dom-nodelist-item
  53. Node const* LiveNodeList::item(u32 index) const
  54. {
  55. // The item(index) method must return the indexth node in the collection. If there is no indexth node in the collection, then the method must return null.
  56. auto nodes = collection();
  57. if (index >= nodes.size())
  58. return nullptr;
  59. return nodes[index];
  60. }
  61. // https://dom.spec.whatwg.org/#ref-for-dfn-supported-property-indices
  62. bool LiveNodeList::is_supported_property_index(u32 index) const
  63. {
  64. // The object’s supported property indices are the numbers in the range zero to one less than the number of nodes represented by the collection.
  65. // If there are no such elements, then there are no supported property indices.
  66. return index < length();
  67. }
  68. }