Serenity Operating System
at master 63 lines 2.7 kB view raw
1/* 2 * Copyright (c) 2021, Luke Wilde <lukew@serenityos.org> 3 * 4 * SPDX-License-Identifier: BSD-2-Clause 5 */ 6 7#include <LibJS/Heap/Heap.h> 8#include <LibWeb/DOM/Document.h> 9#include <LibWeb/DOM/DocumentFragment.h> 10#include <LibWeb/DOMParsing/InnerHTML.h> 11#include <LibWeb/HTML/Parser/HTMLParser.h> 12#include <LibWeb/WebIDL/ExceptionOr.h> 13 14namespace Web::DOMParsing { 15 16// https://w3c.github.io/DOM-Parsing/#dfn-fragment-parsing-algorithm 17WebIDL::ExceptionOr<JS::NonnullGCPtr<DOM::DocumentFragment>> parse_fragment(DeprecatedString const& markup, DOM::Element& context_element) 18{ 19 // FIXME: Handle XML documents. 20 21 auto& realm = context_element.realm(); 22 23 auto new_children = HTML::HTMLParser::parse_html_fragment(context_element, markup); 24 auto fragment = MUST_OR_THROW_OOM(realm.heap().allocate<DOM::DocumentFragment>(realm, context_element.document())); 25 26 for (auto& child : new_children) { 27 // I don't know if this can throw here, but let's be safe. 28 (void)TRY(fragment->append_child(*child)); 29 } 30 31 return fragment; 32} 33 34// https://w3c.github.io/DOM-Parsing/#dom-innerhtml-innerhtml 35WebIDL::ExceptionOr<void> inner_html_setter(JS::NonnullGCPtr<DOM::Node> context_object, DeprecatedString const& value) 36{ 37 // 1. Let context element be the context object's host if the context object is a ShadowRoot object, or the context object otherwise. 38 // (This is handled in Element and ShadowRoot) 39 JS::NonnullGCPtr<DOM::Element> context_element = is<DOM::ShadowRoot>(*context_object) ? *verify_cast<DOM::ShadowRoot>(*context_object).host() : verify_cast<DOM::Element>(*context_object); 40 41 // 2. Let fragment be the result of invoking the fragment parsing algorithm with the new value as markup, and with context element. 42 auto fragment = TRY(parse_fragment(value, context_element)); 43 44 // 3. If the context object is a template element, then let context object be the template's template contents (a DocumentFragment). 45 if (is<HTML::HTMLTemplateElement>(*context_object)) 46 context_object = verify_cast<HTML::HTMLTemplateElement>(*context_object).content(); 47 48 // 4. Replace all with fragment within the context object. 49 context_object->replace_all(fragment); 50 51 // NOTE: We don't invalidate style & layout for <template> elements since they don't affect rendering. 52 if (!is<HTML::HTMLTemplateElement>(*context_object)) { 53 context_object->set_needs_style_update(true); 54 55 // NOTE: Since the DOM has changed, we have to rebuild the layout tree. 56 context_object->document().invalidate_layout(); 57 context_object->document().set_needs_layout(); 58 } 59 60 return {}; 61} 62 63}