Lightpanda: the headless browser designed for AI and automation
chore: cleanup selected / selected options
Karl Seguin0d9e5441f540
diff --git a/src/browser/Frame.zig b/src/browser/Frame.zigindex 4ae6e1938..788ee71ed 100644--- a/src/browser/Frame.zig+++ b/src/browser/Frame.zig@@ -2691,7 +2691,8 @@ pub fn removeNode(self: *Frame, parent: *Node, child: *Node, opts: RemoveNodeOptconst old_id_maps = idMapsForRoot(old_root);child._parent = null;- Element.Html.Select.optionListChanged(parent, child);++ Element.Html.Select.childRemoved(parent, child);// Update live ranges for removal (DOM spec remove steps 4-7)if (child_index_for_ranges) |idx| {@@ -2921,7 +2922,8 @@ fn _insertNodeRelative(self: *Frame, comptime from_parser: bool, parent: *Node,},}child._parent = parent;- Element.Html.Select.optionListChanged(parent, child);++ Element.Html.Select.childInserted(parent, child);// Update live ranges for insertion (DOM spec insert step 6).// For .before/.after the child was inserted at a specific position;diff --git a/src/browser/frame/parse.zig b/src/browser/frame/parse.zigindex d5ac48504..cb0cf50f6 100644--- a/src/browser/frame/parse.zig+++ b/src/browser/frame/parse.zig@@ -107,10 +107,8 @@ pub fn fragment(frame: *Frame, node: *Node, html: []const u8, opts: FragmentParswhile (it.next()) |child| {child._parent = node;}- it = node.childrenIterator();- while (it.next()) |child| {- Element.Html.Select.optionListChanged(node, child);- }+ // Nor did the options among them reach their select.+ Element.Html.Select.childrenInserted(node);}// Build a detached XMLDocument from `xml` (DOMParser.parseFromString anddiff --git a/src/browser/tests/element/html/select.html b/src/browser/tests/element/html/select.htmlindex a8caee1e2..603d9a259 100644--- a/src/browser/tests/element/html/select.html+++ b/src/browser/tests/element/html/select.html@@ -575,6 +575,16 @@testing.expectEqual('', select.value);testing.expectEqual(2, select.selectedIndex);testing.expectTrue(empty.selected);++ // Deselecting an option that isn't selected changes nothing; deselecting the+ // selected one asks for a reset, which re-selects the first option.+ select.value = 'nope';+ select.options[1].selected = false;+ testing.expectEqual('', select.value);+ select.options[1].selected = true;+ select.options[1].selected = false;+ testing.expectEqual('a', select.value);+ testing.expectEqual(0, select.selectedIndex);}</script>@@ -752,3 +762,214 @@testing.expectTrue(hops < 10);}</script>++<select id="parsed_default" autocomplete="off">+ <option value="a">A</option>+ <option value="b">B</option>+</select>+<select id="parsed_disabled_first" autocomplete="off">+ <option value="a" disabled>A</option>+ <option value="b">B</option>+</select>+<select id="parsed_two_selected" autocomplete="off">+ <option value="a" selected>A</option>+ <option value="b" selected>B</option>+</select>+<script id="parsed_selectedness">+{+ // The parser's insertions keep selectedness the way script's do: the first+ // enabled option really is selected, and of two selected options the last+ // one wins.+ const s1 = $('#parsed_default');+ testing.expectEqual(true, s1.options[0].selected);+ testing.expectEqual(1, s1.selectedOptions.length);++ const s2 = $('#parsed_disabled_first');+ testing.expectEqual(false, s2.options[0].selected);+ testing.expectEqual(true, s2.options[1].selected);+ testing.expectEqual('b', s2.value);++ const s3 = $('#parsed_two_selected');+ testing.expectEqual(false, s3.options[0].selected);+ testing.expectEqual('b', s3.value);+}+</script>++<script id="list_changes_ask_for_a_reset">+{+ const mk = (html) => {+ const select = document.createElement('select');+ select.innerHTML = html;+ return select;+ };+ const option = (value, props = {}) => Object.assign(document.createElement('option'), { value }, props);++ {+ // Nothing selected: adding a disabled option changes nothing, an enabled+ // one brings back the default.+ const s = mk('<option value="a">A</option><option value="b">B</option>');+ s.value = 'nope';+ s.add(option('c', { disabled: true }));+ testing.expectEqual(-1, s.selectedIndex);+ s.add(option('d'));+ testing.expectEqual('a', s.value);+ testing.expectEqual(0, s.selectedIndex);+ }++ {+ // Nothing selected: removing any option brings back the default.+ const s = mk('<option value="a">A</option><option value="b">B</option><option value="c">C</option>');+ s.value = 'nope';+ s.options[2].remove();+ testing.expectEqual('a', s.value);+ }++ {+ // Repopulating after a value no option had.+ const s = mk('<option value="a">A</option><option value="b">B</option>');+ s.value = 'nope';+ s.innerHTML = '<option value="x">X</option><option value="y">Y</option>';+ testing.expectEqual('x', s.value);+ testing.expectEqual(true, s.options[0].selected);+ }++ {+ // Removing the selected option falls back to the first enabled one.+ const s = mk('<option value="a" disabled>A</option><option value="b">B</option><option value="c">C</option>');+ s.value = 'c';+ s.options[2].remove();+ testing.expectEqual('b', s.value);+ testing.expectEqual(1, s.selectedIndex);++ const t = mk('<option value="a">A</option><option value="b">B</option><option value="c">C</option>');+ t.selectedIndex = 2;+ t.options[2].remove();+ testing.expectEqual('a', t.value);+ testing.expectEqual(0, t.selectedIndex);+ }++ {+ // An inserted selected option wins, directly or inside an optgroup.+ const s = mk('<option value="a">A</option><option value="b">B</option>');+ s.add(option('c', { selected: true }), 0);+ testing.expectEqual('c', s.value);+ testing.expectEqual(1, s.selectedOptions.length);++ const t = mk('<option value="a">A</option><option value="b">B</option>');+ const group = document.createElement('optgroup');+ group.innerHTML = '<option value="x">X</option><option value="y" selected>Y</option>';+ t.appendChild(group);+ testing.expectEqual('y', t.value);+ testing.expectEqual(3, t.selectedIndex);+ testing.expectEqual(1, t.selectedOptions.length);++ group.remove();+ testing.expectEqual('a', t.value);+ }++ {+ // Moving the selected option keeps it selected.+ const s = mk('<option value="a">A</option><option value="b">B</option>');+ s.options[1].selected = true;+ s.insertBefore(s.options[1], s.options[0]);+ testing.expectEqual('b', s.value);+ testing.expectEqual(0, s.selectedIndex);+ }++ {+ const s = mk('<option value="a">A</option><option value="b">B</option>');+ const clone = s.cloneNode(true);+ testing.expectEqual(true, clone.options[0].selected);+ }+}+</script>++<form id="disabled_value_form">+ <select id="disabled_value" name="s" autocomplete="off">+ <option value="a">A</option>+ <option value="b" disabled>B</option>+ </select>+</form>+<script id="disabled_option_is_the_value">+{+ // A disabled option can be selected by script and is then the value; it is+ // only left out of the form data.+ const s = $('#disabled_value');+ s.value = 'b';+ testing.expectEqual('b', s.value);+ testing.expectEqual(1, s.selectedIndex);+ testing.expectEqual(null, new FormData($('#disabled_value_form')).get('s'));+}+</script>++<script id="multiple_and_list_box_have_no_default">+{+ const mk = (html, props) => {+ const select = Object.assign(document.createElement('select'), props);+ select.innerHTML = html;+ return select;+ };++ {+ const s = mk('<option value="a">A</option><option value="b">B</option>', { multiple: true });+ testing.expectEqual('', s.value);+ testing.expectEqual(-1, s.selectedIndex);+ s.value = 'nope';+ testing.expectEqual('', s.value);+ }++ {+ // selectedIndex deselects every other option, even in a multiple select.+ const s = mk('<option selected>a</option><option selected>b</option><option selected>c</option>', { multiple: true });+ s.selectedIndex = 1;+ testing.expectEqual(1, s.selectedOptions.length);+ testing.expectEqual('b', s.value);+ }++ {+ // Dropping multiple keeps the first selected option, or asks for a reset.+ const s = mk('<option>a</option><option selected>b</option><option selected>c</option>', { multiple: true });+ s.multiple = false;+ testing.expectEqual('b', s.value);+ testing.expectEqual(1, s.selectedOptions.length);++ const t = mk('<option>a</option><option>b</option>', { multiple: true });+ t.multiple = false;+ testing.expectEqual('a', t.value);+ }++ {+ // A list box has no default selection; turning it into a menu list does.+ const s = mk('<option>a</option><option>b</option>', { size: 3 });+ testing.expectEqual(-1, s.selectedIndex);+ s.size = 1;+ testing.expectEqual(0, s.selectedIndex);+ }+}+</script>++<script id="selected_attribute_changes_selectedness">+{+ const s = document.createElement('select');+ s.innerHTML = '<option value="a">A</option><option value="b">B</option>';+ s.options[1].setAttribute('selected', '');+ testing.expectEqual('b', s.value);+ testing.expectEqual(false, s.options[0].selected);++ s.options[1].removeAttribute('selected');+ testing.expectEqual('a', s.value);+}+</script>++<script id="required_with_no_selection">+{+ const s = document.createElement('select');+ s.required = true;+ s.innerHTML = '<option value="">choose</option><option value="a">A</option>';+ testing.expectEqual(true, s.validity.valueMissing);+ s.value = 'a';+ testing.expectEqual(false, s.validity.valueMissing);+ s.value = 'nope';+ testing.expectEqual(true, s.validity.valueMissing);+}+</script>diff --git a/src/browser/webapi/element/html/Option.zig b/src/browser/webapi/element/html/Option.zigindex a67b48b3e..609744fd6 100644--- a/src/browser/webapi/element/html/Option.zig+++ b/src/browser/webapi/element/html/Option.zig@@ -80,17 +80,19 @@ pub fn getSelected(self: *const Option) bool {}fn setSelected(self: *Option, selected: bool, frame: *Frame) !void {+ self.setSelectedness(selected);+ frame.domChanged();+}++fn setSelectedness(self: *Option, selected: bool) void {+ if (self._selected == selected) {+ // Deselecting an option that isn't selected doesn't ask for a reset.+ return;+ }self._selected = selected;if (self.ownerSelect()) |select| {- if (selected) {- if (!select.getMultiple()) {- select.deselectOthers(self);- }- } else {- select.resetToDefaultSelection();- }+ select.optionSelectednessChanged(self);}- frame.domChanged();}/// The <select> this option belongs to, directly or through an <optgroup>.@@ -169,7 +171,7 @@ pub const Build = struct {.value => self._value = element.getAttributeInterned("value"),.selected => {self._default_selected = true;- self._selected = true;+ self.setSelectedness(true);},}}@@ -181,7 +183,7 @@ pub const Build = struct {.value => self._value = null,.selected => {self._default_selected = false;- self._selected = false;+ self.setSelectedness(false);},}}diff --git a/src/browser/webapi/element/html/Select.zig b/src/browser/webapi/element/html/Select.zigindex c91b6056b..fbda4d009 100644--- a/src/browser/webapi/element/html/Select.zig+++ b/src/browser/webapi/element/html/Select.zig@@ -34,12 +34,13 @@ const Form = @import("Form.zig");pub const Option = @import("Option.zig");const ValidityState = @import("ValidityState.zig");+const String = lp.String;+const Select = @This();pub const Proto = HtmlElement;_proto_canary: if (lp.IS_DEBUG) *HtmlElement else void = undefined,-_explicit_selection: bool = false,_custom_validity: ?[]const u8 = null,_validity: ?*ValidityState = null,@@ -56,6 +57,125 @@ pub fn asConstNode(self: *const Select) *const Node {return self.asConstElement().asConstNode();}+// Called by the Frame for every node, an inserted option has to update its select.+// TODO: if ever we have more of these, we should add inserted/removed Build+// hooks. For this one off, I'm sticking with a direct call from Frame because+// it's easier.+pub fn childInserted(parent: *Node, child: *Node) void {+ if (ListChange.isinList(parent, child) == false) {+ return;+ }+ const select = ListChange.getSelect(parent) orelse return;+ var change: ListChange = .{};+ change.add(child);+ change.processInserted(select);+}++// parser.fragment links every child of a parent at once.+pub fn childrenInserted(parent: *Node) void {+ const select = ListChange.getSelect(parent) orelse return;+ var change: ListChange = .{};+ var it = parent.childrenIterator();+ while (it.next()) |child| {+ if (ListChange.isinList(parent, child)) {+ change.add(child);+ }+ }+ change.processInserted(select);+}++// Called by the Frame for every node, a removed option has to update its select.+pub fn childRemoved(parent: *Node, child: *Node) void {+ if (ListChange.isinList(parent, child) == false) {+ return;+ }+ const select = ListChange.getSelect(parent) orelse return;+ if (select.isMenuList() == false) {+ return;+ }++ var change: ListChange = .{};+ change.add(child);+ if (change.last_selected != null or select.selectedOption() == null) {+ select.selectFirstEnabled();+ }+}++// The options that nodes linked into, or unlinked from, a select's list of+// options carry: options themselves, and an optgroup's option children.+const ListChange = struct {+ has_enabled: bool = false,+ last_selected: ?*Option = null,++ fn add(self: *ListChange, child: *Node) void {+ if (child.is(Option)) |option| {+ self.addOption(option);+ return;+ }+ var it = child.childrenIterator();+ while (it.next()) |node| {+ if (node.is(Option)) |option| {+ self.addOption(option);+ }+ }+ }++ fn addOption(self: *ListChange, option: *Option) void {+ if (option._selected) {+ self.last_selected = option;+ }+ if (self.has_enabled == false and option.asElement().isDisabled() == false) {+ self.has_enabled = true;+ }+ }++ fn getSelect(parent: *Node) ?*Select {+ if (parent.is(Select)) |select| {+ return select;+ }+ if (parent.is(Element.Html.OptGroup) == null) {+ return null;+ }+ // optgroup's select+ const grandparent = parent.parentNode() orelse return null;+ return grandparent.is(Select);+ }++ fn isinList(parent: *Node, child: *Node) bool {+ if (child.is(Option) != null) {+ // an option is always in a select+ return true;+ }+ // an optgroup may be in a select+ return child.is(Element.Html.OptGroup) != null and parent.is(Select) != null;+ }++ fn processInserted(self: *const ListChange, select: *const Select) void {+ if (select.getMultiple()) {+ // can have multiple selected, nothing to do+ return;+ }+ if (self.last_selected) |option| {+ // the newcome wins+ select.deselectOthers(option);+ } else if (self.has_enabled) {+ // there's at least 1 enabled option+ select.resetToDefaultSelection();+ }+ }+};++pub fn optionSelectednessChanged(self: *const Select, option: *const Option) void {+ if (option._selected) {+ if (self.getMultiple() == false) {+ self.deselectOthers(option);+ }+ } else {+ // this isn't a multiple, so our only selected option became unselected+ self.resetToDefaultSelection();+ }+}+// Walks the select's list of options in tree order: its option children plus// the option children of its optgroup children, per HTML// §the-select-element. Options nested any deeper are not in the list.@@ -95,58 +215,37 @@ const OptionIterator = struct {}};-pub fn deselectOthers(self: *const Select, keep: *const Option) void {+fn deselectOthers(self: *const Select, keep: *const Option) void {var it = OptionIterator.init(self);while (it.next()) |option| {if (option != keep) option._selected = false;}}-pub fn resetToDefaultSelection(self: *const Select) void {- if (self.getMultiple() or self.displaySize() > 1) {- return;+// HTML's "ask for a reset". Every path that selects an option in a+// non-multiple select deselects the others, so this only has to handle a+// menu list left with nothing selected.+fn resetToDefaultSelection(self: *const Select) void {+ if (self.isMenuList() and self.selectedOption() == null) {+ self.selectFirstEnabled();}+}- var first_enabled: ?*Option = null;- var last_selected: ?*Option = null;+// For a menu list with nothing selected.+fn selectFirstEnabled(self: *const Select) void {var it = OptionIterator.init(self);while (it.next()) |option| {- if (option._selected) {- if (last_selected) |prev| prev._selected = false;- last_selected = option;- }- if (first_enabled == null and !option.asElement().isDisabled()) {- first_enabled = option;- }- }-- if (last_selected == null) {- if (first_enabled) |option| {+ if (option.asElement().isDisabled() == false) {option._selected = true;+ return;}}}-pub fn optionListChanged(parent: *Node, child: *Node) void {- const select = parent.is(Select) orelse blk: {- if (parent.is(Element.Html.OptGroup) == null) return;- break :blk (parent.parentNode() orelse return).is(Select) orelse return;- };- if (!select._explicit_selection) return;-- if (child.is(Option) == null) {- if (child.is(Element.Html.OptGroup) == null or parent != select.asNode()) return;- var children = child.childrenIterator();- while (children.next()) |node| {- if (node.is(Option) != null) break;- } else return;- }-- var options = OptionIterator.init(select);- while (options.next()) |option| {- if (option.getSelected()) return;- }- select.resetToDefaultSelection();+// A menu list (Blink's UsesMenuList) always shows a selected option when it+// has an enabled one; multiple selects and list boxes have no default.+fn isMenuList(self: *const Select) bool {+ return self.getMultiple() == false and self.displaySize() < 2;}// The size attribute, as the size IDL attribute parses it (0 when absent or@@ -158,77 +257,55 @@ fn displaySize(self: *const Select) i64 {return @max(parsed, 0);}-pub fn effectiveOption(self: *const Select) ?*Option {- var first_option: ?*Option = null;+// The first selected option in tree order. Disabled options count: they can be+// selected by script, they just aren't submitted.+fn selectedOption(self: *const Select) ?*Option {var it = OptionIterator.init(self);while (it.next()) |option| {- // Includes disabled optgroups.- if (option.asElement().isDisabled()) {- continue;- }- if (option.getSelected()) {+ if (option._selected) {return option;}- if (first_option == null) first_option = option;}- if (self._explicit_selection) {- return null;- }- return first_option;+ return null;}pub fn getValue(self: *Select, frame: *Frame) []const u8 {- if (self.effectiveOption()) |opt| {- return opt.getValue(frame);- }- return "";+ const option = self.selectedOption() orelse return "";+ return option.getValue(frame);}pub fn setValue(self: *Select, value: []const u8, frame: *Frame) !void {+ // Selects the first matching option only, and none when nothing matches.+ // This updates the current state (_selected), not the default state+ // (attribute).var matched = false;var it = OptionIterator.init(self);while (it.next()) |option| {- const is_match = !matched and std.mem.eql(u8, option.getValue(frame), value);+ const is_match = matched == false and std.mem.eql(u8, option.getValue(frame), value);option._selected = is_match;- if (is_match) matched = true;+ matched = matched or is_match;}- self._explicit_selection = !matched;frame.domChanged();}pub fn getSelectedIndex(self: *Select) i32 {var index: i32 = 0;- var has_options = false;var it = OptionIterator.init(self);- while (it.next()) |option| {- has_options = true;- if (option.getSelected()) {+ while (it.next()) |option| : (index += 1) {+ if (option._selected) {return index;}- index += 1;- }- if (self._explicit_selection) {- return -1;}- return if (has_options) 0 else -1;+ return -1;}pub fn setSelectedIndex(self: *Select, index: i32, frame: *Frame) !void {- self._explicit_selection = true;-- // Select option at given index- // Note: This updates the current state (_selected), not the default state (attribute)- const is_multiple = self.getMultiple();+ // Every other option is deselected, even in a multiple select, and an+ // out-of-range index leaves none selected.var current_index: i32 = 0;var it = OptionIterator.init(self);- while (it.next()) |option| {- if (current_index == index) {- option._selected = true;- } else if (!is_multiple) {- // Only deselect others if not multiple- option._selected = false;- }- current_index += 1;+ while (it.next()) |option| : (current_index += 1) {+ option._selected = current_index == index;}frame.domChanged();}@@ -377,8 +454,8 @@ pub fn hasCustomValidity(self: *const Select) bool {pub fn suffersValueMissing(self: *const Select) bool {if (!self.getWillValidate()) return false;if (!self.getRequired()) return false;- // No selectable option ⇒ no value to submit.- const opt = self.effectiveOption() orelse return true;+ // No selected option ⇒ no value to submit.+ const opt = self.selectedOption() orelse return true;// The selected option's `value` attribute (`opt._value`) is what matters// for the missing-value check; an explicit `value=""` is the canonical// placeholder pattern. When `value=` is absent the option's text would@@ -433,6 +510,28 @@ pub const Build = struct {pub fn created(_: *Node, _: *Frame) !void {// No initialization needed - disabled is lazy from attribute}++ pub fn attributeChange(element: *Element, name: String, _: String, _: *Frame) !void {+ // Switching between a list box and a menu list asks for a reset.+ if (name.eql(comptime .wrap("size"))) {+ element.as(Select).resetToDefaultSelection();+ }+ }++ pub fn attributeRemove(element: *Element, name: String, _: *Frame) !void {+ const attribute = std.meta.stringToEnum(enum { multiple, size }, name.str()) orelse return;+ const self = element.as(Select);+ switch (attribute) {+ // Blink, Gecko and WebKit keep the first selected option; the+ // spec is silent.+ .multiple => if (self.selectedOption()) |option| {+ self.deselectOthers(option);+ } else {+ self.resetToDefaultSelection();+ },+ .size => self.resetToDefaultSelection(),+ }+ }};const std = @import("std");diff --git a/src/browser/webapi/net/FormData.zig b/src/browser/webapi/net/FormData.zigindex e4ab869bc..5c82cb8ef 100644--- a/src/browser/webapi/net/FormData.zig+++ b/src/browser/webapi/net/FormData.zig@@ -861,18 +861,14 @@ fn collectForm(arena: Allocator, form_: ?*Form, submitter_: ?*Element, charset:}if (element.is(Form.Select)) |select| {- if (select.getMultiple() == false) {- // Per the HTML spec, a single-select with no selectedness- // candidate (zero options or every option disabled)- // contributes no entry. Otherwise emit the candidate's- // value.- const opt = select.effectiveOption() orelse continue;- break :blk opt.getValue(frame);- }-var options = try select.getSelectedOptions(frame);- while (options.next()) |option| {- try appendString(&list, arena, name, option.as(Form.Select.Option).getValue(frame));+ while (options.next()) |node| {+ const option = node.as(Form.Select.Option);+ // A disabled option can be selected, but isn't submitted.+ if (option.asElement().isDisabled()) {+ continue;+ }+ try appendString(&list, arena, name, option.getValue(frame));}continue;}diff --git a/src/server/cdp/AXNode.zig b/src/server/cdp/AXNode.zigindex 372911e3e..b34da361c 100644--- a/src/server/cdp/AXNode.zig+++ b/src/server/cdp/AXNode.zig@@ -441,33 +441,7 @@ pub const Writer = struct {const option = el.as(DOMNode.Element.Html.Option);try self.writeAXProperty(.{ .name = .focusable, .value = .{ .booleanOrUndefined = true } }, w);- // Check if this option is selected by examining the parent select- const is_selected = blk: {- // First check if explicitly selected- if (option.getSelected()) break :blk true;-- // Check if implicitly selected (first enabled option in select with no explicit selection)- const parent = dom_node._parent orelse break :blk false;- const parent_el = parent.as(DOMNode.Element);- if (parent_el.getTag() != .select) break :blk false;-- const select = parent_el.as(DOMNode.Element.Html.Select);- const selected_idx = select.getSelectedIndex();-- // Find this option's index- var idx: i32 = 0;- var it = parent.childrenIterator();- while (it.next()) |child| {- if (child.is(DOMNode.Element.Html.Option) == null) continue;- if (child == dom_node) {- break :blk idx == selected_idx;- }- idx += 1;- }- break :blk false;- };-- if (is_selected) {+ if (option.getSelected()) {try self.writeAXProperty(.{ .name = .selected, .value = .{ .booleanOrUndefined = true } }, w);}},