NodeIterator.h 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /*
  2. * Copyright (c) 2022, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <LibJS/Runtime/Object.h>
  8. #include <LibWeb/DOM/NodeFilter.h>
  9. namespace Web::DOM {
  10. // https://dom.spec.whatwg.org/#nodeiterator
  11. class NodeIterator final : public Bindings::PlatformObject {
  12. WEB_PLATFORM_OBJECT(NodeIterator, Bindings::PlatformObject);
  13. public:
  14. static JS::NonnullGCPtr<NodeIterator> create(Node& root, unsigned what_to_show, JS::GCPtr<NodeFilter>);
  15. virtual ~NodeIterator() override;
  16. JS::NonnullGCPtr<Node> root() { return m_root; }
  17. JS::NonnullGCPtr<Node> reference_node() { return m_reference.node; }
  18. bool pointer_before_reference_node() const { return m_reference.is_before_node; }
  19. unsigned what_to_show() const { return m_what_to_show; }
  20. NodeFilter* filter() { return m_filter.ptr(); }
  21. JS::ThrowCompletionOr<JS::GCPtr<Node>> next_node();
  22. JS::ThrowCompletionOr<JS::GCPtr<Node>> previous_node();
  23. void detach();
  24. void run_pre_removing_steps(Node&);
  25. private:
  26. explicit NodeIterator(Node& root);
  27. virtual void visit_edges(Cell::Visitor&) override;
  28. virtual void finalize() override;
  29. enum class Direction {
  30. Next,
  31. Previous,
  32. };
  33. JS::ThrowCompletionOr<JS::GCPtr<Node>> traverse(Direction);
  34. JS::ThrowCompletionOr<NodeFilter::Result> filter(Node&);
  35. // https://dom.spec.whatwg.org/#concept-traversal-root
  36. JS::NonnullGCPtr<Node> m_root;
  37. struct NodePointer {
  38. JS::NonnullGCPtr<Node> node;
  39. // https://dom.spec.whatwg.org/#nodeiterator-pointer-before-reference
  40. bool is_before_node { true };
  41. };
  42. void run_pre_removing_steps_with_node_pointer(Node&, NodePointer&);
  43. // https://dom.spec.whatwg.org/#nodeiterator-reference
  44. NodePointer m_reference;
  45. // While traversal is ongoing, we keep track of the current node pointer.
  46. // This allows us to adjust it during traversal if calling the filter ends up removing the node from the DOM.
  47. Optional<NodePointer> m_traversal_pointer;
  48. // https://dom.spec.whatwg.org/#concept-traversal-whattoshow
  49. unsigned m_what_to_show { 0 };
  50. // https://dom.spec.whatwg.org/#concept-traversal-filter
  51. JS::GCPtr<NodeFilter> m_filter;
  52. // https://dom.spec.whatwg.org/#concept-traversal-active
  53. bool m_active { false };
  54. };
  55. }