Truly independent web browser
LibWeb+LibWebView: Track visible text fragments
Sam Atkins67079390df00
diff --git a/Libraries/LibWeb/DOM/Document.cpp b/Libraries/LibWeb/DOM/Document.cppindex 53bd7449fdd..9720c91f6b4 100644--- a/Libraries/LibWeb/DOM/Document.cpp+++ b/Libraries/LibWeb/DOM/Document.cpp@@ -158,7 +158,6 @@#include <LibWeb/HTML/HTMLBodyElement.h>#include <LibWeb/HTML/HTMLDialogElement.h>#include <LibWeb/HTML/HTMLDocument.h>-#include <LibWeb/HTML/TextDirective.h>#include <LibWeb/HTML/HTMLEmbedElement.h>#include <LibWeb/HTML/HTMLFormElement.h>#include <LibWeb/HTML/HTMLFrameSetElement.h>@@ -204,6 +203,7 @@#include <LibWeb/HTML/Storage.h>#include <LibWeb/HTML/StorageEvent.h>#include <LibWeb/HTML/StructuredSerialize.h>+#include <LibWeb/HTML/TextDirective.h>#include <LibWeb/HTML/Window.h>#include <LibWeb/HTML/WindowOrWorkerGlobalScope.h>#include <LibWeb/HTML/WindowProxy.h>@@ -2220,7 +2220,10 @@ void Document::after_layout_commit(Layout::BegunRead const& read, LayoutTreeChanbool const collects_boxes_with_auto_content_visibility = layout_tree_changed == LayoutTreeChanged::Yes&& Layout::RustFFI::render_state_may_have_auto_content_visibility(layout_node_arena().host(), &read);Layout::RustFFI::render_state_invalidate_searchable_text(layout_node_arena().host());- if (auto* viewport = layout_node(read))+ // A committed layout may be stale relative to style changes made while its frame was in flight. This callback+ // reconciles caches against that committed tree, so use the node from the read rather than asking whether it is+ // the latest tree for the document.+ if (auto* viewport = unsafe_layout_node(read))viewport->invalidate_searchable_text_cache();set_needs_to_record_display_list();@@ -4264,6 +4267,57 @@ void Document::set_accessibility_focus_target(GC::Ptr<Element> element)set_needs_repaint();}+// https://wicg.github.io/scroll-to-text-fragment/#urls-in-ua-features+void Document::update_text_fragment_indication_visibility(bool visible)+{+ auto navigable = this->navigable();+ if (!navigable || !navigable->is_top_level_traversable() || !is_fully_active())+ return;+ page().client().page_did_set_text_fragment_indication_visibility(visible);+}++static void invalidate_text_fragment_range_paint(Vector<GC::Ref<Range>> const& ranges)+{+ // Text-fragment indication spans are generated while recording foreground paint commands.+ // Invalidate the paintables covered by the ranges so cached commands cannot retain an old+ // indication or omit a new one.+ for (auto const& range : ranges) {+ range->common_ancestor_container()->for_each_in_inclusive_subtree_of_type<Text>([&](Text& text) {+ if (range->intersects_node(text))+ text.set_needs_repaint(InvalidateDisplayList::PaintCommands);+ return TraversalDecision::Continue;+ });+ }+}++// https://wicg.github.io/scroll-to-text-fragment/#applying-directives-to-a-document+void Document::set_pending_text_directives(Optional<Vector<HTML::TextDirective>> directives)+{+ invalidate_text_fragment_range_paint(m_text_fragment_ranges);+ m_text_fragment_ranges.clear();+ m_pending_text_directives = move(directives);+ if (m_pending_text_directives.has_value())+ update_text_fragment_indication_visibility(!m_pending_text_directives->is_empty());+}++// https://wicg.github.io/scroll-to-text-fragment/#invoking-text-directives+void Document::clear_pending_text_directives()+{+ // 1. Set pending text directives to null.+ m_pending_text_directives.clear();+ if (m_text_fragment_ranges.is_empty())+ update_text_fragment_indication_visibility(false);+}++// https://wicg.github.io/scroll-to-text-fragment/#indicating-the-text-match+void Document::dismiss_text_fragment_indication()+{+ invalidate_text_fragment_range_paint(m_text_fragment_ranges);+ m_text_fragment_ranges.clear();+ m_pending_text_directives.clear();+ update_text_fragment_indication_visibility(false);+}+// https://html.spec.whatwg.org/multipage/browsing-the-web.html#the-indicated-part-of-the-document// https://wicg.github.io/scroll-to-text-fragment/#invoking-text-directivesDocument::IndicatedPart Document::determine_the_indicated_part()@@ -4278,21 +4332,6 @@ Document::IndicatedPart Document::determine_the_indicated_part()// 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);-- // Text-fragment indication spans are generated while recording foreground paint commands.- // Invalidate both sets of paintables so cached commands cannot retain the old indication or- // omit the new one.- auto invalidate_text_fragment_range_paint = [](Vector<GC::Ref<Range>> const& ranges) {- for (auto const& range : ranges) {- range->common_ancestor_container()->for_each_in_inclusive_subtree_of_type<Text>([&](Text& text) {- if (range->intersects_node(text)) {- if (auto* layout_text = as_if<Layout::TextNode>(text.unsafe_layout_node()))- layout_text->set_needs_repaint(InvalidateDisplayList::Yes);- }- return TraversalDecision::Continue;- });- }- };invalidate_text_fragment_range_paint(m_text_fragment_ranges);m_text_fragment_ranges.clear();m_text_fragment_ranges.extend(ranges);@@ -4306,6 +4345,7 @@ Document::IndicatedPart Document::determine_the_indicated_part()// 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.+ update_text_fragment_indication_visibility(true);// 3. Set firstRange as document's indicated part, return.return GC::Ptr<Range> { first_range };@@ -5790,6 +5830,12 @@ void Document::increment_number_of_things_delaying_the_load_event(Badge<Document{++m_number_of_things_delaying_the_load_event;page().client().page_did_update_resource_count(m_number_of_things_delaying_the_load_event);++ // A newly added load-event delayer can make this document's container wait again, including when that container+ // lives in another process. Publish the new state immediately, and wake any same-process ancestor parser checks.+ if (auto navigable = this->navigable())+ navigable->report_state_to_remote_container();+ schedule_html_parser_end_check();}void Document::decrement_number_of_things_delaying_the_load_event(Badge<DocumentLoadEventDelayer>)@@ -7596,7 +7642,7 @@ void Document::restore_the_history_object_state(NonnullRefPtr<HTML::SessionHisto}// https://html.spec.whatwg.org/multipage/browsing-the-web.html#update-document-for-history-step-application-void Document::update_for_history_step_application(NonnullRefPtr<HTML::SessionHistoryEntry> entry, bool do_not_reactivate, size_t script_history_length, size_t script_history_index, Optional<HTML::NavigationType> navigation_type, Optional<Vector<NonnullRefPtr<HTML::SessionHistoryEntry>>> entries_for_navigation_api, RefPtr<HTML::SessionHistoryEntry> previous_entry_for_activation, bool previous_entry_for_activation_document_is_initial_about_blank, bool allow_text_directive_scroll)+void Document::update_for_history_step_application(NonnullRefPtr<HTML::SessionHistoryEntry> entry, bool do_not_reactivate, size_t script_history_length, size_t script_history_index, Optional<HTML::NavigationType> navigation_type, Optional<Vector<NonnullRefPtr<HTML::SessionHistoryEntry>>> entries_for_navigation_api, RefPtr<HTML::SessionHistoryEntry> previous_entry_for_activation, bool previous_entry_for_activation_document_is_initial_about_blank, bool allow_text_directive_scroll, Optional<URL::Origin> initiator_origin, Optional<HTML::UserNavigationInvolvement> user_involvement){// 1. Let documentIsNew be true if document's latest entry is null; otherwise false.auto document_is_new = !m_latest_entry;@@ -7623,6 +7669,8 @@ void Document::update_for_history_step_application(NonnullRefPtr<HTML::SessionHi// or we are asynchronously finishing up a synchronous navigation which already synchronously set document's latest entry.// The doNotReactivate argument distinguishes between these two cases.if (documents_entry_changed) {+ bool text_directive_state_changed = false;+// 1. Let oldURL be document's latest entry's URL.auto old_url = m_latest_entry ? m_latest_entry->url() : URL::URL {};@@ -7637,6 +7685,7 @@ void Document::update_for_history_step_application(NonnullRefPtr<HTML::SessionHireturn nullptr;}();if (!latest_entry_directive_state || latest_entry_directive_state.ptr() != entry->directive_state().ptr()) {+ text_directive_state_changed = true;// 1. Let fragment directive be entry's directive state's value.auto const& fragment_directive = entry->directive_state()->value();@@ -7653,6 +7702,16 @@ void Document::update_for_history_step_application(NonnullRefPtr<HTML::SessionHi// 4. Restore the history object state given document and entry.restore_the_history_object_state(entry);+ // https://wicg.github.io/scroll-to-text-fragment/#restricting-the-text-fragment+ // Check permission after applying the entry's directive state so the check sees this entry's pending directives.+ if (user_involvement.has_value() && text_directive_state_changed)+ allow_text_directive_scroll = check_if_a_text_directive_can_be_scrolled(initiator_origin, user_involvement);++ // A traversal can reactivate an existing Document with a different directive state. Unlike a newly-created+ // Document, it will not reach the parser-completion scrolling path, so retry it here.+ if (!document_is_new && user_involvement.has_value() && text_directive_state_changed)+ try_to_scroll_to_the_fragment(allow_text_directive_scroll);+// 5. If documentIsNew is false, then:if (!document_is_new) {// NOTE: Not in the spec, but otherwise document's url won't be updated in case of a same-document back/forward navigation.diff --git a/Libraries/LibWeb/DOM/Document.h b/Libraries/LibWeb/DOM/Document.hindex 28c6402abc7..a8520afb408 100644--- a/Libraries/LibWeb/DOM/Document.h+++ b/Libraries/LibWeb/DOM/Document.h@@ -45,8 +45,6 @@#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>@@ -75,8 +73,8 @@#include <LibWebCommon/HTML/CrossOrigin/OpenerPolicy.h>#include <LibWebCommon/HTML/CrossProcessId.h>#include <LibWebCommon/HTML/SandboxingFlagSet.h>-#include <LibWebCommon/HTML/VisibilityState.h>#include <LibWebCommon/HTML/UserNavigationInvolvement.h>+#include <LibWebCommon/HTML/VisibilityState.h>namespace Web::Compositor {@@ -833,18 +831,10 @@ public:// https://wicg.github.io/scroll-to-text-fragment/#feature-detectabilityGC::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_text_fragment_ranges.clear();- m_pending_text_directives = move(directives);- }- void clear_pending_text_directives() { m_pending_text_directives.clear(); }+ void set_pending_text_directives(Optional<Vector<HTML::TextDirective>> directives);+ void clear_pending_text_directives();ReadonlySpan<GC::Ref<Range>> text_fragment_ranges() const { return m_text_fragment_ranges; }- void dismiss_text_fragment_indication()- {- m_text_fragment_ranges.clear();- m_pending_text_directives.clear();- }+ void dismiss_text_fragment_indication();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; }@@ -1161,10 +1151,11 @@ public:struct TopOfTheDocument { };using IndicatedPart = Variant<Element*, GC::Ptr<Range>, TopOfTheDocument>;IndicatedPart determine_the_indicated_part();+ void update_text_fragment_indication_visibility(bool visible);u32 unload_counter() const { return m_unload_counter; }- void update_for_history_step_application(NonnullRefPtr<HTML::SessionHistoryEntry>, bool do_not_reactivate, size_t script_history_length, size_t script_history_index, Optional<HTML::NavigationType> navigation_type, Optional<Vector<NonnullRefPtr<HTML::SessionHistoryEntry>>> entries_for_navigation_api = {}, RefPtr<HTML::SessionHistoryEntry> previous_entry_for_activation = {}, bool previous_entry_for_activation_document_is_initial_about_blank = false, bool allow_text_directive_scroll = false);+ void update_for_history_step_application(NonnullRefPtr<HTML::SessionHistoryEntry>, bool do_not_reactivate, size_t script_history_length, size_t script_history_index, Optional<HTML::NavigationType> navigation_type, Optional<Vector<NonnullRefPtr<HTML::SessionHistoryEntry>>> entries_for_navigation_api = {}, RefPtr<HTML::SessionHistoryEntry> previous_entry_for_activation = {}, bool previous_entry_for_activation_document_is_initial_about_blank = false, bool allow_text_directive_scroll = false, Optional<URL::Origin> initiator_origin = {}, Optional<HTML::UserNavigationInvolvement> user_involvement = {});HashMap<URL::URL, GC::Ptr<HTML::SharedResourceRequest>>& shared_resource_requests();HashMap<URL::URL, GC::Ptr<HTML::SharedResourceRequest>> const& shared_resource_requests() const;diff --git a/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Requests.h b/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Requests.hindex a188179dee9..14ed25ecf97 100644--- a/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Requests.h+++ b/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Requests.h@@ -260,6 +260,11 @@ public:[[nodiscard]] bool user_activation() const { return m_user_activation; }void set_user_activation(bool user_activation) { m_user_activation = user_activation; }+ [[nodiscard]] 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; }+ [[nodiscard]] bool browsing_context_group_has_multiple_contexts() const { return m_browsing_context_group_has_multiple_contexts; }+ void set_browsing_context_group_has_multiple_contexts(bool value) { m_browsing_context_group_has_multiple_contexts = value; }+[[nodiscard]] bool user_agent_initiated() const { return m_user_agent_initiated; }void set_user_agent_initiated(bool user_agent_initiated) { m_user_agent_initiated = user_agent_initiated; }@@ -492,6 +497,11 @@ private:// A request has an associated boolean user-activation. Unless stated otherwise, it is false.bool m_user_activation { false };+ // https://wicg.github.io/scroll-to-text-fragment/#restricting-the-text-fragment+ // The one-shot authorization to scroll to a text directive, propagated through navigation requests.+ bool m_text_directive_user_activation { false };+ bool m_browsing_context_group_has_multiple_contexts { false };+// NB: Not a Fetch concept. Fetch Metadata's "set site" sends Sec-Fetch-Site:none for a navigation whose URL// the user agent itself supplied, and populating a history entry sets this from the entry's document state.bool m_user_agent_initiated { false };diff --git a/Libraries/LibWeb/HTML/DirectiveState.h b/Libraries/LibWeb/HTML/DirectiveState.hindex 7ce4358ab92..91cb9d0b6be 100644--- a/Libraries/LibWeb/HTML/DirectiveState.h+++ b/Libraries/LibWeb/HTML/DirectiveState.h@@ -9,7 +9,7 @@#include <AK/Optional.h>#include <AK/RefCounted.h>#include <AK/String.h>-#include <LibWeb/HTML/CrossProcessId.h>+#include <LibWebCommon/HTML/CrossProcessId.h>namespace Web::HTML {diff --git a/Libraries/LibWeb/HTML/HistoryExecutor.cpp b/Libraries/LibWeb/HTML/HistoryExecutor.cppindex 9659e85e56f..be38756ba62 100644--- a/Libraries/LibWeb/HTML/HistoryExecutor.cpp+++ b/Libraries/LibWeb/HTML/HistoryExecutor.cpp@@ -42,6 +42,7 @@ struct ChangingNavigableContinuationState : public GC::Cell {GC::Ptr<PopulateSessionHistoryEntryDocumentOutput> population_output;GC::Ptr<DOM::Document> resolved_document;Optional<URL::Origin> old_origin;+ UserNavigationInvolvement user_involvement { UserNavigationInvolvement::None };virtual void visit_edges(Cell::Visitor& visitor) override{@@ -367,6 +368,7 @@ bool HistoryExecutor::run_changing_navigable_history_step_job_impl(ChangingNavigchanging_navigable_continuation->navigable = navigable;changing_navigable_continuation->update_only = false;changing_navigable_continuation->navigation_type = job.navigation_type;+ changing_navigable_continuation->user_involvement = job.user_involvement;changing_navigable_continuation->pending_document = pending_document;changing_navigable_continuation->population_output = nullptr;@@ -745,13 +747,13 @@ void HistoryExecutor::apply_changing_navigable_history_step_continuation_impl(GC// 3. Let updateDocument be an algorithm step which performs update document for history step application given// targetEntry's document, targetEntry, changingNavigableContinuation's update-only, scriptHistoryLength,// scriptHistoryIndex, navigationType, entriesForNavigationAPI, and previousEntry.- auto update_document = [script_history_length, script_history_index, entries_for_navigation_api = move(entries_for_navigation_api), target_entry, update_only, navigation_type, previous_entry, previous_entry_document_is_initial_about_blank, resolved_document, navigable] {+ auto update_document = [script_history_length, script_history_index, entries_for_navigation_api = move(entries_for_navigation_api), target_entry, update_only, navigation_type, previous_entry, previous_entry_document_is_initial_about_blank, resolved_document, navigable, continuation] {// NB: The specification initializes the navigation API entries for every newly activated document.// Gating this on a non-null navigationType left documents activated by a creation/destruction// update without an initialized navigation API entry list, which crashes the first same-document// update on them (for example a document.open() on a child that finished loading while the// creation update was still queued).- resolved_document->update_for_history_step_application(*target_entry, update_only, script_history_length, script_history_index, navigation_type, entries_for_navigation_api, previous_entry, previous_entry_document_is_initial_about_blank);+ resolved_document->update_for_history_step_application(*target_entry, update_only, script_history_length, script_history_index, navigation_type, entries_for_navigation_api, previous_entry, previous_entry_document_is_initial_about_blank, false, target_entry->document_state()->initiator_origin(), continuation->user_involvement);if (update_only)navigable->notify_navigation_observers_navigation_complete();diff --git a/Libraries/LibWeb/HTML/LocalNavigable.cpp b/Libraries/LibWeb/HTML/LocalNavigable.cppindex 68f6a4646f7..ab8943e03e3 100644--- a/Libraries/LibWeb/HTML/LocalNavigable.cpp+++ b/Libraries/LibWeb/HTML/LocalNavigable.cpp@@ -2566,6 +2566,7 @@ static void create_navigation_params_by_fetching(request->set_policy_container(source_snapshot_params->source_policy_container);request->set_text_directive_user_activation(source_snapshot_params->text_directive_user_activation);request->set_browsing_context_group_has_multiple_contexts(source_snapshot_params->browsing_context_group_has_multiple_contexts);+ active_document.set_text_directive_user_activation(false);// 4. If navigable is a top-level traversable, then set request's top-level navigation initiator origin to entry's// document state's initiator origin.@@ -3800,17 +3801,19 @@ void LocalNavigable::begin_navigation(PreparedNavigation navigation)// 23. In parallel, run these steps:auto source_snapshot = create_navigation_source_snapshot(source_snapshot_params);- source_snapshot.text_directive_user_activation = active_document()->text_directive_user_activation();- source_snapshot.browsing_context_group_has_multiple_contexts = active_document()->browsing_context_group_has_multiple_contexts();- source_snapshot.browsing_context_group_has_remote_contexts = active_document()->browsing_context_group_has_remote_contexts();- active_document()->set_text_directive_user_activation(false);+ source_snapshot.text_directive_user_activation = active_document.text_directive_user_activation();+ source_snapshot.browsing_context_group_has_multiple_contexts = active_document.browsing_context_group_has_multiple_contexts();+ source_snapshot.browsing_context_group_has_remote_contexts = active_document.browsing_context_group_has_remote_contexts();+ active_document.set_text_directive_user_activation(false);// Session history entry state is structured-serialized in WebContent, where the JavaScript VM lives. The UI// process owns the pending entry and document state created from these initial values.auto entry_defaults = SessionHistoryEntry::create();+ auto stripped_url = url;+ auto directive_state_value = remove_the_fragment_directive(stripped_url);auto start_request = NavigationStartRequest {.navigable_id = id(),- .url = url,+ .url = stripped_url,.document_resource = document_resource,.request_referrer = Fetch::Infrastructure::Request::Referrer::Client,.request_referrer_policy = referrer_policy,@@ -3827,11 +3830,13 @@ void LocalNavigable::begin_navigation(PreparedNavigation navigation).navigation_api_state = entry_defaults->navigation_api_state(),.navigation_api_key = entry_defaults->navigation_api_key(),.navigation_api_id = entry_defaults->navigation_api_id(),+ .directive_state_id = entry_defaults->directive_state()->cross_process_id(),+ .directive_state_value = move(directive_state_value),};park_navigation_for_population(navigation_id, move(navigation));auto target = is_top_level_traversable() ? NavigationTarget::TopLevel : NavigationTarget::IFrame;- active_browsing_context()->page().client().request_navigation_start(*this, target, url, navigation_id, move(start_request));+ active_browsing_context()->page().client().request_navigation_start(*this, target, stripped_url, navigation_id, move(start_request));return;}@@ -3932,6 +3937,7 @@ void LocalNavigable::navigate_to_a_fragment(URL::URL const& url, HistoryHandlingauto directive_state = active_session_history_entry()->directive_state();auto stripped_url = url;auto fragment_directive = remove_the_fragment_directive(stripped_url);+ auto const has_fragment_directive = fragment_directive.has_value();if (fragment_directive.has_value())directive_state = DirectiveState::create(page().client().allocate_cross_process_id(), move(fragment_directive));@@ -3954,6 +3960,12 @@ void LocalNavigable::navigate_to_a_fragment(URL::URL const& url, HistoryHandlingif (!continue_)return;+ if (!has_fragment_directive && source_element) {+ // AD-HOC: A trusted in-page link dismisses the current indication without changing the+ // directive state's identity in session history.+ active_document()->dismiss_text_fragment_indication();+ }+save_persisted_state_to_active_session_history_entry();auto active_entry = active_session_history_entry();auto previous_entry_persisted_state = create_session_history_entry_persisted_state(*active_entry);@@ -4048,10 +4060,7 @@ void LocalNavigable::navigate_to_a_fragment(URL::URL const& url, HistoryHandlingactive_document()->scroll_to_the_fragment();}- // 21. Let traversable be navigable's traversable navigable.- auto traversable = traversable_navigable();-- // 22. Append the following session history synchronous navigation steps involving navigable to traversable:+ // Append the following session history synchronous navigation steps involving navigable to its 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));@@ -4465,13 +4474,23 @@ void perform_url_and_history_update_steps(DOM::Document& document, URL::URL new_navigable->save_persisted_state_to_active_session_history_entry();auto previous_entry_persisted_state = create_session_history_entry_persisted_state(*active_entry);+ // https://wicg.github.io/scroll-to-text-fragment/#the-fragment-directive+ // Keep the directive in session history state while exposing only the stripped URL to the document.+ auto directive_state = active_entry->directive_state();+ bool has_fragment_directive = false;+ if (auto const& fragment = new_url.fragment(); fragment.has_value())+ has_fragment_directive = fragment->find(":~:"sv).has_value();+ auto directive_state_value = remove_the_fragment_directive(new_url);+ if (has_fragment_directive)+ directive_state = DirectiveState::create(navigable->page().client().allocate_cross_process_id(), move(directive_state_value));+// 3. Let newEntry be a new session history entry, with// URL: newURL// serialized state: if serializedData is not null, serializedData; otherwise activeEntry's classic history API state// document state: activeEntry's document state// scroll restoration mode: activeEntry's scroll restoration mode// FIXME: persisted user state: activeEntry's persisted user state- auto new_entry = SessionHistoryEntry::create();+ auto new_entry = SessionHistoryEntry::create(directive_state);new_entry->set_url(new_url);new_entry->set_classic_history_api_state(serialized_data.value_or(active_entry->classic_history_api_state()));new_entry->set_document_state(active_entry->document_state());diff --git a/Libraries/LibWeb/HTML/SessionHistoryEntry.cpp b/Libraries/LibWeb/HTML/SessionHistoryEntry.cppindex c840edddb05..8a41323ca3b 100644--- a/Libraries/LibWeb/HTML/SessionHistoryEntry.cpp+++ b/Libraries/LibWeb/HTML/SessionHistoryEntry.cpp@@ -4,10 +4,10 @@* SPDX-License-Identifier: BSD-2-Clause*/+#include <AK/CharacterTypes.h>#include <LibIPC/Decoder.h>#include <LibIPC/Encoder.h>#include <LibJS/Runtime/Value.h>-#include <AK/CharacterTypes.h>#include <LibWeb/Crypto/Crypto.h>#include <LibWeb/HTML/DocumentState.h>#include <LibWeb/HTML/SameDocumentNavigationEntry.h>@@ -32,11 +32,10 @@ static CrossProcessId generate_directive_state_id()if (byte == '-')continue;auto const nibble = parse_ascii_hex_digit(byte);- VERIFY(nibble.has_value());if (digit_count < 16)- namespace_id = (namespace_id << 4) | *nibble;+ namespace_id = (namespace_id << 4) | nibble;else- local_id = (local_id << 4) | *nibble;+ local_id = (local_id << 4) | nibble;++digit_count;}VERIFY(digit_count == 32);@@ -133,8 +132,6 @@ Optional<SessionHistoryEntryPersistedState> create_session_history_entry_persistreturn SessionHistoryEntryPersistedState {.entry_identity = session_history_entry_identity(entry),.scroll_position_data = entry.scroll_position_data(),- .directive_state_id = entry.directive_state()->cross_process_id(),- .directive_state_value = entry.directive_state()->value(),};}@@ -182,6 +179,8 @@ SameDocumentNavigationEntry create_same_document_navigation_entry(SessionHistory.navigation_api_id = entry.navigation_api_id(),.scroll_restoration_mode = entry.scroll_restoration_mode(),.scroll_position_data = entry.scroll_position_data(),+ .directive_state_id = entry.directive_state()->cross_process_id(),+ .directive_state_value = entry.directive_state()->value(),};}@@ -234,14 +233,11 @@ RefPtr<DocumentState> get_or_create_document_state_from_ui_process(SessionHistorNonnullRefPtr<SessionHistoryEntry> create_session_history_entry_from_ui_process(SessionHistoryEntryDescriptor entry_descriptor, SessionHistoryEntryReconstructionState& reconstruction_state){- auto directive_state = reconstruction_state.directive_states.get(entry_descriptor.directive_state_id);- if (!directive_state.has_value()) {- directive_state = DirectiveState::create(entry_descriptor.directive_state_id, entry_descriptor.directive_state_value);- reconstruction_state.directive_states.set(entry_descriptor.directive_state_id, *directive_state);- } else {- (*directive_state)->set_value(entry_descriptor.directive_state_value);- }- auto entry = SessionHistoryEntry::create(*directive_state);+ auto& directive_state = reconstruction_state.directive_states.ensure(entry_descriptor.directive_state_id, [&] {+ return DirectiveState::create(entry_descriptor.directive_state_id, entry_descriptor.directive_state_value);+ });+ directive_state->set_value(entry_descriptor.directive_state_value);+ auto entry = SessionHistoryEntry::create(directive_state);apply_session_history_entry_descriptor_from_ui_process(*entry, entry_descriptor);auto document_state = get_or_create_document_state_from_ui_process(entry_descriptor.document_state, reconstruction_state);diff --git a/Libraries/LibWeb/HTML/SourceSnapshotParams.cpp b/Libraries/LibWeb/HTML/SourceSnapshotParams.cppindex 70bfff49a63..f2b7f3b46a6 100644--- a/Libraries/LibWeb/HTML/SourceSnapshotParams.cpp+++ b/Libraries/LibWeb/HTML/SourceSnapshotParams.cpp@@ -60,7 +60,13 @@ GC::Ref<SourceSnapshotParams> snapshot_source_snapshot_params(GC::Ptr<DOM::Docum// source policy container// a clone of sourceDocument's policy container- source_document->policy_container()->clone(source_document->heap()));+ source_document->policy_container()->clone(source_document->heap()),++ // https://wicg.github.io/scroll-to-text-fragment/#restricting-the-text-fragment+ // Transfer the one-shot activation and browsing-context-group facts with the source snapshot.+ source_document->text_directive_user_activation(),+ source_document->browsing_context_group_has_multiple_contexts(),+ source_document->browsing_context_group_has_remote_contexts());}void SourceSnapshotParams::visit_edges(Cell::Visitor& visitor)diff --git a/Libraries/LibWeb/HTML/TextDirective.cpp b/Libraries/LibWeb/HTML/TextDirective.cppindex 76bc86158ef..db640ea9699 100644--- a/Libraries/LibWeb/HTML/TextDirective.cpp+++ b/Libraries/LibWeb/HTML/TextDirective.cpp@@ -32,20 +32,20 @@ Optional<String> remove_the_fragment_directive(URL::URL& url)if (raw_fragment.has_value()) {// 1. Let position be the string position variable pointing to the first code point of the first instance, if// one exists, of the fragment directive delimiter in raw fragment, or past the end of raw fragment otherwise.- auto position = raw_fragment->find_byte_offset(":~:"sv);+ auto position = raw_fragment->find(":~:"sv);if (position.has_value()) {// 2. Let new fragment be the code point substring by positions of raw fragment from the start of raw// fragment to position.- auto new_fragment = MUST(raw_fragment->substring_from_byte_offset_with_shared_superstring(0, *position));+ auto new_fragment = raw_fragment->substring_view(0, *position);// 3. Advance position by the code point length of the fragment directive delimiter.*position += 3;// 4. If position does not point past the end of raw fragment:- if (*position < raw_fragment->byte_count()) {+ if (*position < raw_fragment->length()) {// 1. Set fragment directive to the code point substring to the end of the string raw fragment starting// from position.- fragment_directive = MUST(raw_fragment->substring_from_byte_offset_with_shared_superstring(*position));+ fragment_directive = MUST(String::from_utf8(raw_fragment->substring_view(*position)));}// 5. Set url's fragment to new fragment.@@ -676,7 +676,8 @@ static void advance_a_range_start_to_the_next_non_whitespace_position(SearchRangOptional<GC::Ref<DOM::Range>> find_a_range_from_a_text_directive(TextDirective const& parsed_values, DOM::Document& document){document.update_layout(DOM::UpdateLayoutReason::DocumentFindMatchingText);- auto* viewport = document.layout_node();+ Layout::ForcedReadScope read { document };+ auto* viewport = document.layout_node(read);if (!viewport)return {};diff --git a/Libraries/LibWeb/Page/Page.h b/Libraries/LibWeb/Page/Page.hindex 456e020af89..0a9f7f2d973 100644--- a/Libraries/LibWeb/Page/Page.h+++ b/Libraries/LibWeb/Page/Page.h@@ -695,6 +695,7 @@ public:virtual void inject_rendering_opportunity([[maybe_unused]] double frame_time) { }virtual void page_did_change_title(Utf16String const&) { }virtual void page_did_update_editing_history_state(bool, bool) { }+ virtual void page_did_set_text_fragment_indication_visibility(bool) { }virtual void page_did_request_refresh() { }virtual void page_did_request_resize_window(Gfx::IntSize, u64) { }virtual void page_did_request_reposition_window(Gfx::IntPoint, u64) { }diff --git a/Libraries/LibWeb/Rust/src/painting/ffi.rs b/Libraries/LibWeb/Rust/src/painting/ffi.rsindex 6d5e46bb3f0..ca3db1fc334 100644--- a/Libraries/LibWeb/Rust/src/painting/ffi.rs+++ b/Libraries/LibWeb/Rust/src/painting/ffi.rs@@ -536,24 +536,6 @@ pub struct FfiImageMapArea {pub coords_count: u32,}-/// # Safety-///-/// `sink` must be the pointer handed to the callback, used synchronously.-#[unsafe(no_mangle)]-pub unsafe extern "C" fn layout_arena_paint_push_text_fragment_indication_range(- sink: *mut c_void,- start: usize,- end: usize,-) {- abort_on_panic(|| {- // SAFETY: `sink` is the Vec pointer handed out by- // FfiPaintHostCallbacks::text_fragment_indication_facts.- let ranges =- unsafe { &mut *sink.cast::<Vec<crate::painting::record::paint::text::TextFragmentIndicationRange>>() };- ranges.push(crate::painting::record::paint::text::TextFragmentIndicationRange { start, end });- });-}-/// # Safety////// `sink` must be the pointer handed to the callback, used synchronously.diff --git a/Libraries/LibWeb/Rust/src/painting/record/paint/text.rs b/Libraries/LibWeb/Rust/src/painting/record/paint/text.rsindex d0a9d2580ba..ae1c575fdfb 100644--- a/Libraries/LibWeb/Rust/src/painting/record/paint/text.rs+++ b/Libraries/LibWeb/Rust/src/painting/record/paint/text.rs@@ -254,14 +254,7 @@ fn compute_render_spans<O: Observer>(.text_fragment_indications.iter().filter(|range| range.text_node == fragment.layout_node)- .filter_map(|range| {- text_fragment::selection_offsets_for_dom_range(- arena,- fragment,- range.start,- range.end,- )- })+ .filter_map(|range| text_fragment::selection_offsets_for_dom_range(arena, fragment, range.start, range.end)).filter(|offsets| offsets.start != offsets.end).collect();if highlights.is_empty() && indication_offsets.is_empty() {@@ -279,7 +272,11 @@ fn compute_render_spans<O: Observer>(}let mut boundaries = vec![0, fragment.length_in_code_units];- boundaries.extend(indication_offsets.iter().flat_map(|offsets| [offsets.start, offsets.end]));+ boundaries.extend(+ indication_offsets+ .iter()+ .flat_map(|offsets| [offsets.start, offsets.end]),+ );for (_, ranges, _) in &highlights {boundaries.extend(ranges.iter().flat_map(|offsets| [offsets.start, offsets.end]));}@@ -453,7 +450,10 @@ pub(crate) fn paint_fragments<O: Observer>(recorder: &mut PaintRecorder<'_, O>,for span in &spans {paint_text_shadow(recorder, block, span, &span.shadow_layers);}- for span in spans.iter().filter(|span| span.text_fragment_indication_background_color.is_some()) {+ for span in spans+ .iter()+ .filter(|span| span.text_fragment_indication_background_color.is_some())+ {let background_color = span.text_fragment_indication_background_color.unwrap();let indication_rect = highlight_rect(recorder, block, span);let converter = recorder.converter;diff --git a/Libraries/LibWebCommon/HTML/NavigationPopulationRequest.cpp b/Libraries/LibWebCommon/HTML/NavigationPopulationRequest.cppindex 64cc2f6c3ea..fa8edabadca 100644--- a/Libraries/LibWebCommon/HTML/NavigationPopulationRequest.cpp+++ b/Libraries/LibWebCommon/HTML/NavigationPopulationRequest.cpp@@ -11,8 +11,55 @@namespace Web::HTML {+// https://wicg.github.io/scroll-to-text-fragment/#extracting-the-fragment-directive+static Optional<String> remove_the_fragment_directive(URL::URL& url)+{+ // 1. Let raw fragment be equal to url's fragment.+ auto const& raw_fragment = url.fragment();++ // 2. Let fragment directive be null.+ Optional<String> fragment_directive;++ // 3. If raw fragment is non-null and contains the fragment directive delimiter as a substring:+ if (raw_fragment.has_value()) {+ // 1. Let position be the string position variable pointing to the first code point of the first instance,+ // if one exists, of the fragment directive delimiter in raw fragment, or past the end of raw fragment+ // otherwise.+ auto position = raw_fragment->find(":~:"sv);+ if (position.has_value()) {+ // 2. Let new fragment be the code point substring by positions of raw fragment from the start of raw+ // fragment to position.+ auto new_fragment = raw_fragment->substring_view(0, *position);++ // 3. Advance position by the code point length of the fragment directive delimiter.+ *position += 3;++ // 4. If position does not point past the end of raw fragment:+ if (*position < raw_fragment->length()) {+ // 1. Set fragment directive to the code point substring to the end of the string raw fragment+ // starting from position.+ fragment_directive = MUST(String::from_utf8(raw_fragment->substring_view(*position)));+ }++ // 5. Set url's fragment to new fragment.+ url.set_fragment(new_fragment);+ }+ }++ // 4. Return fragment directive.+ return fragment_directive;+}+NavigationPopulationRequest create_navigation_population_request(NavigationStartRequest start_request, CrossProcessId document_state_id){+ auto url = start_request.url;+ auto directive_state_id = start_request.directive_state_id;+ auto directive_state_value = start_request.directive_state_value;+ if (directive_state_id.namespace_id == 0 || directive_state_id.local_id == 0)+ directive_state_id = document_state_id;+ if (auto fragment_directive = remove_the_fragment_directive(url); fragment_directive.has_value())+ directive_state_value = move(fragment_directive);+// 4. Let documentState be a new document state with// request referrer policy: referrerPolicy// initiator origin: initiatorOriginSnapshot@@ -38,10 +85,10 @@ NavigationPopulationRequest create_navigation_population_request(NavigationStart// 5. If url matches about:blank or is about:srcdoc, then:// FIXME: Is calling url_matches_about_srcdoc() correct? https://github.com/whatwg/html/issues/10900- if (url_matches_about_blank(start_request.url) || url_matches_about_srcdoc(start_request.url)) {+ if (url_matches_about_blank(url) || url_matches_about_srcdoc(url)) {// AD-HOC: documentResource cannot be null if url is about:srcdoc since create navigation params from a// srcdoc resource expects it to contain a string.- if (url_matches_about_srcdoc(start_request.url) && document_state.resource.has<Empty>())+ if (url_matches_about_srcdoc(url) && document_state.resource.has<Empty>())document_state.resource = Utf16String {};// 1. Set documentState's origin to initiatorOriginSnapshot.@@ -53,7 +100,7 @@ NavigationPopulationRequest create_navigation_population_request(NavigationStart// 6. Let historyEntry be a new session history entry, with its URL set to url and its document state set to documentState.PendingSessionHistoryEntryDescriptor history_entry {- .url = move(start_request.url),+ .url = move(url),.document_state = move(document_state),.classic_history_api_state = move(start_request.classic_history_api_state),.navigation_api_state = move(start_request.navigation_api_state),@@ -61,6 +108,8 @@ NavigationPopulationRequest create_navigation_population_request(NavigationStart.navigation_api_id = move(start_request.navigation_api_id),.scroll_restoration_mode = ScrollRestorationMode::Auto,.scroll_position_data = {},+ .directive_state_id = directive_state_id,+ .directive_state_value = move(directive_state_value),};return {@@ -118,6 +167,8 @@ ErrorOr<void> encode(Encoder& encoder, Web::HTML::NavigationStartRequest const&TRY(encoder.encode(request.navigation_api_state));TRY(encoder.encode(request.navigation_api_key));TRY(encoder.encode(request.navigation_api_id));+ TRY(encoder.encode(request.directive_state_id));+ TRY(encoder.encode(request.directive_state_value));return {};}@@ -146,6 +197,8 @@ ErrorOr<Web::HTML::NavigationStartRequest> decode(Decoder& decoder).navigation_api_state = TRY(decoder.decode<Web::HTML::StorageSerializationRecord>()),.navigation_api_key = TRY(decoder.decode<Utf16String>()),.navigation_api_id = TRY(decoder.decode<Utf16String>()),+ .directive_state_id = TRY(decoder.decode<Web::HTML::CrossProcessId>()),+ .directive_state_value = TRY(decoder.decode<Optional<String>>()),};}diff --git a/Libraries/LibWebView/CanonicalNavigable.cpp b/Libraries/LibWebView/CanonicalNavigable.cppindex 84a15fb8028..b5c87f8400b 100644--- a/Libraries/LibWebView/CanonicalNavigable.cpp+++ b/Libraries/LibWebView/CanonicalNavigable.cpp@@ -304,6 +304,8 @@ void CanonicalNavigable::begin_navigation(Web::HTML::PreparedNavigationDescripto.navigation_api_state = Web::HTML::storage_serialization_record_for_undefined(),.navigation_api_key = generate_a_random_uuid(),.navigation_api_id = generate_a_random_uuid(),+ .directive_state_id = {},+ .directive_state_value = {},};auto retry = prepare_navigation_to_retry(start_request);set_ongoing_navigation({diff --git a/Libraries/LibWebView/CanonicalTraversable.cpp b/Libraries/LibWebView/CanonicalTraversable.cppindex dd5169565fc..24754a0c61a 100644--- a/Libraries/LibWebView/CanonicalTraversable.cpp+++ b/Libraries/LibWebView/CanonicalTraversable.cpp@@ -2052,6 +2052,8 @@ NonnullRefPtr<CanonicalSessionHistoryEntry> CanonicalTraversable::session_histor{auto entry = CanonicalSessionHistoryEntry::create(navigable.active_session_history_entry()->document_state);entry->url = same_document_entry.url;+ entry->directive_state_id = same_document_entry.directive_state_id;+ entry->directive_state_value = same_document_entry.directive_state_value;entry->classic_history_api_state = same_document_entry.classic_history_api_state;entry->navigation_api_state = same_document_entry.navigation_api_state;entry->navigation_api_key = same_document_entry.navigation_api_key;@@ -2438,6 +2440,10 @@ void CanonicalTraversable::finalize_a_same_document_navigation(HistoryOperation&target_step = current_step;}+ // Canonical entries carry a stable ID and a copied value for a directive state shared across+ // history entries. Keep those copies synchronized when the shared state is mutated.+ m_session_history.update_directive_state_value(target_entry->directive_state_id, target_entry->directive_state_value);+target_navigable->set_active_session_history_entry(target_entry);// 6. Apply the push/replace history step targetStep to traversable given historyHandling and userInvolvement.diff --git a/Libraries/LibWebView/HistoryStore.cpp b/Libraries/LibWebView/HistoryStore.cppindex 963fafc5773..a96b7620d45 100644--- a/Libraries/LibWebView/HistoryStore.cpp+++ b/Libraries/LibWebView/HistoryStore.cpp@@ -468,7 +468,8 @@ ErrorOr<NonnullOwnPtr<HistoryStore>> HistoryStore::create(Database::Database& da)#"sv));statements.delete_omnibox_engagements_for_url = TRY(database.prepare_statement(R"#(DELETE FROM OmniboxEngagements- WHERE destination_kind = 0 AND destination_key = ?;+ WHERE destination_kind = 0+ AND (destination_key = ?1 OR substr(destination_key, 1, length(?1) + 1) = ?1 || '#');)#"sv));statements.delete_omnibox_engagements_used_since = TRY(database.prepare_statement(R"#(DELETE FROM OmniboxEngagements@@ -978,8 +979,11 @@ void HistoryStore::TransientStorage::remove_entry_for_url(String const& url, Remif (remove_engagements == RemoveHistoryEntryEngagements::No)return;m_omnibox_engagements.remove_all_matching([&](auto const& engagement) {- return engagement.destination_kind == OmniboxDestinationKind::URL- && normalize_omnibox_destination(engagement.destination, engagement.destination_kind) == url;+ if (engagement.destination_kind != OmniboxDestinationKind::URL)+ return false;+ auto destination = normalize_omnibox_destination(engagement.destination, engagement.destination_kind);+ return destination == url+ || (destination.bytes_as_string_view().starts_with(url) && destination.bytes_as_string_view()[url.bytes_as_string_view().length()] == '#');});}diff --git a/Libraries/LibWebView/OmniboxEngagement.cpp b/Libraries/LibWebView/OmniboxEngagement.cppindex fe0cced72b2..0c07c457798 100644--- a/Libraries/LibWebView/OmniboxEngagement.cpp+++ b/Libraries/LibWebView/OmniboxEngagement.cpp@@ -55,7 +55,7 @@ String normalize_omnibox_destination(StringView destination, OmniboxDestinationKurl = URL::Parser::basic_parse(MUST(String::formatted("https://{}", destination)));if (!url.has_value())return MUST(String::from_utf8(destination.trim_whitespace()));- return url->serialize(URL::ExcludeFragment::Yes);+ return url->serialize();}}diff --git a/Libraries/LibWebView/SessionHistory.cpp b/Libraries/LibWebView/SessionHistory.cppindex e77caeb6475..191716bccc5 100644--- a/Libraries/LibWebView/SessionHistory.cpp+++ b/Libraries/LibWebView/SessionHistory.cpp@@ -7,11 +7,29 @@#include <AK/HashTable.h>#include <AK/NumericLimits.h>#include <AK/QuickSort.h>+#include <AK/StringBuilder.h>+#include <LibURL/Parser.h>#include <LibWebView/CanonicalNavigable.h>#include <LibWebView/SessionHistory.h>namespace WebView {+URL::URL display_url_for_session_history_entry(Web::HTML::SessionHistoryEntryDescriptor const& entry, bool include_fragment_directive)+{+ auto displayed_url = entry.url;+ if (!include_fragment_directive || !entry.directive_state_value.has_value())+ return displayed_url;++ StringBuilder fragment;+ if (displayed_url.fragment().has_value())+ fragment.append(*displayed_url.fragment());+ fragment.append(":~:"sv);+ fragment.append(*entry.directive_state_value);+ auto fragment_string = MUST(fragment.to_string());+ displayed_url.set_fragment(fragment_string.bytes_as_string_view());+ return displayed_url;+}+// https://html.spec.whatwg.org/multipage/browsing-the-web.html#getting-all-used-history-stepsstatic Vector<i32> get_all_used_history_steps(Vector<NonnullRefPtr<CanonicalSessionHistoryEntry>> const& traversable_session_history_entries){@@ -351,6 +369,27 @@ bool TraversableSessionHistory::replace_session_history_entry(CanonicalNavigablereturn true;}+void TraversableSessionHistory::update_directive_state_value(Web::HTML::CrossProcessId directive_state_id, Optional<String> directive_state_value)+{+ if (directive_state_id.namespace_id == 0 || directive_state_id.local_id == 0)+ return;++ Vector<Vector<NonnullRefPtr<CanonicalSessionHistoryEntry>>*> entry_lists { &m_entries };++ for (size_t i = 0; i < entry_lists.size(); ++i) {+ auto* entries = entry_lists[i];+ for (auto& entry : *entries) {+ if (entry->directive_state_id == directive_state_id)+ entry->directive_state_value = directive_state_value;++ for (auto& nested_history : entry->document_state->nested_histories) {+ if (!entry_lists.contains_slow(&nested_history.entries))+ entry_lists.append(&nested_history.entries);+ }+ }+ }+}+size_t TraversableSessionHistory::current_top_level_entry_index() const{return top_level_entry_index_for_step(m_entries, m_current_session_history_step).value();diff --git a/Libraries/LibWebView/SessionHistory.h b/Libraries/LibWebView/SessionHistory.hindex c77ff7f16c0..3d8017cc82d 100644--- a/Libraries/LibWebView/SessionHistory.h+++ b/Libraries/LibWebView/SessionHistory.h@@ -56,6 +56,7 @@ public:// Replaces entry_to_replace in navigable's session history entries with entry, at its step. Changes nothing if// entry_to_replace is not among them.bool replace_session_history_entry(CanonicalNavigable const&, CanonicalSessionHistoryEntry const& entry_to_replace, NonnullRefPtr<CanonicalSessionHistoryEntry>);+ void update_directive_state_value(Web::HTML::CrossProcessId, Optional<String>);Vector<Web::HTML::SessionHistoryEntryDescriptor> entries() const;// https://html.spec.whatwg.org/multipage/browsing-the-web.html#getting-all-used-history-stepsVector<i32> used_steps() const;@@ -99,5 +100,6 @@ struct SessionHistorySnapshot {};WEBVIEW_API ErrorOr<void> validate_snapshot_is_restorable(Vector<Web::HTML::SessionHistoryEntryDescriptor> const& entries, Vector<i32> const& used_steps, size_t current_used_step_index);+WEBVIEW_API URL::URL display_url_for_session_history_entry(Web::HTML::SessionHistoryEntryDescriptor const&, bool include_fragment_directive = true);}diff --git a/Libraries/LibWebView/URL.cpp b/Libraries/LibWebView/URL.cppindex 034cc08f1f8..fbd5cb05b4a 100644--- a/Libraries/LibWebView/URL.cpp+++ b/Libraries/LibWebView/URL.cpp@@ -235,7 +235,7 @@ bool autocomplete_urls_match(StringView left, StringView right)if (!left_url.has_value() || !right_url.has_value())return false;- return left_url->equals(*right_url, URL::ExcludeFragment::Yes);+ return left_url->equals(*right_url);}bool autocomplete_url_can_complete(StringView query, StringView suggestion)@@ -251,7 +251,7 @@ bool autocomplete_url_can_complete(StringView query, StringView suggestion)&& form.starts_with(query, CaseSensitivity::CaseInsensitive);};- auto serialized_suggestion = suggestion_url->serialize(URL::ExcludeFragment::Yes);+ auto serialized_suggestion = suggestion_url->serialize();if (can_complete_form(serialized_suggestion))return true;diff --git a/Libraries/LibWebView/ViewImplementation.cpp b/Libraries/LibWebView/ViewImplementation.cppindex 1f9fc31dedc..454ead67a6e 100644--- a/Libraries/LibWebView/ViewImplementation.cpp+++ b/Libraries/LibWebView/ViewImplementation.cpp@@ -148,16 +148,49 @@ WebContentPage& ViewImplementation::page() constvoid ViewImplementation::set_url(URL::URL url){- if (m_url == url)- return;+ if (url.fragment().has_value() && url.fragment()->contains(":~:"sv))+ m_text_fragment_indication_is_visible = true;++ if (m_url != url) {+ m_url = move(url);+ update_bookmark_action();+ if (auto page = traversable().display_page(); page && page->routed_connection())+ page->routed_connection()->update_audio_capture_permission();+ }- m_url = move(url);- update_bookmark_action();- if (auto page = traversable().display_page(); page && page->routed_connection())- page->routed_connection()->update_audio_capture_permission();+ update_displayed_url();+}+void ViewImplementation::update_displayed_url()+{+ auto displayed_url = m_url;+ auto displayed_url_without_fragment_directive = displayed_url;+ if (auto const& raw_fragment = displayed_url_without_fragment_directive.fragment(); raw_fragment.has_value()) {+ if (auto position = raw_fragment->find(":~:"sv); position.has_value())+ displayed_url_without_fragment_directive.set_fragment(raw_fragment->substring_view(0, *position));+ }+ if (!m_text_fragment_indication_is_visible)+ displayed_url = displayed_url_without_fragment_directive;++ if (m_top_level_traversable) {+ auto const& current_entry = traversable().session_history().current_entry();+ if (current_entry.url == displayed_url_without_fragment_directive)+ displayed_url = display_url_for_session_history_entry(current_entry.descriptor(), m_text_fragment_indication_is_visible);+ }++ if (m_displayed_url == displayed_url)+ return;+ m_displayed_url = move(displayed_url);if (on_url_change)- on_url_change(m_url);+ on_url_change(m_displayed_url);+}++void ViewImplementation::set_text_fragment_indication_visibility(Badge<WebContentPage>, bool visible)+{+ if (m_text_fragment_indication_is_visible == visible)+ return;+ m_text_fragment_indication_is_visible = visible;+ update_displayed_url();}void ViewImplementation::set_title(Badge<WebContentPage>, Utf16String title)diff --git a/Libraries/LibWebView/ViewImplementation.h b/Libraries/LibWebView/ViewImplementation.hindex ba45fedc4c3..fb12d13e916 100644--- a/Libraries/LibWebView/ViewImplementation.h+++ b/Libraries/LibWebView/ViewImplementation.h@@ -117,7 +117,9 @@ public:void did_stop_loading(Badge<CanonicalTraversable>, bool stopped_navigation);void set_url(Badge<WebContentPage>, URL::URL url) { set_url(move(url)); }+ void set_text_fragment_indication_visibility(Badge<WebContentPage>, bool);URL::URL const& url() const { return m_url; }+ URL::URL const& displayed_url() const { return m_displayed_url; }void set_title(Badge<WebContentPage>, Utf16String title);Utf16String const& title() const { return m_title; }@@ -584,6 +586,7 @@ protected:explicit ViewImplementation(IsPrivate = IsPrivate::No);void set_url(URL::URL);+ void update_displayed_url();void did_start_navigation();void did_finish_navigation();void did_end_uncommitted_navigation(StringView reason);@@ -695,6 +698,8 @@ protected:NonnullRefPtr<BrowsingSession> m_session;URL::URL m_url { URL::about_blank() };+ URL::URL m_displayed_url { URL::about_blank() };+ bool m_text_fragment_indication_is_visible { false };Utf16String m_title;Optional<String> m_favicon_hash;diff --git a/Libraries/LibWebView/WebContentPage.cpp b/Libraries/LibWebView/WebContentPage.cppindex c5cc2ad61dd..ed96a141f6e 100644--- a/Libraries/LibWebView/WebContentPage.cpp+++ b/Libraries/LibWebView/WebContentPage.cpp@@ -855,6 +855,12 @@ void WebContentPage::did_update_editing_history_state(bool can_undo, bool can_review().set_editing_history_state(can_undo, can_redo);}+void WebContentPage::did_set_text_fragment_indication_visibility(bool visible)+{+ if (displays_tab())+ view().set_text_fragment_indication_visibility({}, visible);+}+void WebContentPage::did_request_tooltip_override(Gfx::IntPoint position, ByteString title){if (displays_tab()) {diff --git a/Libraries/LibWebView/WebContentPage.h b/Libraries/LibWebView/WebContentPage.hindex 0649b41a3ad..ff08d6d218c 100644--- a/Libraries/LibWebView/WebContentPage.h+++ b/Libraries/LibWebView/WebContentPage.h@@ -181,6 +181,7 @@ private:virtual void did_request_refresh() override;virtual void did_request_cursor_change(Gfx::Cursor cursor) override;virtual void did_update_editing_history_state(bool can_undo, bool can_redo) override;+ virtual void did_set_text_fragment_indication_visibility(bool visible) override;virtual void did_request_tooltip_override(Gfx::IntPoint position, ByteString title) override;virtual void did_stop_tooltip_override() override;virtual void did_enter_tooltip_area(ByteString title) override;diff --git a/Services/WebContent/PageClient.cpp b/Services/WebContent/PageClient.cppindex d7180b9f128..a4eb6974bb8 100644--- a/Services/WebContent/PageClient.cpp+++ b/Services/WebContent/PageClient.cpp@@ -337,7 +337,7 @@ void PageClient::navigate_to_a_fragment(Web::HTML::CrossProcessId navigable_id,auto* navigable = as_if<Web::HTML::LocalNavigable>(page().navigable_with_id(navigable_id).ptr());if (!navigable || navigable->has_been_destroyed() || !navigable->active_window())return;- navigable->navigate_to_a_fragment(url, history_handling, user_involvement, nullptr, {}, move(navigation_id), nullptr);+ navigable->navigate_to_a_fragment(url, history_handling, user_involvement, nullptr, {}, move(navigation_id), nullptr, {});}void PageClient::navigate_to_a_javascript_url(Web::HTML::CrossProcessId navigable_id, URL::URL const& url, Web::HTML::HistoryHandlingBehavior history_handling, URL::Origin const& initiator_origin, Web::HTML::NavigationSourceSnapshot const& source_snapshot_params, Web::HTML::UserNavigationInvolvement user_involvement, Web::ContentSecurityPolicy::Directives::Directive::NavigationType csp_navigation_type, Utf16String navigation_id)@@ -856,6 +856,10 @@ void PageClient::page_did_update_editing_history_state(bool can_undo, bool can_rclient().async_did_update_editing_history_state(m_id, can_undo, can_redo);}+void PageClient::page_did_set_text_fragment_indication_visibility(bool visible)+{+ client().async_did_set_text_fragment_indication_visibility(m_id, visible);+}void PageClient::page_did_request_refresh(){client().async_did_request_refresh(m_id);diff --git a/Services/WebContent/PageClient.h b/Services/WebContent/PageClient.hindex 82607fcb113..a362331f362 100644--- a/Services/WebContent/PageClient.h+++ b/Services/WebContent/PageClient.h@@ -226,6 +226,7 @@ private:virtual void inject_rendering_opportunity(double frame_time) override;virtual void page_did_change_title(Utf16String const&) override;virtual void page_did_update_editing_history_state(bool can_undo, bool can_redo) override;+ virtual void page_did_set_text_fragment_indication_visibility(bool) override;virtual void page_did_request_refresh() override;virtual void page_did_request_resize_window(Gfx::IntSize, u64 completion_id) override;virtual void page_did_request_reposition_window(Gfx::IntPoint, u64 completion_id) override;diff --git a/Services/WebContent/WebContentClient.ipc b/Services/WebContent/WebContentClient.ipcindex 0742037c164..39916cb691d 100644--- a/Services/WebContent/WebContentClient.ipc+++ b/Services/WebContent/WebContentClient.ipc@@ -115,6 +115,7 @@ endpoint WebContentClient routed by Web::PageId page_iddid_request_cursor_change(Web::PageId page_id, Gfx::Cursor cursor) =|did_change_title(Web::PageId page_id, Utf16String title) =|did_update_editing_history_state(Web::PageId page_id, bool can_undo, bool can_redo) =|+ did_set_text_fragment_indication_visibility(Web::PageId page_id, bool visible) =|did_request_tooltip_override(Web::PageId page_id, Gfx::IntPoint position, ByteString title) =|did_stop_tooltip_override(Web::PageId page_id) =|did_enter_tooltip_area(Web::PageId page_id, ByteString title) =|diff --git a/Tests/LibWeb/Ref/expected/scroll-to-text-fragment-indication-ref.html b/Tests/LibWeb/Ref/expected/scroll-to-text-fragment-indication-ref.htmlindex a343f1982d9..be6fa1f02fa 100644--- a/Tests/LibWeb/Ref/expected/scroll-to-text-fragment-indication-ref.html+++ b/Tests/LibWeb/Ref/expected/scroll-to-text-fragment-indication-ref.html@@ -4,9 +4,17 @@ p {font: 20px sans-serif;line-height: 1.5;}-.indication {+::selection {color: black;background: yellow;}</style>-<p>Before <span class="indication">Highlighted passage</span> after</p>+<p>Before Highlighted passage after</p>+<script>+const text = document.querySelector("p").firstChild;+const start = text.textContent.indexOf("Highlighted passage");+const range = new Range();+range.setStart(text, start);+range.setEnd(text, start + "Highlighted passage".length);+getSelection().addRange(range);+</script>diff --git a/Tests/LibWebView/TestApplyHistoryStep.cpp b/Tests/LibWebView/TestApplyHistoryStep.cppindex 7e6f2665047..d6e5f3e6feb 100644--- a/Tests/LibWebView/TestApplyHistoryStep.cpp+++ b/Tests/LibWebView/TestApplyHistoryStep.cpp@@ -67,6 +67,8 @@ static WebView::CanonicalNavigation::Start navigation_for_testing(Utf16String na.navigation_api_state = {},.navigation_api_key = {},.navigation_api_id = {},+ .directive_state_id = {},+ .directive_state_value = {},} },.history_entry = move(history_entry),};diff --git a/Tests/LibWebView/TestAutocompleteMuxer.cpp b/Tests/LibWebView/TestAutocompleteMuxer.cppindex 9860bc5679f..f35eb66cb55 100644--- a/Tests/LibWebView/TestAutocompleteMuxer.cpp+++ b/Tests/LibWebView/TestAutocompleteMuxer.cpp@@ -6,6 +6,7 @@#include <LibTest/TestCase.h>#include <LibWebView/AutocompleteMuxer.h>+#include <LibWebView/OmniboxEngagement.h>namespace {@@ -302,6 +303,32 @@ TEST_CASE(http_and_https_destinations_are_not_deduplicated)EXPECT_EQ(results.size(), 2u);}+TEST_CASE(fragment_literal_is_not_replaced_by_fragmentless_history)+{+ auto const fragment_url = "https://example.com/page#target"sv;+ auto literal = suggestion(WebView::AutocompleteSuggestionSource::LiteralURL, fragment_url, 900, true, true);+ auto adaptive = suggestion(WebView::AutocompleteSuggestionSource::Adaptive, "https://example.com/page"sv, 1050, true);++ auto results = WebView::mux_autocomplete_suggestions(+ fragment_url,+ move(literal),+ { move(adaptive) },+ {},+ 8);++ EXPECT_EQ(results.size(), 2u);+ EXPECT_EQ(results[0].source, WebView::AutocompleteSuggestionSource::LiteralURL);+ EXPECT_EQ(results[0].text, fragment_url);+ EXPECT(results[0].is_verbatim);+}++TEST_CASE(fragment_omnibox_destinations_are_preserved)+{+ EXPECT_EQ(+ WebView::normalize_omnibox_destination("https://example.com/page#section"sv, WebView::OmniboxDestinationKind::URL),+ "https://example.com/page#section"sv);+}+TEST_CASE(history_and_bookmark_evidence_is_combined){auto history_suggestion = history("https://example.com/"sv, 900);diff --git a/Tests/LibWebView/TestCanonicalBrowsingContextGroup.cpp b/Tests/LibWebView/TestCanonicalBrowsingContextGroup.cppindex 308113f6e4b..95916f73bd7 100644--- a/Tests/LibWebView/TestCanonicalBrowsingContextGroup.cpp+++ b/Tests/LibWebView/TestCanonicalBrowsingContextGroup.cpp@@ -47,6 +47,8 @@ static WebView::CanonicalNavigation::Start navigation_for_testing(Utf16String na.navigation_api_state = {},.navigation_api_key = {},.navigation_api_id = {},+ .directive_state_id = {},+ .directive_state_value = {},} },.history_entry = move(history_entry),};diff --git a/Tests/LibWebView/TestHistoryStore.cpp b/Tests/LibWebView/TestHistoryStore.cppindex cabe51f30ad..21b309a9192 100644--- a/Tests/LibWebView/TestHistoryStore.cpp+++ b/Tests/LibWebView/TestHistoryStore.cpp@@ -155,13 +155,26 @@ static void expect_omnibox_engagements_are_normalized_and_accumulated(WebView::HUnixDateTime::from_seconds_since_epoch(30));auto url_engagements = store.omnibox_engagements("DO"sv);- VERIFY(url_engagements.size() == 1);- EXPECT_EQ(url_engagements[0].normalized_input, "docs"sv);- EXPECT_EQ(url_engagements[0].destination_kind, WebView::OmniboxDestinationKind::URL);- EXPECT_EQ(url_engagements[0].destination, "https://example.com/manual"sv);- EXPECT_EQ(url_engagements[0].explicit_use_count, 1u);- EXPECT_EQ(url_engagements[0].default_use_count, 1u);- EXPECT_EQ(url_engagements[0].last_used_time, UnixDateTime::from_seconds_since_epoch(20));+ VERIFY(url_engagements.size() == 2);+ auto first_fragment = url_engagements.find_if([](auto const& engagement) {+ return engagement.destination == "https://example.com/manual#first"sv;+ });+ VERIFY(first_fragment != url_engagements.end());+ EXPECT_EQ(first_fragment->normalized_input, "docs"sv);+ EXPECT_EQ(first_fragment->destination_kind, WebView::OmniboxDestinationKind::URL);+ EXPECT_EQ(first_fragment->explicit_use_count, 1u);+ EXPECT_EQ(first_fragment->default_use_count, 0u);+ EXPECT_EQ(first_fragment->last_used_time, UnixDateTime::from_seconds_since_epoch(10));++ auto second_fragment = url_engagements.find_if([](auto const& engagement) {+ return engagement.destination == "https://example.com/manual#second"sv;+ });+ VERIFY(second_fragment != url_engagements.end());+ EXPECT_EQ(second_fragment->normalized_input, "docs"sv);+ EXPECT_EQ(second_fragment->destination_kind, WebView::OmniboxDestinationKind::URL);+ EXPECT_EQ(second_fragment->explicit_use_count, 0u);+ EXPECT_EQ(second_fragment->default_use_count, 1u);+ EXPECT_EQ(second_fragment->last_used_time, UnixDateTime::from_seconds_since_epoch(20));auto search_engagements = store.omnibox_engagements("lady"sv);VERIFY(search_engagements.size() == 1);@@ -203,7 +216,7 @@ static void expect_history_entries_can_be_removed(WebView::HistoryStore& store)store.record_omnibox_engagement({.input = "example"_string,.destination_kind = WebView::OmniboxDestinationKind::URL,- .destination = example_url.serialize(),+ .destination = MUST(String::formatted("{}#fragment", example_url.serialize())),.was_explicit = true,});store.record_omnibox_engagement({diff --git a/Tests/LibWebView/TestRendererOriginClaims.cpp b/Tests/LibWebView/TestRendererOriginClaims.cppindex d65d1da8bfd..23574600b2c 100644--- a/Tests/LibWebView/TestRendererOriginClaims.cpp+++ b/Tests/LibWebView/TestRendererOriginClaims.cpp@@ -96,6 +96,8 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments).navigation_api_state = {},.navigation_api_key = {},.navigation_api_id = {},+ .directive_state_id = {},+ .directive_state_value = {},};stub.did_request_navigation_start(page_id, traversable.id(), Web::NavigationTarget::TopLevel, URL::about_blank(), navigation_id, move(request));return traversable.navigation_with_id(navigation_id) != nullptr;diff --git a/Tests/LibWebView/TestSessionHistory.cpp b/Tests/LibWebView/TestSessionHistory.cppindex b4e332dc109..31da5e2c490 100644--- a/Tests/LibWebView/TestSessionHistory.cpp+++ b/Tests/LibWebView/TestSessionHistory.cpp@@ -10,6 +10,7 @@#include <LibURL/Parser.h>#include <LibWebCommon/HTML/CrossProcessId.h>#include <LibWebView/CanonicalBrowsingContext.h>+#include <LibWebView/CanonicalSessionHistoryEntry.h>#include <LibWebView/CanonicalTraversable.h>#include <LibWebView/HistoryDebug.h>#include <LibWebView/SessionHistory.h>@@ -273,26 +274,34 @@ static void run_canonical_history_operation(WebView::CanonicalTraversable& traveVERIFY(queue_promise->is_resolved());}-TEST_CASE(display_url_includes_fragment_directive_state)+TEST_CASE(fragment_directive_state_is_separate_from_entry_url){auto entry = create_test_entry(0, parse_url("https://example.test/#feature-detectability"sv));entry.directive_state_value = "text=For-,feature%20detectability"_string;-EXPECT_EQ(WebView::display_url_for_session_history_entry(entry),parse_url("https://example.test/#feature-detectability:~:text=For-,feature%20detectability"sv));+ EXPECT_EQ(+ WebView::display_url_for_session_history_entry(entry, false),+ parse_url("https://example.test/#feature-detectability"sv));entry.directive_state_value.clear();EXPECT_EQ(WebView::display_url_for_session_history_entry(entry),parse_url("https://example.test/#feature-detectability"sv));++ entry.directive_state_value = "text=For-,feature%20detectability"_string;+ auto canonical_entry = MUST(WebView::CanonicalSessionHistoryEntry::create_from_descriptor(entry));+ auto descriptor = canonical_entry->descriptor();+ EXPECT_EQ(descriptor.url, parse_url("https://example.test/#feature-detectability"sv));+ EXPECT_EQ(descriptor.directive_state_value, "text=For-,feature%20detectability"sv);}TEST_CASE(replace_navigation_updates_every_shared_directive_state_descriptor){Core::EventLoop event_loop;- WebView::CanonicalTraversable traversable;- traversable.set_id({ 9, 1 });+ WebView::CanonicalTraversable traversable({ 9, 1 }, canonical_entry(entry(0, "https://example.test/initial"sv)));+ give_active_document(traversable);auto shared_directive_state_id = test_document_state_id(3000);auto first_entry = entry(0, "https://example.test/first"sv);@@ -320,8 +329,7 @@ TEST_CASE(replace_navigation_updates_every_shared_directive_state_descriptor).history_handling = Web::HTML::HistoryHandlingBehavior::Replace,.user_involvement = Web::HTML::UserNavigationInvolvement::None,};- auto operation_result = run_canonical_history_operation(traversable, move(request));- EXPECT_EQ(operation_result.result, Web::HTML::HistoryStepResult::Applied);+ run_canonical_history_operation(traversable, move(request));EXPECT_EQ(traversable.session_history().entry_at(0)->directive_state_value, "text=new"sv);EXPECT_EQ(traversable.session_history().entry_at(1)->directive_state_value, "text=new"sv);diff --git a/Tests/LibWebView/TestWebViewURL.cpp b/Tests/LibWebView/TestWebViewURL.cppindex c57ad4d04ea..4c04753dc72 100644--- a/Tests/LibWebView/TestWebViewURL.cpp+++ b/Tests/LibWebView/TestWebViewURL.cpp@@ -386,7 +386,8 @@ TEST_CASE(context_menu_url_text)TEST_CASE(autocomplete_url_matching){- expect_autocomplete_urls_match("example.com/path?q=1"sv, "https://example.com/path?q=1#fragment"sv);+ expect_autocomplete_urls_match("example.com/path?q=1#fragment"sv, "https://example.com/path?q=1#fragment"sv);+ expect_autocomplete_urls_match("https://example.com/page#:~:text=target"sv, "https://example.com/page#:~:text=target"sv);expect_autocomplete_urls_do_not_match("google.com"sv, "https://www.google.com/"sv);expect_autocomplete_urls_do_not_match("http://example.com"sv, "https://example.com/"sv);@@ -394,6 +395,9 @@ TEST_CASE(autocomplete_url_matching)expect_autocomplete_urls_do_not_match("https://example.com"sv, "https://example.com:8443"sv);expect_autocomplete_urls_do_not_match("hello"sv, "https://hello.example/"sv);expect_autocomplete_urls_do_not_match("steam://launch/1536610"sv, "https://steam://launch/1536610"sv);+ expect_autocomplete_urls_do_not_match("example.com/path?q=1"sv, "https://example.com/path?q=1#fragment"sv);+ expect_autocomplete_urls_do_not_match("https://example.com/page"sv, "https://example.com/page#:~:text=target"sv);+ expect_autocomplete_urls_do_not_match("https://example.com/page#section"sv, "https://example.com/page#section:~:text=target"sv);}TEST_CASE(autocomplete_url_completion)@@ -402,6 +406,7 @@ TEST_CASE(autocomplete_url_completion)expect_autocomplete_url_can_complete("reddit.co"sv, "https://reddit.com/"sv);expect_autocomplete_url_can_complete("https://reddit.co"sv, "https://www.reddit.com/"sv);expect_autocomplete_url_can_complete("www.reddit.co"sv, "https://www.reddit.com/"sv);+ expect_autocomplete_url_can_complete("example.com/page#sec"sv, "https://example.com/page#section"sv);expect_autocomplete_url_cannot_complete("reddit.com"sv, "https://reddit.com/"sv);expect_autocomplete_url_cannot_complete("reddit.co"sv, "https://reddit.co/"sv);diff --git a/UI/Qt/Application.cpp b/UI/Qt/Application.cppindex 67d40737271..568a0a0025b 100644--- a/UI/Qt/Application.cpp+++ b/UI/Qt/Application.cpp@@ -1259,7 +1259,7 @@ NonnullRefPtr<Application::BookmarkPromise> Application::display_add_bookmark_diOptional<String> current_favicon_hash;if (auto view = active_web_view(); view.has_value()) {- current_url = view->url();+ current_url = view->displayed_url();current_title = view->title().to_utf8();current_favicon_hash = view->favicon_hash();}