InnerHTML.cpp 2.1 KB

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