Serenity Operating System
1/*
2 * Copyright (c) 2022, Luke Wilde <lukew@serenityos.org>
3 *
4 * SPDX-License-Identifier: BSD-2-Clause
5 */
6
7#include <AK/DeprecatedString.h>
8#include <AK/Vector.h>
9#include <LibWeb/DOM/Document.h>
10#include <LibWeb/DOM/DocumentFragment.h>
11#include <LibWeb/DOM/NodeOperations.h>
12#include <LibWeb/DOM/Text.h>
13
14namespace Web::DOM {
15
16// https://dom.spec.whatwg.org/#converting-nodes-into-a-node
17WebIDL::ExceptionOr<JS::NonnullGCPtr<Node>> convert_nodes_to_single_node(Vector<Variant<JS::Handle<Node>, DeprecatedString>> const& nodes, DOM::Document& document)
18{
19 // 1. Let node be null.
20 // 2. Replace each string in nodes with a new Text node whose data is the string and node document is document.
21 // 3. If nodes contains one node, then set node to nodes[0].
22 // 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.
23 // 5. Return node.
24
25 auto potentially_convert_string_to_text_node = [&document](Variant<JS::Handle<Node>, DeprecatedString> const& node) -> JS::ThrowCompletionOr<JS::NonnullGCPtr<Node>> {
26 if (node.has<JS::Handle<Node>>())
27 return *node.get<JS::Handle<Node>>();
28
29 return MUST_OR_THROW_OOM(document.heap().allocate<DOM::Text>(document.realm(), document, node.get<DeprecatedString>()));
30 };
31
32 if (nodes.size() == 1)
33 return TRY(potentially_convert_string_to_text_node(nodes.first()));
34
35 auto document_fragment = MUST_OR_THROW_OOM(document.heap().allocate<DOM::DocumentFragment>(document.realm(), document));
36 for (auto& unconverted_node : nodes) {
37 auto node = TRY(potentially_convert_string_to_text_node(unconverted_node));
38 (void)TRY(document_fragment->append_child(node));
39 }
40
41 return document_fragment;
42}
43
44}