NodeOperations.cpp 1.7 KB

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