Lightpanda: the headless browser designed for AI and automation
webapi: fix custom element upgrade ordering during fragment parsing
Karl Seguin4487176490d6
diff --git a/src/browser/Frame.zig b/src/browser/Frame.zigindex 75f91e52b..e160bdd2f 100644--- a/src/browser/Frame.zig+++ b/src/browser/Frame.zig@@ -195,7 +195,7 @@ _upgrading_element: ?*Node = null,_upgrading_consumed: bool = false,// How node_factory creates an element with a hyphenated HTML tag name.-_custom_element_creation: enum {+_custom_element_creation: union(enum) {// Look the definition up in this frame's registry and run the// constructor synchronously.construct,@@ -203,6 +203,10 @@ _custom_element_creation: enum {// constructor must not run (you end up in an endless loop if the constructor// does this.innerHTML = '...', which happens).bare_context,+ // During fragment parsing (e.g., innerHTML = '...'), the upgrade is queued+ // on the caller's CEReaction scope. (The constructor has to be run _after_+ // the fragment is inserted).+ upgrade: *Frame,} = .construct,// List of custom elements that were created before their definition was registereddiff --git a/src/browser/frame/node_factory.zig b/src/browser/frame/node_factory.zigindex 1c0b5f2d1..8c8dbbcd3 100644--- a/src/browser/frame/node_factory.zig+++ b/src/browser/frame/node_factory.zig@@ -845,24 +845,25 @@ pub fn createElementNS(document: *const Node.Document, namespace: Element.Namesp//// Undefined elements are created in the "undefined" state and// upgraded later, when a matching definition is registered.- if (creation != .construct or definition == null) {+ if (creation == .bare_context or definition == null) {const node = try createHtmlElementT(document, Element.Html.Custom, namespace, attribute_iterator, .{._tag_name = tag_name,._definition = definition,- ._upgrade_candidate = creation == .construct,+ ._upgrade_candidate = creation != .bare_context,});- if (creation == .construct) {+ if (creation != .bare_context) {try realm._undefined_custom_elements.append(realm.arena, node.as(Element).is(Element.Html.Custom).?);}return node;}- if (from_clone) {+ if (from_clone or creation == .upgrade) {const node = try createHtmlElementT(document, Element.Html.Custom, namespace, attribute_iterator, .{._tag_name = tag_name,._definition = null,});- try realm._ce_reactions.enqueueUpgrade(realm, node.as(Element).is(Element.Html.Custom).?, definition.?);+ const reactions_frame = if (creation == .upgrade) creation.upgrade else realm;+ try reactions_frame._ce_reactions.enqueueUpgrade(reactions_frame, node.as(Element).is(Element.Html.Custom).?, definition.?);return node;}diff --git a/src/browser/parser/Parser.zig b/src/browser/parser/Parser.zigindex bf7de6dab..1e1643fa8 100644--- a/src/browser/parser/Parser.zig+++ b/src/browser/parser/Parser.zig@@ -109,6 +109,9 @@ allow_declarative_shadow: bool = false,// behavior.context: ?*Element = null,+// // Fragment parsing doesn't run custom element constructor synchronously+fragment: bool = false,+xml_error: bool = false,terminated: bool = false,appends_until_terminate_check: u16 = TERMINATE_CHECK_INTERVAL,@@ -311,6 +314,7 @@ pub fn parseXML(self: *Parser, xml: []const u8) void {}pub fn parseFragment(self: *Parser, html: []const u8) void {+ self.fragment = true;const context_name: []const u8 = if (self.context orelse self.container.node.is(Element)) |el|el.getLocalName()else@@ -532,6 +536,17 @@ fn createContextElementCallback(ctx: *anyopaque, data: *anyopaque, qname: h5e.Qufn _createElementCallbackWithDefaultnamespace(ctx: *anyopaque, data: *anyopaque, qname: h5e.QualName, attributes: h5e.AttributeIterator, default_namespace: Element.Namespace) ?*anyopaque {const self: *Parser = @ptrCast(@alignCast(ctx));+ if (self.fragment) {+ const frame = self.document._frame orelse self.frame;+ const previous_creation = frame._custom_element_creation;+ frame._custom_element_creation = .{ .upgrade = self.frame };+ defer frame._custom_element_creation = previous_creation;+ return self._createElementCallback(data, qname, attributes, default_namespace) catch |err| {+ self.err = .{ .err = err, .source = .create_element };+ return null;+ };+ }+const cp = self.frame._ce_reactions.push();defer self.frame._ce_reactions.popAndInvoke(cp, self.frame);return self._createElementCallback(data, qname, attributes, default_namespace) catch |err| {diff --git a/src/browser/tests/custom_elements/create_element_post_conditions.html b/src/browser/tests/custom_elements/create_element_post_conditions.htmlindex 91b64ecba..412995098 100644--- a/src/browser/tests/custom_elements/create_element_post_conditions.html+++ b/src/browser/tests/custom_elements/create_element_post_conditions.html@@ -101,46 +101,77 @@}</script>+<!-- Same thing, but driven through the document parser, which constructs+ synchronously: the fallback element is what gets inserted. -->+<div id="parser_attaches_self_host"></div>+<script>+ class ParserAttachesSelf extends HTMLElement {+ constructor() {+ super();+ document.getElementById('parser_attaches_self_host').appendChild(this);+ }+ }+ customElements.define('ce-parser-attaches-self', ParserAttachesSelf);+ window.parserReported = [];+ window.parserOnError = (e) => {+ parserReported.push(e.error.name);+ e.preventDefault();+ };+ window.addEventListener('error', parserOnError);+</script>+<div id="parser_attaches_self_container"><ce-parser-attaches-self></ce-parser-attaches-self></div><script id="parser_falls_back_without_crashing">{- // Same thing, but driven through the fragment parser rather than- // createElement: the fallback element is what gets inserted.- const host = document.createElement('div');- class ParserAttachesSelf extends HTMLElement {- constructor() {- super();- host.appendChild(this);- }- }- customElements.define('ce-parser-attaches-self', ParserAttachesSelf);+ window.removeEventListener('error', parserOnError);+ testing.expectEqual(['NotSupportedError'], parserReported);+ const container = document.getElementById('parser_attaches_self_container');+ testing.expectEqual(1, container.children.length);+ testing.expectEqual(true, container.firstElementChild instanceof HTMLUnknownElement);+ }+</script>+<script id="fragment_parser_upgrades_instead">+ {+ // The fragment parser creates the element undefined and upgrades it+ // once inserted, where attaching itself elsewhere is allowed.+ const host = document.getElementById('parser_attaches_self_host');+ host.replaceChildren();const container = document.createElement('div');const errors = testing.withReportedErrors(() => {container.innerHTML = '<ce-parser-attaches-self></ce-parser-attaches-self>';});- testing.expectEqual(['NotSupportedError'], errors.map((e) => e.name));- testing.expectEqual(1, container.children.length);- testing.expectEqual(true, container.firstElementChild instanceof HTMLUnknownElement);+ testing.expectEqual([], errors);+ testing.expectEqual(0, container.children.length);+ testing.expectEqual(true, host.firstElementChild instanceof ParserAttachesSelf);}</script>+<script>+ window.seenTitle = 'unset';+ class ObservesAttribute extends HTMLElement {+ static get observedAttributes() { return ['title']; }+ constructor() {+ super();+ seenTitle = this.getAttribute('title');+ }+ }+ customElements.define('ce-observes-attribute', ObservesAttribute);+</script>+<ce-observes-attribute id="observes_attribute" title="after"></ce-observes-attribute><script id="attributes_applied_after_constructor">{// The constructor must not observe the token's attributes; they are// applied afterwards, which is also what enqueues their reactions.- let seen = 'unset';- class ObservesAttribute extends HTMLElement {- static get observedAttributes() { return ['title']; }- constructor() {- super();- seen = this.getAttribute('title');- }- }- customElements.define('ce-observes-attribute', ObservesAttribute);+ testing.expectEqual(null, seenTitle);+ testing.expectEqual('after', document.getElementById('observes_attribute').getAttribute('title'));+ }+</script>+<script id="fragment_parser_upgrade_sees_attributes">+ {+ // An upgrade runs the constructor on the element as parsed.const container = document.createElement('div');- container.innerHTML = '<ce-observes-attribute title="after"></ce-observes-attribute>';- testing.expectEqual(null, seen);- testing.expectEqual('after', container.firstElementChild.getAttribute('title'));+ container.innerHTML = '<ce-observes-attribute title="parsed"></ce-observes-attribute>';+ testing.expectEqual('parsed', seenTitle);}</script>diff --git a/src/browser/tests/custom_elements/error_reporting.html b/src/browser/tests/custom_elements/error_reporting.htmlindex 0b608c671..8598988c2 100644--- a/src/browser/tests/custom_elements/error_reporting.html+++ b/src/browser/tests/custom_elements/error_reporting.html@@ -164,8 +164,9 @@<script id="parser_reports_constructor_exception">{- // The parser's create-element path must report too, and still insert- // the HTMLUnknownElement fallback.+ // The fragment parser upgrades rather than constructs, so a throwing+ // constructor is reported and leaves a failed (not unknown) element,+ // whose prototype super() had already set.const thrown = new Error('from parser constructor');class ParserThrows extends HTMLElement {constructor() {@@ -183,7 +184,8 @@testing.expectEqual(true, reported === thrown);testing.expectEqual(1, container.children.length);- testing.expectEqual(true, container.firstElementChild instanceof HTMLUnknownElement);+ testing.expectEqual(false, container.firstElementChild instanceof HTMLUnknownElement);+ testing.expectEqual(true, container.firstElementChild instanceof ParserThrows);}</script>diff --git a/src/browser/tests/custom_elements/registry.html b/src/browser/tests/custom_elements/registry.htmlindex 0640b851b..173606235 100644--- a/src/browser/tests/custom_elements/registry.html+++ b/src/browser/tests/custom_elements/registry.html@@ -121,11 +121,10 @@<script id="constructor_self_insert_foster_parent">{- // Regression: custom element constructor inserting itself (via appendChild) during- // innerHTML parsing. When the element is not valid table content, the HTML5 parser- // foster-parents it before the <table> via appendBeforeSiblingCallback. That callback- // previously didn't check for an existing _parent before calling insertNodeRelative,- // causing the "Page.insertNodeRelative parent" assertion to fire.+ // Regression: when innerHTML ran constructors synchronously, a constructor+ // inserting itself left the element with a parent before the parser+ // foster-parented it, and the "Page.insertNodeRelative parent" assertion+ // fired. The fragment parser now upgrades the element after insertion.let constructorCalled = 0;let container;@@ -133,8 +132,6 @@constructor() {super();constructorCalled++;- // Insert self into container so _parent is set before the parser- // officially places this element via appendBeforeSiblingCallback.if (container) container.appendChild(this);}}@@ -142,17 +139,12 @@container = document.createElement('div');// ctor-self-insert is not valid table content; the parser foster-parents it- // before the <table>, calling appendBeforeSiblingCallback(sibling=table, node=element).- // At that point the element already has _parent=container from the constructor.- // TODO: we construct synchronously during fragment parsing, so the parent- // fails the create-an-element post-conditions. Per spec (and Firefox) the- // element is upgraded after insertion instead, and nothing is reported.- const errors = testing.withReportedErrors(() => {- container.innerHTML = '<table><ctor-self-insert></ctor-self-insert></table>';- });- testing.expectEqual(['NotSupportedError'], errors.map((e) => e.name));+ // before the <table>, then the upgrade moves it to the end.+ container.innerHTML = '<table><ctor-self-insert></ctor-self-insert></table>';testing.expectEqual(1, constructorCalled);+ testing.expectEqual(true, container.firstElementChild instanceof HTMLTableElement);+ testing.expectEqual(true, container.lastElementChild instanceof CtorSelfInsert);}</script>diff --git a/src/browser/webapi/element/html/Custom.zig b/src/browser/webapi/element/html/Custom.zigindex cc6525f54..c96ef9664 100644--- a/src/browser/webapi/element/html/Custom.zig+++ b/src/browser/webapi/element/html/Custom.zig@@ -228,7 +228,10 @@ pub fn fireReaction(reaction: Reaction, frame: *Frame) void {.upgrade => |u| {if (u.element._definition != null or u.element._upgrade_failed) return;const CustomElementRegistry = @import("../../CustomElementRegistry.zig");- CustomElementRegistry.upgradeCustomElement(u.element, u.definition, frame) catch {};+ // queue on the caller's frame, which might not be the element's+ // (e.g. iframe.contentDocument.body.innerHTML = '....')+ const owner = u.element.asNode().ownerFrame(frame) orelse frame;+ CustomElementRegistry.upgradeCustomElement(u.element, u.definition, owner) catch {};},.connected => |el| {if (el.is(Custom)) |custom| {