Skip to content

Truly independent web browser

LibWeb: Run insertion steps once for fast-parsed innerHTML

Andreas Kling0648dc9f1d6e
diff --git a/Libraries/LibWeb/DOM/Element.cpp b/Libraries/LibWeb/DOM/Element.cpp
index f9209e1a004..7a193ccb84a 100644
--- a/Libraries/LibWeb/DOM/Element.cpp
+++ b/Libraries/LibWeb/DOM/Element.cpp
@@ -2700,12 +2700,20 @@ WebIDL::ExceptionOr<void> Element::set_inner_html(Utf16View html)
auto* template_element = as_if<HTML::HTMLTemplateElement>(*this);
if (template_element)
target = template_element->content();
- auto fragment = TRY(parse_fragment(target, html));
- // 5. Replace all with fragment within target.
- target.visit([&](auto node) {
- node->replace_all(fragment);
- });
+ // OPTIMIZATION: Markup the fast fragment parser supports needs no fragment. Inserting the parsed nodes directly
+ // runs their insertion steps once and skips removing them from a fragment no one can observe.
+ GC::RootVector<GC::Ref<Node>> fast_parsed_nodes;
+ if (!template_element && HTML::HTMLParser::try_parse_html_fragment_fast_into_detached_nodes(*this, html, fast_parsed_nodes)) {
+ replace_all(move(fast_parsed_nodes));
+ } else {
+ auto fragment = TRY(parse_fragment(target, html, HTML::ParserScriptingMode::Inert, HTML::FragmentFastPath::Skip));
+
+ // 5. Replace all with fragment within target.
+ target.visit([&](auto node) {
+ node->replace_all(fragment);
+ });
+ }
// NOTE: We don't invalidate style & layout for <template> elements since they don't affect rendering.
if (!template_element) {
@@ -3934,7 +3942,7 @@ bool Element::is_actually_disabled() const
}
// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#fragment-parsing-algorithm-steps
-WebIDL::ExceptionOr<GC::Ref<DOM::DocumentFragment>> Element::parse_fragment(Variant<GC::Ref<Element>, GC::Ref<DocumentFragment>> target, Utf16View markup, HTML::ParserScriptingMode scripting_mode)
+WebIDL::ExceptionOr<GC::Ref<DOM::DocumentFragment>> Element::parse_fragment(Variant<GC::Ref<Element>, GC::Ref<DocumentFragment>> target, Utf16View markup, HTML::ParserScriptingMode scripting_mode, HTML::FragmentFastPath fast_path)
{
// 1. Assert: scriptingMode is either Inert or Fragment.
VERIFY(scripting_mode == HTML::ParserScriptingMode::Inert || scripting_mode == HTML::ParserScriptingMode::Fragment);
@@ -3945,7 +3953,7 @@ WebIDL::ExceptionOr<GC::Ref<DOM::DocumentFragment>> Element::parse_fragment(Vari
return XMLFragmentParser::parse_xml_fragment(target, markup);
// 3. If context's node document is an XML document, then set newChildren to the result of invoking the XML fragment parsing algorithm given context and markup.
- return HTML::HTMLParser::parse_html_fragment(target, markup, HTML::HTMLParser::AllowDeclarativeShadowRoots::No, scripting_mode);
+ return HTML::HTMLParser::parse_html_fragment(target, markup, HTML::HTMLParser::AllowDeclarativeShadowRoots::No, scripting_mode, fast_path);
}
// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-element-outerhtml
diff --git a/Libraries/LibWeb/DOM/Element.h b/Libraries/LibWeb/DOM/Element.h
index e21c8b1a3f2..1191f9908a1 100644
--- a/Libraries/LibWeb/DOM/Element.h
+++ b/Libraries/LibWeb/DOM/Element.h
@@ -507,7 +507,7 @@ public:
CSS::StyleScope& document_or_shadow_root_style_scope();
ElementByIdMap& document_or_shadow_root_element_by_id_map();
- static WebIDL::ExceptionOr<GC::Ref<DOM::DocumentFragment>> parse_fragment(Variant<GC::Ref<Element>, GC::Ref<DocumentFragment>> target, Utf16View markup, HTML::ParserScriptingMode = HTML::ParserScriptingMode::Inert);
+ static WebIDL::ExceptionOr<GC::Ref<DOM::DocumentFragment>> parse_fragment(Variant<GC::Ref<Element>, GC::Ref<DocumentFragment>> target, Utf16View markup, HTML::ParserScriptingMode = HTML::ParserScriptingMode::Inert, HTML::FragmentFastPath = HTML::FragmentFastPath::Allow);
[[nodiscard]] GC::Ptr<Element const> element_to_inherit_style_from(Optional<CSS::PseudoElement>) const;
diff --git a/Libraries/LibWeb/DOM/Node.h b/Libraries/LibWeb/DOM/Node.h
index 84065400329..d73c03293de 100644
--- a/Libraries/LibWeb/DOM/Node.h
+++ b/Libraries/LibWeb/DOM/Node.h
@@ -285,6 +285,13 @@ public:
void insert_before(GC::Ref<Node> node, GC::Ptr<Node> child, bool suppress_observers = false);
void parser_insert_before(GC::Ref<Node> node, GC::Ptr<Node> child);
void parser_append_child(GC::Ref<Node> node) { parser_insert_before(node, nullptr); }
+ // Links a node the parser has just created into a new subtree that is not yet in any tree. The caller must
+ // insert the subtree's root, which runs the insertion steps for every node of the subtree.
+ void parser_append_child_without_insertion_steps(GC::Ref<Node> node)
+ {
+ VERIFY(!is_connected() && &node->document() == &document());
+ append_child_impl(node);
+ }
void remove(bool suppress_observers = false);
void remove_all_children(bool suppress_observers = false);
diff --git a/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp b/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp
index f8be6fe990b..d8f91f975ff 100644
--- a/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp
+++ b/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp
@@ -1203,7 +1203,8 @@ struct FragmentAttribute {
Utf16FlyString const* supported_fragment_tag(StringView name)
{
// Keep this subset deliberately small. Adding a tag requires checking its in-body tree-builder rules,
- // its insertion steps, and interactions with every other supported tag.
+ // its insertion steps, and interactions with every other supported tag. A supported tag must not have children
+ // changed steps, since the fast path links children below a new element without running them.
if (name == "a"sv)
return &TagNames::a;
if (name == "b"sv)
@@ -1393,32 +1394,41 @@ private:
}
-GC::Ptr<DOM::DocumentFragment> HTMLParser::try_parse_html_fragment_fast(DOM::Element& context, Utf16View input)
+bool HTMLParser::try_parse_html_fragment_fast_into_detached_nodes(DOM::Element& context, Utf16View input, GC::RootVector<GC::Ref<DOM::Node>>& top_level_nodes)
{
// OPTIMIZATION: Validate a restricted in-body grammar before allocating or exposing any DOM nodes. The second
// pass borrows input spans and constructs elements directly, bypassing tokenization and tree building.
// All unsupported syntax falls back without side effects, including custom elements and foreign content.
- if (context.namespace_uri() != Namespace::HTML || !input.has_ascii_storage())
- return nullptr;
+ // Like Blink and WebKit, only link the nodes below each top-level node without running the insertion
+ // steps. The caller inserts the top-level nodes, which runs the insertion steps for every node once.
+ // Nothing can observe the skipped steps: the nodes are new, so no script, observer, live range or
+ // collection can reach them, and the children changed steps of a new element have nothing to update.
+ VERIFY(top_level_nodes.is_empty());
+ if (context.namespace_uri() != Namespace::HTML || context.document().is_xml_document() || !input.has_ascii_storage())
+ return false;
if (!context.local_name().is_one_of(TagNames::body, TagNames::div, TagNames::span, TagNames::ul, TagNames::ol,
TagNames::li, TagNames::footer, TagNames::button, TagNames::label, TagNames::p))
- return nullptr;
+ return false;
if (context.first_ancestor_of_type<HTMLFormElement>())
- return nullptr;
+ return false;
StringView source { input.ascii_span().data(), input.length_in_code_units() };
// Character references and input preprocessing use the general parser.
if (!FragmentScanner { source }.parse([](auto const&, auto, bool) { }, [] { }, [](auto) { }))
- return nullptr;
+ return false;
- auto fragment = DOM::DocumentFragment::create(context.document());
+ auto& document = context.document();
auto registry = look_up_a_custom_element_registry(context);
GC::RootVector<GC::Ref<DOM::Node>, 32> parents;
- parents.append(fragment);
+ auto append = [&](GC::Ref<DOM::Node> node) {
+ if (parents.is_empty())
+ top_level_nodes.append(node);
+ else
+ parents.last()->parser_append_child_without_insertion_steps(node);
+ };
auto success = FragmentScanner { source }.parse(
[&](Utf16FlyString const& tag, ReadonlySpan<FragmentAttribute> attributes, bool is_void) {
- auto& parent = *parents.last();
- auto element = MUST(DOM::create_element(context.document(), tag, Namespace::HTML, {}, {}, false, registry));
+ auto element = MUST(DOM::create_element(document, tag, Namespace::HTML, {}, {}, false, registry));
element->ensure_attribute_capacity(attributes.size());
for (auto const& attribute : attributes) {
DOM::QualifiedName name { Utf16FlyString::from_utf8_without_validation(attribute.name), {}, {} };
@@ -1427,20 +1437,31 @@ GC::Ptr<DOM::DocumentFragment> HTMLParser::try_parse_html_fragment_fast(DOM::Ele
auto& html_element = as<HTMLElement>(*element);
if (html_element.is_form_associated_element() && html_element.is_resettable())
html_element.reset_algorithm();
- parent.parser_append_child(element);
+ append(element);
if (!is_void)
parents.append(element);
},
[&] { parents.take_last(); },
[&](StringView text) {
- parents.last()->parser_append_child(DOM::Text::create(context.document(), Utf16String::from_utf8_without_validation(text)));
+ append(DOM::Text::create(document, Utf16String::from_utf8_without_validation(text)));
});
VERIFY(success);
+ return true;
+}
+
+GC::Ptr<DOM::DocumentFragment> HTMLParser::try_parse_html_fragment_fast(DOM::Element& context, Utf16View input)
+{
+ GC::RootVector<GC::Ref<DOM::Node>> top_level_nodes;
+ if (!try_parse_html_fragment_fast_into_detached_nodes(context, input, top_level_nodes))
+ return nullptr;
+ auto fragment = DOM::DocumentFragment::create(context.document());
+ for (auto node : top_level_nodes)
+ fragment->parser_append_child(node);
return fragment;
}
// https://html.spec.whatwg.org/multipage/parsing.html#parsing-html-fragments
-WebIDL::ExceptionOr<GC::Ref<DOM::DocumentFragment>> HTMLParser::parse_html_fragment(Variant<GC::Ref<DOM::Element>, GC::Ref<DOM::DocumentFragment>> target, Utf16View input, AllowDeclarativeShadowRoots allow_declarative_shadow_roots, ParserScriptingMode scripting_mode)
+WebIDL::ExceptionOr<GC::Ref<DOM::DocumentFragment>> HTMLParser::parse_html_fragment(Variant<GC::Ref<DOM::Element>, GC::Ref<DOM::DocumentFragment>> target, Utf16View input, AllowDeclarativeShadowRoots allow_declarative_shadow_roots, ParserScriptingMode scripting_mode, FragmentFastPath fast_path)
{
// 1. Assert: scriptingMode is either Inert or Fragment.
VERIFY(scripting_mode == HTML::ParserScriptingMode::Inert || scripting_mode == HTML::ParserScriptingMode::Fragment);
@@ -1454,7 +1475,7 @@ WebIDL::ExceptionOr<GC::Ref<DOM::DocumentFragment>> HTMLParser::parse_html_fragm
VERIFY(context);
// OPTIMIZATION: A validated subset of in-body fragments can be constructed directly from input spans.
- if (target.has<GC::Ref<DOM::Element>>()) {
+ if (fast_path == FragmentFastPath::Allow && target.has<GC::Ref<DOM::Element>>()) {
if (auto fragment = try_parse_html_fragment_fast(*context, input))
return GC::Ref { *fragment };
}
diff --git a/Libraries/LibWeb/HTML/Parser/HTMLParser.h b/Libraries/LibWeb/HTML/Parser/HTMLParser.h
index aad68d07fc3..7f24840bc40 100644
--- a/Libraries/LibWeb/HTML/Parser/HTMLParser.h
+++ b/Libraries/LibWeb/HTML/Parser/HTMLParser.h
@@ -62,7 +62,12 @@ public:
};
static WebIDL::ExceptionOr<GC::Ref<DOM::DocumentFragment>> parse_html_fragment(Variant<GC::Ref<DOM::Element>, GC::Ref<DOM::DocumentFragment>> target, Utf16View markup,
- AllowDeclarativeShadowRoots = AllowDeclarativeShadowRoots::No, ParserScriptingMode = ParserScriptingMode::Inert);
+ AllowDeclarativeShadowRoots = AllowDeclarativeShadowRoots::No, ParserScriptingMode = ParserScriptingMode::Inert, FragmentFastPath = FragmentFastPath::Allow);
+
+ // Parses a restricted subset of in-body markup in context. On success, appends the parsed top-level nodes to
+ // top_level_nodes. Their subtrees are linked without running the insertion steps, which inserting each top-level
+ // node into a parent runs for the whole subtree.
+ static bool try_parse_html_fragment_fast_into_detached_nodes(DOM::Element& context, Utf16View, GC::RootVector<GC::Ref<DOM::Node>>& top_level_nodes);
enum class SerializableShadowRoots {
No,
diff --git a/Libraries/LibWeb/HTML/Parser/ParserScriptingMode.h b/Libraries/LibWeb/HTML/Parser/ParserScriptingMode.h
index 9be72ceb487..f7a42dbd02f 100644
--- a/Libraries/LibWeb/HTML/Parser/ParserScriptingMode.h
+++ b/Libraries/LibWeb/HTML/Parser/ParserScriptingMode.h
@@ -27,4 +27,10 @@ enum class ParserScriptingMode : u8 {
Fragment,
};
+// Whether the HTML fragment parsing algorithm may try the fragment fast path. Callers that have already tried it skip it.
+enum class FragmentFastPath : u8 {
+ Allow,
+ Skip,
+};
+
}
diff --git a/Tests/LibWeb/Text/expected/HTML/fragment-parser-fast-path.txt b/Tests/LibWeb/Text/expected/HTML/fragment-parser-fast-path.txt
index fec00885bd3..17c9f487b82 100644
--- a/Tests/LibWeb/Text/expected/HTML/fragment-parser-fast-path.txt
+++ b/Tests/LibWeb/Text/expected/HTML/fragment-parser-fast-path.txt
@@ -5,4 +5,7 @@ Form context: true, true, inside form
Registry scoped: true
Registry null: true
Custom: constructor, data-value:test, connected
+Collection before: 0
+Collection after: 2, true, true, rgb(0, 128, 0)
+Contextual: 2, true, false
Customized input: true, custom
diff --git a/Tests/LibWeb/Text/input/HTML/fragment-parser-fast-path.html b/Tests/LibWeb/Text/input/HTML/fragment-parser-fast-path.html
index 10213494c6f..c4654d92c17 100644
--- a/Tests/LibWeb/Text/input/HTML/fragment-parser-fast-path.html
+++ b/Tests/LibWeb/Text/input/HTML/fragment-parser-fast-path.html
@@ -108,6 +108,16 @@ test(() => {
host.innerHTML = '<div>before</div><fragment-parser-custom data-value="test"></fragment-parser-custom>';
println(`Custom: ${reactions.join(', ')}`);
+ const spans = host.getElementsByTagName('span');
+ println(`Collection before: ${spans.length}`);
+ host.innerHTML = '<ul><li><div><span style="color: rgb(0, 128, 0)">deep</span></div></li></ul><span>top</span>';
+ const deep = host.querySelector('div > span');
+ println(`Collection after: ${spans.length}, ${deep.isConnected}, ${deep.parentNode.parentNode.parentNode.parentNode === host}, ${getComputedStyle(deep).color}`);
+ const range = document.createRange();
+ range.selectNodeContents(host);
+ const contextual = range.createContextualFragment('<div><span>in fragment</span></div>text');
+ println(`Contextual: ${contextual.childNodes.length}, ${contextual.firstChild.firstChild.parentNode === contextual.firstChild}, ${contextual.firstChild.isConnected}`);
+
class CustomInput extends HTMLInputElement {}
customElements.define('fragment-parser-input', CustomInput, { extends: 'input' });
host.innerHTML = '<input is="fragment-parser-input" value="custom">';