InnerHTML.cpp 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. /*
  2. * Copyright (c) 2021, Luke Wilde <lukew@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibWeb/DOM/DocumentFragment.h>
  7. #include <LibWeb/DOM/ExceptionOr.h>
  8. #include <LibWeb/DOMParsing/InnerHTML.h>
  9. #include <LibWeb/HTML/Parser/HTMLParser.h>
  10. namespace Web::DOMParsing {
  11. // https://w3c.github.io/DOM-Parsing/#dfn-fragment-parsing-algorithm
  12. static DOM::ExceptionOr<NonnullRefPtr<DOM::DocumentFragment>> parse_fragment(String const& markup, DOM::Element& context_element)
  13. {
  14. // FIXME: Handle XML documents.
  15. auto new_children = HTML::HTMLParser::parse_html_fragment(context_element, markup);
  16. auto fragment = make_ref_counted<DOM::DocumentFragment>(context_element.document());
  17. for (auto& child : new_children) {
  18. // I don't know if this can throw here, but let's be safe.
  19. (void)TRY(fragment->append_child(child));
  20. }
  21. return fragment;
  22. }
  23. // https://w3c.github.io/DOM-Parsing/#dom-innerhtml-innerhtml
  24. DOM::ExceptionOr<void> inner_html_setter(NonnullRefPtr<DOM::Node> context_object, String const& value)
  25. {
  26. // 1. Let context element be the context object's host if the context object is a ShadowRoot object, or the context object otherwise.
  27. // (This is handled in Element and ShadowRoot)
  28. NonnullRefPtr<DOM::Element> context_element = is<DOM::ShadowRoot>(*context_object) ? *verify_cast<DOM::ShadowRoot>(*context_object).host() : verify_cast<DOM::Element>(*context_object);
  29. // 2. Let fragment be the result of invoking the fragment parsing algorithm with the new value as markup, and with context element.
  30. auto fragment = TRY(parse_fragment(value, context_element));
  31. // 3. If the context object is a template element, then let context object be the template's template contents (a DocumentFragment).
  32. if (is<HTML::HTMLTemplateElement>(*context_object))
  33. context_object = verify_cast<HTML::HTMLTemplateElement>(*context_object).content();
  34. // 4. Replace all with fragment within the context object.
  35. context_object->replace_all(fragment);
  36. return {};
  37. }
  38. }