NodeOperations.cpp 1.7 KB

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