summaryrefslogtreecommitdiff
path: root/Userland/Libraries/LibWeb/DOM/TreeWalker.h
blob: b2dbff68d12f972aa9910f6a9ea0af876b5d8a18 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/*
 * Copyright (c) 2022, Andreas Kling <kling@serenityos.org>
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#pragma once

#include <LibWeb/DOM/NodeFilter.h>

namespace Web::DOM {

// https://dom.spec.whatwg.org/#treewalker
class TreeWalker final : public Bindings::PlatformObject {
    WEB_PLATFORM_OBJECT(TreeWalker, Bindings::PlatformObject);

public:
    static WebIDL::ExceptionOr<JS::NonnullGCPtr<TreeWalker>> create(Node& root, unsigned what_to_show, JS::GCPtr<NodeFilter>);

    virtual ~TreeWalker() override;

    JS::NonnullGCPtr<Node> current_node() const;
    void set_current_node(Node&);

    JS::ThrowCompletionOr<JS::GCPtr<Node>> parent_node();
    JS::ThrowCompletionOr<JS::GCPtr<Node>> first_child();
    JS::ThrowCompletionOr<JS::GCPtr<Node>> last_child();
    JS::ThrowCompletionOr<JS::GCPtr<Node>> previous_sibling();
    JS::ThrowCompletionOr<JS::GCPtr<Node>> next_sibling();
    JS::ThrowCompletionOr<JS::GCPtr<Node>> previous_node();
    JS::ThrowCompletionOr<JS::GCPtr<Node>> next_node();

    JS::NonnullGCPtr<Node> root() { return m_root; }

    NodeFilter* filter() { return m_filter.ptr(); }

    unsigned what_to_show() const { return m_what_to_show; }

private:
    explicit TreeWalker(Node& root);

    virtual JS::ThrowCompletionOr<void> initialize(JS::Realm&) override;
    virtual void visit_edges(Cell::Visitor&) override;

    enum class ChildTraversalType {
        First,
        Last,
    };
    JS::ThrowCompletionOr<JS::GCPtr<Node>> traverse_children(ChildTraversalType);

    enum class SiblingTraversalType {
        Next,
        Previous,
    };
    JS::ThrowCompletionOr<JS::GCPtr<Node>> traverse_siblings(SiblingTraversalType);

    JS::ThrowCompletionOr<NodeFilter::Result> filter(Node&);

    // https://dom.spec.whatwg.org/#concept-traversal-root
    JS::NonnullGCPtr<Node> m_root;

    // https://dom.spec.whatwg.org/#treewalker-current
    JS::NonnullGCPtr<Node> m_current;

    // https://dom.spec.whatwg.org/#concept-traversal-whattoshow
    unsigned m_what_to_show { 0 };

    // https://dom.spec.whatwg.org/#concept-traversal-filter
    JS::GCPtr<NodeFilter> m_filter;

    // https://dom.spec.whatwg.org/#concept-traversal-active
    bool m_active { false };
};

}