InnerHTML.cpp 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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/Document.h>
  8. #include <LibWeb/DOM/DocumentFragment.h>
  9. #include <LibWeb/DOMParsing/InnerHTML.h>
  10. #include <LibWeb/HTML/Parser/HTMLParser.h>
  11. #include <LibWeb/WebIDL/ExceptionOr.h>
  12. namespace Web::DOMParsing {
  13. // https://w3c.github.io/DOM-Parsing/#dfn-fragment-parsing-algorithm
  14. WebIDL::ExceptionOr<JS::NonnullGCPtr<DOM::DocumentFragment>> parse_fragment(DeprecatedString const& markup, DOM::Element& context_element)
  15. {
  16. // FIXME: Handle XML documents.
  17. auto& realm = context_element.realm();
  18. auto new_children = HTML::HTMLParser::parse_html_fragment(context_element, markup);
  19. auto fragment = MUST_OR_THROW_OOM(realm.heap().allocate<DOM::DocumentFragment>(realm, context_element.document()));
  20. for (auto& child : new_children) {
  21. // I don't know if this can throw here, but let's be safe.
  22. (void)TRY(fragment->append_child(*child));
  23. }
  24. return fragment;
  25. }
  26. // https://w3c.github.io/DOM-Parsing/#dom-innerhtml-innerhtml
  27. WebIDL::ExceptionOr<void> inner_html_setter(JS::NonnullGCPtr<DOM::Node> context_object, DeprecatedString const& value)
  28. {
  29. // 1. Let context element be the context object's host if the context object is a ShadowRoot object, or the context object otherwise.
  30. // (This is handled in Element and ShadowRoot)
  31. JS::NonnullGCPtr<DOM::Element> context_element = is<DOM::ShadowRoot>(*context_object) ? *verify_cast<DOM::ShadowRoot>(*context_object).host() : verify_cast<DOM::Element>(*context_object);
  32. // 2. Let fragment be the result of invoking the fragment parsing algorithm with the new value as markup, and with context element.
  33. auto fragment = TRY(parse_fragment(value, context_element));
  34. // 3. If the context object is a template element, then let context object be the template's template contents (a DocumentFragment).
  35. if (is<HTML::HTMLTemplateElement>(*context_object))
  36. context_object = verify_cast<HTML::HTMLTemplateElement>(*context_object).content();
  37. // 4. Replace all with fragment within the context object.
  38. context_object->replace_all(fragment);
  39. // NOTE: We don't invalidate style & layout for <template> elements since they don't affect rendering.
  40. if (!is<HTML::HTMLTemplateElement>(*context_object)) {
  41. context_object->set_needs_style_update(true);
  42. // NOTE: Since the DOM has changed, we have to rebuild the layout tree.
  43. context_object->document().invalidate_layout();
  44. context_object->document().set_needs_layout();
  45. }
  46. return {};
  47. }
  48. }