LiveNodeList.cpp 2.0 KB

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