Skip to content

Truly independent web browser

LibWeb: Leave a select's selectedness to its options

Shannon Bootha99aa5d7fc38
diff --git a/Libraries/LibWeb/DOM/Node.cpp b/Libraries/LibWeb/DOM/Node.cpp
index 7c4e2ab1972..cd12ff20c16 100644
--- a/Libraries/LibWeb/DOM/Node.cpp
+++ b/Libraries/LibWeb/DOM/Node.cpp
@@ -1127,7 +1127,7 @@ void Node::insert_nodes_before(ReadonlySpan<GC::Ref<Node>> nodes, GC::Ptr<Node>
}
// 9. Run the children changed steps for parent.
- ChildrenChangedMetadata metadata { ChildrenChangedMetadata::Type::Inserted, metadata_node, affects_elements, {}, nodes };
+ ChildrenChangedMetadata metadata { ChildrenChangedMetadata::Type::Inserted, metadata_node, affects_elements };
children_changed(metadata);
invalidate_html_collection_caches_in_ancestors(affects_elements);
diff --git a/Libraries/LibWeb/DOM/Node.h b/Libraries/LibWeb/DOM/Node.h
index b312c40c2a6..9c702181d89 100644
--- a/Libraries/LibWeb/DOM/Node.h
+++ b/Libraries/LibWeb/DOM/Node.h
@@ -450,8 +450,6 @@ public:
AffectsElements affects_elements { AffectsElements::No };
// For a removal, the sibling that was before the removed node, if any.
GC::Ptr<Node> old_previous_sibling {};
- // For an insertion of several nodes, such as a document fragment's children, the nodes inserted.
- ReadonlySpan<GC::Ref<Node>> inserted_nodes {};
};
// FIXME: It would be good if we could always provide this metadata for use in optimizations.
virtual void children_changed(ChildrenChangedMetadata const&) { }
diff --git a/Libraries/LibWeb/HTML/HTMLOptionElement.cpp b/Libraries/LibWeb/HTML/HTMLOptionElement.cpp
index e33494f93c4..6c7e9d8ecff 100644
--- a/Libraries/LibWeb/HTML/HTMLOptionElement.cpp
+++ b/Libraries/LibWeb/HTML/HTMLOptionElement.cpp
@@ -8,6 +8,7 @@
#include <AK/Utf16StringBuilder.h>
#include <LibWeb/ARIA/Roles.h>
#include <LibWeb/CSS/Invalidation/ElementStateInvalidator.h>
+#include <LibWeb/CSS/Invalidation/FormControlInvalidator.h>
#include <LibWeb/DOM/Document.h>
#include <LibWeb/DOM/DocumentFragment.h>
#include <LibWeb/DOM/ElementFactory.h>
@@ -320,6 +321,16 @@ GC::Ptr<HTMLFormElement const> HTMLOptionElement::form() const
return select->form();
}
+// Whether option comes before every other option in select's list of options.
+static bool is_first_listed_option(HTMLOptionElement const& option, HTMLSelectElement const& select)
+{
+ for (auto const* node = option.previous_in_pre_order(); node && node != &select; node = node->previous_in_pre_order()) {
+ if (auto const* other = as_if<HTMLOptionElement>(*node); other && other->nearest_select_element().ptr() == &select)
+ return false;
+ }
+ return true;
+}
+
// https://html.spec.whatwg.org/multipage/form-elements.html#update-an-option's-nearest-ancestor-select
void HTMLOptionElement::update_nearest_select_element()
{
@@ -351,8 +362,14 @@ void HTMLOptionElement::update_nearest_select_element()
old_select->update_selectedness();
// 2. If newSelect is not null, then run the selectedness setting algorithm given newSelect.
- if (new_select && !new_select->can_skip_selectedness_update_for_inserted_option(*this))
+ if (new_select && !new_select->can_skip_selectedness_update_for_inserted_option(*this)) {
new_select->update_selectedness();
+ } else if (new_select && new_select->has_attribute(AttributeNames::required) && new_select->display_size() == 1 && is_first_listed_option(*this, *new_select)) {
+ // AD-HOC: Skipping the algorithm skips the validity update it ends with. But an option that isn't selected
+ // changes which option is the placeholder label option when it comes first in the list of options,
+ // and so whether a required select is suffering from being missing.
+ CSS::Invalidation::invalidate_style_after_validity_change(*new_select);
+ }
}
// 4. Set option's cached nearest ancestor select element to newSelect.
diff --git a/Libraries/LibWeb/HTML/HTMLSelectElement.cpp b/Libraries/LibWeb/HTML/HTMLSelectElement.cpp
index 28472f1ad49..85a2687d0fa 100644
--- a/Libraries/LibWeb/HTML/HTMLSelectElement.cpp
+++ b/Libraries/LibWeb/HTML/HTMLSelectElement.cpp
@@ -7,7 +7,6 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-#include <AK/AnyOf.h>
#include <LibJS/Runtime/NativeFunction.h>
#include <LibWeb/Bindings/Wrappable.h>
#include <LibWeb/CSS/CSSStyleProperties.h>
@@ -374,84 +373,15 @@ bool HTMLSelectElement::can_skip_selectedness_update_for_inserted_option(HTMLOpt
return true;
}
-// Whether node, a child of a select or one just removed from it, holds an option of the select's list of options.
-static bool holds_listed_option(DOM::Node const& node)
-{
- if (!is<DOM::Element>(node))
- return false;
-
- // An optgroup with an ancestor optgroup in between itself and the select.
- auto is_nested_optgroup = [&node](DOM::Node const& descendant) {
- if (!is<HTMLOptGroupElement>(descendant) || &descendant == &node)
- return false;
- for (auto const* ancestor = descendant.parent(); ancestor; ancestor = ancestor->parent()) {
- if (is<HTMLOptGroupElement>(*ancestor))
- return true;
- if (ancestor == &node)
- break;
- }
- return false;
- };
-
- bool found_option = false;
- node.for_each_in_inclusive_subtree([&](DOM::Node const& descendant) {
- if (is<HTMLOptionElement>(descendant)) {
- found_option = true;
- return TraversalDecision::Break;
- }
- // NB: The list of options leaves out the options in these, as the steps that build it skip their descendants.
- if (is<HTMLSelectElement>(descendant) || is<HTMLHRElement>(descendant) || is<HTMLDataListElement>(descendant) || is_nested_optgroup(descendant))
- return TraversalDecision::SkipChildrenAndContinue;
- return TraversalDecision::Continue;
- });
- return found_option;
-}
-
-bool HTMLSelectElement::can_skip_children_changed_selectedness_update(ChildrenChangedMetadata const& metadata) const
-{
- // If the following criteria are met, there is no need to re-run the selectedness algorithm.
- // NB: The selectedness setting algorithm runs when the list of options gains or loses an option element, so a
- // child that can't change the list, such as the text and comments between the options, leaves it alone.
- switch (metadata.type) {
- case ChildrenChangedMetadata::Type::Mutation:
- // The data of a text or comment child changed.
- return true;
- case ChildrenChangedMetadata::Type::Inserted:
- if (auto* option = as_if<HTMLOptionElement>(*metadata.node))
- return can_skip_selectedness_update_for_inserted_option(*option);
- // NB: An insertion of several nodes, such as a document fragment's children, names the nodes it inserted.
- if (!metadata.inserted_nodes.is_empty())
- return !any_of(metadata.inserted_nodes, [](auto const& node) { return holds_listed_option(*node); });
- return !holds_listed_option(*metadata.node);
- case ChildrenChangedMetadata::Type::Removal:
- return !holds_listed_option(*metadata.node);
- case ChildrenChangedMetadata::Type::AllChildrenRemoved:
- return false;
- }
- VERIFY_NOT_REACHED();
-}
-
void HTMLSelectElement::children_changed(ChildrenChangedMetadata const& metadata)
{
Base::children_changed(metadata);
- if (can_skip_children_changed_selectedness_update(metadata)) {
- // A list box still shows a row for the label of each optgroup child, even one with no options.
- auto changes_optgroup_children = [&] {
- if (metadata.type != ChildrenChangedMetadata::Type::Inserted && metadata.type != ChildrenChangedMetadata::Type::Removal)
- return false;
- if (!metadata.inserted_nodes.is_empty())
- return any_of(metadata.inserted_nodes, [](auto const& node) { return is<HTMLOptGroupElement>(*node); });
- return is<HTMLOptGroupElement>(*metadata.node);
- };
- if (changes_optgroup_children())
- list_box_options_did_change();
- return;
- }
-
- update_cached_list_of_options();
- update_selectedness();
- list_box_options_did_change();
+ // NB: The insertion, removing and moving steps of each option run the selectedness setting algorithm when the list
+ // of options gains or loses it, so the select only builds its list box rows again. Those show the label of
+ // each optgroup child too, even one with no options.
+ if (metadata.type != ChildrenChangedMetadata::Type::Mutation)
+ list_box_options_did_change();
}
// https://html.spec.whatwg.org/multipage/form-elements.html#dom-select-type
@@ -1256,6 +1186,16 @@ void HTMLSelectElement::update_list_box()
auto rows = max(display_size(), 1u);
m_list_box_element->set_attribute_value(HTML::AttributeNames::style, Utf16String::formatted("block-size: {}em; overflow-x: hidden; overflow-y: auto;", rows * list_box_row_height_in_em));
+ // NB: The rows are built again whenever the options change, so the anchor and focus of a range selection are kept
+ // on the options they were on, as long as those still have a row.
+ auto option_at = [&](Optional<size_t> index) -> GC::Ptr<HTMLOptionElement> {
+ if (!index.has_value() || *index >= m_list_box_rows.size())
+ return nullptr;
+ return m_list_box_rows[*index].option;
+ };
+ auto anchor_option = option_at(m_list_box_anchor_index);
+ auto focus_option = option_at(m_list_box_focus_index);
+
m_list_box_rows.clear();
m_list_box_anchor_index = {};
m_list_box_focus_index = {};
@@ -1287,6 +1227,14 @@ void HTMLSelectElement::update_list_box()
}
}
}
+
+ auto index_of = [&](GC::Ptr<HTMLOptionElement> option) -> Optional<size_t> {
+ if (!option)
+ return {};
+ return m_list_box_rows.find_first_index_if([&](auto const& row) { return row.option == option; });
+ };
+ m_list_box_anchor_index = index_of(anchor_option);
+ m_list_box_focus_index = index_of(focus_option);
}
void HTMLSelectElement::handle_list_box_mousedown(UIEvents::MouseEvent& event)
diff --git a/Libraries/LibWeb/HTML/HTMLSelectElement.h b/Libraries/LibWeb/HTML/HTMLSelectElement.h
index a9cf736a681..1c0dc7aa51f 100644
--- a/Libraries/LibWeb/HTML/HTMLSelectElement.h
+++ b/Libraries/LibWeb/HTML/HTMLSelectElement.h
@@ -163,7 +163,6 @@ private:
virtual void computed_properties_changed() override;
virtual void children_changed(ChildrenChangedMetadata const&) override;
- bool can_skip_children_changed_selectedness_update(ChildrenChangedMetadata const& metadata) const;
void update_cached_list_of_options() const;
void show_the_picker_if_applicable();
diff --git a/Tests/LibWeb/Text/expected/HTML/select-required-option-insertion-validity.txt b/Tests/LibWeb/Text/expected/HTML/select-required-option-insertion-validity.txt
new file mode 100644
index 00000000000..7a61ffd8b86
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/HTML/select-required-option-insertion-validity.txt
@@ -0,0 +1,3 @@
+direct: matches :invalid in style: false, checkValidity(): true
+wrapped: matches :invalid in style: false, checkValidity(): true
+after: matches :invalid in style: true, checkValidity(): false
diff --git a/Tests/LibWeb/Text/expected/select-list-box-anchor-kept-for-text-children.txt b/Tests/LibWeb/Text/expected/select-list-box-anchor-kept-for-text-children.txt
new file mode 100644
index 00000000000..aede16066cc
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/select-list-box-anchor-kept-for-text-children.txt
@@ -0,0 +1,2 @@
+After shift-clicking D: B,C,D
+After shift-clicking F: B,C,D,E,F
diff --git a/Tests/LibWeb/Text/input/HTML/select-required-option-insertion-validity.html b/Tests/LibWeb/Text/input/HTML/select-required-option-insertion-validity.html
new file mode 100644
index 00000000000..23cccd17786
--- /dev/null
+++ b/Tests/LibWeb/Text/input/HTML/select-required-option-insertion-validity.html
@@ -0,0 +1,30 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<style>
+ select:invalid {
+ color: rgb(255, 0, 0);
+ }
+</style>
+<select id="direct" required><option value="" selected>A</option></select>
+<select id="wrapped" required><option value="" selected>A</option></select>
+<select id="after" required><option value="" selected>A</option></select>
+<script>
+ test(() => {
+ // A is selected and is the placeholder label option, so each select starts out suffering from being missing.
+ // An option inserted before A, but not one inserted after it, stops A from being the placeholder label option.
+ function report(select) {
+ const style = getComputedStyle(select).color === "rgb(255, 0, 0)" ? "invalid" : "valid";
+ println(`${select.id}: matches :invalid in style: ${style === "invalid"}, checkValidity(): ${select.checkValidity()}`);
+ }
+
+ direct.prepend(new Option("B", "b"));
+ const group = document.createElement("optgroup");
+ group.append(new Option("B", "b"));
+ wrapped.prepend(group);
+ after.append(new Option("B", "b"));
+
+ report(direct);
+ report(wrapped);
+ report(after);
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/select-list-box-anchor-kept-for-text-children.html b/Tests/LibWeb/Text/input/select-list-box-anchor-kept-for-text-children.html
new file mode 100644
index 00000000000..97d5ef45a10
--- /dev/null
+++ b/Tests/LibWeb/Text/input/select-list-box-anchor-kept-for-text-children.html
@@ -0,0 +1,39 @@
+<!DOCTYPE html>
+<script src="include.js"></script>
+<style>
+ body {
+ margin: 0;
+ font: 16px SerenitySans;
+ }
+</style>
+<select id="select" multiple size="6"><option>A</option><option>B</option><option>C</option><option>D</option><option>E</option><option>F</option></select>
+<script>
+ function press(index, modifiers = 0) {
+ const rect = select.getBoundingClientRect();
+ const rowHeight = (rect.height - 4) / select.size;
+ const x = rect.left + 10;
+ const y = rect.top + 2 + rowHeight * (index + 0.5);
+ internals.mouseDown(x, y, 1, 0, modifiers);
+ internals.mouseUp(x, y, 0, modifiers);
+ }
+
+ function selectedLabels() {
+ return [...select.selectedOptions].map(option => option.label).join(",");
+ }
+
+ asyncTest(async done => {
+ press(1);
+ press(3, internals.MOD_SHIFT);
+ println(`After shift-clicking D: ${selectedLabels()}`);
+
+ // Text and comments between the options add no rows, so the range selection keeps its anchor at B.
+ select.append("\n", document.createComment("comment"));
+ select.firstChild.before("\n");
+ await new Promise(resolve => setTimeout(resolve, 0));
+ await new Promise(resolve => setTimeout(resolve, 0));
+
+ press(5, internals.MOD_SHIFT);
+ println(`After shift-clicking F: ${selectedLabels()}`);
+ done();
+ });
+</script>