TreeWalker.h 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /*
  2. * Copyright (c) 2022, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <LibWeb/DOM/NodeFilter.h>
  8. namespace Web::DOM {
  9. // https://dom.spec.whatwg.org/#treewalker
  10. class TreeWalker final : public Bindings::PlatformObject {
  11. WEB_PLATFORM_OBJECT(TreeWalker, Bindings::PlatformObject);
  12. JS_DECLARE_ALLOCATOR(TreeWalker);
  13. public:
  14. [[nodiscard]] static JS::NonnullGCPtr<TreeWalker> create(Node& root, unsigned what_to_show, JS::GCPtr<NodeFilter>);
  15. virtual ~TreeWalker() override;
  16. JS::NonnullGCPtr<Node> current_node() const;
  17. void set_current_node(Node&);
  18. JS::ThrowCompletionOr<JS::GCPtr<Node>> parent_node();
  19. JS::ThrowCompletionOr<JS::GCPtr<Node>> first_child();
  20. JS::ThrowCompletionOr<JS::GCPtr<Node>> last_child();
  21. JS::ThrowCompletionOr<JS::GCPtr<Node>> previous_sibling();
  22. JS::ThrowCompletionOr<JS::GCPtr<Node>> next_sibling();
  23. JS::ThrowCompletionOr<JS::GCPtr<Node>> previous_node();
  24. JS::ThrowCompletionOr<JS::GCPtr<Node>> next_node();
  25. JS::NonnullGCPtr<Node> root() { return m_root; }
  26. NodeFilter* filter() { return m_filter.ptr(); }
  27. unsigned what_to_show() const { return m_what_to_show; }
  28. private:
  29. explicit TreeWalker(Node& root);
  30. virtual void initialize(JS::Realm&) override;
  31. virtual void visit_edges(Cell::Visitor&) override;
  32. enum class ChildTraversalType {
  33. First,
  34. Last,
  35. };
  36. JS::ThrowCompletionOr<JS::GCPtr<Node>> traverse_children(ChildTraversalType);
  37. enum class SiblingTraversalType {
  38. Next,
  39. Previous,
  40. };
  41. JS::ThrowCompletionOr<JS::GCPtr<Node>> traverse_siblings(SiblingTraversalType);
  42. JS::ThrowCompletionOr<NodeFilter::Result> filter(Node&);
  43. // https://dom.spec.whatwg.org/#concept-traversal-root
  44. JS::NonnullGCPtr<Node> m_root;
  45. // https://dom.spec.whatwg.org/#treewalker-current
  46. JS::NonnullGCPtr<Node> m_current;
  47. // https://dom.spec.whatwg.org/#concept-traversal-whattoshow
  48. unsigned m_what_to_show { 0 };
  49. // https://dom.spec.whatwg.org/#concept-traversal-filter
  50. JS::GCPtr<NodeFilter> m_filter;
  51. // https://dom.spec.whatwg.org/#concept-traversal-active
  52. bool m_active { false };
  53. };
  54. }