NodeIterator.h 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. JS_DECLARE_ALLOCATOR(NodeIterator);
  14. public:
  15. static WebIDL::ExceptionOr<JS::NonnullGCPtr<NodeIterator>> create(Node& root, unsigned what_to_show, JS::GCPtr<NodeFilter>);
  16. virtual ~NodeIterator() override;
  17. JS::NonnullGCPtr<Node> root() { return m_root; }
  18. JS::NonnullGCPtr<Node> reference_node() { return m_reference.node; }
  19. bool pointer_before_reference_node() const { return m_reference.is_before_node; }
  20. unsigned what_to_show() const { return m_what_to_show; }
  21. NodeFilter* filter() { return m_filter.ptr(); }
  22. JS::ThrowCompletionOr<JS::GCPtr<Node>> next_node();
  23. JS::ThrowCompletionOr<JS::GCPtr<Node>> previous_node();
  24. void detach();
  25. void run_pre_removing_steps(Node&);
  26. private:
  27. explicit NodeIterator(Node& root);
  28. virtual void initialize(JS::Realm&) override;
  29. virtual void visit_edges(Cell::Visitor&) override;
  30. virtual void finalize() override;
  31. enum class Direction {
  32. Next,
  33. Previous,
  34. };
  35. JS::ThrowCompletionOr<JS::GCPtr<Node>> traverse(Direction);
  36. JS::ThrowCompletionOr<NodeFilter::Result> filter(Node&);
  37. // https://dom.spec.whatwg.org/#concept-traversal-root
  38. JS::NonnullGCPtr<Node> m_root;
  39. struct NodePointer {
  40. JS::NonnullGCPtr<Node> node;
  41. // https://dom.spec.whatwg.org/#nodeiterator-pointer-before-reference
  42. bool is_before_node { true };
  43. };
  44. void run_pre_removing_steps_with_node_pointer(Node&, NodePointer&);
  45. // https://dom.spec.whatwg.org/#nodeiterator-reference
  46. NodePointer m_reference;
  47. // While traversal is ongoing, we keep track of the current node pointer.
  48. // This allows us to adjust it during traversal if calling the filter ends up removing the node from the DOM.
  49. Optional<NodePointer> m_traversal_pointer;
  50. // https://dom.spec.whatwg.org/#concept-traversal-whattoshow
  51. unsigned m_what_to_show { 0 };
  52. // https://dom.spec.whatwg.org/#concept-traversal-filter
  53. JS::GCPtr<NodeFilter> m_filter;
  54. // https://dom.spec.whatwg.org/#concept-traversal-active
  55. bool m_active { false };
  56. };
  57. }