2022-01-29 20:23:48 +00:00
|
|
|
/*
|
|
|
|
* Copyright (c) 2022, Luke Wilde <lukew@serenityos.org>
|
2023-09-11 18:36:23 +12:00
|
|
|
* Copyright (c) 2023, Shannon Booth <shannon@serenityos.org>
|
2022-01-29 20:23:48 +00:00
|
|
|
*
|
|
|
|
* SPDX-License-Identifier: BSD-2-Clause
|
|
|
|
*/
|
|
|
|
|
2025-07-24 12:05:52 -04:00
|
|
|
#include <AK/Utf16String.h>
|
2022-01-29 20:23:48 +00:00
|
|
|
#include <AK/Vector.h>
|
2022-08-28 13:42:07 +02:00
|
|
|
#include <LibWeb/DOM/Document.h>
|
2022-01-29 20:23:48 +00:00
|
|
|
#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
|
2025-07-24 12:05:52 -04:00
|
|
|
WebIDL::ExceptionOr<GC::Ref<Node>> convert_nodes_to_single_node(Vector<Variant<GC::Root<Node>, Utf16String>> const& nodes, DOM::Document& document)
|
2022-01-29 20:23:48 +00:00
|
|
|
{
|
|
|
|
// 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.
|
|
|
|
|
2025-07-24 12:05:52 -04:00
|
|
|
auto potentially_convert_string_to_text_node = [&document](Variant<GC::Root<Node>, Utf16String> const& node) -> GC::Ref<Node> {
|
2024-11-15 04:01:23 +13:00
|
|
|
if (node.has<GC::Root<Node>>())
|
|
|
|
return *node.get<GC::Root<Node>>();
|
2022-01-29 20:23:48 +00:00
|
|
|
|
2025-07-24 12:05:52 -04:00
|
|
|
return document.realm().create<DOM::Text>(document, node.get<Utf16String>());
|
2022-01-29 20:23:48 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
if (nodes.size() == 1)
|
2023-08-13 13:05:26 +02:00
|
|
|
return potentially_convert_string_to_text_node(nodes.first());
|
2022-01-29 20:23:48 +00:00
|
|
|
|
2024-11-14 05:50:17 +13:00
|
|
|
auto document_fragment = document.realm().create<DOM::DocumentFragment>(document);
|
2023-09-11 18:36:23 +12:00
|
|
|
for (auto const& unconverted_node : nodes) {
|
2023-08-13 13:05:26 +02:00
|
|
|
auto node = potentially_convert_string_to_text_node(unconverted_node);
|
2022-03-22 12:39:33 +00:00
|
|
|
(void)TRY(document_fragment->append_child(node));
|
2022-01-29 20:23:48 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return document_fragment;
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|