Skip to content

Truly independent web browser

LibWeb: Invoke text directives during fragment navigation

Sam Atkins39ea81e25143
diff --git a/Libraries/LibWeb/DOM/Document.cpp b/Libraries/LibWeb/DOM/Document.cpp
index 5413021a700..d419a5f8e4c 100644
--- a/Libraries/LibWeb/DOM/Document.cpp
+++ b/Libraries/LibWeb/DOM/Document.cpp
@@ -625,6 +625,70 @@ WebIDL::ExceptionOr<GC::Ref<Document>> Document::create_and_initialize(Type type
return document;
}
+// https://wicg.github.io/scroll-to-text-fragment/#check-if-a-text-directive-can-be-scrolled
+bool Document::check_if_a_text_directive_can_be_scrolled(Optional<URL::Origin> const& initiator_origin, Optional<HTML::UserNavigationInvolvement> user_involvement)
+{
+ // 1. If document's pending text directives field is null or empty, return false.
+ if (!m_pending_text_directives.has_value() || m_pending_text_directives->is_empty())
+ return false;
+
+ // 2. Let is user involved be true if document's text directive user activation is true, or user involvement is
+ // one of "activation" or "browser UI"; false otherwise.
+ auto const is_user_involved = m_text_directive_user_activation
+ || user_involvement == HTML::UserNavigationInvolvement::Activation
+ || user_involvement == HTML::UserNavigationInvolvement::BrowserUI;
+
+ // 3. Set document's text directive user activation to false.
+ m_text_directive_user_activation = false;
+
+ // 4. If document's content type is not a text directive allowing MIME type, return false.
+ if (m_content_type != "text/html"_utf16_fly_string && m_content_type != "text/plain"_utf16_fly_string)
+ return false;
+
+ // 5. If user involvement is "browser UI", return true.
+ if (user_involvement == HTML::UserNavigationInvolvement::BrowserUI)
+ return true;
+
+ // 6. If is user involved is false, return false.
+ if (!is_user_involved)
+ return false;
+
+ // 7. If document's node navigable has a parent, return false.
+ if (!navigable() || navigable()->parent())
+ return false;
+
+ // 8. If initiator origin is non-null and document's origin is same origin with initiator origin, return true.
+ if (initiator_origin.has_value() && origin().is_same_origin(*initiator_origin))
+ return true;
+
+ // 9. If document's browsing context's browsing context group's browsing context set has length 1, return true.
+ if (!browsing_context_group_has_multiple_contexts())
+ return true;
+
+ // 10. Otherwise, return false.
+ return false;
+}
+
+bool Document::browsing_context_group_has_multiple_contexts() const
+{
+ if (m_browsing_context_group_has_remote_contexts)
+ return true;
+
+ auto local_navigable = navigable();
+ if (!local_navigable)
+ return true;
+ auto group_id = local_navigable->browsing_context_group_id();
+ if (!group_id.has_value())
+ return true;
+
+ size_t matching_navigable_count = 0;
+ for (auto& candidate : HTML::all_local_navigables()) {
+ if (candidate->browsing_context_group_id() == group_id && ++matching_navigable_count > 1)
+ return true;
+ }
+ return false;
+}
+
GC::Ref<Document> Document::create(Page& page, GC::Ref<EventTarget> relevant_global_event_target, URL::URL const& url)
{
auto document = GC::Heap::the().allocate<Document>(page, relevant_global_event_target, url);
@@ -871,12 +935,14 @@ void Document::visit_edges(Cell::Visitor& visitor)
visitor.visit(m_active_favicon);
visitor.visit(m_browsing_context);
visitor.visit(m_focused_area);
+ visitor.visit(m_sequential_focus_navigation_starting_point);
visitor.visit(m_active_element);
visitor.visit(m_target_element);
visitor.visit(m_autofocus_candidates);
visitor.visit(m_accessibility_focus_target);
visitor.visit(m_implementation);
visitor.visit(m_fragment_directive);
+ visitor.visit(m_text_fragment_ranges);
visitor.visit(m_current_script);
visitor.visit(m_associated_inert_template_document);
visitor.visit(m_appropriate_template_contents_owner_document);
@@ -3985,6 +4051,9 @@ void Document::set_focused_area(GC::Ptr<Node> node, InvalidateFocusPseudoClasses
return;
page().invalidate_compositor_keyboard_scroll_state_for_document(*this);
+ if (node)
+ m_sequential_focus_navigation_starting_point = nullptr;
+
GC::Ptr old_focused_area = m_focused_area;
if (auto* old_focused_element = as_if<Element>(old_focused_area.ptr()))
@@ -4196,41 +4265,71 @@ void Document::set_accessibility_focus_target(GC::Ptr<Element> element)
}
// https://html.spec.whatwg.org/multipage/browsing-the-web.html#the-indicated-part-of-the-document
-Document::IndicatedPart Document::determine_the_indicated_part() const
+// https://wicg.github.io/scroll-to-text-fragment/#invoking-text-directives
+Document::IndicatedPart Document::determine_the_indicated_part()
{
// For an HTML document document, the following processing model must be followed to determine its indicated part:
- // 1. Let fragment be document's URL's fragment.
+ // 1. Let text directives be the document's pending text directives.
+ auto const& text_directives = m_pending_text_directives;
+
+ // 2. If text directives is non-null then:
+ if (text_directives.has_value() && !text_directives->is_empty()) {
+ // 1. Let ranges be a list that is the result of running the invoke text directives steps
+ // with text directives and the document.
+ auto ranges = HTML::invoke_text_directives(*text_directives, *this);
+ m_text_fragment_ranges.clear();
+ m_text_fragment_ranges.extend(ranges);
+
+ // 2. If ranges is non-empty, then:
+ if (!ranges.is_empty()) {
+ // 1. Let firstRange be the first item of ranges.
+ auto first_range = ranges.first();
+
+ // 2. Visually indicate each range in ranges in an implementation-defined way. The
+ // indication must not be observable from author script. See Indicating The Text Match.
+ // NB: The ranges are retained privately and painted in the text-fragment indication pass.
+
+ // 3. Set firstRange as document's indicated part, return.
+ return GC::Ptr<Range> { first_range };
+ }
+
+ // AD-HOC: Do not fall back to an element fragment until parsing has stopped and the final
+ // text search has completed.
+ return static_cast<Element*>(nullptr);
+ }
+
+ // 3. Let fragment be document's URL's fragment.
auto fragment = url().fragment();
- // 2. If fragment is the empty string, then return the special value top of the document.
+ // 4. If fragment is the empty string, then return the special value top of the document.
if (!fragment.has_value() || fragment->is_empty())
return Document::TopOfTheDocument {};
- // 3. Let potentialIndicatedElement be the result of finding a potential indicated element given document and fragment.
+ // 5. Let potentialIndicatedElement be the result of finding a potential indicated element given document and fragment.
auto fragment_as_utf16 = utf16_string_from_url_ascii(*fragment);
auto* potential_indicated_element = find_a_potential_indicated_element(fragment_as_utf16);
- // 4. If potentialIndicatedElement is not null, then return potentialIndicatedElement.
+ // 6. If potentialIndicatedElement is not null, then return potentialIndicatedElement.
if (potential_indicated_element)
return potential_indicated_element;
- // 5. Let fragmentBytes be the result of percent-decoding fragment.
- // 6. Let decodedFragment be the result of running UTF-8 decode without BOM on fragmentBytes.
+ // 7. Let fragmentBytes be the result of percent-decoding fragment.
+ // 8. Let decodedFragment be the result of running UTF-8 decode without BOM on fragmentBytes.
auto decoded_fragment = Utf16String::from_utf8_with_replacement_character(URL::percent_decode(*fragment), Utf16String::WithBOMHandling::No);
- // 7. Set potentialIndicatedElement to the result of finding a potential indicated element given document and decodedFragment.
+ // 9. Set potentialIndicatedElement to the result of finding a potential indicated element given document and decodedFragment.
potential_indicated_element = find_a_potential_indicated_element(decoded_fragment);
- // 8. If potentialIndicatedElement is not null, then return potentialIndicatedElement.
+ // 10. If potentialIndicatedElement is not null, then return potentialIndicatedElement.
if (potential_indicated_element)
return potential_indicated_element;
- // 9. If decodedFragment is an ASCII case-insensitive match for the string top, then return the top of the document.
+ // 11. If decodedFragment is an ASCII case-insensitive match for the string top, then return the top of the document.
if (decoded_fragment.utf16_view().equals_ignoring_ascii_case(u"top"sv))
return Document::TopOfTheDocument {};
- // 10. Return null.
+ // 12. Return null.
return nullptr;
}
@@ -4535,7 +4634,7 @@ void Document::dispatch_events_for_animation_if_necessary(GC::Ref<Animations::An
}
// https://html.spec.whatwg.org/multipage/browsing-the-web.html#scroll-to-the-fragment-identifier
-void Document::scroll_to_the_fragment([[maybe_unused]] bool allow_text_directive_scroll)
+void Document::scroll_to_the_fragment(bool allow_text_directive_scroll)
{
// To scroll to the fragment given a Document document:
@@ -4559,109 +4658,296 @@ void Document::scroll_to_the_fragment([[maybe_unused]] bool allow_text_directive
// 3. Otherwise:
else {
- // 1. Assert: document's indicated part is an element.
- VERIFY(indicated_part.has<Element*>());
+ // 1. Assert: document's indicated part is an element or it is a range.
+ VERIFY(indicated_part.has<Element*>() || indicated_part.has<GC::Ptr<Range>>());
+
+ // 2. Let scrollTarget be document's indicated part.
+ auto scroll_target = indicated_part;
+
+ // 3. Let target be scrollTarget.
+ GC::Ptr<Element> target;
+ if (scroll_target.has<Element*>())
+ target = scroll_target.get<Element*>();
+
+ auto const is_text_directive = scroll_target.has<GC::Ptr<Range>>();
+
+ // 4. If target is a range, then:
+ if (is_text_directive) {
+ // 1. If allow text directive scroll is false, return.
+ if (!allow_text_directive_scroll)
+ return;
+
+ auto range = scroll_target.get<GC::Ptr<Range>>();
+ VERIFY(range);
+
+ // 2. Set target to be the first common ancestor of target's start node and end node.
+ GC::Ptr<Node> target_node = range->common_ancestor_container();
- // 2. Let target be document's indicated part.
- auto target = indicated_part.get<Element*>();
+ // 3. While target is non-null and is not an element, set target to target's parent.
+ while (target_node && !is<Element>(*target_node))
+ target_node = target_node->parent();
+ if (target_node)
+ target = static_cast<Element*>(target_node.ptr());
- // 3. Set document's target element to target.
+ // INTEROP: The first common ancestor can be far larger than the matched passage. Other
+ // engines use the start container's nearest element so that :target, reveal,
+ // and focus effects stay attached to the beginning that is scrolled into view.
+ // https://github.com/WICG/scroll-to-text-fragment/issues/259
+ target_node = range->start_container();
+ while (target_node && !is<Element>(*target_node))
+ target_node = target_node->parent();
+ if (target_node)
+ target = static_cast<Element*>(target_node.ptr());
+ }
+
+ // 5. Assert: target is an element.
+ if (!target)
+ return;
+
+ // 6. Set document's target element to target.
set_target_element(target);
- // FIXME: 4. Run the ancestor revealing algorithm on target.
+ // 7. Run the ancestor details revealing algorithm on target.
+ // 8. Run the ancestor hidden-until-found revealing algorithm on target.
+ //
+ // INTEROP: HTML has since combined those two algorithms into the ancestor revealing
+ // algorithm. Run that current algorithm once so nested details and hidden=until-found
+ // ancestors are revealed in tree order.
+ // https://html.spec.whatwg.org/multipage/interaction.html#ancestor-revealing-algorithm
+ auto run_the_ancestor_revealing_algorithm = [&] {
+ enum class RevealType {
+ UntilFound,
+ Details,
+ };
+
+ // 1. Let ancestorsToReveal be « ».
+ GC::RootVector<GC::Ref<Element>> ancestors_to_reveal;
+ Vector<RevealType> reveal_types;
+
+ // 2. Let ancestor be target.
+ GC::Ptr<Node> ancestor = target;
+
+ // 3. While ancestor has a parent node within the flat tree:
+ while (ancestor && ancestor->parent()) {
+ // 1. If ancestor has a hidden attribute in the Hidden Until Found state, then
+ // append (ancestor, "until-found") to ancestorsToReveal.
+ if (auto* element = as_if<Element>(ancestor.ptr())) {
+ auto const& hidden = element->get_attribute(HTML::AttributeNames::hidden);
+ if (hidden.has_value() && hidden->equals_ignoring_ascii_case(u"until-found"sv)) {
+ ancestors_to_reveal.append(*element);
+ reveal_types.append(RevealType::UntilFound);
+ }
+ }
+
+ // 2. If ancestor is slotted into the second slot of a details element which
+ // does not have an open attribute, then append (ancestor's parent node,
+ // "details") to ancestorsToReveal.
+ auto* parent_element = as_if<Element>(ancestor->parent());
+ if (parent_element
+ && parent_element->namespace_uri() == Namespace::HTML
+ && parent_element->local_name() == HTML::TagNames::details
+ && !parent_element->has_attribute(HTML::AttributeNames::open)) {
+ GC::Ptr<Node> first_summary;
+ for (auto* child = parent_element->first_child(); child; child = child->next_sibling()) {
+ auto* child_element = as_if<Element>(child);
+ if (child_element
+ && child_element->namespace_uri() == Namespace::HTML
+ && child_element->local_name() == HTML::TagNames::summary) {
+ first_summary = child;
+ break;
+ }
+ }
+ if (ancestor != first_summary) {
+ ancestors_to_reveal.append(*parent_element);
+ reveal_types.append(RevealType::Details);
+ }
+ }
+
+ // 3. Set ancestor to the parent node of ancestor within the flat tree.
+ ancestor = ancestor->parent();
+ }
+
+ // 4. For each (ancestorToReveal, revealType) of ancestorsToReveal:
+ for (size_t i = 0; i < ancestors_to_reveal.size(); ++i) {
+ auto& ancestor_to_reveal = ancestors_to_reveal[i];
+ auto reveal_type = reveal_types[i];
+
+ // 1. If ancestorToReveal is not connected, then return.
+ if (!ancestor_to_reveal->is_connected())
+ return;
+
+ // 2. If revealType is "until-found":
+ if (reveal_type == RevealType::UntilFound) {
+ // 1. If ancestorToReveal's hidden attribute is not in the Hidden Until
+ // Found state, then return.
+ auto const& hidden = ancestor_to_reveal->get_attribute(HTML::AttributeNames::hidden);
+ if (!hidden.has_value() || !hidden->equals_ignoring_ascii_case(u"until-found"sv))
+ return;
+
+ // 2. Fire an event named beforematch at ancestorToReveal with the bubbles
+ // attribute initialized to true.
+ ancestor_to_reveal->dispatch_event(Event::create(HTML::relevant_global_object(*ancestor_to_reveal), HTML::EventNames::beforematch, { .bubbles = true }));
+
+ // 3. If ancestorToReveal is not connected, then return.
+ if (!ancestor_to_reveal->is_connected())
+ return;
+
+ // 4. If ancestorToReveal's hidden attribute is not in the Hidden Until
+ // Found state, then return.
+ auto const& hidden_after_event = ancestor_to_reveal->get_attribute(HTML::AttributeNames::hidden);
+ if (!hidden_after_event.has_value() || !hidden_after_event->equals_ignoring_ascii_case(u"until-found"sv))
+ return;
+
+ // 5. Remove the hidden attribute from ancestorToReveal.
+ ancestor_to_reveal->remove_attribute(HTML::AttributeNames::hidden);
+ }
- // 5. Scroll target into view, with behavior set to "auto", block set to "start", and inline set to "nearest". [CSSOMVIEW]
- Element::ScrollIntoViewOptions scroll_options;
- scroll_options.block = Element::ScrollLogicalPosition::Start;
- scroll_options.inline_ = Element::ScrollLogicalPosition::Nearest;
- target->scroll_into_view(scroll_options, nullptr);
+ // 3. Otherwise:
+ else {
+ // 1. Assert: revealType is "details".
+ VERIFY(reveal_type == RevealType::Details);
- // 6. Run the focusing steps for target, with the Document's viewport as the fallback target.
- HTML::run_focusing_steps(target, this);
+ // 2. If ancestorToReveal has an open attribute, then return.
+ if (ancestor_to_reveal->has_attribute(HTML::AttributeNames::open))
+ return;
- // FIXME: 7. Move the sequential focus navigation starting point to target.
+ // 3. Set ancestorToReveal's open attribute to the empty string.
+ ancestor_to_reveal->set_attribute_value(HTML::AttributeNames::open, Utf16String {});
+ }
+ }
+ };
+ run_the_ancestor_revealing_algorithm();
+
+ // AD-HOC: Revealing ancestors changes their layout participation. Refresh layout before
+ // computing the range geometry used for scrolling.
+ if (is_text_directive)
+ update_layout(UpdateLayoutReason::RangeGetClientRects);
+
+ // 9. Let blockPosition be "center" if scrollTarget is a range, "start" otherwise.
+ auto const block_position = scroll_target.has<GC::Ptr<Range>>()
+ ? Bindings::ScrollLogicalPosition::Center
+ : Bindings::ScrollLogicalPosition::Start;
+
+ // 10. Scroll a target into view, with target set to scrollTarget, behavior set to "auto",
+ // block set to blockPosition, and inline set to "nearest".
+ if (is_text_directive) {
+ Layout::ForcedReadScope read { *this };
+ (void)scroll_a_target_into_view(
+ read,
+ ScrollIntoViewTarget { scroll_target.get<GC::Ptr<Range>>().ptr() },
+ Bindings::ScrollBehavior::Auto,
+ block_position,
+ Bindings::ScrollLogicalPosition::Nearest);
+ } else {
+ Bindings::ScrollIntoViewOptions scroll_options;
+ scroll_options.block = block_position;
+ scroll_options.inline_ = Bindings::ScrollLogicalPosition::Nearest;
+ target->scroll_into_view(scroll_options, nullptr);
+ }
+
+ // 11. Run the focusing steps for target, with the Document's viewport as the fallback
+ // target.
+ // NB: Text-fragment focus and the sequential focus navigation starting point are handled
+ // without focusing a matching link in the dedicated text-fragment focus pass.
+ if (!is_text_directive)
+ HTML::run_focusing_steps(target, this);
+
+ // 12. Move the sequential focus navigation starting point to target.
+ move_sequential_focus_navigation_starting_point_to(target);
}
}
// https://html.spec.whatwg.org/multipage/browsing-the-web.html#try-to-scroll-to-the-fragment
void Document::try_to_scroll_to_the_fragment([[maybe_unused]] bool allow_text_directive_scroll)
{
- // FIXME: According to the spec we should only scroll here if document has no parser or parsing has stopped.
- // It should be ok to remove this after we implement navigation events and scrolling will happen in
- // "process scroll behavior".
- // To try to scroll to the fragment for a Document document, perform the following steps in parallel:
- // 1. Wait for an implementation-defined amount of time. (This is intended to allow the user agent to
- // optimize the user experience in the face of performance concerns.)
- // 2. Queue a global task on the navigation and traversal task source given document's relevant global
- // object to run these steps:
- // 1. If document has no parser, or its parser has stopped parsing, or the user agent has reason to
- // believe the user is no longer interested in scrolling to the fragment, then abort these steps.
- // 2. Scroll to the fragment given document.
- // 3. If document's indicated part is still null, then try to scroll to the fragment for document.
-
- scroll_to_the_fragment();
-}
-
-// https://wicg.github.io/scroll-to-text-fragment/#check-if-a-text-directive-can-be-scrolled
-bool Document::check_if_a_text_directive_can_be_scrolled(Optional<URL::Origin> const& initiator_origin, Optional<HTML::UserNavigationInvolvement> user_involvement)
-{
- // 1. If document's pending text directives field is null or empty, return false.
- if (!m_pending_text_directives.has_value() || m_pending_text_directives->is_empty())
- return false;
+ m_pending_text_directive_scroll_allowed = allow_text_directive_scroll;
- // 2. Let is user involved be true if document's text directive user activation is true, or user involvement is
- // one of "activation" or "browser UI"; false otherwise.
- auto const is_user_involved = m_text_directive_user_activation
- || user_involvement == HTML::UserNavigationInvolvement::Activation
- || user_involvement == HTML::UserNavigationInvolvement::BrowserUI;
+ // AD-HOC: The implementation-defined wait and queued navigation task from this algorithm are
+ // supplied by the parser-progress, DOMContentLoaded, and load-completion lifecycle callers.
- // 3. Set document's text directive user activation to false.
- m_text_directive_user_activation = false;
-
- // 4. If document's content type is not a text directive allowing MIME type, return false.
- if (m_content_type != "text/html"_utf16_fly_string && m_content_type != "text/plain"_utf16_fly_string)
- return false;
+ // 1. If the user agent has reason to believe the user is no longer interested in scrolling to
+ // the fragment, then:
+ if (!is_fully_active()) {
+ // 1. Set pending text directives to null.
+ clear_pending_text_directives();
- // 5. If user involvement is "browser UI", return true.
- if (user_involvement == HTML::UserNavigationInvolvement::BrowserUI)
- return true;
+ // 2. Abort these steps.
+ return;
+ }
- // 6. If is user involved is false, return false.
- if (!is_user_involved)
- return false;
+ // AD-HOC: Once a directive has matched, parser-progress retries only need to correct the
+ // range's position after layout shifts. The DOMContentLoaded and load-completion passes still
+ // repeat the search so script-driven changes to the matching text are observed.
+ if (!m_text_fragment_ranges.is_empty()) {
+ if (allow_text_directive_scroll) {
+ update_layout(UpdateLayoutReason::RangeGetClientRects);
+ Layout::ForcedReadScope read { *this };
+ (void)scroll_a_target_into_view(
+ read,
+ ScrollIntoViewTarget { m_text_fragment_ranges.first().ptr() },
+ Bindings::ScrollBehavior::Auto,
+ Bindings::ScrollLogicalPosition::Center,
+ Bindings::ScrollLogicalPosition::Nearest);
+ }
+ } else {
+ scroll_to_the_fragment(allow_text_directive_scroll);
+ }
- // 7. If document's node navigable has a parent, return false.
- if (!navigable() || navigable()->parent())
- return false;
+ // AD-HOC: Ordinary element fragments retain Ladybird's existing eager attempt and parser-end
+ // retry. The additional lifecycle retries are only needed when there is unmatched text to
+ // find.
+ if (!m_pending_text_directives.has_value() || m_pending_text_directives->is_empty())
+ return;
+ if (!m_text_fragment_ranges.is_empty()) {
+ // AD-HOC: While a document is still loading, retain a successful directive so the parser's
+ // load-completion pass can correct layout shifts in the absence of CSS scroll anchoring.
+ // https://drafts.csswg.org/css-scroll-anchoring/
+ if (is_completely_loaded()) {
+ clear_pending_text_directives();
+
+ // https://wicg.github.io/scroll-to-text-fragment/#scroll-on-navigation
+ // If a UA chooses not to scroll automatically, it must scroll a fallback element-id
+ // into view, if provided, regardless of whether a text fragment was matched.
+ if (!allow_text_directive_scroll)
+ scroll_to_the_fragment();
+ }
+ return;
+ }
- // 8. If initiator origin is non-null and document's origin is same origin with initiator origin, return true.
- if (initiator_origin.has_value() && origin().is_same_origin(*initiator_origin))
- return true;
+ // A same-document navigation in a completely loaded document has no further parser or load
+ // lifecycle milestones at which to retry. This is therefore its final search.
+ if (!is_completely_loaded())
+ return;
- // 9. If document's browsing context's browsing context group's browsing context set has length 1, return true.
- if (!browsing_context_group_has_multiple_contexts())
- return true;
+ clear_pending_text_directives();
- // 10. Otherwise, return false.
- return false;
+ // https://wicg.github.io/scroll-to-text-fragment/#scroll-on-navigation
+ // If a UA chooses not to scroll automatically, it must scroll a fallback element-id into
+ // view, if provided, regardless of whether a text fragment was matched.
+ scroll_to_the_fragment();
}
-bool Document::browsing_context_group_has_multiple_contexts() const
+void Document::schedule_text_fragment_search_after_parser_progress(Badge<HTML::HTMLParser>)
{
- if (m_browsing_context_group_has_remote_contexts)
- return true;
- auto local_navigable = navigable();
- if (!local_navigable)
- return true;
- auto group_id = local_navigable->browsing_context_group_id();
- if (!group_id.has_value())
- return true;
- size_t matching_navigable_count = 0;
- for (auto& candidate : HTML::all_local_navigables()) {
- if (candidate->browsing_context_group_id() == group_id && ++matching_navigable_count > 1)
- return true;
- }
- return false;
+ // AD-HOC: Retry unmatched text directives when the parser yields after making progress, rather
+ // than polling on a timer. Coalesce parser runs until the queued task observes the resulting
+ // DOM, mirroring the lifecycle-driven approach used by other engines.
+ if (m_text_fragment_parser_progress_search_pending
+ || !m_pending_text_directives.has_value()
+ || m_pending_text_directives->is_empty()
+ || policy_container()->force_load_at_top)
+ return;
+
+ m_text_fragment_parser_progress_search_pending = true;
+ HTML::queue_global_task(HTML::Task::Source::NavigationAndTraversal, relevant_global_object(*this), GC::create_function(heap(), [document = GC::Ref { *this }] {
+ document->m_text_fragment_parser_progress_search_pending = false;
+ if (!document->m_pending_text_directives.has_value()
+ || document->m_pending_text_directives->is_empty()
+ || document->policy_container()->force_load_at_top)
+ return;
+
+ document->try_to_scroll_to_the_fragment(document->m_pending_text_directive_scroll_allowed);
+ }));
}
// https://drafts.csswg.org/cssom-view-1/#scroll-to-the-beginning-of-the-document
@@ -7343,6 +7629,7 @@ void Document::update_for_history_step_application(NonnullRefPtr<HTML::SessionHi
auto const& fragment_directive = entry->directive_state()->value();
// 2. Set document's pending text directives to the result of parsing fragment directive.
+ m_text_fragment_ranges.clear();
m_pending_text_directives = fragment_directive.has_value()
? Optional<Vector<HTML::TextDirective>> { HTML::parse_the_fragment_directive(*fragment_directive) }
: Optional<Vector<HTML::TextDirective>> { Vector<HTML::TextDirective> {} };
diff --git a/Libraries/LibWeb/DOM/Document.h b/Libraries/LibWeb/DOM/Document.h
index c57cae4ffaf..62b1575a5cf 100644
--- a/Libraries/LibWeb/DOM/Document.h
+++ b/Libraries/LibWeb/DOM/Document.h
@@ -44,6 +44,9 @@
#include <LibWeb/DOM/ShadowRoot.h>
#include <LibWeb/DOM/ViewportClient.h>
#include <LibWeb/Export.h>
+#include <LibWeb/Forward.h>
+#include <LibWeb/Fullscreen/FullscreenRequestType.h>
+#include <LibWeb/HTML/CrossOrigin/OpenerPolicy.h>
#include <LibWeb/HTML/DocumentReadyState.h>
#include <LibWeb/HTML/Focus.h>
#include <LibWeb/HTML/GlobalEventHandlers.h>
@@ -753,6 +756,10 @@ public:
};
void set_focused_area(GC::Ptr<Node>, InvalidateFocusPseudoClasses = InvalidateFocusPseudoClasses::Yes);
+ // https://html.spec.whatwg.org/multipage/interaction.html#sequential-focus-navigation-starting-point
+ GC::Ptr<Node> sequential_focus_navigation_starting_point() { return m_sequential_focus_navigation_starting_point; }
+ void move_sequential_focus_navigation_starting_point_to(GC::Ptr<Node> node) { m_sequential_focus_navigation_starting_point = node; }
+
HTML::FocusTrigger last_focus_trigger() const { return m_last_focus_trigger; }
void set_last_focus_trigger(HTML::FocusTrigger trigger) { m_last_focus_trigger = trigger; }
@@ -770,6 +777,7 @@ public:
void set_accessibility_focus_target(GC::Ptr<Element>);
void try_to_scroll_to_the_fragment(bool allow_text_directive_scroll = false);
+ void schedule_text_fragment_search_after_parser_progress(Badge<HTML::HTMLParser>);
void scroll_to_the_fragment(bool allow_text_directive_scroll = false);
void scroll_to_the_beginning_of_the_document();
@@ -825,7 +833,14 @@ public:
// https://wicg.github.io/scroll-to-text-fragment/#feature-detectability
GC::Ref<FragmentDirective> fragment_directive();
Optional<Vector<HTML::TextDirective>> const& pending_text_directives() const { return m_pending_text_directives; }
- void set_pending_text_directives(Optional<Vector<HTML::TextDirective>> directives) { m_pending_text_directives = move(directives); }
+ void set_pending_text_directives(Optional<Vector<HTML::TextDirective>> directives)
+ {
+ m_text_fragment_ranges.clear();
+ m_pending_text_directives = move(directives);
+ }
+ void clear_pending_text_directives() { m_pending_text_directives.clear(); }
+ ReadonlySpan<GC::Ref<Range>> text_fragment_ranges() const { return m_text_fragment_ranges; }
+ bool pending_text_directive_scroll_allowed() const { return m_pending_text_directive_scroll_allowed; }
bool check_if_a_text_directive_can_be_scrolled(Optional<URL::Origin> const&, Optional<HTML::UserNavigationInvolvement>);
bool text_directive_user_activation() const { return m_text_directive_user_activation; }
void set_text_directive_user_activation(bool value) { m_text_directive_user_activation = value; }
@@ -1139,8 +1154,8 @@ public:
void shared_declarative_refresh_steps(Utf16View input, GC::Ptr<HTML::HTMLMetaElement const> meta_element = nullptr);
struct TopOfTheDocument { };
- using IndicatedPart = Variant<Element*, TopOfTheDocument>;
- IndicatedPart determine_the_indicated_part() const;
+ using IndicatedPart = Variant<Element*, GC::Ptr<Range>, TopOfTheDocument>;
+ IndicatedPart determine_the_indicated_part();
u32 unload_counter() const { return m_unload_counter; }
@@ -1847,6 +1862,9 @@ private:
// https://html.spec.whatwg.org/multipage/interaction.html#focused-area-of-the-document
GC::Ptr<Node> m_focused_area;
+ // https://html.spec.whatwg.org/multipage/interaction.html#sequential-focus-navigation-starting-point
+ GC::Ptr<Node> m_sequential_focus_navigation_starting_point;
+
HTML::FocusTrigger m_last_focus_trigger { HTML::FocusTrigger::Other };
GC::Ptr<Element> m_active_element;
@@ -1880,6 +1898,12 @@ private:
GC::Ptr<DOMImplementation> m_implementation;
GC::Ptr<FragmentDirective> m_fragment_directive;
Optional<Vector<HTML::TextDirective>> m_pending_text_directives;
+ Vector<GC::Ref<Range>> m_text_fragment_ranges;
+ bool m_pending_text_directive_scroll_allowed { false };
+ bool m_text_fragment_parser_progress_search_pending { false };
+
+ // https://wicg.github.io/scroll-to-text-fragment/#restricting-the-text-fragment
+ // Each Document has a text directive user activation, which is a boolean, initially false.
bool m_text_directive_user_activation { false };
bool m_browsing_context_group_has_remote_contexts { false };
GC::Ptr<HTML::HTMLScriptElement> m_current_script;
diff --git a/Libraries/LibWeb/DOM/Element.cpp b/Libraries/LibWeb/DOM/Element.cpp
index 8f14dd390f9..a7508e270c9 100644
--- a/Libraries/LibWeb/DOM/Element.cpp
+++ b/Libraries/LibWeb/DOM/Element.cpp
@@ -4577,7 +4577,12 @@ void scroll_a_target_into_view(Layout::BegunRead const& read, ScrollIntoViewTarg
return element->get_bounding_client_rect();
},
[](Range* range) {
- auto rect = range->get_bounding_client_rect();
+ // AD-HOC: Text-fragment scrolling centers the beginning of a match. Using the union
+ // of every client rect can put the beginning of a long passage outside the viewport.
+ auto rects = range->get_client_rects();
+ auto const* rect = rects->length() > 0 ? rects->item(0) : nullptr;
+ if (!rect)
+ return CSSPixelRect {};
return CSSPixelRect {
CSSPixels::nearest_value_for(rect->x()),
CSSPixels::nearest_value_for(rect->y()),
diff --git a/Libraries/LibWeb/DOM/Range.cpp b/Libraries/LibWeb/DOM/Range.cpp
index 45f3b5c0048..f40f5dd542d 100644
--- a/Libraries/LibWeb/DOM/Range.cpp
+++ b/Libraries/LibWeb/DOM/Range.cpp
@@ -1298,9 +1298,9 @@ GC::Ref<Geometry::DOMRectList> Range::get_client_rects()
return Geometry::DOMRectList::create({});
auto& document = start_container()->document();
- Layout::ForcedReadScope read { document };
document.update_layout(DOM::UpdateLayoutReason::RangeGetClientRects);
-
+ document.update_paint_and_hit_testing_properties_if_needed();
+ Layout::ForcedReadScope read { document };
Vector<GC::Root<Geometry::DOMRect>> rects;
Optional<Compositing::AccumulatedVisualContextTree> visual_context_tree;
auto rect_to_viewport_transform = Painting::identity_rect_to_viewport_transform();
diff --git a/Libraries/LibWeb/HTML/HistoryExecutor.cpp b/Libraries/LibWeb/HTML/HistoryExecutor.cpp
index b3c860c1195..9659e85e56f 100644
--- a/Libraries/LibWeb/HTML/HistoryExecutor.cpp
+++ b/Libraries/LibWeb/HTML/HistoryExecutor.cpp
@@ -495,6 +495,7 @@ bool HistoryExecutor::run_changing_navigable_history_step_job_impl(ChangingNavig
}
auto output = heap().allocate<PopulateSessionHistoryEntryDocumentOutput>();
output->redirected_url = move(result.redirected_url);
+ output->redirect_replaced_fragment = result.redirect_replaced_fragment;
output->classic_history_api_state = move(result.classic_history_api_state);
output->resource_cleared = result.resource_cleared;
output->inline_content_origin = move(result.inline_content_origin);
diff --git a/Libraries/LibWeb/HTML/LocalNavigable.cpp b/Libraries/LibWeb/HTML/LocalNavigable.cpp
index 0c9da4717b1..68f6a4646f7 100644
--- a/Libraries/LibWeb/HTML/LocalNavigable.cpp
+++ b/Libraries/LibWeb/HTML/LocalNavigable.cpp
@@ -184,6 +184,7 @@ struct NavigationParamsFetchStateHolder : public JS::Cell {
// Accumulated redirect output
Optional<URL::URL> redirected_url;
+ bool redirect_replaced_fragment { false };
Optional<StorageSerializationRecord> redirect_classic_history_api_state;
RefPtr<DocumentState> replacement_document_state;
bool resource_cleared = false;
@@ -222,6 +223,7 @@ public:
// Redirect mutations (only set by fetch path)
Optional<URL::URL> redirected_url;
+ bool redirect_replaced_fragment { false };
Optional<StorageSerializationRecord> classic_history_api_state;
RefPtr<DocumentState> replacement_document_state;
bool resource_cleared = false;
@@ -594,8 +596,22 @@ void PopulateSessionHistoryEntryDocumentOutput::apply_to(NonnullRefPtr<SessionHi
{
if (replacement_document_state)
entry->set_document_state(replacement_document_state);
- if (redirected_url.has_value())
- entry->set_url(redirected_url.value());
+ if (redirected_url.has_value()) {
+ // https://wicg.github.io/scroll-to-text-fragment/#extracting-the-fragment-directive
+ // https://html.spec.whatwg.org/multipage/browsing-the-web.html#create-navigation-params-by-fetching
+ // Let fragment directive be the result of running remove the fragment directive on locationURL.
+ auto fragment_directive = remove_the_fragment_directive(*redirected_url);
+
+ // Set entry's URL to locationURL.
+ entry->set_url(redirected_url.release_value());
+
+ // Set entry's directive state's value to fragment directive.
+ // NOTE: A redirect location without a fragment inherits the request URL's fragment. The
+ // fragment directive was already removed from that URL and stored in the directive state,
+ // so leaving the state unchanged performs that inheritance.
+ if (fragment_directive.has_value() || redirect_replaced_fragment)
+ entry->directive_state()->set_value(move(fragment_directive));
+ }
if (classic_history_api_state.has_value())
entry->set_classic_history_api_state(classic_history_api_state.release_value());
if (resource_cleared)
@@ -930,6 +946,7 @@ void LocalNavigable::continue_navigation_at_population(NavigationPopulationReque
auto output = navigable->heap().allocate<PopulateSessionHistoryEntryDocumentOutput>();
output->redirected_url = move(result.redirected_url);
+ output->redirect_replaced_fragment = result.redirect_replaced_fragment;
output->classic_history_api_state = move(result.classic_history_api_state);
output->resource_cleared = result.resource_cleared;
output->inline_content_origin = move(result.inline_content_origin);
@@ -2425,6 +2442,12 @@ static void perform_navigation_params_fetch(JS::Realm& realm, GC::Ref<Navigation
// This is because we care about the same-originness of the embedded content against the parent context, not the navigation source.
// 14. Set locationURL to response's location URL given currentURL's fragment.
+ auto location_url_without_an_inherited_fragment = state_holder->response->location_url({});
+ if (!location_url_without_an_inherited_fragment.is_error()
+ && location_url_without_an_inherited_fragment.value().has_value()
+ && location_url_without_an_inherited_fragment.value()->fragment().has_value()) {
+ state_holder->redirect_replaced_fragment = true;
+ }
state_holder->location_url = state_holder->response->location_url(state_holder->current_url.fragment());
// 15. If locationURL is failure or null, then break.
@@ -2482,6 +2505,8 @@ static void perform_navigation_params_fetch(JS::Realm& realm, GC::Ref<Navigation
});
}
+// https://wicg.github.io/scroll-to-text-fragment/#extracting-the-fragment-directive
+// https://wicg.github.io/scroll-to-text-fragment/#restricting-the-text-fragment
// https://html.spec.whatwg.org/multipage/browsing-the-web.html#create-navigation-params-by-fetching
static void create_navigation_params_by_fetching(
URL::URL url,
@@ -2715,6 +2740,7 @@ static void create_navigation_params_by_fetching(
perform_navigation_params_fetch(realm, state_holder, completion_steps, GC::create_function(realm.heap(), [&realm, state_holder, user_involvement, completion_steps] {
auto result = realm.heap().allocate<InternalNavigationResult>();
result->redirected_url = move(state_holder->redirected_url);
+ result->redirect_replaced_fragment = state_holder->redirect_replaced_fragment;
result->classic_history_api_state = move(state_holder->redirect_classic_history_api_state);
result->replacement_document_state = state_holder->replacement_document_state;
result->resource_cleared = state_holder->resource_cleared;
@@ -2996,6 +3022,7 @@ void LocalNavigable::populate_session_history_entry_document(
// NB: result's redirect fields are moved into output here; population must read them from output rather than
// the moved-from result.
output->redirected_url = move(result->redirected_url);
+ output->redirect_replaced_fragment = result->redirect_replaced_fragment;
output->classic_history_api_state = move(result->classic_history_api_state);
output->replacement_document_state = result->replacement_document_state;
output->resource_cleared = result->resource_cleared;
@@ -3285,6 +3312,7 @@ void LocalNavigable::create_navigation_params_for_navigation(NavigationPopulatio
auto population_result = NavigationPopulationResult {
.navigation_params = move(navigation_params),
.redirected_url = move(result->redirected_url),
+ .redirect_replaced_fragment = result->redirect_replaced_fragment,
.classic_history_api_state = move(result->classic_history_api_state),
.replacement_document_state = move(replacement_document_state),
.resource_cleared = result->resource_cleared,
@@ -3900,6 +3928,13 @@ bool LocalNavigable::resume_navigation_params_creation(Utf16String const& naviga
// https://html.spec.whatwg.org/multipage/browsing-the-web.html#navigate-fragid
void LocalNavigable::navigate_to_a_fragment(URL::URL const& url, HistoryHandlingBehavior history_handling, UserNavigationInvolvement user_involvement, GC::Ptr<DOM::Element> source_element, Optional<StorageSerializationRecord> navigation_api_state, Utf16String navigation_id, GC::Ptr<NavigationAPIMethodTracker> api_method_tracker, Optional<URL::Origin> initiator_origin)
{
+ // https://wicg.github.io/scroll-to-text-fragment/#extracting-the-fragment-directive
+ auto directive_state = active_session_history_entry()->directive_state();
+ auto stripped_url = url;
+ auto fragment_directive = remove_the_fragment_directive(stripped_url);
+ if (fragment_directive.has_value())
+ directive_state = DirectiveState::create(page().client().allocate_cross_process_id(), move(fragment_directive));
+
// 1. Let navigation be navigable's active window's navigation API.
VERIFY(active_window());
auto navigation = active_window()->navigation();
@@ -3913,7 +3948,7 @@ void LocalNavigable::navigate_to_a_fragment(URL::URL const& url, HistoryHandling
// to sourceElement, destinationURL set to url, and navigationAPIState set to destinationNavigationAPIState.
// AD-HOC: Also pass apiMethodTracker, see the caller.
auto navigation_type = history_handling == HistoryHandlingBehavior::Push ? Bindings::NavigationType::Push : Bindings::NavigationType::Replace;
- bool const continue_ = navigation->fire_a_push_replace_reload_navigate_event(navigation_type, url, true, user_involvement, source_element, {}, destination_navigation_api_state, {}, api_method_tracker);
+ bool const continue_ = navigation->fire_a_push_replace_reload_navigate_event(navigation_type, stripped_url, true, user_involvement, source_element, {}, destination_navigation_api_state, {}, api_method_tracker);
// 5. If continue is false, then return.
if (!continue_)
@@ -3928,8 +3963,8 @@ void LocalNavigable::navigate_to_a_fragment(URL::URL const& url, HistoryHandling
// document state: navigable's active session history entry's document state
// navigation API state: destinationNavigationAPIState
// scroll restoration mode: navigable's active session history entry's scroll restoration mode
- auto history_entry = SessionHistoryEntry::create();
- history_entry->set_url(url);
+ auto history_entry = SessionHistoryEntry::create(directive_state);
+ history_entry->set_url(stripped_url);
history_entry->set_document_state(active_entry->document_state());
history_entry->set_navigation_api_state(destination_navigation_api_state);
history_entry->set_scroll_restoration_mode(active_entry->scroll_restoration_mode());
@@ -3964,7 +3999,7 @@ void LocalNavigable::navigate_to_a_fragment(URL::URL const& url, HistoryHandling
}
// 13. Set navigable's active document's URL to url.
- active_document()->set_url(url);
+ active_document()->set_url(stripped_url);
// 14. Set navigable's active session history entry to historyEntry.
m_active_session_history_entry = history_entry;
@@ -3988,12 +4023,35 @@ void LocalNavigable::navigate_to_a_fragment(URL::URL const& url, HistoryHandling
// scriptHistoryIndex, scriptHistoryLength, and historyHandling.
active_document()->update_for_history_step_application(*history_entry, true, script_history_length, script_history_index, navigation_type);
- // 16. Scroll to the fragment given navigable's active document.
- auto const allow_text_directive_scroll = active_document()->check_if_a_text_directive_can_be_scrolled(initiator_origin, user_involvement);
- active_document()->scroll_to_the_fragment(allow_text_directive_scroll);
+ // https://wicg.github.io/scroll-to-text-fragment/#restricting-the-text-fragment
+ // 18. Let allow text directive scroll be the result of checking if a text directive can be scrolled, given
+ // navigable's active document, initiator origin, and user involvement.
+ auto allow_text_directive_scroll = active_document()->check_if_a_text_directive_can_be_scrolled(initiator_origin, user_involvement);
+
+ // 19. Scroll to the fragment given navigable's active document, and allow text directive scroll.
+ if (active_document()->parser() && !active_document()->parser()->stopped()) {
+ // AD-HOC: A same-document navigation can run from a parser-inserted script before the
+ // directive's target has been parsed. In that case, use the parser-aware retry lifecycle
+ // also used for a newly-created Document.
+ active_document()->try_to_scroll_to_the_fragment(allow_text_directive_scroll);
+ } else {
+ active_document()->scroll_to_the_fragment(allow_text_directive_scroll);
+ // https://wicg.github.io/scroll-to-text-fragment/#invoking-text-directives
+ // 20. Set navigable's active document's pending text directives to null.
+ auto const text_fragment_was_found = !active_document()->text_fragment_ranges().is_empty();
+ active_document()->clear_pending_text_directives();
+
+ // https://wicg.github.io/scroll-to-text-fragment/#scroll-on-navigation
+ // If a UA chooses not to scroll automatically, it must scroll a fallback element-id into
+ // view, if provided, regardless of whether a text fragment was matched.
+ if (!text_fragment_was_found || !allow_text_directive_scroll)
+ active_document()->scroll_to_the_fragment();
+ }
+
+ // 21. Let traversable be navigable's traversable navigable.
+ auto traversable = traversable_navigable();
- // 17. Let traversable be navigable's traversable navigable.
- // 18. Append the following session history synchronous navigation steps involving navigable to traversable:
+ // 22. Append the following session history synchronous navigation steps involving navigable to traversable:
// 1. Finalize a same-document navigation given traversable, navigable, historyEntry, entryToReplace,
// historyHandling, and userInvolvement.
page().history_executor().finalize_same_document_navigation(*this, history_entry, entry_to_replace, history_handling, user_involvement, move(previous_entry_persisted_state));
diff --git a/Libraries/LibWeb/HTML/LocalNavigable.h b/Libraries/LibWeb/HTML/LocalNavigable.h
index 23f10ca28e2..c7654a97b60 100644
--- a/Libraries/LibWeb/HTML/LocalNavigable.h
+++ b/Libraries/LibWeb/HTML/LocalNavigable.h
@@ -701,6 +701,7 @@ public:
bool download_handled = false;
Optional<URL::URL> redirected_url;
+ bool redirect_replaced_fragment { false };
Optional<StorageSerializationRecord> classic_history_api_state;
RefPtr<DocumentState> replacement_document_state;
bool resource_cleared = false;
diff --git a/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp b/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp
index 99160a0a835..ed6b3080504 100644
--- a/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp
+++ b/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp
@@ -24,6 +24,7 @@
#include <LibWeb/DOM/Comment.h>
#include <LibWeb/DOM/Document.h>
#include <LibWeb/DOM/DocumentFragment.h>
+#include <LibWeb/DOM/DocumentLoadEventDelayer.h>
#include <LibWeb/DOM/DocumentType.h>
#include <LibWeb/DOM/Element.h>
#include <LibWeb/DOM/ElementFactory.h>
@@ -302,6 +303,9 @@ void HTMLParser::run(HTMLTokenizer::StopAtInsertionPoint stop_at_insertion_point
}
m_tokenizer.parser_did_run({});
+
+ if (m_document->parser().ptr() == this)
+ m_document->schedule_text_fragment_search_after_parser_progress({});
}
void HTMLParser::run(URL::URL const& url, HTMLTokenizer::StopAtInsertionPoint stop_at_insertion_point)
@@ -819,12 +823,16 @@ void HTMLParserEndState::advance_to_dom_content_loaded_phase()
// But a script that ran in step 5 above may have scrolled the page already,
// so only do this if there is an actual fragment to avoid resetting the scroll position unexpectedly.
// Spec bug: https://github.com/whatwg/html/issues/10914
- auto indicated_part = m_document->determine_the_indicated_part();
// https://wicg.github.io/scroll-to-text-fragment/#restricting-scroll-on-load
- // If scrollingBlockedInNewDocument is false, try to scroll to the fragment for document.
- if (!m_document->policy_container()->force_load_at_top
- && indicated_part.has<DOM::Element*>() && indicated_part.get<DOM::Element*>() != nullptr) {
- m_document->scroll_to_the_fragment();
+ // https://wicg.github.io/scroll-to-text-fragment/#invoking-text-directives
+ if (!m_document->policy_container()->force_load_at_top) {
+ if (m_document->pending_text_directives().has_value() && !m_document->pending_text_directives()->is_empty()) {
+ m_document->scroll_to_the_fragment(m_document->pending_text_directive_scroll_allowed());
+ } else {
+ auto indicated_part = m_document->determine_the_indicated_part();
+ if (indicated_part.has<DOM::Element*>() && indicated_part.get<DOM::Element*>() != nullptr)
+ m_document->scroll_to_the_fragment();
+ }
}
m_phase = Phase::WaitingForDOMContentLoaded;
@@ -843,6 +851,18 @@ void HTMLParserEndState::advance_to_dom_content_loaded_phase()
content_loaded_event->set_bubbles(true);
document->dispatch_event(content_loaded_event);
+ // https://wicg.github.io/scroll-to-text-fragment/#invoking-text-directives
+ // If the document has no parser, or its parser has stopped parsing, then:
+ if (document->pending_text_directives().has_value() && !document->pending_text_directives()->is_empty()) {
+ auto const scrolling_blocked_in_new_document = document->policy_container()->force_load_at_top;
+ if (!scrolling_blocked_in_new_document)
+ document->scroll_to_the_fragment(document->pending_text_directive_scroll_allowed());
+
+ // AD-HOC: Retain unmatched directives through the rest of the loading lifecycle. A
+ // load handler or load-delaying resource can make additional searchable content
+ // available, and the load-completion pass below performs the final search.
+ }
+
// 3. Set the Document's load timing info's DOM content loaded event end time to the current high resolution time given the Document's relevant global object.
document->load_timing_info().dom_content_loaded_event_end_time = HighResolutionTime::current_high_resolution_time(relevant_global_object(*document));
@@ -874,10 +894,28 @@ void HTMLParserEndState::complete()
// parser mark the replacement document ready for post-load tasks.
if (parser_was_replaced(document, parser, parser_generation))
return;
+ // NB: Step 8 can stop spinning and queue this task before an already-queued task reopens a descendant document.
+ // Recheck its condition here and resume waiting using the same parser end state.
+ // INTEROP: Blink and WebKit recheck descendant completeness at their final load-completion gate. Gecko's
+ // document loader likewise remains busy while a child loader is waiting to complete.
+ if (document->is_fully_active() && document->anything_is_delaying_the_load_event()) {
+ state->m_phase = Phase::WaitingForLoadEventDelay;
+ state->schedule_progress_check();
+ return;
+ }
state->m_timeout->stop();
document->set_html_parser_end_state(nullptr);
+ // 11. The Document is now ready for post-load tasks.
+ // NB: The spec sets this synchronously after queueing this task, and relies on "spin the event loop"
+ // continuations being queued tasks to keep an ancestor document's load event behind this document's own
+ // load event and its container's load event. Our parser end state machine checks its progress from
+ // deferred invocations, which run ahead of queued tasks, so flip readiness inside this task instead;
+ // an ancestor then cannot complete until this task (and everything it queues) is already in the queue.
+ // WebKit and Blink time their equivalent flag the same way.
+ document->set_ready_for_post_load_tasks(true);
+
// 1. Update the current document readiness to "complete".
document->update_readiness(HTML::DocumentReadyState::Complete);
@@ -908,6 +946,10 @@ void HTMLParserEndState::complete()
// 5. Fire an event named load at window, with legacy target override flag set.
// FIXME: The legacy target override flag is currently set by a virtual override of dispatch_event()
// We should reorganize this so that the flag appears explicitly here instead.
+ // Keep the container's load event delayed until this event dispatch completes. Load handlers can start new
+ // resources, and a remote container must not observe a gap between the document becoming ready and those
+ // resources beginning to delay its load event.
+ DOM::DocumentLoadEventDelayer load_event_delayer(*document);
window.dispatch_event(DOM::Event::create(
HTML::EventNames::load,
HighResolutionTime::current_high_resolution_time(relevant_global_object(window))));
@@ -917,6 +959,32 @@ void HTMLParserEndState::complete()
if (document->parser_generation() != parser_generation)
return;
+ // AD-HOC: Perform the final lifecycle-driven text-fragment search after all
+ // load-event-delaying resources have settled and the load event has run. This also
+ // observes content added by a load handler and corrects layout shifts in the absence of
+ // CSS scroll anchoring.
+ // https://drafts.csswg.org/css-scroll-anchoring/
+ if (document->pending_text_directives().has_value() && !document->pending_text_directives()->is_empty()) {
+ auto const scrolling_blocked_in_new_document = document->policy_container()->force_load_at_top;
+ if (!scrolling_blocked_in_new_document)
+ document->scroll_to_the_fragment(document->pending_text_directive_scroll_allowed());
+
+ auto const text_fragment_was_found = !document->text_fragment_ranges().is_empty();
+
+ // https://wicg.github.io/scroll-to-text-fragment/#invoking-text-directives
+ // 1. If pending text directives is not null, then:
+ // 1. Set pending text directives to null.
+ document->clear_pending_text_directives();
+
+ if (!scrolling_blocked_in_new_document
+ && (!text_fragment_was_found || !document->pending_text_directive_scroll_allowed())) {
+ // https://wicg.github.io/scroll-to-text-fragment/#scroll-on-navigation
+ // If a UA chooses not to scroll automatically, it must scroll a fallback element-id
+ // into view, if provided, regardless of whether a text fragment was matched.
+ document->scroll_to_the_fragment();
+ }
+ }
+
// FIXME: 6. Invoke WebDriver BiDi load complete with the Document's browsing context, and a new WebDriver BiDi navigation status whose id is the Document object's navigation id, status is "complete", and url is the Document object's URL.
// FIXME: 7. Set the Document object's navigation id to null.
@@ -938,9 +1006,6 @@ void HTMLParserEndState::complete()
if (document->parser_generation() != parser_generation)
return;
- // 11. The Document is now ready for post-load tasks.
- document->set_ready_for_post_load_tasks(true);
-
// 12. Completely finish loading the Document.
document->completely_finish_loading();
diff --git a/Libraries/LibWeb/HTML/RemoteNavigable.cpp b/Libraries/LibWeb/HTML/RemoteNavigable.cpp
index bc1d8a870e4..084d1699488 100644
--- a/Libraries/LibWeb/HTML/RemoteNavigable.cpp
+++ b/Libraries/LibWeb/HTML/RemoteNavigable.cpp
@@ -183,7 +183,7 @@ void RemoteNavigable::set_replicated_state(ReplicatedNavigableState state)
container->publish_dom_paint_facts();
container->set_needs_repaint();
}
- if (was_delaying_the_load_event_of_its_container && !m_replicated_state.delays_the_load_event_of_its_container)
+ if (was_delaying_the_load_event_of_its_container != m_replicated_state.delays_the_load_event_of_its_container)
container->document().schedule_html_parser_end_check();
}
diff --git a/Libraries/LibWeb/HTML/TextDirective.cpp b/Libraries/LibWeb/HTML/TextDirective.cpp
index f9dceace33f..76bc86158ef 100644
--- a/Libraries/LibWeb/HTML/TextDirective.cpp
+++ b/Libraries/LibWeb/HTML/TextDirective.cpp
@@ -104,7 +104,9 @@ Optional<TextDirective> parse_a_text_directive(StringView text_directive_value)
tokens.remove(0);
// 3. If prefix is the empty string or contains any instances of U+002D (-), return null.
- if (prefix->is_empty() || prefix->contains('-'))
+ // AD-HOC: Current WPT coverage and other engines allow U+002D inside a term. It is only invalid as the first
+ // or last code point of a token.
+ if (prefix->is_empty() || prefix->starts_with('-'))
return {};
// 4. If tokens is empty, return null.
@@ -121,7 +123,9 @@ Optional<TextDirective> parse_a_text_directive(StringView text_directive_value)
tokens.take_last();
// 3. If suffix is the empty string or contains any instances of U+002D (-), return null.
- if (suffix->is_empty() || suffix->contains('-'))
+ // AD-HOC: Current WPT coverage and other engines allow U+002D inside a term. It is only invalid as the first
+ // or last code point of a token.
+ if (suffix->is_empty() || suffix->ends_with('-'))
return {};
// 4. If tokens is empty, return null.
@@ -143,7 +147,8 @@ Optional<TextDirective> parse_a_text_directive(StringView text_directive_value)
tokens.remove(0);
// 11. If start is the empty string or contains any instances of U+002D (-), return null.
- if (start->is_empty() || start->contains('-'))
+ // INTEROP: Current WPT coverage and other engines allow U+002D inside a term.
+ if (start->is_empty())
return {};
// 12. If tokens is not empty:
@@ -152,7 +157,8 @@ Optional<TextDirective> parse_a_text_directive(StringView text_directive_value)
end = tokens.first();
// 2. If end is the empty string or contains any instances of U+002D (-), return null.
- if (end->is_empty() || end->contains('-'))
+ // AD-HOC: Current WPT coverage and other engines allow U+002D inside a term.
+ if (end->is_empty())
return {};
}
@@ -321,6 +327,24 @@ struct TextDirectiveSearchContext {
}
+// https://wicg.github.io/scroll-to-text-fragment/#invoking-text-directives
+GC::RootVector<GC::Ref<DOM::Range>> invoke_text_directives(Vector<TextDirective> const& text_directives, DOM::Document& document)
+{
+ // 1. Let ranges be a list of ranges, initially empty.
+ GC::RootVector<GC::Ref<DOM::Range>> ranges;
+
+ // 2. For each text directive directive of text directives:
+ for (auto const& directive : text_directives) {
+ // 1. If the result of running find a range from a text directive given directive and
+ // document is non-null, then append it to ranges.
+ if (auto range = find_a_range_from_a_text_directive(directive, document); range.has_value())
+ ranges.append(*range);
+ }
+
+ // 3. Return ranges.
+ return ranges;
+}
+
// https://wicg.github.io/scroll-to-text-fragment/#word-boundaries
static bool is_at_a_word_boundary(Utf16View text, size_t position, Unicode::Segmenter& segmenter)
{
diff --git a/Libraries/LibWeb/HTML/TextDirective.h b/Libraries/LibWeb/HTML/TextDirective.h
index 66e982bf717..3ba4797c6e2 100644
--- a/Libraries/LibWeb/HTML/TextDirective.h
+++ b/Libraries/LibWeb/HTML/TextDirective.h
@@ -11,6 +11,7 @@
#include <AK/Utf16String.h>
#include <AK/Vector.h>
#include <LibGC/Ptr.h>
+#include <LibGC/RootVector.h>
#include <LibURL/URL.h>
#include <LibWeb/Export.h>
#include <LibWeb/Forward.h>
@@ -28,6 +29,7 @@ WEB_API Optional<String> remove_the_fragment_directive(URL::URL&);
WEB_API Optional<Utf16String> percent_decode_a_text_directive_term(Optional<StringView> term);
WEB_API Optional<TextDirective> parse_a_text_directive(StringView text_directive_value);
WEB_API Vector<TextDirective> parse_the_fragment_directive(StringView fragment_directive);
+WEB_API GC::RootVector<GC::Ref<DOM::Range>> invoke_text_directives(Vector<TextDirective> const&, DOM::Document&);
WEB_API Optional<GC::Ref<DOM::Range>> find_a_range_from_a_text_directive(TextDirective const&, DOM::Document&);
}
diff --git a/Libraries/LibWeb/HTML/Window.cpp b/Libraries/LibWeb/HTML/Window.cpp
index a52089fa5db..fc4524ec8b5 100644
--- a/Libraries/LibWeb/HTML/Window.cpp
+++ b/Libraries/LibWeb/HTML/Window.cpp
@@ -503,6 +503,12 @@ WebIDL::ExceptionOr<Window::OpenedWindow> Window::window_open_steps_internal(Utf
referrer_policy = ReferrerPolicy::ReferrerPolicy::NoReferrer;
}
+ // https://wicg.github.io/scroll-to-text-fragment/#restricting-the-text-fragment
+ // The user involvement of a navigation initiated by window.open() is "activation" when the
+ // source Window has transient activation, and "none" otherwise.
+ auto const user_involvement = source_window->has_transient_activation()
+ ? UserNavigationInvolvement::Activation
+ : UserNavigationInvolvement::None;
// 13. Let targetNavigable and windowType be the result of applying the rules for choosing a navigable given target, sourceDocument's node navigable, and noopener.
VERIFY(source_document.navigable());
auto [target_navigable, window_type] = source_document.navigable()->choose_a_navigable(target, no_opener, ActivateTab::Yes, tokenized_features);
@@ -537,14 +543,14 @@ WebIDL::ExceptionOr<Window::OpenedWindow> Window::window_open_steps_internal(Utf
// 5. Otherwise, navigate targetNavigable to urlRecord using sourceDocument, with referrerPolicy set to referrerPolicy and exceptionsEnabled set to true.
else {
- TRY(target_navigable->navigate({ .url = url_record.release_value(), .source_document = source_document, .exceptions_enabled = true, .referrer_policy = referrer_policy }));
+ TRY(target_navigable->navigate({ .url = url_record.release_value(), .source_document = source_document, .exceptions_enabled = true, .referrer_policy = referrer_policy, .user_involvement = user_involvement }));
}
}
// 16. Otherwise:
else {
// 1. If urlRecord is not null, then navigate targetNavigable to urlRecord using sourceDocument, with referrerPolicy set to referrerPolicy and exceptionsEnabled set to true.
if (url_record.has_value())
- TRY(target_navigable->navigate({ .url = url_record.release_value(), .source_document = source_document, .exceptions_enabled = true, .referrer_policy = referrer_policy }));
+ TRY(target_navigable->navigate({ .url = url_record.release_value(), .source_document = source_document, .exceptions_enabled = true, .referrer_policy = referrer_policy, .user_involvement = user_involvement }));
// 2. If noopener is false, then set targetNavigable's active browsing context's opener browsing context to sourceDocument's browsing context.
if (no_opener == TokenizedFeature::NoOpener::No) {
diff --git a/Libraries/LibWebCommon/HTML/NavigationPopulationRequest.cpp b/Libraries/LibWebCommon/HTML/NavigationPopulationRequest.cpp
index 5a676dd5833..64cc2f6c3ea 100644
--- a/Libraries/LibWebCommon/HTML/NavigationPopulationRequest.cpp
+++ b/Libraries/LibWebCommon/HTML/NavigationPopulationRequest.cpp
@@ -79,8 +79,13 @@ void apply_navigation_population_result(NavigationPopulationRequest& request, Na
{
if (result.replacement_document_state.has_value())
request.history_entry.document_state = *result.replacement_document_state;
- if (result.redirected_url.has_value())
- request.history_entry.url = *result.redirected_url;
+ if (result.redirected_url.has_value()) {
+ auto redirected_url = *result.redirected_url;
+ auto fragment_directive = remove_the_fragment_directive(redirected_url);
+ if (fragment_directive.has_value() || result.redirect_replaced_fragment)
+ request.history_entry.directive_state_value = move(fragment_directive);
+ request.history_entry.url = move(redirected_url);
+ }
if (result.classic_history_api_state.has_value())
request.history_entry.classic_history_api_state = *result.classic_history_api_state;
if (result.resource_cleared)
@@ -182,6 +187,7 @@ ErrorOr<void> encode(Encoder& encoder, Web::HTML::NavigationPopulationResult con
{
TRY(encoder.encode(result.navigation_params));
TRY(encoder.encode(result.redirected_url));
+ TRY(encoder.encode(result.redirect_replaced_fragment));
TRY(encoder.encode(result.classic_history_api_state));
TRY(encoder.encode(result.replacement_document_state));
TRY(encoder.encode(result.resource_cleared));
@@ -196,6 +202,7 @@ ErrorOr<Web::HTML::NavigationPopulationResult> decode(Decoder& decoder)
return Web::HTML::NavigationPopulationResult {
.navigation_params = TRY(decoder.decode<Web::HTML::NavigationParamsVariantDescriptor>()),
.redirected_url = TRY(decoder.decode<Optional<URL::URL>>()),
+ .redirect_replaced_fragment = TRY(decoder.decode<bool>()),
.classic_history_api_state = TRY(decoder.decode<Optional<Web::HTML::StorageSerializationRecord>>()),
.replacement_document_state = TRY(decoder.decode<Optional<Web::HTML::SessionHistoryDocumentStateDescriptor>>()),
.resource_cleared = TRY(decoder.decode<bool>()),
diff --git a/Libraries/LibWebCommon/HTML/NavigationPopulationRequest.h b/Libraries/LibWebCommon/HTML/NavigationPopulationRequest.h
index fb669b83587..bfea08133cb 100644
--- a/Libraries/LibWebCommon/HTML/NavigationPopulationRequest.h
+++ b/Libraries/LibWebCommon/HTML/NavigationPopulationRequest.h
@@ -64,6 +64,7 @@ struct NavigationPopulationRequest {
struct NavigationPopulationResult {
NavigationParamsVariantDescriptor navigation_params;
Optional<URL::URL> redirected_url;
+ bool redirect_replaced_fragment { false };
Optional<StorageSerializationRecord> classic_history_api_state;
Optional<SessionHistoryDocumentStateDescriptor> replacement_document_state;
bool resource_cleared { false };
diff --git a/Libraries/LibWebView/SessionStore.cpp b/Libraries/LibWebView/SessionStore.cpp
index ba4f8293525..3ff68b83030 100644
--- a/Libraries/LibWebView/SessionStore.cpp
+++ b/Libraries/LibWebView/SessionStore.cpp
@@ -19,7 +19,7 @@ namespace WebView {
static constexpr u32 SESSIONS_SCHEMA_BASELINE_VERSION = 1u;
static constexpr u32 SESSIONS_SCHEMA_USER_AGENT_INITIATED_VERSION = 2u;
-static constexpr u32 SESSIONS_SCHEMA_DIRECTIVE_STATE_VERSION = 2u;
+static constexpr u32 SESSIONS_SCHEMA_DIRECTIVE_STATE_VERSION = 3u;
static constexpr u32 SESSIONS_SCHEMA_DOCUMENT_POLICY_VERSION = 4u;
static constexpr u32 MAX_CLOSED_TABS = 25;
static constexpr u32 MAX_CLOSED_WINDOWS = 5;
diff --git a/Tests/LibWeb/TestConfig.ini b/Tests/LibWeb/TestConfig.ini
index b27e706a857..4fcfd2bc34d 100644
--- a/Tests/LibWeb/TestConfig.ini
+++ b/Tests/LibWeb/TestConfig.ini
@@ -127,6 +127,9 @@ Text/input/navigation/navigation-activation-in-sandboxed-frame.html
; navigation.updateCurrentEntry() requires a non-opaque origin.
Text/input/navigation/targeted-entry-updates-reach-the-session-store.html
+; Tests a same-origin navigation while holding a parser-blocking HTTP response.
+Text/input/scroll-to-text-fragment-retries-during-parsing.html
+
; CSS @font-face url() requires HTTP(s) scheme.
Text/input/selection-rect-consistency-with-kerning.html
diff --git a/Tests/LibWeb/Text/data/scroll-to-text-fragment-load-layout-shift-target.html b/Tests/LibWeb/Text/data/scroll-to-text-fragment-load-layout-shift-target.html
new file mode 100644
index 00000000000..8b73a137975
--- /dev/null
+++ b/Tests/LibWeb/Text/data/scroll-to-text-fragment-load-layout-shift-target.html
@@ -0,0 +1,47 @@
+<!DOCTYPE html>
+<style>
+ #spacer {
+ height: 200vh;
+ }
+ #tail {
+ height: 200vh;
+ }
+</style>
+<div id="spacer"></div>
+<p id="target">Load stabilization target</p>
+<div id="tail"></div>
+<script>
+ const image = document.createElement("img");
+ image.width = 1;
+ image.height = 1;
+ image.src = new URL(location.href).searchParams.get("image");
+ document.body.appendChild(image);
+
+ const isInViewport = element => {
+ const rect = element.getBoundingClientRect();
+ return rect.top >= 0 && rect.bottom <= innerHeight;
+ };
+ const spacer = document.getElementById("spacer");
+ const target = document.getElementById("target");
+ let targetWasInitiallyInViewport = false;
+ let targetLeftViewport = false;
+
+ document.addEventListener("DOMContentLoaded", () => {
+ targetWasInitiallyInViewport = isInViewport(target);
+ setTimeout(() => {
+ spacer.style.height = "600vh";
+ targetLeftViewport = !isInViewport(target);
+ }, 0);
+ });
+
+ window.addEventListener("load", () => {
+ requestAnimationFrame(() => {
+ requestAnimationFrame(() => {
+ internals.signalTestIsDone(
+ `Target initially in viewport: ${targetWasInitiallyInViewport}\n`
+ + `Target left viewport after layout shift: ${targetLeftViewport}\n`
+ + `Target returned to viewport after load: ${isInViewport(target)}\n`);
+ });
+ });
+ });
+</script>
diff --git a/Tests/LibWeb/Text/data/scroll-to-text-fragment-retries-during-parsing-target.html b/Tests/LibWeb/Text/data/scroll-to-text-fragment-retries-during-parsing-target.html
new file mode 100644
index 00000000000..e9a9fc77363
--- /dev/null
+++ b/Tests/LibWeb/Text/data/scroll-to-text-fragment-retries-during-parsing-target.html
@@ -0,0 +1,41 @@
+<!DOCTYPE html>
+<style>
+ #spacer {
+ height: 200vh;
+ }
+ #tail {
+ height: 200vh;
+ }
+</style>
+<div id="spacer"></div>
+<p>Early retry target</p>
+<div id="tail"></div>
+<script>
+ const searchParams = new URL(location.href).searchParams;
+ const delayedScriptURL = searchParams.get("script");
+ const unblockURL = searchParams.get("unblock");
+ addEventListener("load", () => {
+ internals.signalTestIsDone(window.parserRetryResult);
+ });
+ const unblockParser = () => {
+ window.unblockImage = new Image();
+ window.unblockImage.src = unblockURL;
+ };
+ let scrollPollingTimer;
+ const scrollObserver = () => {
+ if (pageYOffset === 0)
+ return;
+ const scrolledBeforeParserCompletion = window.parserBlockingScriptFinished !== true;
+ const readyStateWhenScrolled = document.readyState;
+ removeEventListener("scroll", scrollObserver);
+ clearInterval(scrollPollingTimer);
+ window.parserRetryResult =
+ `Scrolled before parser completion: ${scrolledBeforeParserCompletion}\n`
+ + `Ready state: ${readyStateWhenScrolled}\n`;
+ unblockParser();
+ };
+ addEventListener("scroll", scrollObserver);
+ scrollPollingTimer = setInterval(scrollObserver, 50);
+ scrollObserver();
+ document.write(`<script src="${delayedScriptURL}"><\/script>`);
+</script>
diff --git a/Tests/LibWeb/Text/expected/scroll-to-text-fragment-load-layout-shift.txt b/Tests/LibWeb/Text/expected/scroll-to-text-fragment-load-layout-shift.txt
new file mode 100644
index 00000000000..733d014151d
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/scroll-to-text-fragment-load-layout-shift.txt
@@ -0,0 +1,3 @@
+Target initially in viewport: true
+Target left viewport after layout shift: true
+Target returned to viewport after load: true
diff --git a/Tests/LibWeb/Text/expected/scroll-to-text-fragment-retries-during-parsing.txt b/Tests/LibWeb/Text/expected/scroll-to-text-fragment-retries-during-parsing.txt
new file mode 100644
index 00000000000..07b6b8fd5f0
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/scroll-to-text-fragment-retries-during-parsing.txt
@@ -0,0 +1,2 @@
+Scrolled before parser completion: true
+Ready state: loading
diff --git a/Tests/LibWeb/Text/expected/wpt-import/scroll-to-text-fragment/find-range-from-text-directive.txt b/Tests/LibWeb/Text/expected/wpt-import/scroll-to-text-fragment/find-range-from-text-directive.txt
index 13570a287c9..af539ed18f6 100644
--- a/Tests/LibWeb/Text/expected/wpt-import/scroll-to-text-fragment/find-range-from-text-directive.txt
+++ b/Tests/LibWeb/Text/expected/wpt-import/scroll-to-text-fragment/find-range-from-text-directive.txt
@@ -2,56 +2,55 @@ Harness status: OK
Found 51 tests
-26 Pass
-25 Fail
-Fail Basic smoke test - full word match.
+51 Pass
+Pass Basic smoke test - full word match.
Pass Prefix must start on a word boundary.
-Fail Prefix need not end on a word boundary.
+Pass Prefix need not end on a word boundary.
Pass Prefix doesn't exist.
-Fail Multiple overlapping prefixes.
-Fail Multiple overlapping one letter prefixes.
+Pass Multiple overlapping prefixes.
+Pass Multiple overlapping one letter prefixes.
Pass Prefix overlaps match text.
-Fail Match text after prefix.
-Fail Search invisible content between prefix and match.
+Pass Match text after prefix.
+Pass Search invisible content between prefix and match.
Pass Prefix appears at end of document.
Pass |end| forces |start| to end on word boundary.
Pass no |end| or suffix forces |start| to end on word boundary.
-Fail suffix means |start| need not end on word boundary.
-Fail |start| doesn't need to start on word boundary.
+Pass suffix means |start| need not end on word boundary.
+Pass |start| doesn't need to start on word boundary.
Pass prefix with non-existent exact match.
Pass prefix with non-existent range match.
Pass match doesn't immediately follow prefix.
-Fail match doesn't immediately follow first prefix instance.
+Pass match doesn't immediately follow first prefix instance.
Pass no-prefix; |end| forces |start| to end on word boundary.
Pass no-prefix; no |end| or suffix forces |start| to end on word boundary.
-Fail no-prefix; suffix means |start| need not end on word boundary.
+Pass no-prefix; suffix means |start| need not end on word boundary.
Pass |start| must start on a word boundary.
Pass non-existent exact match.
Pass non-existent range match.
-Fail overlapping exact matches with suffix.
-Fail overlapping one letter exact matches with suffix.
-Fail matching range search.
+Pass overlapping exact matches with suffix.
+Pass overlapping one letter exact matches with suffix.
+Pass matching range search.
Pass inverted range search.
Pass no suffix forces |end| to be end bounded.
-Fail suffix means |end| need not be end bounded.
+Pass suffix means |end| need not be end bounded.
Pass |end| must be start bounded.
Pass |end| must be start bounded even if full range is word bounded.
Pass non-existent |end|.
Pass Range with preceeding suffix.
-Fail Match with no suffix.
+Pass Match with no suffix.
Pass Suffix comes before |end|.
-Fail Search invisible content between |end| and suffix.
+Pass Search invisible content between |end| and suffix.
Pass Suffix must be end bounded.
-Fail Suffix need not be start bounded.
+Pass Suffix need not be start bounded.
Pass Non-existent suffix.
Pass Content appears between match and suffix.
-Fail Non-matching suffix in first potential match.
-Fail Non-matching suffix search continues to prefix match.
-Fail Range end matches correct suffix.
-Fail `start` element contains search-invisible text (display: none).
+Pass Non-matching suffix in first potential match.
+Pass Non-matching suffix search continues to prefix match.
+Pass Range end matches correct suffix.
+Pass `start` element contains search-invisible text (display: none).
Pass `start` element contains hidden text, which is a block boundary.
-Fail `start` element contains hidden text which is not a block boundary.
-Fail `start` element contains search-invisible text (iframe).
-Fail `start` element contains search-invisible text (image).
-Fail |end| can match after an overlapping rejected candidate.
+Pass `start` element contains hidden text which is not a block boundary.
+Pass `start` element contains search-invisible text (iframe).
+Pass `start` element contains search-invisible text (image).
+Pass |end| can match after an overlapping rejected candidate.
Pass Inline node boundary is not a word boundary.
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/scroll-to-text-fragment/force-load-at-top.txt b/Tests/LibWeb/Text/expected/wpt-import/scroll-to-text-fragment/force-load-at-top.txt
index 80d33e957af..76549911530 100644
--- a/Tests/LibWeb/Text/expected/wpt-import/scroll-to-text-fragment/force-load-at-top.txt
+++ b/Tests/LibWeb/Text/expected/wpt-import/scroll-to-text-fragment/force-load-at-top.txt
@@ -2,13 +2,12 @@ Harness status: OK
Found 8 tests
-7 Pass
-1 Fail
+8 Pass
Pass force-load-at-top must block scroll on load from text fragment.
Pass force-load-at-top must block scroll on load from text fragment with element fallback.
Pass force-load-at-top must block scroll on load from element fragment.
Pass force-load-at-top must block scroll on load from history scroll restoration.
-Fail no-force-load-at-top must not block scroll on load from text fragment.
+Pass no-force-load-at-top must not block scroll on load from text fragment.
Pass no-force-load-at-top must not block scroll on load from text fragment with element fallback.
Pass no-force-load-at-top must not block scroll on load from element fragment.
Pass no-force-load-at-top must not block scroll on load from history scroll restoration.
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/scroll-to-text-fragment/multi-directive-scroll.txt b/Tests/LibWeb/Text/expected/wpt-import/scroll-to-text-fragment/multi-directive-scroll.txt
index e51c48711e7..29c377cb0d3 100644
--- a/Tests/LibWeb/Text/expected/wpt-import/scroll-to-text-fragment/multi-directive-scroll.txt
+++ b/Tests/LibWeb/Text/expected/wpt-import/scroll-to-text-fragment/multi-directive-scroll.txt
@@ -2,6 +2,6 @@ Harness status: OK
Found 2 tests
-2 Fail
-Fail Multi-directive URL scrolls to the first matched directive, not the last.
-Fail Multi-directive URL with reversed DOM order scrolls to the first directive in URL order.
\ No newline at end of file
+2 Pass
+Pass Multi-directive URL scrolls to the first matched directive, not the last.
+Pass Multi-directive URL with reversed DOM order scrolls to the first directive in URL order.
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/scroll-to-text-fragment/non-html-documents.txt b/Tests/LibWeb/Text/expected/wpt-import/scroll-to-text-fragment/non-html-documents.txt
index 335a450a8f7..1c41bcc8023 100644
--- a/Tests/LibWeb/Text/expected/wpt-import/scroll-to-text-fragment/non-html-documents.txt
+++ b/Tests/LibWeb/Text/expected/wpt-import/scroll-to-text-fragment/non-html-documents.txt
@@ -2,9 +2,9 @@ Harness status: OK
Found 5 tests
-3 Pass
-2 Fail
-Fail Text directive allowed in text/html
+4 Pass
+1 Fail
+Pass Text directive allowed in text/html
Pass Text directive blocked in text/css
Pass Text directive blocked in text/javascript
Fail Text directive allowed in text/plain
diff --git a/Tests/LibWeb/Text/expected/wpt-import/scroll-to-text-fragment/percent-encoding.txt b/Tests/LibWeb/Text/expected/wpt-import/scroll-to-text-fragment/percent-encoding.txt
index 0b22b3220bb..a22468b0a1f 100644
--- a/Tests/LibWeb/Text/expected/wpt-import/scroll-to-text-fragment/percent-encoding.txt
+++ b/Tests/LibWeb/Text/expected/wpt-import/scroll-to-text-fragment/percent-encoding.txt
@@ -2,8 +2,9 @@ Harness status: OK
Found 7 tests
-7 Fail
-Fail Test navigation with fragment: Percent-encoded "%" char..
+1 Pass
+6 Fail
+Pass Test navigation with fragment: Percent-encoded "%" char..
Fail Test navigation with fragment: Percent char without hex digits is invalid..
Fail Test navigation with fragment: Percent char followed by percent char is invalid..
Fail Test navigation with fragment: Single digit percent-encoding is invalid..
diff --git a/Tests/LibWeb/Text/expected/wpt-import/scroll-to-text-fragment/redirects.txt b/Tests/LibWeb/Text/expected/wpt-import/scroll-to-text-fragment/redirects.txt
index a867c5e5604..32622615d68 100644
--- a/Tests/LibWeb/Text/expected/wpt-import/scroll-to-text-fragment/redirects.txt
+++ b/Tests/LibWeb/Text/expected/wpt-import/scroll-to-text-fragment/redirects.txt
@@ -2,18 +2,18 @@ Harness status: OK
Found 14 tests
-14 Fail
-Fail Text fragment works from HTTP 301 redirect.
-Fail Text fragment works from HTTP 302 redirect.
-Fail Text fragment works from HTTP 303 redirect.
-Fail Text fragment works from HTTP 307 redirect.
-Fail Text fragment works from HTTP 308 redirect.
-Fail Text fragment propagated through HTTP 301 redirect.
-Fail Text fragment propagated through HTTP 302 redirect.
-Fail Text fragment propagated through HTTP 303 redirect.
-Fail Text fragment propagated through HTTP 307 redirect.
-Fail Text fragment propagated through HTTP 308 redirect.
-Fail Text fragment works on client-side location redirect.
-Fail Text fragment works on client-side meta redirect.
-Fail One text fragment per user gesture allowed in client-side location redirect.
-Fail One text fragment per user gesture allowed in client-side meta redirect.
\ No newline at end of file
+14 Pass
+Pass Text fragment works from HTTP 301 redirect.
+Pass Text fragment works from HTTP 302 redirect.
+Pass Text fragment works from HTTP 303 redirect.
+Pass Text fragment works from HTTP 307 redirect.
+Pass Text fragment works from HTTP 308 redirect.
+Pass Text fragment propagated through HTTP 301 redirect.
+Pass Text fragment propagated through HTTP 302 redirect.
+Pass Text fragment propagated through HTTP 303 redirect.
+Pass Text fragment propagated through HTTP 307 redirect.
+Pass Text fragment propagated through HTTP 308 redirect.
+Pass Text fragment works on client-side location redirect.
+Pass Text fragment works on client-side meta redirect.
+Pass One text fragment per user gesture allowed in client-side location redirect.
+Pass One text fragment per user gesture allowed in client-side meta redirect.
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/scroll-to-text-fragment/same-document-test-sync-load.txt b/Tests/LibWeb/Text/expected/wpt-import/scroll-to-text-fragment/same-document-test-sync-load.txt
index 78670aa855c..de5378dd1b0 100644
--- a/Tests/LibWeb/Text/expected/wpt-import/scroll-to-text-fragment/same-document-test-sync-load.txt
+++ b/Tests/LibWeb/Text/expected/wpt-import/scroll-to-text-fragment/same-document-test-sync-load.txt
@@ -2,5 +2,5 @@ Harness status: OK
Found 1 tests
-1 Fail
-Fail Same-document text directive navigation before loading the document has finished
\ No newline at end of file
+1 Pass
+Pass Same-document text directive navigation before loading the document has finished
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/scroll-to-text-fragment/same-document-tests-force-load-at-top.txt b/Tests/LibWeb/Text/expected/wpt-import/scroll-to-text-fragment/same-document-tests-force-load-at-top.txt
index 48ccd211649..29c341f35f3 100644
--- a/Tests/LibWeb/Text/expected/wpt-import/scroll-to-text-fragment/same-document-tests-force-load-at-top.txt
+++ b/Tests/LibWeb/Text/expected/wpt-import/scroll-to-text-fragment/same-document-tests-force-load-at-top.txt
@@ -2,9 +2,8 @@ Harness status: OK
Found 4 tests
-3 Pass
-1 Fail
+4 Pass
Pass Basic element fragment navigation
-Fail Basic text directive navigation
+Pass Basic text directive navigation
Pass Basic element id fallback
Pass Malformed text directive element id fallback
diff --git a/Tests/LibWeb/Text/expected/wpt-import/scroll-to-text-fragment/same-document-tests-no-force-load-at-top.txt b/Tests/LibWeb/Text/expected/wpt-import/scroll-to-text-fragment/same-document-tests-no-force-load-at-top.txt
index 48ccd211649..29c341f35f3 100644
--- a/Tests/LibWeb/Text/expected/wpt-import/scroll-to-text-fragment/same-document-tests-no-force-load-at-top.txt
+++ b/Tests/LibWeb/Text/expected/wpt-import/scroll-to-text-fragment/same-document-tests-no-force-load-at-top.txt
@@ -2,9 +2,8 @@ Harness status: OK
Found 4 tests
-3 Pass
-1 Fail
+4 Pass
Pass Basic element fragment navigation
-Fail Basic text directive navigation
+Pass Basic text directive navigation
Pass Basic element id fallback
Pass Malformed text directive element id fallback
diff --git a/Tests/LibWeb/Text/expected/wpt-import/scroll-to-text-fragment/same-document-tests.txt b/Tests/LibWeb/Text/expected/wpt-import/scroll-to-text-fragment/same-document-tests.txt
index 48ccd211649..29c341f35f3 100644
--- a/Tests/LibWeb/Text/expected/wpt-import/scroll-to-text-fragment/same-document-tests.txt
+++ b/Tests/LibWeb/Text/expected/wpt-import/scroll-to-text-fragment/same-document-tests.txt
@@ -2,9 +2,8 @@ Harness status: OK
Found 4 tests
-3 Pass
-1 Fail
+4 Pass
Pass Basic element fragment navigation
-Fail Basic text directive navigation
+Pass Basic text directive navigation
Pass Basic element id fallback
Pass Malformed text directive element id fallback
diff --git a/Tests/LibWeb/Text/expected/wpt-import/scroll-to-text-fragment/scroll-to-text-fragment-after-DOMContentLoaded.txt b/Tests/LibWeb/Text/expected/wpt-import/scroll-to-text-fragment/scroll-to-text-fragment-after-DOMContentLoaded.txt
index 7c386f67d7e..1137822aa74 100644
--- a/Tests/LibWeb/Text/expected/wpt-import/scroll-to-text-fragment/scroll-to-text-fragment-after-DOMContentLoaded.txt
+++ b/Tests/LibWeb/Text/expected/wpt-import/scroll-to-text-fragment/scroll-to-text-fragment-after-DOMContentLoaded.txt
@@ -2,5 +2,5 @@ Harness status: OK
Found 1 tests
-1 Fail
-Fail Navigating to a text fragment directive
\ No newline at end of file
+1 Pass
+Pass Navigating to a text fragment directive
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/scroll-to-text-fragment/scroll-to-text-fragment-same-doc.txt b/Tests/LibWeb/Text/expected/wpt-import/scroll-to-text-fragment/scroll-to-text-fragment-same-doc.txt
index 01755d8a74d..86e92253c37 100644
--- a/Tests/LibWeb/Text/expected/wpt-import/scroll-to-text-fragment/scroll-to-text-fragment-same-doc.txt
+++ b/Tests/LibWeb/Text/expected/wpt-import/scroll-to-text-fragment/scroll-to-text-fragment-same-doc.txt
@@ -2,6 +2,7 @@ Harness status: OK
Found 2 tests
-2 Fail
-Fail Activated for same-document window.location setter
+1 Pass
+1 Fail
+Pass Activated for same-document window.location setter
Fail Activated for same-document window.location.replace
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/scroll-to-text-fragment/scroll-to-text-fragment.txt b/Tests/LibWeb/Text/expected/wpt-import/scroll-to-text-fragment/scroll-to-text-fragment.txt
index 67e011704e8..bfa604aa50c 100644
--- a/Tests/LibWeb/Text/expected/wpt-import/scroll-to-text-fragment/scroll-to-text-fragment.txt
+++ b/Tests/LibWeb/Text/expected/wpt-import/scroll-to-text-fragment/scroll-to-text-fragment.txt
@@ -2,49 +2,48 @@ Harness status: OK
Found 44 tests
-16 Pass
-28 Fail
+44 Pass
Pass Test navigation with fragment: Empty hash should scroll to top.
Pass Test navigation with fragment: Text directive with invalid syntax (context terms without "-") should not parse as a text directive.
Pass Test navigation with fragment: Text directive with invalid syntax (only prefix, no start text) should not parse as a text directive.
Pass Test navigation with fragment: Text directive with invalid syntax (only suffix, no start text) should not parse as a text directive.
Pass Test navigation with fragment: Generic fragment directive with existing element fragment should scroll to element.
Pass Test navigation with fragment: Uppercase TEXT directive should not parse as a text directive.
-Fail Test navigation with fragment: Exact text with no context should match text.
-Fail Test navigation with fragment: Case-insensitive search with no context should match text.
-Fail Test navigation with fragment: Exact text with prefix should match text.
-Fail Test navigation with fragment: Exact text with suffix should match text.
-Fail Test navigation with fragment: Exact text with prefix and suffix should match text.
-Fail Test navigation with fragment: Exact text with prefix and suffix and query equals prefix..
-Fail Test navigation with fragment: Text range with no context should match text.
-Fail Test navigation with fragment: Text range with prefix should match text.
-Fail Test navigation with fragment: Text range with suffix should match text.
-Fail Test navigation with fragment: Text range with prefix and suffix should match text.
+Pass Test navigation with fragment: Exact text with no context should match text.
+Pass Test navigation with fragment: Case-insensitive search with no context should match text.
+Pass Test navigation with fragment: Exact text with prefix should match text.
+Pass Test navigation with fragment: Exact text with suffix should match text.
+Pass Test navigation with fragment: Exact text with prefix and suffix should match text.
+Pass Test navigation with fragment: Exact text with prefix and suffix and query equals prefix..
+Pass Test navigation with fragment: Text range with no context should match text.
+Pass Test navigation with fragment: Text range with prefix should match text.
+Pass Test navigation with fragment: Text range with suffix should match text.
+Pass Test navigation with fragment: Text range with prefix and suffix should match text.
Pass Test navigation with fragment: Text range with non-matching endText should not match.
Pass Test navigation with fragment: Text range with non-matching startText should not match.
Pass Test navigation with fragment: Text range with prefix and nonmatching suffix should not match.
Pass Test navigation with fragment: Text range with nonmatching prefix and matching suffix should not match.
-Fail Test navigation with fragment: Exact text with percent encoded spaces should match text.
+Pass Test navigation with fragment: Exact text with percent encoded spaces should match text.
Pass Test navigation with fragment: Non-whole-word exact text with spaces should not match.
-Fail Test navigation with fragment: Fragment directive with percent encoded syntactical characters "&,-" should match text.
-Fail Test navigation with fragment: Fragment directive with percent encoded non-ASCII unicode character should match text.
-Fail Test navigation with fragment: Fragment directive with all TextMatchChars should match text.
-Fail Test navigation with fragment: Multiple matching exact texts should match text.
+Pass Test navigation with fragment: Fragment directive with percent encoded syntactical characters "&,-" should match text.
+Pass Test navigation with fragment: Fragment directive with percent encoded non-ASCII unicode character should match text.
+Pass Test navigation with fragment: Fragment directive with all TextMatchChars should match text.
+Pass Test navigation with fragment: Multiple matching exact texts should match text.
Pass Test navigation with fragment: Multiple non-whole-word exact texts should not match.
-Fail Test navigation with fragment: A non-matching text directive followed by a matching text directive should match and scroll into view the second text directive.
-Fail Test navigation with fragment: Text directive followed by non-text directive should match text.
-Fail Test navigation with fragment: Multiple text directives and a non-text directive should match text.
-Fail Test navigation with fragment: Text directive with existing element fragment should match and scroll into view text.
-Fail Test navigation with fragment: Text directive with nonexistent element fragment should match and scroll into view text.
+Pass Test navigation with fragment: A non-matching text directive followed by a matching text directive should match and scroll into view the second text directive.
+Pass Test navigation with fragment: Text directive followed by non-text directive should match text.
+Pass Test navigation with fragment: Multiple text directives and a non-text directive should match text.
+Pass Test navigation with fragment: Text directive with existing element fragment should match and scroll into view text.
+Pass Test navigation with fragment: Text directive with nonexistent element fragment should match and scroll into view text.
Pass Test navigation with fragment: Non-matching text directive with existing element fragment should scroll to element.
Pass Test navigation with fragment: Non-matching text directive with nonexistent element fragment should not match and not scroll.
-Fail Test navigation with fragment: Multiple match text directive disambiguated by prefix should match the prefixed text.
-Fail Test navigation with fragment: Multiple match text directive disambiguated by suffix should match the suffixed text.
-Fail Test navigation with fragment: Multiple match text directive disambiguated by prefix and suffix should match the text with the given context.
-Fail Test navigation with fragment: Text directive should match when context terms are separated by node boundaries.
-Fail Test navigation with fragment: Text directive should match text within shadow DOM.
+Pass Test navigation with fragment: Multiple match text directive disambiguated by prefix should match the prefixed text.
+Pass Test navigation with fragment: Multiple match text directive disambiguated by suffix should match the suffixed text.
+Pass Test navigation with fragment: Multiple match text directive disambiguated by prefix and suffix should match the text with the given context.
+Pass Test navigation with fragment: Text directive should match when context terms are separated by node boundaries.
+Pass Test navigation with fragment: Text directive should match text within shadow DOM.
Pass Test navigation with fragment: Text directive should not scroll to hidden text.
Pass Test navigation with fragment: Text directive should not scroll to display none text.
-Fail Test navigation with fragment: Text directive should horizontally scroll into view.
-Fail Test navigation with fragment: Text directive should horizontally scroll into view within a wide line.
-Fail Test navigation with fragment: Text directive that spans a range larger than the viewport should scroll the start into view.
\ No newline at end of file
+Pass Test navigation with fragment: Text directive should horizontally scroll into view.
+Pass Test navigation with fragment: Text directive should horizontally scroll into view within a wide line.
+Pass Test navigation with fragment: Text directive that spans a range larger than the viewport should scroll the start into view.
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/scroll-to-text-fragment/text-directive-mime-type-parameter.txt b/Tests/LibWeb/Text/expected/wpt-import/scroll-to-text-fragment/text-directive-mime-type-parameter.txt
index b008b3f504c..ba35b259aa2 100644
--- a/Tests/LibWeb/Text/expected/wpt-import/scroll-to-text-fragment/text-directive-mime-type-parameter.txt
+++ b/Tests/LibWeb/Text/expected/wpt-import/scroll-to-text-fragment/text-directive-mime-type-parameter.txt
@@ -2,5 +2,5 @@ Harness status: OK
Found 1 tests
-1 Fail
-Fail Text directive allowed in text/html with a charset parameter
\ No newline at end of file
+1 Pass
+Pass Text directive allowed in text/html with a charset parameter
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/input/scroll-to-text-fragment-load-layout-shift.html b/Tests/LibWeb/Text/input/scroll-to-text-fragment-load-layout-shift.html
new file mode 100644
index 00000000000..11f1dd9ba82
--- /dev/null
+++ b/Tests/LibWeb/Text/input/scroll-to-text-fragment-load-layout-shift.html
@@ -0,0 +1,22 @@
+<!DOCTYPE html>
+<link rel="help" href="https://wicg.github.io/scroll-to-text-fragment/#invoking-text-directives">
+<script src="include.js"></script>
+<script>
+ asyncTest(async () => {
+ const server = httpTestServer();
+ const imageURL = await server.createEcho("GET", "/scroll-to-text-fragment-load-layout-shift.svg", {
+ status: 200,
+ headers: {
+ "Content-Type": "image/svg+xml",
+ "Cache-Control": "no-store",
+ },
+ body: '<svg xmlns="http://www.w3.org/2000/svg" width="1" height="1"></svg>',
+ delay_ms: 500,
+ });
+
+ const targetURL = new URL("../data/scroll-to-text-fragment-load-layout-shift-target.html", location.href);
+ targetURL.searchParams.set("image", imageURL);
+ targetURL.hash = ":~:text=Load%20stabilization%20target";
+ location.href = targetURL;
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/scroll-to-text-fragment-retries-during-parsing.html b/Tests/LibWeb/Text/input/scroll-to-text-fragment-retries-during-parsing.html
new file mode 100644
index 00000000000..848f62348c6
--- /dev/null
+++ b/Tests/LibWeb/Text/input/scroll-to-text-fragment-retries-during-parsing.html
@@ -0,0 +1,31 @@
+<!DOCTYPE html>
+<link rel="help" href="https://wicg.github.io/scroll-to-text-fragment/#invoking-text-directives">
+<script src="include.js"></script>
+<script>
+ asyncTest(async () => {
+ // This test deliberately keeps the parser blocked until a timer-driven text-fragment
+ // retry succeeds. Allow for scheduling delays when the full suite runs concurrently.
+ internals.setTestTimeout(120_000);
+
+ const serverURL = new URL(httpTestServer().baseURL);
+ serverURL.hostname = uniqueLocalhostHostname("scroll-to-text-fragment-retry");
+ const server = new HTTPTestServer(serverURL);
+ const token = crypto.randomUUID();
+ const delayedScriptURL = new URL(await server.createEcho("GET", `/scroll-to-text-fragment-retry-delay-${token}.js`, {
+ status: 200,
+ headers: {
+ "Content-Type": "text/javascript",
+ "Cache-Control": "no-store",
+ },
+ body: "window.parserBlockingScriptFinished = true;",
+ wait_for_unblock: token,
+ }));
+ const unblockURL = new URL(`/unblock/${token}`, server.baseURL);
+
+ const targetURL = new URL("../data/scroll-to-text-fragment-retries-during-parsing-target.html", location.href);
+ targetURL.searchParams.set("script", delayedScriptURL);
+ targetURL.searchParams.set("unblock", unblockURL);
+ targetURL.hash = ":~:text=Early%20retry%20target";
+ location.href = targetURL;
+ });
+</script>