Lightpanda: the headless browser designed for AI and automation
webapi Custom Element ElementInternals
Karl Seguinea333bef59cb
diff --git a/src/browser/interactive.zig b/src/browser/interactive.zigindex e1c080dd5..1a0a80c78 100644--- a/src/browser/interactive.zig+++ b/src/browser/interactive.zig@@ -404,7 +404,12 @@ pub fn isContentRole(role: []const u8) bool {// ARIA `role` is a space-separated fallback list; the first token wins.pub fn explicitRole(el: *Element) ?[]const u8 {- const attr = el.getAttributeInterned("role") orelse return null;+ // ElementInternals.role is a custom element's default role.+ const attr = el.getAttributeInterned("role") orelse blk: {+ const custom = el.is(Element.Html.Custom) orelse return null;+ const internals = custom._internals orelse return null;+ break :blk internals.getAria("role") orelse return null;+ };var it = std.mem.tokenizeAny(u8, attr, " \t\n\r");return it.next();}diff --git a/src/browser/js/bridge.zig b/src/browser/js/bridge.zigindex 34cb880d3..a8f5d5844 100644--- a/src/browser/js/bridge.zig+++ b/src/browser/js/bridge.zig@@ -1155,6 +1155,8 @@ pub const PageJsApis = flattenTypes(&.{@import("../webapi/element/html/UL.zig"),@import("../webapi/element/html/Unknown.zig"),@import("../webapi/element/html/ValidityState.zig"),+ @import("../webapi/ElementInternals.zig"),+ @import("../webapi/CustomStateSet.zig"),@import("../webapi/element/Svg.zig"),@import("../webapi/element/svg/Generic.zig"),@import("../webapi/element/svg/Graphics.zig"),diff --git a/src/browser/tests/custom_elements/element_internals.html b/src/browser/tests/custom_elements/element_internals.htmlnew file mode 100644index 000000000..d15907433--- /dev/null+++ b/src/browser/tests/custom_elements/element_internals.html@@ -0,0 +1,289 @@+<!DOCTYPE html>+<script src="../testing.js"></script>++<div id="container"></div>+<x-pre-shadow></x-pre-shadow>+<x-declarative><template shadowrootmode="open"><span></span></template></x-declarative>++<script id="attach">+{+ class PlainEl extends HTMLElement {}+ customElements.define('ei-plain', PlainEl);++ const el = new PlainEl();+ const internals = el.attachInternals();+ testing.expectTrue(internals instanceof ElementInternals);+ testing.expectError('NotSupportedError', () => el.attachInternals());++ const parsed = document.getElementById('container');+ parsed.innerHTML = '<ei-plain></ei-plain>';+ testing.expectTrue(parsed.firstChild.attachInternals() instanceof ElementInternals);++ testing.expectError('NotSupportedError', () => document.createElement('div').attachInternals());+ testing.expectError('NotSupportedError', () => document.createElement('ei-undefined').attachInternals());++ class BuiltIn extends HTMLDivElement {}+ customElements.define('ei-builtin', BuiltIn, { extends: 'div' });+ testing.expectError('NotSupportedError', () => document.createElement('div', { is: 'ei-builtin' }).attachInternals());++ class Disabled extends HTMLElement {+ static disabledFeatures = ['internals'];+ }+ customElements.define('ei-disabled', Disabled);+ testing.expectError('NotSupportedError', () => new Disabled().attachInternals());+}++{+ // defined, but not yet upgraded+ const el = document.createElement('ei-later');+ customElements.define('ei-later', class extends HTMLElement {});+ testing.expectError('NotSupportedError', () => el.attachInternals());+ customElements.upgrade(el);+ testing.expectTrue(el.attachInternals() instanceof ElementInternals);+}+</script>++<script id="not_form_associated">+{+ class NotFA extends HTMLElement {}+ customElements.define('ei-not-fa', NotFA);+ const i = new NotFA().attachInternals();+ testing.expectError('NotSupportedError', () => i.setFormValue(''));+ testing.expectError('NotSupportedError', () => i.form);+ testing.expectError('NotSupportedError', () => i.setValidity({}));+ testing.expectError('NotSupportedError', () => i.willValidate);+ testing.expectError('NotSupportedError', () => i.validity);+ testing.expectError('NotSupportedError', () => i.validationMessage);+ testing.expectError('NotSupportedError', () => i.checkValidity());+ testing.expectError('NotSupportedError', () => i.reportValidity());+ testing.expectError('NotSupportedError', () => i.labels);++ // ARIA and states work on any custom element+ testing.expectEqual(null, i.role);+ i.role = 'checkbox';+ i.ariaLabel = 'Accept';+ testing.expectEqual('checkbox', i.role);+ testing.expectEqual('Accept', i.ariaLabel);+ i.ariaLabel = null;+ testing.expectEqual(null, i.ariaLabel);+}+</script>++<script id="shadow_root">+{+ customElements.define('ei-shadow', class extends HTMLElement {+ constructor() {+ super();+ this.i = this.attachInternals();+ testing.expectEqual(null, this.i.shadowRoot);+ this.s = this.attachShadow({ mode: 'closed' });+ }+ });+ const el = document.createElement('ei-shadow');+ testing.expectEqual(el.s, el.i.shadowRoot);++ // attached before the element was defined: not revealed+ const pre = document.querySelector('x-pre-shadow');+ pre.attachShadow({ mode: 'closed' });+ customElements.define('x-pre-shadow', class extends HTMLElement {+ constructor() {+ super();+ this.i = this.attachInternals();+ }+ });+ testing.expectEqual(null, pre.i.shadowRoot);++ // declarative shadow roots are always available+ const decl = document.querySelector('x-declarative');+ customElements.define('x-declarative', class extends HTMLElement {+ constructor() {+ super();+ this.i = this.attachInternals();+ }+ });+ testing.expectEqual(decl.shadowRoot, decl.i.shadowRoot);+}+</script>++<script id="states">+{+ customElements.define('ei-states', class extends HTMLElement {+ constructor() {+ super();+ this.i = this.attachInternals();+ }+ });+ const i = document.createElement('ei-states').i;+ const states = i.states;+ testing.expectTrue(states instanceof CustomStateSet);+ testing.expectEqual(states, i.states);+ testing.expectEqual(0, states.size);++ states.add('a');+ states.add('b');+ states.add('a');+ testing.expectEqual(2, states.size);+ testing.expectTrue(states.has('a'));+ testing.expectEqual(['a', 'b'], [...states]);++ testing.expectTrue(states.delete('a'));+ testing.expectFalse(states.delete('a'));+ states.add('a');+ testing.expectEqual(['b', 'a'], [...states.values()]);+ testing.expectEqual([['b', 'b'], ['a', 'a']], [...states.entries()]);++ const seen = [];+ states.forEach((v, k, s) => seen.push(v, k, s === states));+ testing.expectEqual(['b', 'b', true, 'a', 'a', true], seen);++ // live iteration, like a Set+ states.clear();+ states.add('1');+ states.add('2');+ states.add('3');+ let it = states.values();+ states.delete('1');+ testing.expectEqual('2', it.next().value);+ states.clear();+ testing.expectTrue(it.next().done);+ states.add('4');+ testing.expectTrue(it.next().done);++ // churn while no iterator is held+ for (let n = 0; n < 50; n++) {+ states.add('x');+ states.delete('x');+ }+ testing.expectEqual(['4'], [...states]);+}+</script>++<script id="validity">+{+ class Control extends HTMLElement {+ static formAssociated = true;+ constructor() {+ super();+ this.i = this.attachInternals();+ }+ }+ customElements.define('ei-control', Control);++ const control = new Control();+ const validity = control.i.validity;+ testing.expectEqual(validity, control.i.validity);+ testing.expectTrue(validity.valid);+ testing.expectTrue(control.i.willValidate);++ let invalid = 0;+ control.addEventListener('invalid', () => invalid++);+ testing.expectTrue(control.i.checkValidity());++ control.i.setValidity({ valueMissing: true }, 'missing');+ testing.expectTrue(validity.valueMissing);+ testing.expectFalse(validity.customError);+ testing.expectFalse(validity.valid);+ testing.expectEqual('missing', control.i.validationMessage);+ testing.expectTrue(control.matches(':invalid'));+ testing.expectFalse(control.i.checkValidity());+ testing.expectFalse(control.i.reportValidity());+ testing.expectEqual(2, invalid);++ testing.expectError('TypeError', () => control.i.setValidity({ customError: true }));+ testing.expectError('NotFoundError', () => control.i.setValidity({ customError: true }, 'x', document.body));+ control.i.setValidity({ customError: true }, 'x', control);++ control.i.setValidity({}, 'ignored');+ testing.expectTrue(validity.valid);+ testing.expectTrue(control.matches(':valid'));+ testing.expectEqual('', control.i.validationMessage);++ control.setAttribute('readonly', '');+ testing.expectFalse(control.i.willValidate);+ control.removeAttribute('readonly');++ const fieldset = document.createElement('fieldset');+ fieldset.disabled = true;+ fieldset.appendChild(control);+ testing.expectFalse(control.i.willValidate);+ testing.expectTrue(control.matches(':disabled'));++ const datalist = document.createElement('datalist');+ datalist.appendChild(control);+ testing.expectFalse(control.i.willValidate);+}+</script>++<script id="form">+{+ const container = document.getElementById('container');+ container.innerHTML = `+ <label for="c1">One</label>+ <form id="f">+ <input name="before" value="b">+ <ei-control id="c1" name="c1"></ei-control>+ <ei-control id="c2"></ei-control>+ <ei-control id="c3" name="c3" disabled></ei-control>+ <ei-plain name="plain"></ei-plain>+ <input name="after" value="a">+ </form>`;+ const form = document.getElementById('f');+ const c1 = document.getElementById('c1');+ const c2 = document.getElementById('c2');+ const c3 = document.getElementById('c3');++ testing.expectEqual(form, c1.i.form);+ testing.expectEqual(null, new (customElements.get("ei-control"))().i.form);+ testing.expectEqual(c1, document.querySelector('label').control);+ testing.expectEqual(1, c1.i.labels.length);+ testing.expectEqual(5, form.elements.length);+ testing.expectEqual(c1, form.elements.namedItem('c1'));++ // no value yet+ testing.expectEqual([['before', 'b'], ['after', 'a']], [...new FormData(form)]);++ c1.i.setFormValue('one');+ c3.i.setFormValue('three');+ testing.expectEqual([['before', 'b'], ['c1', 'one'], ['after', 'a']], [...new FormData(form)]);++ c1.i.setFormValue(null);+ testing.expectEqual([['before', 'b'], ['after', 'a']], [...new FormData(form)]);++ // a FormData value brings its own names, even without a name attribute+ const fd = new FormData();+ fd.append('x', '1');+ fd.append('y', '2');+ c2.i.setFormValue(fd);+ fd.append('z', '3');+ testing.expectEqual([['before', 'b'], ['x', '1'], ['y', '2'], ['after', 'a']], [...new FormData(form)]);++ const file = new File(['abc'], 'a.txt');+ c1.i.setFormValue(file);+ testing.expectEqual(['before', 'c1', 'x', 'y', 'after'], [...new FormData(form).keys()]);++ c1.i.setFormValue(undefined);+ c2.i.setFormValue(null);++ // owner form validation+ testing.expectTrue(form.checkValidity());+ c1.i.setValidity({ valueMissing: true }, 'required');+ testing.expectFalse(form.checkValidity());+ testing.expectTrue(form.matches(':invalid'));+ c1.i.setValidity({});+ testing.expectTrue(form.checkValidity());+}+</script>++<script id="role">+{+ customElements.define('ei-role', class extends HTMLElement {+ constructor() {+ super();+ this.attachInternals().role = 'button';+ }+ });+ const el = document.createElement('ei-role');+ testing.expectEqual(null, el.getAttribute('role'));+ testing.expectEqual(null, el.role);+}+</script>diff --git a/src/browser/webapi/CustomElementDefinition.zig b/src/browser/webapi/CustomElementDefinition.zigindex 951ebf28c..1fbd5bb98 100644--- a/src/browser/webapi/CustomElementDefinition.zig+++ b/src/browser/webapi/CustomElementDefinition.zig@@ -36,8 +36,9 @@ observed_attributes: std.StringHashMapUnmanaged(void) = .{},// For autonomous custom elements, this is nullextends: ?Element.Tag = null,-// when disabledFeatures = ["shadow"], we'll throw if attachShadow is calleddisable_shadow: bool = false,+disable_internals: bool = false,+form_associated: bool = false,pub fn isAttributeObserved(self: *const CustomElementDefinition, name: String) bool {return self.observed_attributes.contains(name.str());diff --git a/src/browser/webapi/CustomElementRegistry.zig b/src/browser/webapi/CustomElementRegistry.zigindex 87f9c69c0..96b011e71 100644--- a/src/browser/webapi/CustomElementRegistry.zig+++ b/src/browser/webapi/CustomElementRegistry.zig@@ -84,7 +84,8 @@ pub fn define(self: *CustomElementRegistry, name: []const u8, constructor: js.Fu}}- // Read disabledFeatures static property: ["shadow"] makes attachShadow throw.+ // Read disabledFeatures static property: ["shadow"] makes attachShadow throw+ // ["internals"] makes attachInternals throw.if (constructor.getPropertyValue("disabledFeatures") catch null) |disabled| {if (disabled.isArray()) {var js_arr = disabled.toArray();@@ -93,11 +94,17 @@ pub fn define(self: *CustomElementRegistry, name: []const u8, constructor: js.Fuconst feature = val.toSSO(false) catch continue;if (feature.eql(comptime .wrap("shadow"))) {definition.disable_shadow = true;+ } else if (feature.eql(comptime .wrap("internals"))) {+ definition.disable_internals = true;}}}}+ if (constructor.getPropertyValue("formAssociated") catch null) |form_associated| {+ definition.form_associated = form_associated.toBool();+ }+const gop = try self._definitions.getOrPut(frame.page_arena, owned_name);if (gop.found_existing) {return error.NotSupported;diff --git a/src/browser/webapi/CustomStateSet.zig b/src/browser/webapi/CustomStateSet.zignew file mode 100644index 000000000..ae3d6a79f--- /dev/null+++ b/src/browser/webapi/CustomStateSet.zig@@ -0,0 +1,177 @@+// Copyright (C) 2023-2026 Lightpanda (Selecy SAS)+//+// Francis Bouvier <[email protected]>+// Pierre Tachoire <[email protected]>+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as+// published by the Free Software Foundation, either version 3 of the+// License, or (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++const std = @import("std");+const lp = @import("lightpanda");++const js = @import("../js/js.zig");+const Page = @import("../Page.zig");+const Frame = @import("../Frame.zig");++const log = lp.log;+const String = lp.String;+const Execution = js.Execution;++const CustomStateSet = @This();++pub fn registerTypes() []const type {+ return &.{+ CustomStateSet,+ ValueIterator,+ EntryIterator,+ };+}++_size: u32 = 0,+_items: std.ArrayList(?String) = .empty,+_iterators: u32 = 0, // live iterators, while != 0, tomestones must stay put++fn has(self: *const CustomStateSet, value: String) bool {+ return self.indexOf(value) != null;+}++fn getSize(self: *const CustomStateSet) u32 {+ return self._size;+}++fn add(self: *CustomStateSet, value: String, frame: *Frame) !*CustomStateSet {+ if (self.indexOf(value) != null) {+ return self;+ }+ if (self._iterators == 0 and self._items.items.len > self._size) {+ self.compact();+ }+ try self._items.append(frame.page_arena, try frame.dupeSSO(value.str()));+ self._size += 1;+ return self;+}++fn delete(self: *CustomStateSet, value: String) bool {+ const index = self.indexOf(value) orelse return false;+ self._items.items[index] = null;+ self._size -= 1;+ return true;+}++fn clear(self: *CustomStateSet) void {+ @memset(self._items.items, null);+ self._size = 0;+}++fn indexOf(self: *const CustomStateSet, value: String) ?usize {+ for (self._items.items, 0..) |item_, i| {+ const item = item_ orelse continue;+ if (item.eql(value)) {+ return i;+ }+ }+ return null;+}++fn compact(self: *CustomStateSet) void {+ var len: usize = 0;+ for (self._items.items) |item| {+ if (item != null) {+ self._items.items[len] = item;+ len += 1;+ }+ }+ self._items.shrinkRetainingCapacity(len);+}++fn values(self: *CustomStateSet, exec: *const Execution) !*ValueIterator {+ return ValueIterator.init(.{ .set = self }, exec);+}++fn entries(self: *CustomStateSet, exec: *const Execution) !*EntryIterator {+ return EntryIterator.init(.{ .set = self }, exec);+}++fn forEach(self: *CustomStateSet, cb_: js.Function, js_this_: ?js.Object, exec: *const Execution) !void {+ const cb = if (js_this_) |js_this| try cb_.withThis(js_this) else cb_;++ var it = Iterator{ .set = self };+ it.acquireRef();+ defer it.releaseRef(exec.page);++ while (it.next(exec)) |entry| {+ var caught: js.TryCatch.Caught = .{};+ cb.tryCall(void, .{ entry.@"0", entry.@"1", self }, &caught) catch {+ log.debug(.js, "forEach callback", .{ .caught = caught, .source = "CustomStateSet" });+ };+ }+}++pub const Iterator = struct {+ index: u32 = 0,+ done: bool = false,+ set: *CustomStateSet,++ pub const Entry = struct { []const u8, []const u8 };++ pub fn next(self: *Iterator, _: *const Execution) ?Iterator.Entry {+ if (self.done) {+ return null;+ }+ const items = self.set._items.items;+ while (self.index < items.len) {+ const index = self.index;+ self.index = index + 1;+ // by pointer: an SSO String's bytes may be inline+ if (items[index]) |*value| {+ return .{ value.str(), value.str() };+ }+ }+ // Like a Set iterator, once exhausted it stays exhausted.+ self.done = true;+ return null;+ }++ pub fn acquireRef(self: *Iterator) void {+ self.set._iterators += 1;+ }++ pub fn releaseRef(self: *Iterator, _: *Page) void {+ self.set._iterators -= 1;+ }+};++const GenericIterator = @import("collections/iterator.zig").Entry;+pub const ValueIterator = GenericIterator(Iterator, "0");+pub const EntryIterator = GenericIterator(Iterator, null);++pub const JsApi = struct {+ pub const bridge = js.Bridge(CustomStateSet);++ pub const Meta = struct {+ pub const name = "CustomStateSet";+ pub const prototype_chain = bridge.prototypeChain();+ pub var class_id: bridge.ClassId = undefined;+ };++ pub const size = bridge.accessor(CustomStateSet.getSize, null, .{});+ pub const has = bridge.function(CustomStateSet.has, .{});+ pub const add = bridge.function(CustomStateSet.add, .{});+ pub const delete = bridge.function(CustomStateSet.delete, .{});+ pub const clear = bridge.function(CustomStateSet.clear, .{});+ pub const keys = bridge.function(CustomStateSet.values, .{});+ pub const values = bridge.function(CustomStateSet.values, .{});+ pub const entries = bridge.function(CustomStateSet.entries, .{});+ pub const forEach = bridge.function(CustomStateSet.forEach, .{});+ pub const symbol_iterator = bridge.iterator(CustomStateSet.values, .{});+};diff --git a/src/browser/webapi/Element.zig b/src/browser/webapi/Element.zigindex 23dd63d88..7a900583a 100644--- a/src/browser/webapi/Element.zig+++ b/src/browser/webapi/Element.zig@@ -779,6 +779,10 @@ pub fn hasAttributeInterned(self: *const Element, comptime name: []const u8) boopub fn hasDisabledConcept(self: *const Element) bool {return switch (self.getTag()) {.button, .input, .select, .textarea, .optgroup, .option, .fieldset => true,+ .custom => {+ const custom = @constCast(self).is(Html.Custom) orelse return false;+ return custom.isFormAssociated();+ },else => false,};}@@ -925,6 +929,10 @@ pub fn attachShadow(self: *Element, opts: ShadowRoot.AttachOptions, frame: *Fram}const shadow_root = try ShadowRoot.init(self, opts, frame);+ shadow_root._available_to_internals = opts.declarative or blk: {+ const custom = self.is(Html.Custom) orelse break :blk false;+ break :blk custom._definition != null;+ };const page = frame.page;try page.element_shadow_roots.put(page.arena, self, shadow_root);self._flags.shadow_host = true;diff --git a/src/browser/webapi/ElementInternals.zig b/src/browser/webapi/ElementInternals.zignew file mode 100644index 000000000..879d080cd--- /dev/null+++ b/src/browser/webapi/ElementInternals.zig@@ -0,0 +1,407 @@+// Copyright (C) 2023-2026 Lightpanda (Selecy SAS)+//+// Francis Bouvier <[email protected]>+// Pierre Tachoire <[email protected]>+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as+// published by the Free Software Foundation, either version 3 of the+// License, or (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++const std = @import("std");+const lp = @import("lightpanda");++const js = @import("../js/js.zig");+const Frame = @import("../Frame.zig");++const Node = @import("Node.zig");+const Event = @import("Event.zig");+const Element = @import("Element.zig");+const Blob = @import("Blob.zig");+const File = @import("File.zig");+const FileList = @import("FileList.zig");+const ShadowRoot = @import("ShadowRoot.zig");+const CustomStateSet = @import("CustomStateSet.zig");++const FormData = @import("net/FormData.zig");++const HtmlElement = @import("element/Html.zig");+const Custom = @import("element/html/Custom.zig");+const Form = @import("element/html/Form.zig");+const Label = @import("element/html/Label.zig");+const ValidityState = @import("element/html/ValidityState.zig");++const String = lp.String;++const ElementInternals = @This();++_host: *Custom,+_states: ?*CustomStateSet = null,+_aria: std.StringHashMapUnmanaged([]const u8) = .empty,++_submission: Submission = .none,+// Holds a ref on each File in _submission, released at frame teardown.+_files: ?*FileList = null,++_flags: ValidityFlags = .{},+_validation_message: []const u8 = "",+_validity: ?*ValidityState = null,++pub const Submission = union(enum) {+ none,+ string: []const u8,+ file: *File,+ entries: []const FormData.Entry,+};++pub const ValidityFlags = struct {+ badInput: bool = false,+ customError: bool = false,+ patternMismatch: bool = false,+ rangeOverflow: bool = false,+ rangeUnderflow: bool = false,+ stepMismatch: bool = false,+ tooLong: bool = false,+ tooShort: bool = false,+ typeMismatch: bool = false,+ valueMissing: bool = false,++ pub fn any(self: ValidityFlags) bool {+ inline for (@typeInfo(ValidityFlags).@"struct".field_names) |name| {+ if (@field(self, name)) {+ return true;+ }+ }+ return false;+ }+};++pub fn init(host: *Custom, frame: *Frame) !*ElementInternals {+ return frame._factory.create(ElementInternals{ ._host = host });+}++fn asElement(self: *const ElementInternals) *Element {+ return self._host.asElement();+}++pub fn getAria(self: *const ElementInternals, comptime name: []const u8) ?[]const u8 {+ return self._aria.get(name);+}++fn getShadowRoot(self: *const ElementInternals, frame: *Frame) ?*ShadowRoot {+ const shadow_root = self.asElement().hostedShadowRoot(frame) orelse return null;+ if (!shadow_root._available_to_internals) {+ return null;+ }+ return shadow_root;+}++fn getStates(self: *ElementInternals, frame: *Frame) !*CustomStateSet {+ if (self._states) |s| {+ return s;+ }+ const s = try frame._factory.create(CustomStateSet{});+ self._states = s;+ return s;+}++fn assertFormAssociated(self: *const ElementInternals) !void {+ if (!self._host.isFormAssociated()) {+ return error.NotSupported;+ }+}++const FormValue = union(enum) {+ blob: *Blob, // only a File is a File; any other Blob stringifies+ form_data: *FormData,+ string: []const u8, // must be last, everything can coerce to a string+};++// The `state` argument is only used to restore a control after navigation,+// which we never do, so it's ignored.+fn setFormValue(self: *ElementInternals, value_: ?FormValue, frame: *Frame) !void {+ try self.assertFormAssociated();++ const value = value_ orelse {+ try self.replaceFiles(&.{}, frame);+ self._submission = .none;+ return;+ };++ switch (value) {+ .string => |s| {+ try self.replaceFiles(&.{}, frame);+ self._submission = .{ .string = try frame.dupeString(s) };+ },+ .blob => |blob| {+ if (blob._type != .file) {+ try self.replaceFiles(&.{}, frame);+ self._submission = .{ .string = "[object Blob]" };+ return;+ }+ const file = blob._type.file;+ try self.replaceFiles(&.{file}, frame);+ self._submission = .{ .file = file };+ },+ .form_data => |form_data| {+ const arena = frame.page_arena;+ const source = form_data._entries.items;++ var files: std.ArrayList(*File) = .empty;+ const copy = try arena.alloc(FormData.Entry, source.len);+ for (source, copy) |entry, *c| {+ c.* = .{+ .name = try String.init(arena, entry.name.str(), .{}),+ .value = switch (entry.value) {+ .string => |s| .{ .string = try String.init(arena, s.str(), .{}) },+ .file => |file| blk: {+ try files.append(frame.local_arena, file);+ break :blk .{ .file = file };+ },+ .no_file => .no_file,+ },+ };+ }+ try self.replaceFiles(files.items, frame);+ self._submission = .{ .entries = copy };+ },+ }+}++fn replaceFiles(self: *ElementInternals, files: []const *File, frame: *Frame) !void {+ const fl = self._files orelse blk: {+ if (files.len == 0) {+ return;+ }+ const fl = try frame._factory.create(FileList{});+ try frame.trackFileList(fl);+ self._files = fl;+ break :blk fl;+ };++ const dupe = try frame.page_arena.dupe(*File, files);+ for (dupe) |file| {+ file._proto.acquireRef();+ }+ for (fl._files) |old| {+ old._proto.releaseRef(frame.page);+ }+ fl._files = dupe;+}++fn getForm(self: *const ElementInternals, frame: *Frame) !?*Form {+ try self.assertFormAssociated();+ return Form.ownerOf(self.asElement(), frame);+}++fn getLabels(self: *const ElementInternals, frame: *Frame) !js.Array {+ try self.assertFormAssociated();+ return Label.getControlLabels(self.asElement(), frame);+}++// Barred from constraint validation: disabled, readonly, or inside a datalist.+pub fn willValidate(self: *const ElementInternals) bool {+ const element = self.asElement();+ if (element.isDisabled()) {+ return false;+ }+ if (element.hasAttributeSafe(comptime .wrap("readonly"))) {+ return false;+ }+ var node = element.asNode()._parent;+ while (node) |n| : (node = n._parent) {+ const el = n.is(Element) orelse continue;+ if (el.getTag() == .datalist) {+ return false;+ }+ }+ return true;+}++fn getWillValidate(self: *const ElementInternals) !bool {+ try self.assertFormAssociated();+ return self.willValidate();+}++fn getValidity(self: *ElementInternals, frame: *Frame) !*ValidityState {+ try self.assertFormAssociated();+ if (self._validity) |v| {+ return v;+ }+ const v = try frame._factory.create(ValidityState{ ._owner = self.asElement() });+ self._validity = v;+ return v;+}++fn getValidationMessage(self: *const ElementInternals) ![]const u8 {+ try self.assertFormAssociated();+ if (!self.willValidate()) {+ return "";+ }+ return self._validation_message;+}++fn setValidity(self: *ElementInternals, flags_: ?ValidityFlags, message_: ?[]const u8, anchor_: ?*HtmlElement, frame: *Frame) !void {+ try self.assertFormAssociated();++ const flags = flags_ orelse ValidityFlags{};+ const message = message_ orelse "";+ if (flags.any() and message.len == 0) {+ return error.TypeError;+ }++ if (anchor_) |anchor| {+ // The anchor must be a shadow-including inclusive descendant of the host.+ if (!isShadowIncludingInclusiveDescendant(anchor.asNode(), self.asElement().asNode())) {+ return error.NotFound;+ }+ }++ self._flags = flags;+ self._validation_message = if (flags.any()) try normalizeNewlines(message, frame) else "";+}++fn isShadowIncludingInclusiveDescendant(node: *Node, ancestor: *Node) bool {+ var current: ?*Node = node;+ while (current) |n| {+ if (n == ancestor) {+ return true;+ }+ if (n._parent) |parent| {+ current = parent;+ } else if (n.is(ShadowRoot)) |shadow_root| {+ current = shadow_root.getHost().asNode();+ } else {+ return false;+ }+ }+ return false;+}++fn normalizeNewlines(message: []const u8, frame: *Frame) ![]const u8 {+ if (std.mem.indexOfScalar(u8, message, '\r') == null) {+ return frame.dupeString(message);+ }+ var out: std.ArrayList(u8) = try .initCapacity(frame.page_arena, message.len);+ var i: usize = 0;+ while (i < message.len) : (i += 1) {+ const c = message[i];+ if (c == '\r') {+ out.appendAssumeCapacity('\n');+ if (i + 1 < message.len and message[i + 1] == '\n') {+ i += 1;+ }+ } else {+ out.appendAssumeCapacity(c);+ }+ }+ return out.items;+}++pub fn checkValidity(self: *ElementInternals, frame: *Frame) !bool {+ if (!self.willValidate() or !self._flags.any()) {+ return true;+ }+ const event = try Event.initTrusted(comptime .wrap("invalid"), .{ .cancelable = true }, frame.page);+ try frame._event_manager.dispatch(self.asElement().asEventTarget(), event);+ return false;+}++fn _checkValidity(self: *ElementInternals, frame: *Frame) !bool {+ try self.assertFormAssociated();+ return self.checkValidity(frame);+}++pub const JsApi = struct {+ pub const bridge = js.Bridge(ElementInternals);++ pub const Meta = struct {+ pub const name = "ElementInternals";+ pub const prototype_chain = bridge.prototypeChain();+ pub var class_id: bridge.ClassId = undefined;+ };++ pub const shadowRoot = bridge.accessor(ElementInternals.getShadowRoot, null, .{});+ pub const states = bridge.accessor(ElementInternals.getStates, null, .{});++ pub const setFormValue = bridge.function(ElementInternals.setFormValue, .{});+ pub const form = bridge.accessor(ElementInternals.getForm, null, .{});+ pub const labels = bridge.accessor(ElementInternals.getLabels, null, .{});+ pub const setValidity = bridge.function(ElementInternals.setValidity, .{});+ pub const willValidate = bridge.accessor(ElementInternals.getWillValidate, null, .{});+ pub const validity = bridge.accessor(ElementInternals.getValidity, null, .{});+ pub const validationMessage = bridge.accessor(ElementInternals.getValidationMessage, null, .{});+ pub const checkValidity = bridge.function(ElementInternals._checkValidity, .{});+ pub const reportValidity = bridge.function(ElementInternals._checkValidity, .{});++ // ARIAMixin+ pub const role = ariaAccessor("role");+ pub const ariaAtomic = ariaAccessor("aria-atomic");+ pub const ariaAutoComplete = ariaAccessor("aria-autocomplete");+ pub const ariaBrailleLabel = ariaAccessor("aria-braillelabel");+ pub const ariaBrailleRoleDescription = ariaAccessor("aria-brailleroledescription");+ pub const ariaBusy = ariaAccessor("aria-busy");+ pub const ariaChecked = ariaAccessor("aria-checked");+ pub const ariaColCount = ariaAccessor("aria-colcount");+ pub const ariaColIndex = ariaAccessor("aria-colindex");+ pub const ariaColIndexText = ariaAccessor("aria-colindextext");+ pub const ariaColSpan = ariaAccessor("aria-colspan");+ pub const ariaCurrent = ariaAccessor("aria-current");+ pub const ariaDescription = ariaAccessor("aria-description");+ pub const ariaDisabled = ariaAccessor("aria-disabled");+ pub const ariaExpanded = ariaAccessor("aria-expanded");+ pub const ariaHasPopup = ariaAccessor("aria-haspopup");+ pub const ariaHidden = ariaAccessor("aria-hidden");+ pub const ariaInvalid = ariaAccessor("aria-invalid");+ pub const ariaKeyShortcuts = ariaAccessor("aria-keyshortcuts");+ pub const ariaLabel = ariaAccessor("aria-label");+ pub const ariaLevel = ariaAccessor("aria-level");+ pub const ariaLive = ariaAccessor("aria-live");+ pub const ariaModal = ariaAccessor("aria-modal");+ pub const ariaMultiLine = ariaAccessor("aria-multiline");+ pub const ariaMultiSelectable = ariaAccessor("aria-multiselectable");+ pub const ariaOrientation = ariaAccessor("aria-orientation");+ pub const ariaPlaceholder = ariaAccessor("aria-placeholder");+ pub const ariaPosInSet = ariaAccessor("aria-posinset");+ pub const ariaPressed = ariaAccessor("aria-pressed");+ pub const ariaReadOnly = ariaAccessor("aria-readonly");+ pub const ariaRelevant = ariaAccessor("aria-relevant");+ pub const ariaRequired = ariaAccessor("aria-required");+ pub const ariaRoleDescription = ariaAccessor("aria-roledescription");+ pub const ariaRowCount = ariaAccessor("aria-rowcount");+ pub const ariaRowIndex = ariaAccessor("aria-rowindex");+ pub const ariaRowIndexText = ariaAccessor("aria-rowindextext");+ pub const ariaRowSpan = ariaAccessor("aria-rowspan");+ pub const ariaSelected = ariaAccessor("aria-selected");+ pub const ariaSetSize = ariaAccessor("aria-setsize");+ pub const ariaSort = ariaAccessor("aria-sort");+ pub const ariaValueMax = ariaAccessor("aria-valuemax");+ pub const ariaValueMin = ariaAccessor("aria-valuemin");+ pub const ariaValueNow = ariaAccessor("aria-valuenow");+ pub const ariaValueText = ariaAccessor("aria-valuetext");++ fn ariaAccessor(comptime attr: []const u8) js.bridge.Accessor {+ const R = struct {+ pub fn get(self: *const ElementInternals) ?[]const u8 {+ return self._aria.get(attr);+ }++ pub fn set(self: *ElementInternals, value_: ?[]const u8, frame: *Frame) !void {+ const value = value_ orelse {+ _ = self._aria.remove(attr);+ return;+ };+ try self._aria.put(frame.page_arena, attr, try frame.dupeString(value));+ }+ };+ return bridge.accessor(R.get, R.set, .{});+ }+};diff --git a/src/browser/webapi/ShadowRoot.zig b/src/browser/webapi/ShadowRoot.zigindex 194755796..732ad587c 100644--- a/src/browser/webapi/ShadowRoot.zig+++ b/src/browser/webapi/ShadowRoot.zig@@ -58,6 +58,7 @@ _slot_assignment: SlotAssignment,_clonable: bool,_serializable: bool,_declarative: bool,+_available_to_internals: bool = false,_elements_by_id: std.StringHashMapUnmanaged(*Element) = .{},_removed_ids: std.StringHashMapUnmanaged(void) = .{},_adopted_style_sheets: ?js.Object.Global = null,diff --git a/src/browser/webapi/collections/node_live.zig b/src/browser/webapi/collections/node_live.zigindex 76b554381..865f22edd 100644--- a/src/browser/webapi/collections/node_live.zig+++ b/src/browser/webapi/collections/node_live.zig@@ -419,6 +419,7 @@ pub fn NodeLive(comptime mode: Mode) type {const html = el.subtype(Element.Html);return switch (html._type) {.input, .button, .select, .textarea => true,+ .custom => html.subtype(Element.Html.Custom).isFormAssociated(),else => false,};}diff --git a/src/browser/webapi/element/Html.zig b/src/browser/webapi/element/Html.zigindex 33f6022f7..948ba93d1 100644--- a/src/browser/webapi/element/Html.zig+++ b/src/browser/webapi/element/Html.zig@@ -27,6 +27,7 @@ const StyleManager = @import("../../StyleManager.zig");const reflection = @import("reflection.zig");const Node = @import("../Node.zig");const Element = @import("../Element.zig");+const ElementInternals = @import("../ElementInternals.zig");const global_event_handlers = @import("../global_event_handlers.zig");const popover = @import("popover.zig");@@ -139,6 +140,17 @@ pub fn upgradeConstruct(frame: *Frame) !*Element {return node.is(Element) orelse return error.TypeError;}+fn attachInternals(self: *HtmlElement, frame: *Frame) !*ElementInternals {+ const custom = self.is(Custom) orelse return error.NotSupported;+ const definition = custom._definition orelse return error.NotSupported;+ if (definition.disable_internals or custom._internals != null) {+ return error.NotSupported;+ }+ const internals = try ElementInternals.init(custom, frame);+ custom._internals = internals;+ return internals;+}+pub const Type = enum(u8) {anchor,area,@@ -1866,6 +1878,7 @@ pub const JsApi = struct {}pub const insertAdjacentHTML = bridge.function(HtmlElement.insertAdjacentHTML, .{ .ce_reactions = true });pub const click = bridge.function(HtmlElement.click, .{});+ pub const attachInternals = bridge.function(HtmlElement.attachInternals, .{});pub const accessKey = bridge.accessor(HtmlElement.getAccessKey, HtmlElement.setAccessKey, .{ .ce_reactions = true });pub const autofocus = bridge.accessor(HtmlElement.getAutofocus, HtmlElement.setAutofocus, .{ .ce_reactions = true });diff --git a/src/browser/webapi/element/html/Button.zig b/src/browser/webapi/element/html/Button.zigindex 8de7e9363..b340121f0 100644--- a/src/browser/webapi/element/html/Button.zig+++ b/src/browser/webapi/element/html/Button.zig@@ -64,29 +64,7 @@ pub fn getType(self: *const Button) []const u8 {}pub fn getForm(self: *Button, frame: *Frame) ?*Form {- const element = self.asElement();-- // If form attribute exists, ONLY use that (even if it references nothing)- if (element.getAttributeSafe(comptime .wrap("form"))) |form_id| {- // form= resolves in the control's own tree (shadow root or document),- // not the calling realm's. getElementByIdFromNode walks to that root.- if (frame.getElementByIdFromNode(element.asNode(), form_id)) |form_element| {- return form_element.is(Form);- }- // form attribute present but invalid - no form owner- return null;- }-- // No form attribute - traverse ancestors looking for a <form>- var node = element.asNode()._parent;- while (node) |n| {- if (n.is(Element.Html.Form)) |form| {- return form;- }- node = n._parent;- }-- return null;+ return Form.ownerOf(self.asElement(), frame);}fn getLabels(self: *Button, frame: *Frame) !js.Array {diff --git a/src/browser/webapi/element/html/Custom.zig b/src/browser/webapi/element/html/Custom.zigindex fa5c83490..e52cb61cf 100644--- a/src/browser/webapi/element/html/Custom.zig+++ b/src/browser/webapi/element/html/Custom.zig@@ -28,6 +28,7 @@ const Node = @import("../../Node.zig");const Element = @import("../../Element.zig");const Document = @import("../../Document.zig");const TreeWalker = @import("../../TreeWalker.zig");+const ElementInternals = @import("../../ElementInternals.zig");const CustomElementDefinition = @import("../../CustomElementDefinition.zig");const HtmlElement = @import("../Html.zig");@@ -46,6 +47,7 @@ _disconnected_callback_invoked: bool = false,_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,pub fn asElement(self: *Custom) *Element {return Factory.protoOf(self).asElement();@@ -54,6 +56,11 @@ pub fn asNode(self: *Custom) *Node {return self.asElement().asNode();}+pub fn isFormAssociated(self: *const Custom) bool {+ const definition = self._definition orelse return false;+ return definition.form_associated;+}+// Reactions are queued via enqueue* and fired via fireReaction at the outer// CEReactions boundary (set up by the JS bridge, the parser pump, etc.).//diff --git a/src/browser/webapi/element/html/Form.zig b/src/browser/webapi/element/html/Form.zigindex a36da939f..9a2dc4663 100644--- a/src/browser/webapi/element/html/Form.zig+++ b/src/browser/webapi/element/html/Form.zig@@ -28,6 +28,7 @@ const Element = @import("../../Element.zig");const HtmlElement = @import("../Html.zig");const collections = @import("../../collections.zig");+const Custom = @import("Custom.zig");pub const Input = @import("Input.zig");pub const Button = @import("Button.zig");pub const Select = @import("Select.zig");@@ -164,7 +165,7 @@ pub fn requestSubmit(self: *Form, submitter: ?*Element, frame: *Frame) !void {}// The submitter's form owner must be this form element.- const submitter_form = getFormOwner(s, frame);+ const submitter_form = ownerOf(s, frame);if (submitter_form == null or submitter_form.? != self) return error.NotFound;break :blk s;@@ -221,13 +222,21 @@ pub fn isSubmitButton(element: *Element) bool {return false;}-/// Returns the form owner of a submittable element (Input or Button).-fn getFormOwner(element: *Element, frame: *Frame) ?*Form {- if (element.is(Input)) |input| {- return input.getForm(frame);+// https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#form-owner+pub fn ownerOf(element: *Element, frame: *Frame) ?*Form {+ // A form attribute is authoritative, even when it names nothing. It+ // resolves in the control's own tree (shadow root or document), not the+ // calling realm's.+ if (element.getAttributeSafe(comptime .wrap("form"))) |form_id| {+ const form_element = frame.getElementByIdFromNode(element.asNode(), form_id) orelse return null;+ return form_element.is(Form);}- if (element.is(Button)) |button| {- return button.getForm(frame);++ var node = element.asNode()._parent;+ while (node) |n| : (node = n._parent) {+ if (n.is(Element.Html.Form)) |form| {+ return form;+ }}return null;}@@ -287,6 +296,10 @@ fn checkElementValidity(element: *Element, frame: *Frame) !bool {if (element.is(Select)) |select| return select.checkValidity(frame);if (element.is(TextArea)) |textarea| return textarea.checkValidity(frame);if (element.is(Button)) |button| return button.checkValidity(frame);+ if (element.is(Custom)) |custom| {+ const internals = custom._internals orelse return true;+ return internals.checkValidity(frame);+ }return true;}diff --git a/src/browser/webapi/element/html/Input.zig b/src/browser/webapi/element/html/Input.zigindex 002a72355..46a062ed3 100644--- a/src/browser/webapi/element/html/Input.zig+++ b/src/browser/webapi/element/html/Input.zig@@ -719,31 +719,7 @@ fn getList(self: *Input, frame: *Frame) ?*HtmlElement.DataList {}pub fn getForm(self: *Input, frame: *Frame) ?*Form {- const element = self.asElement();-- // If form attribute exists, ONLY use that (even if it references nothing)- if (element.getAttributeSafe(comptime .wrap("form"))) |form_id| {- // form= resolves in the control's own tree (shadow root or document),- // not the calling realm's. @constCast: getElementByIdFromNode wants a- // mutable *Node but doesn't mutate it (same idiom as radioGroupIterator);- // keeping getForm const avoids a wide validity-path const cascade.- if (frame.getElementByIdFromNode(element.asNode(), form_id)) |form_element| {- return form_element.is(Form);- }- // form attribute present but invalid - no form owner- return null;- }-- // No form attribute - traverse ancestors looking for a <form>- var node = element.asConstNode()._parent;- while (node) |n| {- if (n.is(Element.Html.Form)) |form| {- return form;- }- node = n._parent;- }-- return null;+ return Form.ownerOf(self.asElement(), frame);}// Form submission attribute overridesdiff --git a/src/browser/webapi/element/html/Label.zig b/src/browser/webapi/element/html/Label.zigindex 679532f54..46419c554 100644--- a/src/browser/webapi/element/html/Label.zig+++ b/src/browser/webapi/element/html/Label.zig@@ -65,6 +65,7 @@ fn isLabelable(el: *Element) bool {return switch (html._type) {.button, .meter, .output, .progress, .select, .textarea => true,.input => html.subtype(HtmlElement.Input)._input_type != .hidden,+ .custom => html.subtype(HtmlElement.Custom).isFormAssociated(),else => false,};}diff --git a/src/browser/webapi/element/html/Select.zig b/src/browser/webapi/element/html/Select.zigindex eac20bb38..e968e60f6 100644--- a/src/browser/webapi/element/html/Select.zig+++ b/src/browser/webapi/element/html/Select.zig@@ -394,27 +394,7 @@ pub fn getSelectedOptions(self: *Select, frame: *Frame) !collections.NodeLive(.s}pub fn getForm(self: *Select, frame: *Frame) ?*Form {- const element = self.asElement();-- // If form attribute exists, ONLY use that (even if it references nothing)- if (element.getAttributeSafe(comptime .wrap("form"))) |form_id| {- if (frame.getElementByIdFromNode(element.asNode(), form_id)) |form_element| {- return form_element.is(Form);- }- // form attribute present but invalid - no form owner- return null;- }-- // No form attribute - traverse ancestors looking for a <form>- var node = element.asNode()._parent;- while (node) |n| {- if (n.is(Element.Html.Form)) |form| {- return form;- }- node = n._parent;- }-- return null;+ return Form.ownerOf(self.asElement(), frame);}fn getLabels(self: *Select, frame: *Frame) !js.Array {diff --git a/src/browser/webapi/element/html/TextArea.zig b/src/browser/webapi/element/html/TextArea.zigindex dca6f4c55..8b3f535f3 100644--- a/src/browser/webapi/element/html/TextArea.zig+++ b/src/browser/webapi/element/html/TextArea.zig@@ -169,27 +169,7 @@ fn getSelectionEnd(self: *const TextArea) u32 {}pub fn getForm(self: *TextArea, frame: *Frame) ?*Form {- const element = self.asElement();-- // If form attribute exists, ONLY use that (even if it references nothing)- if (element.getAttributeSafe(comptime .wrap("form"))) |form_id| {- if (frame.getElementByIdFromNode(element.asNode(), form_id)) |form_element| {- return form_element.is(Form);- }- // form attribute present but invalid - no form owner- return null;- }-- // No form attribute - traverse ancestors looking for a <form>- var node = element.asNode()._parent;- while (node) |n| {- if (n.is(Element.Html.Form)) |form| {- return form;- }- node = n._parent;- }-- return null;+ return Form.ownerOf(self.asElement(), frame);}fn getLabels(self: *TextArea, frame: *Frame) !js.Array {diff --git a/src/browser/webapi/element/html/ValidityState.zig b/src/browser/webapi/element/html/ValidityState.zigindex 8185b61f8..f22aca24f 100644--- a/src/browser/webapi/element/html/ValidityState.zig+++ b/src/browser/webapi/element/html/ValidityState.zig@@ -19,13 +19,16 @@// https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#the-constraint-validation-apiconst js = @import("../../../js/js.zig");+const Frame = @import("../../../Frame.zig");const Element = @import("../../Element.zig");+const ElementInternals = @import("../../ElementInternals.zig");+const Input = @import("Input.zig");const Select = @import("Select.zig");-const TextArea = @import("TextArea.zig");const Button = @import("Button.zig");-const Frame = @import("../../../Frame.zig");+const Custom = @import("Custom.zig");+const TextArea = @import("TextArea.zig");const ValidityState = @This();@@ -35,6 +38,7 @@ const ValidityState = @This();_owner: *Element,fn getValueMissing(self: *const ValidityState, frame: *Frame) bool {+ if (self.customFlags()) |flags| return flags.valueMissing;if (self._owner.is(Input)) |input| return input.suffersValueMissing(frame);if (self._owner.is(Select)) |select| return select.suffersValueMissing();if (self._owner.is(TextArea)) |textarea| return textarea.suffersValueMissing();@@ -42,46 +46,52 @@ fn getValueMissing(self: *const ValidityState, frame: *Frame) bool {}fn getTypeMismatch(self: *const ValidityState) bool {+ if (self.customFlags()) |flags| return flags.typeMismatch;if (self._owner.is(Input)) |input| return input.suffersTypeMismatch();return false;}fn getPatternMismatch(self: *const ValidityState, frame: *Frame) bool {+ if (self.customFlags()) |flags| return flags.patternMismatch;if (self._owner.is(Input)) |input| return input.suffersPatternMismatch(frame);return false;}fn getTooLong(self: *const ValidityState) bool {+ if (self.customFlags()) |flags| return flags.tooLong;if (self._owner.is(Input)) |input| return input.suffersTooLong();if (self._owner.is(TextArea)) |textarea| return textarea.suffersTooLong();return false;}fn getTooShort(self: *const ValidityState) bool {+ if (self.customFlags()) |flags| return flags.tooShort;if (self._owner.is(Input)) |input| return input.suffersTooShort();if (self._owner.is(TextArea)) |textarea| return textarea.suffersTooShort();return false;}fn getRangeUnderflow(self: *const ValidityState) bool {+ if (self.customFlags()) |flags| return flags.rangeUnderflow;if (self._owner.is(Input)) |input| return input.suffersRangeUnderflow();return false;}fn getRangeOverflow(self: *const ValidityState) bool {+ if (self.customFlags()) |flags| return flags.rangeOverflow;if (self._owner.is(Input)) |input| return input.suffersRangeOverflow();return false;}fn getStepMismatch(self: *const ValidityState) bool {- _ = self;+ if (self.customFlags()) |flags| return flags.stepMismatch;// Step matching is not implemented yet (PR #2280 begins step rounding for// <input type=range>). Returning false keeps well-formed values valid.return false;}fn getBadInput(self: *const ValidityState) bool {- _ = self;+ if (self.customFlags()) |flags| return flags.badInput;// badInput flips when the UA cannot convert a user-typed string (e.g. the// user typed "abc" into <input type=number>). Headless Lightpanda receives// values via attributes or JS assignment, never raw keystrokes — there is@@ -90,6 +100,7 @@ fn getBadInput(self: *const ValidityState) bool {}fn getCustomError(self: *const ValidityState) bool {+ if (self.customFlags()) |flags| return flags.customError;if (self._owner.is(Input)) |input| return input.hasCustomValidity();if (self._owner.is(Select)) |select| return select.hasCustomValidity();if (self._owner.is(TextArea)) |textarea| return textarea.hasCustomValidity();@@ -98,6 +109,7 @@ fn getCustomError(self: *const ValidityState) bool {}pub fn getValid(self: *const ValidityState, frame: *Frame) bool {+ if (self.customFlags()) |flags| return !flags.any();return !self.getValueMissing(frame) and!self.getTypeMismatch() and!self.getPatternMismatch(frame) and@@ -110,6 +122,14 @@ pub fn getValid(self: *const ValidityState, frame: *Frame) bool {!self.getCustomError();}+// A form-associated custom element's flags are whatever its ElementInternals+// last passed to setValidity().+fn customFlags(self: *const ValidityState) ?ElementInternals.ValidityFlags {+ const custom = self._owner.is(Custom) orelse return null;+ const internals = custom._internals orelse return .{};+ return internals._flags;+}+pub const JsApi = struct {pub const bridge = js.Bridge(ValidityState);diff --git a/src/browser/webapi/net/FormData.zig b/src/browser/webapi/net/FormData.zigindex 6b94bc700..021bb7073 100644--- a/src/browser/webapi/net/FormData.zig+++ b/src/browser/webapi/net/FormData.zig@@ -48,7 +48,7 @@ pub const Entry = struct {name: String,value: Value,- const Value = union(enum) {+ pub const Value = union(enum) {no_file: void,file: *File,string: String,@@ -819,6 +819,28 @@ fn collectForm(arena: Allocator, form_: ?*Form, submitter_: ?*Element, charset:}}+ if (element.is(Element.Html.Custom)) |custom| {+ const internals = custom._internals orelse continue;+ switch (internals._submission) {+ .none => {},+ .entries => |list_entries| for (list_entries) |entry| switch (entry.value) {+ .string => |s| try appendString(&list, arena, entry.name.str(), s.str()),+ .file => |file| try appendFile(&list, arena, entry.name.str(), file),+ .no_file => try list.append(arena, .{+ .name = try String.init(arena, entry.name.str(), .{}),+ .value = .no_file,+ }),+ },+ .string => |s| if (nonEmptyName(element)) |name| {+ try appendString(&list, arena, name, s);+ },+ .file => |file| if (nonEmptyName(element)) |name| {+ try appendFile(&list, arena, name, file);+ },+ }+ continue;+ }+// A missing or empty name excludes the control from the entry list.const name = element.getName() orelse continue;if (name.len == 0) {@@ -894,6 +916,11 @@ fn collectForm(arena: Allocator, form_: ?*Form, submitter_: ?*Element, charset:return list;}+fn nonEmptyName(element: *Element) ?[]const u8 {+ const name = element.getName() orelse return null;+ return if (name.len == 0) null else name;+}+fn appendString(list: *std.ArrayList(Entry), arena: Allocator, name: []const u8, value: []const u8) !void {try list.append(arena, .{.name = try String.init(arena, name, .{}),diff --git a/src/browser/webapi/selector/List.zig b/src/browser/webapi/selector/List.zigindex 2978bd0f6..bf383af54 100644--- a/src/browser/webapi/selector/List.zig+++ b/src/browser/webapi/selector/List.zig@@ -574,6 +574,9 @@ fn matchesPseudoClass(el: *Node.Element, pseudo: Selector.PseudoClass, scope: *Nif (el.is(Node.Element.Html.Form) != null or el.is(Node.Element.Html.FieldSet) != null) {return !hasInvalidDescendant(node, frame);}+ if (el.is(Node.Element.Html.Custom)) |custom| {+ return isCustomValid(custom) orelse false;+ }return false;},.invalid => {@@ -589,6 +592,9 @@ fn matchesPseudoClass(el: *Node.Element, pseudo: Selector.PseudoClass, scope: *Nif (el.is(Node.Element.Html.Form) != null or el.is(Node.Element.Html.FieldSet) != null) {return hasInvalidDescendant(node, frame);}+ if (el.is(Node.Element.Html.Custom)) |custom| {+ return isCustomValid(custom) == false;+ }return false;},.required => {@@ -760,6 +766,19 @@ fn matchesPseudoClass(el: *Node.Element, pseudo: Selector.PseudoClass, scope: *N}}+fn isCustomValid(custom: *Node.Element.Html.Custom) ?bool {+ if (custom.isFormAssociated() == false) {+ // matches neither:valid nor :invalid+ return null;+ }+ const internals = custom._internals orelse return true;+ if (internals.willValidate() == false) {+ // matches neither:valid nor :invalid+ return null;+ }+ return internals._flags.any() == false;+}+fn hasInvalidDescendant(parent: *Node, frame: *Frame) bool {var child = parent.firstChild();while (child) |c| {@@ -772,6 +791,8 @@ fn hasInvalidDescendant(parent: *Node, frame: *Frame) bool {if (invalid) return true;} else if (child_el.is(Node.Element.Html.Select)) |select| {if (select.getRequired() and select.getValue(frame).len == 0) return true;+ } else if (child_el.is(Node.Element.Html.Custom)) |custom| {+ if (isCustomValid(custom) == false) return true;}}if (hasInvalidDescendant(c, frame)) return true;