summaryrefslogtreecommitdiff
path: root/Userland/Libraries/LibWeb/DOM/NodeOperations.cpp
blob: 91649fc8b2637d76db90700bba2ada5db8a189ae (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
/*
 * Copyright (c) 2022, Luke Wilde <lukew@serenityos.org>
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#include <AK/DeprecatedString.h>
#include <AK/Vector.h>
#include <LibWeb/DOM/Document.h>
#include <LibWeb/DOM/DocumentFragment.h>
#include <LibWeb/DOM/NodeOperations.h>
#include <LibWeb/DOM/Text.h>

namespace Web::DOM {

// https://dom.spec.whatwg.org/#converting-nodes-into-a-node
WebIDL::ExceptionOr<JS::NonnullGCPtr<Node>> convert_nodes_to_single_node(Vector<Variant<JS::Handle<Node>, DeprecatedString>> const& nodes, DOM::Document& document)
{
    // 1. Let node be null.
    // 2. Replace each string in nodes with a new Text node whose data is the string and node document is document.
    // 3. If nodes contains one node, then set node to nodes[0].
    // 4. Otherwise, set node to a new DocumentFragment node whose node document is document, and then append each node in nodes, if any, to it.
    // 5. Return node.

    auto potentially_convert_string_to_text_node = [&document](Variant<JS::Handle<Node>, DeprecatedString> const& node) -> JS::ThrowCompletionOr<JS::NonnullGCPtr<Node>> {
        if (node.has<JS::Handle<Node>>())
            return *node.get<JS::Handle<Node>>();

        return MUST_OR_THROW_OOM(document.heap().allocate<DOM::Text>(document.realm(), document, node.get<DeprecatedString>()));
    };

    if (nodes.size() == 1)
        return TRY(potentially_convert_string_to_text_node(nodes.first()));

    auto document_fragment = MUST_OR_THROW_OOM(document.heap().allocate<DOM::DocumentFragment>(document.realm(), document));
    for (auto& unconverted_node : nodes) {
        auto node = TRY(potentially_convert_string_to_text_node(unconverted_node));
        (void)TRY(document_fragment->append_child(node));
    }

    return document_fragment;
}

}