Skip to content

Lightpanda: the headless browser designed for AI and automation

webapi: Add form-associated custom element form callbacks

Karl Seguin2f59081c46f6
diff --git a/src/browser/CustomElementReactions.zig b/src/browser/CustomElementReactions.zig
index e0b5bdaeb..e26ab68a8 100644
--- a/src/browser/CustomElementReactions.zig
+++ b/src/browser/CustomElementReactions.zig
@@ -18,8 +18,9 @@
// Implements the spec's "custom element reactions" mechanism: callbacks
// (connectedCallback, disconnectedCallback, adoptedCallback,
-// attributeChangedCallback) are enqueued during DOM mutation and invoked at
-// the outer algorithm boundary, not synchronously mid-mutation.
+// attributeChangedCallback and the form-associated callbacks) are enqueued
+// during DOM mutation and invoked at the outer algorithm boundary, not
+// synchronously mid-mutation.
//
// The "stack of element queues" is collapsed to a single flat ArrayList plus
// per-scope checkpoint indices: push() captures items.len, popAndInvoke()
@@ -40,6 +41,7 @@ const lp = @import("lightpanda");
const Frame = @import("Frame.zig");
const Element = @import("webapi/Element.zig");
const Document = @import("webapi/Document.zig");
+const Form = @import("webapi/element/html/Form.zig");
const Custom = @import("webapi/element/html/Custom.zig");
const CustomElementDefinition = @import("webapi/CustomElementDefinition.zig");
@@ -148,6 +150,18 @@ pub fn enqueueAttributeChanged(
} });
}
+pub fn enqueueFormAssociated(self: *Self, frame: *Frame, element: *Custom, form: ?*Form) !void {
+ try self.route(frame, .{ .form_associated = .{ .element = element, .form = form } });
+}
+
+pub fn enqueueFormDisabled(self: *Self, frame: *Frame, element: *Custom, disabled: bool) !void {
+ try self.route(frame, .{ .form_disabled = .{ .element = element, .disabled = disabled } });
+}
+
+pub fn enqueueFormReset(self: *Self, frame: *Frame, element: *Custom) !void {
+ try self.route(frame, .{ .form_reset = element });
+}
+
pub const Reaction = union(enum) {
upgrade: struct { element: *Custom, definition: *CustomElementDefinition },
connected: *Element,
@@ -155,6 +169,9 @@ pub const Reaction = union(enum) {
move: *Element,
adopted: Adopted,
attribute_changed: AttributeChanged,
+ form_associated: struct { element: *Custom, form: ?*Form },
+ form_disabled: struct { element: *Custom, disabled: bool },
+ form_reset: *Custom,
const Adopted = struct {
element: *Element,
diff --git a/src/browser/Frame.zig b/src/browser/Frame.zig
index 941bc863d..5efacccfb 100644
--- a/src/browser/Frame.zig
+++ b/src/browser/Frame.zig
@@ -201,6 +201,9 @@ _custom_element_creation: union(enum) {
// List of custom elements that were created before their definition was registered
_undefined_custom_elements: std.ArrayList(*Element.Html.Custom) = .empty,
+// Every form-associated custom element in this frame (usually none)
+_form_associated: std.ArrayList(*Element.Html.Custom) = .empty,
+
// Pending custom-element reactions (connected/disconnected/adopted/attribute
// changed). Reactions are enqueued during DOM mutation and drained at the
// outer algorithm boundary — set up by the JS bridge for [CEReactions]
@@ -2982,6 +2985,11 @@ pub fn removeNode(self: *Frame, parent: *Node, child: *Node, opts: RemoveNodeOpt
child._parent = null;
+ // deferred: the id maps are only updated further down
+ defer if (self._form_associated.items.len != 0) {
+ Element.Html.Custom.formTreeChanged(parent, child, self);
+ };
+
Element.Html.Select.childRemoved(parent, child);
Element.Html.Picture.childRemoved(parent, child, next_sibling, self);
@@ -3232,6 +3240,11 @@ fn _insertNodeRelative(self: *Frame, comptime from_parser: bool, parent: *Node,
}
child._parent = parent;
+ // deferred: the id maps are only updated further down.
+ defer if (self._form_associated.items.len != 0) {
+ Element.Html.Custom.formTreeChanged(parent, child, self);
+ };
+
Element.Html.Select.childInserted(parent, child);
if (child.is(Element.Html.Image)) |img| {
// noop if it didn't actually change
@@ -3392,6 +3405,9 @@ pub fn attributeChange(self: *Frame, element: *Element, name: String, value: Str
};
Element.Html.Custom.enqueueAttributeChangedCallbackOnElement(element, name, old_value, value, null, self);
+ if (self._form_associated.items.len != 0) {
+ Element.Html.Custom.formAttributeChanged(element, name, self);
+ }
observers.notifyAttributeChange(self, element, name, old_value);
@@ -3428,6 +3444,9 @@ pub fn attributeRemove(self: *Frame, element: *Element, name: String, old_value:
};
Element.Html.Custom.enqueueAttributeChangedCallbackOnElement(element, name, old_value, null, null, self);
+ if (self._form_associated.items.len != 0) {
+ Element.Html.Custom.formAttributeChanged(element, name, self);
+ }
observers.notifyAttributeChange(self, element, name, old_value);
diff --git a/src/browser/frame/node_factory.zig b/src/browser/frame/node_factory.zig
index fa3d256ba..4b1fe08cc 100644
--- a/src/browser/frame/node_factory.zig
+++ b/src/browser/frame/node_factory.zig
@@ -1181,7 +1181,11 @@ pub fn constructCustomElement(frame: *Frame, new_target: JS.Function) !*Element
._tag_name = tag_name,
._definition = definition,
});
- return node.as(Element);
+ const element = node.as(Element);
+ if (definition.form_associated) {
+ try element.is(Element.Html.Custom).?.registerFormAssociated(frame);
+ }
+ return element;
}
pub fn createTextNode(document: *const Node.Document, text: []const u8) !*Node {
diff --git a/src/browser/tests/custom_elements/form_callbacks.html b/src/browser/tests/custom_elements/form_callbacks.html
new file mode 100644
index 000000000..94c647224
--- /dev/null
+++ b/src/browser/tests/custom_elements/form_callbacks.html
@@ -0,0 +1,188 @@
+<!DOCTYPE html>
+<script src="../testing.js"></script>
+
+<script>
+class FcControl extends HTMLElement {
+ static formAssociated = true;
+ constructor() {
+ super();
+ this.forms = [];
+ this.disabled = [];
+ this.resets = 0;
+ }
+ formAssociatedCallback(form) { this.forms.push(form); }
+ formDisabledCallback(disabled) { this.disabled.push(disabled); }
+ formResetCallback() {
+ this.resets += 1;
+ if (this.observe) {
+ this.observed = this.observe.value;
+ }
+ }
+}
+customElements.define('fc-control', FcControl);
+</script>
+
+<form id="parsed_form"><fc-control id="parsed_inside"></fc-control></form>
+<fc-control id="parsed_before" form="parsed_later"></fc-control>
+<form id="parsed_later"></form>
+
+<script id="parser">
+{
+ const inside = document.getElementById('parsed_inside');
+ testing.expectEqual([document.getElementById('parsed_form')], inside.forms);
+
+ // the form attribute names a form the parser hadn't reached yet
+ const before = document.getElementById('parsed_before');
+ testing.expectEqual([document.getElementById('parsed_later')], before.forms);
+}
+</script>
+
+<!-- the misnested </b> makes the parser move the <p>, and what it holds -->
+<form id="adopt_form"><b><p><fc-control id="adopted"></fc-control></b></p></form>
+
+<script id="adoption_agency">
+{
+ const control = document.getElementById('adopted');
+ // form > p > b > fc-control
+ testing.expectEqual('B', control.parentNode.tagName);
+ testing.expectEqual('P', control.parentNode.parentNode.tagName);
+ testing.expectEqual(document.getElementById('adopt_form'), control.forms.at(-1));
+}
+</script>
+
+<div id="container"></div>
+
+<script id="associate">
+{
+ const container = document.getElementById('container');
+ container.innerHTML = '<form id="fc_f1"><fc-control></fc-control></form><form id="fc_f2"></form>';
+ const [f1, f2] = container.querySelectorAll('form');
+ const control = container.querySelector('fc-control');
+ testing.expectEqual([f1], control.forms);
+
+ f2.appendChild(control);
+ testing.expectEqual([f1, null, f2], control.forms);
+
+ control.remove();
+ testing.expectEqual([f1, null, f2, null], control.forms);
+
+ container.appendChild(control);
+ testing.expectEqual([f1, null, f2, null], control.forms);
+
+ control.setAttribute('form', 'fc_f1');
+ testing.expectEqual([f1, null, f2, null, f1], control.forms);
+
+ control.setAttribute('form', 'nope');
+ testing.expectEqual([f1, null, f2, null, f1, null], control.forms);
+
+ f2.id = 'nope';
+ testing.expectEqual([f1, null, f2, null, f1, null, f2], control.forms);
+
+ f2.removeAttribute('id');
+ testing.expectEqual([f1, null, f2, null, f1, null, f2, null], control.forms);
+
+ // a matching form inserted later in a wrapper
+ const wrapper = document.createElement('div');
+ wrapper.innerHTML = '<form id="nope"></form>';
+ container.appendChild(wrapper);
+ testing.expectEqual(wrapper.firstChild, control.forms.at(-1));
+
+ wrapper.remove();
+ testing.expectEqual(null, control.forms.at(-1));
+
+ // innerHTML parses straight into a connected element
+ const target = document.createElement('div');
+ container.appendChild(target);
+ target.innerHTML = '<form id="nope"></form>';
+ testing.expectEqual(target.firstChild, control.forms.at(-1));
+ container.innerHTML = '';
+}
+</script>
+
+<script id="disabled">
+{
+ const control = new FcControl();
+ control.setAttribute('disabled', '');
+ control.removeAttribute('disabled');
+ testing.expectEqual([true, false], control.disabled);
+
+ const outer = document.createElement('fieldset');
+ outer.innerHTML = '<fieldset><fc-control></fc-control></fieldset>';
+ const inner = outer.firstChild;
+ const nested = outer.querySelector('fc-control');
+ inner.disabled = true;
+ outer.disabled = true;
+ inner.disabled = false;
+ testing.expectEqual([true], nested.disabled);
+
+ nested.remove();
+ inner.appendChild(nested);
+ testing.expectEqual([true, false, true], nested.disabled);
+
+ // already disabled by the fieldset: its own attribute changes nothing
+ nested.setAttribute('disabled', '');
+ nested.removeAttribute('disabled');
+ testing.expectEqual([true, false, true], nested.disabled);
+}
+
+{
+ const fieldset = document.createElement('fieldset');
+ fieldset.disabled = true;
+ fieldset.innerHTML = '<legend><fc-control></fc-control></legend>';
+ const control = fieldset.querySelector('fc-control');
+ testing.expectEqual([], control.disabled);
+
+ const legend = document.createElement('legend');
+ fieldset.prepend(legend);
+ testing.expectEqual([true], control.disabled);
+
+ legend.remove();
+ testing.expectEqual([true, false], control.disabled);
+}
+
+{
+ // upgraded with the disabled state already in place
+ const container = document.getElementById('container');
+ container.innerHTML = '<fieldset disabled><form><fc-later></fc-later></form></fieldset>';
+ const el = container.querySelector('fc-later');
+ class FcLater extends FcControl {}
+ customElements.define('fc-later', FcLater);
+ testing.expectEqual([container.querySelector('form')], el.forms);
+ testing.expectEqual([true], el.disabled);
+ container.innerHTML = '';
+}
+</script>
+
+<script id="reset">
+{
+ const container = document.getElementById('container');
+ container.innerHTML = '<form><input value="a"><fc-control></fc-control></form>';
+ const form = container.firstChild;
+ const text = form.querySelector('input');
+ const control = form.querySelector('fc-control');
+ control.observe = text;
+
+ text.value = 'b';
+ form.reset();
+ // synchronous, after the built-in controls were reset
+ testing.expectEqual(1, control.resets);
+ testing.expectEqual('a', control.observed);
+
+ form.addEventListener('reset', (e) => e.preventDefault());
+ form.reset();
+ testing.expectEqual(1, control.resets);
+ container.innerHTML = '';
+}
+</script>
+
+<script id="reset_button">
+{
+ const container = document.getElementById('container');
+ container.innerHTML = '<form><fc-control></fc-control><input type="reset"><button type="reset"></button></form>';
+ const control = container.querySelector('fc-control');
+ container.querySelector('input').click();
+ container.querySelector('button').click();
+ // Chrome fires each one in a microtask; ours wait for the end of the script
+ testing.onload(() => testing.expectEqual(2, control.resets));
+}
+</script>
diff --git a/src/browser/webapi/CustomElementRegistry.zig b/src/browser/webapi/CustomElementRegistry.zig
index 775cb8663..9619413d0 100644
--- a/src/browser/webapi/CustomElementRegistry.zig
+++ b/src/browser/webapi/CustomElementRegistry.zig
@@ -276,6 +276,12 @@ pub fn upgradeCustomElement(custom: *Custom, definition: *CustomElementDefinitio
const connected = node.isConnected();
custom._connected_callback_invoked = connected;
custom._disconnected_callback_invoked = connected == false;
+
+ if (definition.form_associated) {
+ try custom.registerFormAssociated(frame);
+ custom._upgrade_in_progress = false;
+ custom.formStateChanged(frame);
+ }
}
fn upgradeFailed(custom: *Custom) void {
diff --git a/src/browser/webapi/element/html/Custom.zig b/src/browser/webapi/element/html/Custom.zig
index ed548015e..67c740116 100644
--- a/src/browser/webapi/element/html/Custom.zig
+++ b/src/browser/webapi/element/html/Custom.zig
@@ -32,6 +32,7 @@ const ElementInternals = @import("../../ElementInternals.zig");
const CustomElementDefinition = @import("../../CustomElementDefinition.zig");
const HtmlElement = @import("../Html.zig");
+const Form = @import("Form.zig");
const log = lp.log;
const String = lp.String;
@@ -48,6 +49,8 @@ _upgrade_failed: bool = false, // a failed upgrade is never retried
_upgrade_in_progress: bool = false,
_upgrade_candidate: bool = false, // listed in a frame's _undefined_custom_elements
_internals: ?*ElementInternals = null,
+_form_owner: ?*Form = null, // form-associated element only
+_form_disabled: bool = false, // form-associated element only
pub fn asElement(self: *Custom) *Element {
return Factory.protoOf(self).asElement();
@@ -80,6 +83,110 @@ pub fn willValidate(self: *Custom) bool {
return true;
}
+pub fn registerFormAssociated(self: *Custom, frame: *Frame) !void {
+ // @frame.arena
+ try frame._form_associated.append(frame.page_arena, self);
+}
+
+pub fn formStateChanged(self: *Custom, frame: *Frame) void {
+ if (self.isFormAssociated() == false or self._upgrade_in_progress) {
+ return;
+ }
+ const element = self.asElement();
+
+ const owner = Form.ownerOf(element, frame);
+ if (owner != self._form_owner) {
+ // new owner
+ self._form_owner = owner;
+ frame._ce_reactions.enqueueFormAssociated(frame, self, owner) catch |err| {
+ log.warn(.bug, "ce_reactions enqueue fail", .{ .err = err });
+ };
+ }
+
+ const disabled = element.isDisabled();
+ if (disabled != self._form_disabled) {
+ // disabled state changed
+ self._form_disabled = disabled;
+ frame._ce_reactions.enqueueFormDisabled(frame, self, disabled) catch |err| {
+ log.warn(.bug, "ce_reactions enqueue fail", .{ .err = err });
+ };
+ }
+}
+
+// `child` was inserted or removed from `parent`. A form-associated element
+// might have changed (e.g. maybe it moved under a disabled fieldset).
+// Only called when the frame has form-associated elements.
+pub fn formTreeChanged(parent: *Node, child: *Node, frame: *Frame) void {
+ // a non-element can't be a container for our custom element
+ const el = child.is(Element) orelse return;
+
+ var has_form = false;
+ if (child.firstChild() == null) {
+ // common case since the parser inserts every element before its children
+ if (el.is(Custom)) |custom| {
+ custom.formStateChanged(frame);
+ } else {
+ has_form = el.getTag() == .form;
+ }
+ } else {
+ var tw = TreeWalker.Full.Elements.init(child, .{});
+ while (tw.next()) |descendant| {
+ if (descendant.is(Custom)) |custom| {
+ custom.formStateChanged(frame);
+ } else if (descendant.getTag() == .form) {
+ has_form = true;
+ }
+ }
+ }
+
+ if (has_form) {
+ formAttributeTargetsChanged(frame);
+ }
+
+ if (el.getTag() == .legend) {
+ const fieldset = parent.is(Element) orelse return;
+ if (fieldset.getTag() == .fieldset) {
+ // legends moving around in a fieldset can alter the state of the form
+ formStateChangedInSubtree(fieldset.asNode(), frame);
+ }
+ }
+}
+
+pub fn formAttributeChanged(element: *Element, name: String, frame: *Frame) void {
+ if (name.eql(comptime .wrap("disabled"))) {
+ if (element.getTag() == .fieldset) {
+ formStateChangedInSubtree(element.asNode(), frame);
+ } else if (element.is(Custom)) |custom| {
+ custom.formStateChanged(frame);
+ }
+ } else if (name.eql(comptime .wrap("form"))) {
+ if (element.is(Custom)) |custom| {
+ custom.formStateChanged(frame);
+ }
+ } else if (name.eql(comptime .wrap("id"))) {
+ formAttributeTargetsChanged(frame);
+ }
+}
+
+fn formStateChangedInSubtree(root: *Node, frame: *Frame) void {
+ var tw = TreeWalker.FullExcludeSelf.Elements.init(root, .{});
+ while (tw.next()) |el| {
+ if (el.is(Custom)) |custom| {
+ custom.formStateChanged(frame);
+ }
+ }
+}
+
+// An id changed or a form came or went: a form attribute can now resolve to
+// a different form.
+fn formAttributeTargetsChanged(frame: *Frame) void {
+ for (frame._form_associated.items) |custom| {
+ if (custom.asElement().hasAttributeSafe(comptime .wrap("form"))) {
+ custom.formStateChanged(frame);
+ }
+ }
+}
+
// Reactions are queued via enqueue* and fired via fireReaction at the outer
// CEReactions boundary (set up by the JS bridge, the parser pump, etc.).
//
@@ -288,6 +395,9 @@ pub fn fireReaction(reaction: Reaction, frame: *Frame) void {
}
},
.move => |el| invokeCallbackOnElement(el, "move", .{}, frame),
+ .form_associated => |f| f.element.invokeCallback("formAssociatedCallback", .{f.form}, frame),
+ .form_disabled => |f| f.element.invokeCallback("formDisabledCallback", .{f.disabled}, frame),
+ .form_reset => |custom| custom.invokeCallback("formResetCallback", .{}, frame),
}
}
diff --git a/src/browser/webapi/element/html/Form.zig b/src/browser/webapi/element/html/Form.zig
index 8bff08316..2d4a2fbb8 100644
--- a/src/browser/webapi/element/html/Form.zig
+++ b/src/browser/webapi/element/html/Form.zig
@@ -190,6 +190,8 @@ pub fn reset(self: *Form, frame: *Frame) !void {
textarea.reset();
} else if (element.is(Output)) |output| {
try output.reset(frame);
+ } else if (element.is(Custom)) |custom| {
+ try frame._ce_reactions.enqueueFormReset(frame, custom);
}
}
}