LiveNodeList.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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 <LibWeb/DOM/LiveNodeList.h>
  8. #include <LibWeb/DOM/Node.h>
  9. namespace Web::DOM {
  10. WebIDL::ExceptionOr<JS::NonnullGCPtr<NodeList>> LiveNodeList::create(JS::Realm& realm, Node& root, Function<bool(Node const&)> filter)
  11. {
  12. return MUST_OR_THROW_OOM(realm.heap().allocate<LiveNodeList>(realm, realm, root, move(filter)));
  13. }
  14. LiveNodeList::LiveNodeList(JS::Realm& realm, Node& root, Function<bool(Node const&)> filter)
  15. : NodeList(realm)
  16. , m_root(root)
  17. , m_filter(move(filter))
  18. {
  19. }
  20. LiveNodeList::~LiveNodeList() = default;
  21. void LiveNodeList::visit_edges(Cell::Visitor& visitor)
  22. {
  23. Base::visit_edges(visitor);
  24. visitor.visit(m_root.ptr());
  25. }
  26. JS::MarkedVector<Node*> LiveNodeList::collection() const
  27. {
  28. JS::MarkedVector<Node*> nodes(heap());
  29. m_root->for_each_in_inclusive_subtree([&](auto& node) {
  30. if (m_filter(node))
  31. nodes.append(const_cast<Node*>(&node));
  32. return IterationDecision::Continue;
  33. });
  34. return nodes;
  35. }
  36. // https://dom.spec.whatwg.org/#dom-nodelist-length
  37. u32 LiveNodeList::length() const
  38. {
  39. return collection().size();
  40. }
  41. // https://dom.spec.whatwg.org/#dom-nodelist-item
  42. Node const* LiveNodeList::item(u32 index) const
  43. {
  44. // 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.
  45. auto nodes = collection();
  46. if (index >= nodes.size())
  47. return nullptr;
  48. return nodes[index];
  49. }
  50. // https://dom.spec.whatwg.org/#ref-for-dfn-supported-property-indices
  51. bool LiveNodeList::is_supported_property_index(u32 index) const
  52. {
  53. // 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.
  54. // If there are no such elements, then there are no supported property indices.
  55. return index < length();
  56. }
  57. }