Lightpanda: the headless browser designed for AI and automation
webapi: fix custom-element creation logic
Karl Seguin966050aa59ea
diff --git a/src/browser/frame/node_factory.zig b/src/browser/frame/node_factory.zigindex 5a7969fe8..eba49eb94 100644--- a/src/browser/frame/node_factory.zig+++ b/src/browser/frame/node_factory.zig@@ -32,6 +32,7 @@ const Parser = @import("../parser/Parser.zig");const Node = @import("../webapi/Node.zig");const CData = @import("../webapi/CData.zig");const Element = @import("../webapi/Element.zig");+const CustomElementDefinition = @import("../webapi/CustomElementDefinition.zig");const log = lp.log;const String = lp.String;@@ -823,54 +824,40 @@ pub fn createElementNS(frame: *Frame, namespace: Element.Namespace, name: []consconst has_hyphen = std.mem.indexOfScalar(u8, name, '-') != null;if (has_hyphen and namespace == .html) {const definition = frame.window._custom_elements._definitions.get(name);- const node = try createHtmlElementT(frame, Element.Html.Custom, namespace, attribute_iterator, .{- ._proto = undefined,- ._tag_name = tag_name,- ._definition = definition,- });// Fragment-parse context element. It will not be inserted and// we should not run the custom element's constructor.- if (frame._skip_custom_element_upgrade) {+ //+ // Undefined elements are created in the "undefined" state and+ // upgraded later, when a matching definition is registered.+ if (frame._skip_custom_element_upgrade or definition == null) {+ const node = try createHtmlElementT(frame, Element.Html.Custom, namespace, attribute_iterator, .{+ ._proto = undefined,+ ._tag_name = tag_name,+ ._definition = definition,+ });+ if (frame._skip_custom_element_upgrade == false) {+ try frame._undefined_custom_elements.append(frame.arena, node.as(Element).is(Element.Html.Custom).?);+ }return node;}- const def = definition orelse {- const element = node.as(Element);- const custom = element.is(Element.Html.Custom).?;- try frame._undefined_custom_elements.append(frame.arena, custom);- return node;- };-- // Save and restore upgrading element to allow nested createElement calls- const prev_upgrading = frame._upgrading_element;- frame._upgrading_element = node;- defer frame._upgrading_element = prev_upgrading;-- var ls: JS.Local.Scope = undefined;- frame.js.localScope(&ls);- defer ls.deinit();-- if (from_parser) {- // There are some things custom elements aren't allowed to do- // when we're parsing.- frame.document._throw_on_dynamic_markup_insertion_counter += 1;- }- defer if (from_parser) {- frame.document._throw_on_dynamic_markup_insertion_counter -= 1;+ // https://dom.spec.whatwg.org/#concept-create-element, the+ // synchronous branch. super() has to create its own element+ const constructed = constructForToken(frame, definition.?, tag_name, from_parser) catch {+ // Construction failed, we fallback to HTMLUnknownElement+ return createHtmlElementT(frame, Element.Html.Unknown, namespace, attribute_iterator, .{+ ._proto = undefined,+ ._tag_name = tag_name,+ });};- var caught: JS.TryCatch.Caught = .{};- _ = ls.toLocal(def.constructor).newInstance(&caught) catch |err| {- log.warn(.js, "custom element constructor", .{ .name = name, .err = err, .caught = caught, .type = frame._type, .url = frame.url });- return node;- };-- // After constructor runs, invoke attributeChangedCallback for initial attributes- const element = node.as(Element);- for (element.attributeEntries()) |*attr| {+ // Attributes are applied after construction, so the constructor+ // observes none of them and each one enqueues its reaction.+ try populateElementAttributes(frame, constructed, attribute_iterator);+ for (constructed.attributeEntries()) |*attr| {Element.Html.Custom.enqueueAttributeChangedCallbackOnElement(- element,+ constructed,.wrap(attr.name()),null, // old_value is null for initial attributes.wrap(attr.value()),@@ -879,7 +866,7 @@ pub fn createElementNS(frame: *Frame, namespace: Element.Namespace, name: []cons);}- return node;+ return constructed.asNode();}return createHtmlElementT(frame, Element.Html.Unknown, namespace, attribute_iterator, .{ ._proto = undefined, ._tag_name = tag_name });@@ -960,6 +947,61 @@ pub fn createElementNS(frame: *Frame, namespace: Element.Namespace, name: []cons}}+// Runs a custom element constructor for a token being created (parser or+// createElement), and validates the result against the post-conditions.+fn constructForToken(frame: *Frame, definition: *CustomElementDefinition, tag_name: String, comptime from_parser: bool) !*Element {++ // This is a creation, not an upgrade. super() ha to build a new element+ const prev_upgrading = frame._upgrading_element;+ frame._upgrading_element = null;+ defer frame._upgrading_element = prev_upgrading;++ var ls: JS.Local.Scope = undefined;+ frame.js.localScope(&ls);+ defer ls.deinit();++ if (from_parser) {+ // There are some things custom elements aren't allowed to do+ // when we're parsing.+ frame.document._throw_on_dynamic_markup_insertion_counter += 1;+ }+ defer if (from_parser) {+ frame.document._throw_on_dynamic_markup_insertion_counter -= 1;+ };++ const name = tag_name.str();+ var caught: JS.TryCatch.Caught = .{};+ const object = ls.toLocal(definition.constructor).newInstance(&caught) catch |err| {+ log.warn(.js, "custom element constructor", .{ .name = name, .err = err, .caught = caught, .type = frame._type, .url = frame.url });+ return err;+ };++ const reason: []const u8 = blk: {+ // validate the result+ const node = object.toZig(*Node) catch break :blk "not a node";+ const element = node.is(Element) orelse break :blk "not an element";+ if (element._namespace != .html) {+ break :blk "wrong namespace";+ }+ if (node._parent != null) {+ break :blk "has a parent";+ }+ if (node.firstChild() != null) {+ break :blk "has children";+ }+ if (element._attributes.isEmpty() == false) {+ break :blk "has attributes";+ }+ if (std.mem.eql(u8, element.getTagNameLower(), name) == false) {+ break :blk "wrong local name";+ }+ return element;+ };++ log.warn(.js, "custom element not usable", .{ .name = name, .reason = reason, .type = frame._type, .url = frame.url });+ return error.CustomElementConstructionFailed;+}+fn createHtmlElementT(frame: *Frame, comptime E: type, namespace: Element.Namespace, attribute_iterator: anytype, html_element: E) !*Node {const html_element_ptr = try frame._factory.htmlElement(html_element);const element = html_element_ptr.asElement();diff --git a/src/browser/tests/custom_elements/context_element_not_reconstructed.html b/src/browser/tests/custom_elements/context_element_not_reconstructed.htmlindex 4e94dc184..ac9495af7 100644--- a/src/browser/tests/custom_elements/context_element_not_reconstructed.html+++ b/src/browser/tests/custom_elements/context_element_not_reconstructed.html@@ -20,9 +20,13 @@}customElements.define('ce-ctor-innerhtml', CeCtorInnerHtml);+ // Adding children during construction violates a post-condition of+ // "create an element", so the result is a fallback HTMLUnknownElement+ // rather than the constructed instance. What matters here is that the+ // constructor ran exactly once instead of recursing.const el = document.createElement('ce-ctor-innerhtml');testing.expectEqual(1, calls);- testing.expectEqual('<span>hi</span>', el.innerHTML);+ testing.expectEqual(true, el instanceof HTMLUnknownElement);}</script>diff --git a/src/browser/tests/custom_elements/create_element_post_conditions.html b/src/browser/tests/custom_elements/create_element_post_conditions.htmlnew file mode 100644index 000000000..c4f1477ad--- /dev/null+++ b/src/browser/tests/custom_elements/create_element_post_conditions.html@@ -0,0 +1,136 @@+<!DOCTYPE html>+<script src="../testing.js"></script>++<script id="uses_constructor_return_value">+ {+ // https://dom.spec.whatwg.org/#concept-create-element -- creation does+ // not push onto the construction stack, so super() mints its own+ // element and the element we keep is whatever the constructor returns.+ let returned = null;+ class ReturnsAnother extends HTMLElement {+ constructor() {+ super();+ if (returned === null) {+ returned = document.createElement('div');+ // A div is not a valid result for this token, so keep it+ // simple: return a second instance of ourselves instead.+ returned = Reflect.construct(HTMLElement, [], ReturnsAnother);+ return returned;+ }+ }+ }+ customElements.define('ce-returns-another', ReturnsAnother);++ const el = document.createElement('ce-returns-another');+ testing.expectEqual(true, el === returned);+ }+</script>++<script id="rejects_element_with_children">+ {+ class AddsChild extends HTMLElement {+ constructor() {+ super();+ this.appendChild(document.createElement('span'));+ }+ }+ customElements.define('ce-adds-child', AddsChild);++ const el = document.createElement('ce-adds-child');+ testing.expectEqual(true, el instanceof HTMLUnknownElement);+ testing.expectEqual('ce-adds-child', el.localName);+ }+</script>++<script id="allows_child_added_then_removed">+ {+ // The post-condition is on the final state, not on what the+ // constructor touched along the way.+ class AddsAndRemoves extends HTMLElement {+ constructor() {+ super();+ this.appendChild(document.createElement('span'));+ this.removeChild(this.firstChild);+ }+ }+ customElements.define('ce-adds-and-removes', AddsAndRemoves);++ const el = document.createElement('ce-adds-and-removes');+ testing.expectEqual(true, el instanceof AddsAndRemoves);+ }+</script>++<script id="rejects_element_with_attribute">+ {+ class AddsAttribute extends HTMLElement {+ constructor() {+ super();+ this.setAttribute('id', 'nope');+ }+ }+ customElements.define('ce-adds-attribute', AddsAttribute);++ testing.expectEqual(true, document.createElement('ce-adds-attribute') instanceof HTMLUnknownElement);+ }+</script>++<script id="rejects_parented_element">+ {+ // The case that crashed the parser: a constructor that attaches its own+ // element leaves a node with a parent, which the tree builder would+ // then try to append a second time.+ const host = document.createElement('div');+ class AttachesSelf extends HTMLElement {+ constructor() {+ super();+ host.appendChild(this);+ }+ }+ customElements.define('ce-attaches-self', AttachesSelf);++ const el = document.createElement('ce-attaches-self');+ testing.expectEqual(true, el instanceof HTMLUnknownElement);+ testing.expectEqual(null, el.parentNode);+ }+</script>++<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);++ const container = document.createElement('div');+ container.innerHTML = '<ce-parser-attaches-self></ce-parser-attaches-self>';+ testing.expectEqual(1, container.children.length);+ testing.expectEqual(true, container.firstElementChild instanceof HTMLUnknownElement);+ }+</script>++<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);++ 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'));+ }+</script>