Truly independent web browser
LibWeb: Track a writing suggestion at the caret
sideshowbarkerf31290cfc05a
diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txtindex d4f501c0783..b369ea11f9e 100644--- a/Libraries/LibWeb/CMakeLists.txt+++ b/Libraries/LibWeb/CMakeLists.txt@@ -331,6 +331,7 @@ set(SOURCESEditing/ReplacementRangeCleanup.cppEditing/ReplacementStyleCleanup.cppEditing/SpellCheckController.cpp+ Editing/WritingSuggestionController.cppEditing/SpellingMarkers.cppEditing/StyledMarkupAccumulator.cppEditing/StyledMarkupSelection.cppdiff --git a/Libraries/LibWeb/DOM/CharacterData.cpp b/Libraries/LibWeb/DOM/CharacterData.cppindex 4572e78e3e9..ac532c0d691 100644--- a/Libraries/LibWeb/DOM/CharacterData.cpp+++ b/Libraries/LibWeb/DOM/CharacterData.cpp@@ -18,6 +18,7 @@#include <LibWeb/DOM/Text.h>#include <LibWeb/Editing/EditingHistory.h>#include <LibWeb/Editing/SpellingMarkers.h>+#include <LibWeb/Editing/WritingSuggestionController.h>#include <LibWeb/PaintTiming/PaintTiming.h>#include <LibWeb/Selection/Selection.h>@@ -175,6 +176,9 @@ WebIDL::ExceptionOr<void> CharacterData::replace_data(size_t offset, size_t counif (has_spelling_markers())document().spelling_markers().did_replace_data(as<Text>(*this), offset, count, data.length_in_code_units());+ if (auto* controller = document().writing_suggestion_controller_if_exists(); controller && is<Text>(*this))+ controller->did_change_text(as<Text>(*this));+// A text node holding nothing leaves its parent `:empty`, so data arriving in it or leaving it// moves the parent's emptiness without any node being created or destroyed.if (is<Text>(*this) && old_data.is_empty() != m_data.is_empty()) {diff --git a/Libraries/LibWeb/DOM/Document.cpp b/Libraries/LibWeb/DOM/Document.cppindex b43452002d5..7d798c7abae 100644--- a/Libraries/LibWeb/DOM/Document.cpp+++ b/Libraries/LibWeb/DOM/Document.cpp@@ -136,6 +136,7 @@#include <LibWeb/Editing/EditingHistory.h>#include <LibWeb/Editing/SpellCheckController.h>#include <LibWeb/Editing/SpellingMarkers.h>+#include <LibWeb/Editing/WritingSuggestionController.h>#include <LibWeb/Fetch/Fetching/Checks.h>#include <LibWeb/Fetch/Infrastructure/FetchController.h>#include <LibWeb/Fetch/Infrastructure/FetchRecord.h>@@ -1050,6 +1051,8 @@ void Document::visit_edges(Cell::Visitor& visitor)m_spelling_markers->visit_edges(visitor);if (m_spell_check_controller)m_spell_check_controller->visit_edges(visitor);+ if (m_writing_suggestion_controller)+ m_writing_suggestion_controller->visit_edges(visitor);for (auto& event : m_pending_animation_event_queue) {visitor.visit(event.event);@@ -1202,6 +1205,8 @@ void Document::note_selection_changed()request_frame_for_pending_repaint();if (m_spell_check_controller)m_spell_check_controller->did_change_selection();+ if (m_writing_suggestion_controller)+ m_writing_suggestion_controller->did_change_selection();}void Document::update_highlight_states_if_needed(Layout::BegunRead const& read)@@ -1287,6 +1292,13 @@ Editing::SpellCheckController& Document::spell_check_controller()return *m_spell_check_controller;}+Editing::WritingSuggestionController& Document::writing_suggestion_controller()+{+ if (!m_writing_suggestion_controller)+ m_writing_suggestion_controller = make<Editing::WritingSuggestionController>(*this);+ return *m_writing_suggestion_controller;+}+bool Document::has_spelling_markers() const{return m_spelling_markers && !m_spelling_markers->is_empty();@@ -4153,6 +4165,8 @@ void Document::set_focused_area(GC::Ptr<Node> node, InvalidateFocusPseudoClassesif (navigable() && page().spell_checking_available())spell_check_controller().did_focus(m_focused_area);+ if (m_writing_suggestion_controller)+ m_writing_suggestion_controller->did_focus(m_focused_area);}Element const* Document::active_element() constdiff --git a/Libraries/LibWeb/DOM/Document.h b/Libraries/LibWeb/DOM/Document.hindex ad75c249828..f4b246d3653 100644--- a/Libraries/LibWeb/DOM/Document.h+++ b/Libraries/LibWeb/DOM/Document.h@@ -348,6 +348,9 @@ public:Editing::SpellingMarkers& spelling_markers();Editing::SpellCheckController& spell_check_controller();Editing::SpellCheckController* spell_check_controller_if_exists() { return m_spell_check_controller.ptr(); }+ Editing::WritingSuggestionController& writing_suggestion_controller();+ Editing::WritingSuggestionController* writing_suggestion_controller_if_exists() { return m_writing_suggestion_controller.ptr(); }+ Editing::WritingSuggestionController const* writing_suggestion_controller_if_exists() const { return m_writing_suggestion_controller.ptr(); }bool has_spelling_markers() const;void recompute_search_text_paint_states(Layout::BegunRead const&);void note_spelling_markers_changed();@@ -2159,6 +2162,7 @@ private:Vector<GC::Ref<Range>> m_find_in_page_highlighted_matches;OwnPtr<Editing::SpellingMarkers> m_spelling_markers;OwnPtr<Editing::SpellCheckController> m_spell_check_controller;+ OwnPtr<Editing::WritingSuggestionController> m_writing_suggestion_controller;Vector<Utf16String> m_find_in_page_highlighted_match_texts;u64 m_find_in_page_highlighted_matches_dom_tree_version { 0 };u64 m_find_in_page_highlighted_matches_character_data_version { 0 };diff --git a/Libraries/LibWeb/DOM/Node.h b/Libraries/LibWeb/DOM/Node.hindex 943499c4b1d..4f9296fe0e5 100644--- a/Libraries/LibWeb/DOM/Node.h+++ b/Libraries/LibWeb/DOM/Node.h@@ -135,7 +135,8 @@ enum class SetNeedsLayoutReason {X(StyleChange) \X(SVGResourceContentChange) \X(SVGResourceElementRemoved) \- X(TopLayerMembershipChange)+ X(TopLayerMembershipChange) \+ X(WritingSuggestionChange)enum class SetNeedsLayoutTreeUpdateReason {#define ENUMERATE_SET_NEEDS_LAYOUT_TREE_UPDATE_REASON(e) e,diff --git a/Libraries/LibWeb/Editing/ExecCommand.cpp b/Libraries/LibWeb/Editing/ExecCommand.cppindex ad72be122b8..0d6af6ea52c 100644--- a/Libraries/LibWeb/Editing/ExecCommand.cpp+++ b/Libraries/LibWeb/Editing/ExecCommand.cpp@@ -19,6 +19,7 @@#include <LibWeb/Editing/Internal/Algorithms.h>#include <LibWeb/Editing/SpellCheckController.h>#include <LibWeb/Editing/VisiblePosition.h>+#include <LibWeb/Editing/WritingSuggestionController.h>#include <LibWeb/HTML/HTMLAnchorElement.h>#include <LibWeb/HTML/HTMLInputElement.h>#include <LibWeb/HTML/HTMLLIElement.h>@@ -363,9 +364,12 @@ WebIDL::ExceptionOr<bool> Document::exec_command_internal(Utf16FlyString const&if (!command_result)return false;- // A command the user ran by editing, rather than one a script called, is a user edit for spellchecking.- if (user_input_type.has_value() && tree_was_modified && affected_editing_host)+ // A command the user ran by editing, rather than one a script called, is a user edit for spellchecking and writing+ // suggestions.+ if (user_input_type.has_value() && tree_was_modified && affected_editing_host) {spell_check_controller().did_user_edit(*affected_editing_host);+ writing_suggestion_controller().did_user_edit(*affected_editing_host);+ }// 7. If the action modified DOM tree, then fire an event named "input" at affected editing host using InputEvent,// with its isTrusted and bubbles attributes initialized to true, inputType attribute initialized to the mappeddiff --git a/Libraries/LibWeb/Editing/Internal/Algorithms.cpp b/Libraries/LibWeb/Editing/Internal/Algorithms.cppindex 2426cd82bd5..40241b98c42 100644--- a/Libraries/LibWeb/Editing/Internal/Algorithms.cpp+++ b/Libraries/LibWeb/Editing/Internal/Algorithms.cpp@@ -29,6 +29,7 @@#include <LibWeb/Editing/EditCommand.h>#include <LibWeb/Editing/Internal/Algorithms.h>#include <LibWeb/Editing/MutationTrackedRange.h>+#include <LibWeb/HTML/FormAssociatedElement.h>#include <LibWeb/HTML/HTMLAnchorElement.h>#include <LibWeb/HTML/HTMLBRElement.h>#include <LibWeb/HTML/HTMLDivElement.h>@@ -5377,6 +5378,26 @@ bool value_contains_keyword(CSS::StyleValue const& value, CSS::Keyword keyword)return value.to_keyword() == keyword;}+// Where the user's caret is in text: The focused text control's selection end, or else the selection's focus.+Optional<CaretTextPosition> caret_text_position(DOM::Document& document)+{+ auto focused = document.focused_area();+ if (auto* text_control = as_if<HTML::FormAssociatedTextControlElement>(focused.ptr())) {+ auto text = text_control->form_associated_element_to_text_node();+ if (!text)+ return {};+ auto offset = min<size_t>(text_control->selection_end(), text->length_in_utf16_code_units());+ return CaretTextPosition { *text, offset, text_control->selection_start() == text_control->selection_end() };+ }+ auto selection = document.get_selection();+ if (!selection)+ return {};+ auto* text = as_if<DOM::Text>(selection->focus_node().ptr());+ if (!text)+ return {};+ return CaretTextPosition { *text, selection->focus_offset(), selection->is_collapsed() };+}+// The paragraph around a point in a text node, for triple-click selection and spellchecking. A paragraph is delimited// by block nodes or <br> elements.ParagraphBounds paragraph_bounds_containing(DOM::Text& text_node, WebIDL::UnsignedLong offset)diff --git a/Libraries/LibWeb/Editing/Internal/Algorithms.h b/Libraries/LibWeb/Editing/Internal/Algorithms.hindex 0dd63b742f9..3d9f39a0341 100644--- a/Libraries/LibWeb/Editing/Internal/Algorithms.h+++ b/Libraries/LibWeb/Editing/Internal/Algorithms.h@@ -83,6 +83,12 @@ struct ParagraphBounds {WebIDL::UnsignedLong end_offset { 0 };};ParagraphBounds paragraph_bounds_containing(DOM::Text&, WebIDL::UnsignedLong offset);+struct CaretTextPosition {+ GC::Ref<DOM::Text> text;+ size_t offset { 0 };+ bool is_collapsed { false };+};+Optional<CaretTextPosition> caret_text_position(DOM::Document&);GC::Ref<DOM::Range> paragraph_range_containing(DOM::Text&, WebIDL::UnsignedLong offset);bool is_block_start_point(DOM::BoundaryPoint);bool is_collapsed_block_prop(GC::Ref<DOM::Node>);diff --git a/Libraries/LibWeb/Editing/SpellCheckController.cpp b/Libraries/LibWeb/Editing/SpellCheckController.cppindex 1b28261b49e..53ea43daaa9 100644--- a/Libraries/LibWeb/Editing/SpellCheckController.cpp+++ b/Libraries/LibWeb/Editing/SpellCheckController.cpp@@ -135,24 +135,6 @@ bool SpellCheckController::owns(DOM::Text const& text) constreturn text.is_connected() && &text.document() == m_document.ptr();}-Optional<SpellCheckController::TextPosition> SpellCheckController::caret_position() const-{- auto focused = m_document->focused_area();- if (auto* text_control = as_if<HTML::FormAssociatedTextControlElement>(focused.ptr())) {- auto text = text_control->form_associated_element_to_text_node();- if (!text)- return {};- return TextPosition { *text, min<size_t>(text_control->selection_end(), text->length_in_utf16_code_units()) };- }- auto selection = m_document->get_selection();- if (!selection)- return {};- auto* text = as_if<DOM::Text>(selection->focus_node().ptr());- if (!text)- return {};- return TextPosition { *text, selection->focus_offset() };-}-void SpellCheckController::send_window_around(DOM::Text& text, size_t offset, RequestKind kind){if (!owns(text))@@ -213,7 +195,7 @@ void SpellCheckController::run_typing_check()m_typing_check_wanted = true;return;}- auto caret = caret_position();+ auto caret = caret_text_position(m_document);if (!caret.has_value() || !owns(*caret->text) || !checkable_editable_for(*caret->text))return;// Right after an edit, the word touching the caret is still being typed. Its markers come off, and no answer flags@@ -256,7 +238,7 @@ void SpellCheckController::run_exempt_word_check()return;}// A caret still inside the same word, which typing may have lengthened, keeps it exempt.- if (auto caret = caret_position(); caret.has_value() && caret->text.ptr() == text.ptr()) {+ if (auto caret = caret_text_position(m_document); caret.has_value() && caret->text.ptr() == text.ptr()) {if (auto word = word_touching(*text, caret->offset); word.has_value() && word->start <= exempt.start && exempt.start <= word->end) {m_exempt_word = word;return;diff --git a/Libraries/LibWeb/Editing/SpellCheckController.h b/Libraries/LibWeb/Editing/SpellCheckController.hindex 1d233dcfa71..62e8ff67fba 100644--- a/Libraries/LibWeb/Editing/SpellCheckController.h+++ b/Libraries/LibWeb/Editing/SpellCheckController.h@@ -93,13 +93,7 @@ private:size_t next_offset { 0 };};- struct TextPosition {- GC::Ref<DOM::Text> text;- size_t offset { 0 };- };-bool owns(DOM::Text const&) const;- Optional<TextPosition> caret_position() const;void send_window_around(DOM::Text&, size_t offset, RequestKind);void schedule_typing_check();void run_typing_check();diff --git a/Libraries/LibWeb/Editing/WritingSuggestionController.cpp b/Libraries/LibWeb/Editing/WritingSuggestionController.cppnew file mode 100644index 00000000000..5e00a6ec6e2--- /dev/null+++ b/Libraries/LibWeb/Editing/WritingSuggestionController.cpp@@ -0,0 +1,318 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <LibWeb/DOM/Document.h>+#include <LibWeb/DOM/ShadowRoot.h>+#include <LibWeb/DOM/Text.h>+#include <LibWeb/Editing/Internal/Algorithms.h>+#include <LibWeb/Editing/WritingSuggestionController.h>+#include <LibWeb/HTML/EventLoop/EventLoop.h>+#include <LibWeb/HTML/FormAssociatedElement.h>+#include <LibWeb/HTML/HTMLInputElement.h>+#include <LibWeb/HTML/HTMLTextAreaElement.h>+#include <LibWeb/HTML/Window.h>+#include <LibWeb/Page/Page.h>++namespace Web::Editing {++WritingSuggestionController::WritingSuggestionController(DOM::Document& document)+ : m_document(document)+{+}++void WritingSuggestionController::visit_edges(GC::Cell::Visitor& visitor)+{+ visitor.visit(m_document);+}++// https://html.spec.whatwg.org/multipage/interaction.html#writing-suggestions+bool WritingSuggestionController::is_eligible(DOM::Node const& caret_container)+{+ // User agents should only offer suggestions within an element's scope if the result of running the following+ // algorithm given element returns true:++ // NB: The element is a text control, for text in its user-agent shadow tree, or else the element the caret is in.+ GC::Ptr<DOM::Node const> node = caret_container;+ while (auto shadow_root = node->containing_shadow_root()) {+ if (!shadow_root->is_user_agent_internal())+ break;+ node = shadow_root->host();+ }+ GC::Ptr<DOM::Element const> element = is<DOM::Element>(*node) ? as<DOM::Element>(node.ptr()) : node->parent_element();+ if (!element)+ return false;++ // 1. If the user has disabled writing suggestions, then return false.+ // NB: The UI process asks the platform only if the user has them enabled, and answers with no suggestion otherwise.++ // 2. If none of the following conditions are true:+ // - element is an input element whose type attribute is in either the Text, Search, Telephone, URL, or Email+ // state and element is mutable;+ // - element is a textarea element that is mutable; or+ // - element is an editing host or is editable,+ // then return false.+ auto is_eligible_element = [&] {+ if (auto const* input = as_if<HTML::HTMLInputElement>(*element)) {+ using enum HTML::HTMLInputElement::TypeAttributeState;+ return first_is_one_of(input->type_state(), Text, Search, Telephone, URL, Email) && input->is_mutable();+ }+ if (auto const* text_area = as_if<HTML::HTMLTextAreaElement>(*element))+ return text_area->is_mutable();+ return element->is_editable_or_editing_host();+ };+ if (!is_eligible_element())+ return false;++ // 3. If element has an inclusive ancestor with a writingsuggestions content attribute that's not in the Default and+ // the nearest such ancestor's writingsuggestions content attribute is in the False state, then return false.+ auto const* html_element = as_if<HTML::HTMLElement>(*element);+ if (!html_element)+ html_element = element->first_ancestor_of_type<HTML::HTMLElement>();+ if (html_element && html_element->writing_suggestions() == u"false"sv)+ return false;++ // AD-HOC: The spec doesn't consider autocomplete. But a page that turns autocomplete off on a field likely doesn't+ // want text predicted in it either.+ if (auto autocomplete = element->attribute(HTML::AttributeNames::autocomplete); autocomplete.has_value() && autocomplete->equals_ignoring_ascii_case(u"off"sv))+ return false;++ // 4. Otherwise, return true.+ return true;+}++// Whether layout draws a suggestion in the text. Text that a ::first-letter may split gets none, so a suggestion there+// would be one the user can't see.+bool WritingSuggestionController::can_draw_at(DOM::Text const& text)+{+ if (text.style_node_id().value() == 0)+ return false;+ for (auto const* ancestor = text.parent_or_shadow_host_node(); ancestor; ancestor = ancestor->parent_or_shadow_host_node()) {+ if (auto const* element = as_if<DOM::Element>(*ancestor); element && element->has_style(CSS::PseudoElement::FirstLetter))+ return false;+ }+ return true;+}++// How much of the text before the caret is remembered, to notice a script changing it.+static constexpr size_t SHOWING_PREFIX_SIZE = 64;++static Utf16View text_before(DOM::Text const& text, size_t offset)+{+ auto data = text.data().utf16_view();+ offset = min(offset, data.length_in_code_units());+ auto start = offset > SHOWING_PREFIX_SIZE ? offset - SHOWING_PREFIX_SIZE : 0;+ return data.substring_view(start, offset - start);+}++void WritingSuggestionController::set_showing(Optional<ShowingSuggestion> showing)+{+ auto invalidate = [](Optional<ShowingSuggestion> const& suggestion) {+ if (!suggestion.has_value())+ return;+ if (auto text = suggestion->text.ptr(); text && text->parent())+ text->parent()->set_needs_layout_tree_update(true, DOM::SetNeedsLayoutTreeUpdateReason::WritingSuggestionChange);+ };+ invalidate(m_showing);+ m_showing = move(showing);+ if (m_showing.has_value()) {+ if (auto text = m_showing->text.ptr()) {+ m_showing_text_length = text->length_in_utf16_code_units();+ m_showing_prefix = Utf16String::from_utf16(text_before(*text, m_showing->offset));+ }+ }+ invalidate(m_showing);+}++void WritingSuggestionController::dismiss()+{+ ++m_generation;+ if (m_showing.has_value())+ set_showing({});+}++void WritingSuggestionController::did_focus(GC::Ptr<DOM::Node>)+{+ dismiss();+}++// Typing what the suggestion proposes keeps the rest of it showing right away, so it doesn't flicker while a new one+// is on its way. Any other edit drops it. Either way, the text at the caret gets a new prediction.+void WritingSuggestionController::did_user_edit(DOM::Node&)+{+ if (!m_document->page().writing_suggestions_available())+ return;+ ++m_generation;+ if (m_showing.has_value()) {+ auto showing = *m_showing;+ auto text = showing.text.ptr();+ auto caret = caret_text_position(m_document);+ auto typed_through = [&] {+ if (!text || !caret.has_value() || !caret->is_collapsed || caret->text.ptr() != text.ptr() || caret->offset <= showing.offset)+ return false;+ auto typed = caret->offset - showing.offset;+ auto data = text->data().utf16_view();+ return typed < showing.remainder.length_in_code_units()+ && data.length_in_code_units() == m_showing_text_length + typed+ && data.substring_view(showing.offset, typed) == showing.remainder.utf16_view().substring_view(0, typed);+ };+ if (typed_through()) {+ auto typed = caret->offset - showing.offset;+ set_showing(ShowingSuggestion { *text, caret->offset, Utf16String::from_utf16(showing.remainder.utf16_view().substring_view(typed)) });+ } else {+ set_showing({});+ }+ }+ // Committing a composition ends it, and did_end_input_method_composition() then sends the request.+ if (m_document->is_input_method_composing())+ return;+ schedule_request();+}++// When a script changes the text under the suggestion that's showing, the caret moves without a selection change — so+// the suggestion is checked against the text once the change is done.+void WritingSuggestionController::did_change_text(DOM::Text const& text)+{+ if (m_showing.has_value() && m_showing->text.ptr().ptr() == &text)+ schedule_selection_check();+}++void WritingSuggestionController::did_start_input_method_composition()+{+ dismiss();+}++void WritingSuggestionController::did_end_input_method_composition()+{+ if (m_document->page().writing_suggestions_available())+ schedule_request();+}++// Selection changes come in the middle of edits too, so whether the caret left the suggestion is decided once the+// edit is done.+void WritingSuggestionController::did_change_selection()+{+ if (m_showing.has_value() || m_requests_in_flight > 0 || m_request_scheduled)+ schedule_selection_check();+}++void WritingSuggestionController::schedule_selection_check()+{+ if (m_selection_check_scheduled)+ return;+ m_selection_check_scheduled = true;+ HTML::queue_global_task(HTML::Task::Source::UserInteraction, HTML::relevant_global_object(m_document), GC::create_function(m_document->heap(), [document = GC::Weak<DOM::Document> { m_document }] {+ if (auto strong_document = document.ptr()) {+ strong_document->writing_suggestion_controller().run_selection_check();+ strong_document->page().notify_writing_suggestion_progress();+ }+ }));+}++void WritingSuggestionController::run_selection_check()+{+ if (!exchange(m_selection_check_scheduled, false))+ return;+ if (m_showing.has_value() && !caret_is_at_showing_suggestion())+ dismiss();+}++bool WritingSuggestionController::caret_is_at_showing_suggestion() const+{+ if (!m_showing.has_value())+ return false;+ auto caret = caret_text_position(m_document);+ if (!caret.has_value() || !caret->is_collapsed || caret->text.ptr() != m_showing->text.ptr().ptr() || caret->offset != m_showing->offset)+ return false;+ auto& text = *caret->text;+ return text.length_in_utf16_code_units() == m_showing_text_length && text_before(text, caret->offset) == m_showing_prefix.utf16_view()+ && is_eligible(text) && can_draw_at(text);+}++void WritingSuggestionController::schedule_request()+{+ if (m_request_scheduled)+ return;+ m_request_scheduled = true;+ HTML::queue_global_task(HTML::Task::Source::UserInteraction, HTML::relevant_global_object(m_document), GC::create_function(m_document->heap(), [document = GC::Weak<DOM::Document> { m_document }] {+ if (auto strong_document = document.ptr()) {+ strong_document->writing_suggestion_controller().run_request();+ strong_document->page().notify_writing_suggestion_progress();+ }+ }));+}++void WritingSuggestionController::run_request()+{+ if (!exchange(m_request_scheduled, false))+ return;+ auto& page = m_document->page();+ if (!page.writing_suggestions_available() || m_document->is_input_method_composing())+ return;+ auto caret = caret_text_position(m_document);+ if (!caret.has_value() || !caret->is_collapsed || !caret->text->is_connected() || &caret->text->document() != m_document.ptr() || !is_eligible(*caret->text))+ return;++ auto data = caret->text->data().utf16_view();+ auto offset = min(caret->offset, data.length_in_code_units());+ auto start = offset > CONTEXT_SIZE ? offset - CONTEXT_SIZE : 0;+ auto end = min(data.length_in_code_units(), offset + CONTEXT_SIZE);+ Request request {+ .generation = m_generation,+ .text = *caret->text,+ .offset = offset,+ .sent_text = Utf16String::from_utf16(data.substring_view(start, end - start)),+ .caret_offset = static_cast<u32>(offset - start),+ .text_length = data.length_in_code_units(),+ };++ ++m_requests_in_flight;+ auto sent_text = request.sent_text;+ auto caret_offset = request.caret_offset;+ page.request_writing_suggestion(sent_text, caret_offset, GC::create_function(m_document->heap(), [document = GC::Weak<DOM::Document> { m_document }, request = move(request)](Optional<WritingSuggestion> suggestion) {+ auto strong_document = document.ptr();+ if (!strong_document)+ return;+ strong_document->writing_suggestion_controller().did_receive(request, suggestion);+ strong_document->page().notify_writing_suggestion_progress();+ }));+}++void WritingSuggestionController::did_receive(Request const& request, Optional<WritingSuggestion> const& suggestion)+{+ --m_requests_in_flight;+ // An answer to a request that an edit, a caret move, or a dismissal has overtaken describes text that's gone.+ if (request.generation != m_generation || !suggestion.has_value())+ return;+ auto text = request.text.ptr();+ auto caret = caret_text_position(m_document);+ if (!text || !caret.has_value() || !caret->is_collapsed || caret->text.ptr() != text.ptr() || caret->offset != request.offset)+ return;+ // A script may have changed the text, or the element, while the request was out.+ auto sent = request.sent_text.utf16_view();+ if (request.caret_offset > sent.length_in_code_units() || text->length_in_utf16_code_units() != request.text_length+ || text->data().utf16_view().substring_view(request.offset - request.caret_offset, request.caret_offset) != sent.substring_view(0, request.caret_offset)+ || !is_eligible(*text) || !can_draw_at(*text))+ return;++ // Only a suggestion that continues the word that ends at the caret shows. One that corrects it, or that would+ // replace text after the caret, shows nothing.+ auto typed_start = suggestion->replacement_start;+ if (typed_start > request.caret_offset || typed_start + suggestion->replacement_length != request.caret_offset)+ return;+ auto typed = sent.substring_view(typed_start, request.caret_offset - typed_start);+ auto suggested = suggestion->text.utf16_view();+ if (suggested.length_in_code_units() <= typed.length_in_code_units() || suggested.substring_view(0, typed.length_in_code_units()) != typed)+ return;++ set_showing(ShowingSuggestion { *text, request.offset, Utf16String::from_utf16(suggested.substring_view(typed.length_in_code_units())) });+}++bool WritingSuggestionController::is_settled() const+{+ return !m_request_scheduled && !m_selection_check_scheduled && m_requests_in_flight == 0;+}++}diff --git a/Libraries/LibWeb/Editing/WritingSuggestionController.h b/Libraries/LibWeb/Editing/WritingSuggestionController.hnew file mode 100644index 00000000000..1a81b492e64--- /dev/null+++ b/Libraries/LibWeb/Editing/WritingSuggestionController.h@@ -0,0 +1,95 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#pragma once++#include <AK/Noncopyable.h>+#include <AK/Optional.h>+#include <AK/Utf16String.h>+#include <LibGC/Ptr.h>+#include <LibGC/Weak.h>+#include <LibWeb/Export.h>+#include <LibWeb/Forward.h>+#include <LibWebCommon/Page/WritingSuggestion.h>++namespace Web::Editing {++// Asks the UI process to predict how the text at the caret continues as the user types, and keeps the prediction that+// shows after the caret. The suggestion is never in the DOM: Layout draws it after the caret until the user accepts it,+// which types it in.+// https://html.spec.whatwg.org/multipage/interaction.html#writing-suggestions+class WEB_API WritingSuggestionController {+ AK_MAKE_NONCOPYABLE(WritingSuggestionController);+ AK_MAKE_NONMOVABLE(WritingSuggestionController);+ AK_ALLOC_WITH_KMALLOC;++public:+ // How much text on each side of the caret goes with a request, in UTF-16 code units.+ static constexpr size_t CONTEXT_SIZE = 512;++ struct ShowingSuggestion {+ GC::Weak<DOM::Text> text;+ // Where the caret is in the text node, which is where the suggestion shows.+ size_t offset { 0 };+ // What the suggestion would add after the caret.+ Utf16String remainder;+ };++ explicit WritingSuggestionController(DOM::Document&);++ static bool is_eligible(DOM::Node const& caret_container);++ Optional<ShowingSuggestion> const& showing() const { return m_showing; }++ void did_focus(GC::Ptr<DOM::Node>);+ // A user edit changed the text of the editable that contains node.+ void did_user_edit(DOM::Node&);+ void did_change_selection();+ // The data of the text node changed, by a user edit or not.+ void did_change_text(DOM::Text const&);+ void did_start_input_method_composition();+ void did_end_input_method_composition();+ void dismiss();++ bool is_settled() const;++ void visit_edges(GC::Cell::Visitor&);++private:+ struct Request {+ u64 generation { 0 };+ GC::Weak<DOM::Text> text;+ size_t offset { 0 };+ // The text sent, and where the caret is in it.+ Utf16String sent_text;+ u32 caret_offset { 0 };+ size_t text_length { 0 };+ };++ void set_showing(Optional<ShowingSuggestion>);+ void schedule_request();+ void run_request();+ void did_receive(Request const&, Optional<WritingSuggestion> const&);+ void schedule_selection_check();+ void run_selection_check();+ bool caret_is_at_showing_suggestion() const;+ static bool can_draw_at(DOM::Text const&);++ GC::Ref<DOM::Document> m_document;+ Optional<ShowingSuggestion> m_showing;+ // The length of the suggestion's text node when the suggestion showed, so typing through can tell an insertion at+ // the caret from any other change.+ size_t m_showing_text_length { 0 };+ // The text right before the caret when the suggestion showed, so text a script changed under it is noticed.+ Utf16String m_showing_prefix;+ // Bumped by every edit, caret move, and dismissal, so an answer to a request sent before one of them is dropped.+ u64 m_generation { 0 };+ size_t m_requests_in_flight { 0 };+ bool m_request_scheduled { false };+ bool m_selection_check_scheduled { false };+};++}diff --git a/Libraries/LibWeb/Forward.h b/Libraries/LibWeb/Forward.hindex 3b5454154da..dd13eccef84 100644--- a/Libraries/LibWeb/Forward.h+++ b/Libraries/LibWeb/Forward.h@@ -520,6 +520,7 @@ class EditCommand;class EditingHistory;class SpellCheckController;class SpellingMarkers;+class WritingSuggestionController;class UndoStep;enum class HistoryAction : u8;diff --git a/Libraries/LibWeb/HTML/FormAssociatedElement.cpp b/Libraries/LibWeb/HTML/FormAssociatedElement.cppindex b8e12a569d8..9eaf9960da9 100644--- a/Libraries/LibWeb/HTML/FormAssociatedElement.cpp+++ b/Libraries/LibWeb/HTML/FormAssociatedElement.cpp@@ -24,6 +24,7 @@#include <LibWeb/Editing/EditCommand.h>#include <LibWeb/Editing/EditingHistory.h>#include <LibWeb/Editing/SpellCheckController.h>+#include <LibWeb/Editing/WritingSuggestionController.h>#include <LibWeb/HTML/CustomElements/CustomElementReactionNames.h>#include <LibWeb/HTML/Focus.h>#include <LibWeb/HTML/FormAssociatedElement.h>@@ -1331,6 +1332,7 @@ void FormAssociatedTextControlElement::handle_insert(Utf16FlyString const& inputdid_edit_text_node(input_type, data_for_input_event);html_element.document().spell_check_controller().did_user_edit(html_element);+ html_element.document().writing_suggestion_controller().did_user_edit(html_element);reveal_cursor_after_edit();}@@ -1420,6 +1422,7 @@ void FormAssociatedTextControlElement::handle_delete(Utf16FlyString const& inputdid_edit_text_node(input_type, {});html_element.document().spell_check_controller().did_user_edit(html_element);+ html_element.document().writing_suggestion_controller().did_user_edit(html_element);reveal_cursor_after_edit();}@@ -1506,6 +1509,8 @@ void FormAssociatedTextControlElement::selection_was_changed(SelectionSource souif (auto* controller = element.document().spell_check_controller_if_exists())controller->did_change_selection();+ if (auto* controller = element.document().writing_suggestion_controller_if_exists())+ controller->did_change_selection();// NB: Called during selection change handling, layout may be stale. The render state finds the text's box as it// applies the repaint, so the change reads nothing of it.diff --git a/Libraries/LibWeb/HTML/LocalNavigable.cpp b/Libraries/LibWeb/HTML/LocalNavigable.cppindex b5787e6c39e..5aea3bf2cc6 100644--- a/Libraries/LibWeb/HTML/LocalNavigable.cpp+++ b/Libraries/LibWeb/HTML/LocalNavigable.cpp@@ -41,6 +41,7 @@#include <LibWeb/Editing/EditingHistory.h>#include <LibWeb/Editing/Internal/Algorithms.h>#include <LibWeb/Editing/SpellCheckController.h>+#include <LibWeb/Editing/WritingSuggestionController.h>#include <LibWeb/Fetch/Fetching/Checks.h>#include <LibWeb/Fetch/Fetching/Fetching.h>#include <LibWeb/Fetch/Infrastructure/FetchAlgorithms.h>@@ -6174,8 +6175,10 @@ void LocalNavigable::end_input_method_composition(Optional<Utf16View> final_textif (!was_active)return;- if (auto document = active_document())+ if (auto document = active_document()) {document->spell_check_controller().did_end_input_method_composition();+ document->writing_suggestion_controller().did_end_input_method_composition();+ }// https://w3c.github.io/uievents/#event-type-compositionend// A user agent MUST dispatch this event when a text composition system completes or cancels the current composition@@ -6280,6 +6283,8 @@ void LocalNavigable::replace_input_method_marked_text(Utf16View text)// of text.if (!m_input_method_composition_active) {document->set_is_input_method_composing(true);+ if (auto* controller = document->writing_suggestion_controller_if_exists())+ controller->did_start_input_method_composition();m_input_method_composition_active = true;// https://w3c.github.io/uievents/#events-composition-canceling// If the initial compositionstart event is canceled then the text composition session SHOULD be terminated.diff --git a/Libraries/LibWeb/Internals/Internals.cpp b/Libraries/LibWeb/Internals/Internals.cppindex 5ac5f444aba..2d8ae994121 100644--- a/Libraries/LibWeb/Internals/Internals.cpp+++ b/Libraries/LibWeb/Internals/Internals.cpp@@ -60,6 +60,7 @@#include <LibWeb/DOMURL/DOMURL.h>#include <LibWeb/Dump.h>#include <LibWeb/Editing/SpellingMarkers.h>+#include <LibWeb/Editing/WritingSuggestionController.h>#include <LibWeb/Fetch/Fetching/Fetching.h>#include <LibWeb/Fetch/Infrastructure/NetworkPartitionKey.h>#include <LibWeb/Geolocation/Geolocation.h>@@ -2921,6 +2922,41 @@ GC::Ref<WebIDL::Promise> Internals::request_writing_suggestion_for_testing(Utf16return promise;}+// The writing suggestion showing in any document of the page.+Utf16String Internals::writing_suggestion()+{+ for (auto const& navigable : page().hosted_navigables()) {+ auto document = navigable->active_document();+ if (!document)+ continue;+ if (auto* controller = document->writing_suggestion_controller_if_exists(); controller && controller->showing().has_value())+ return controller->showing()->remainder;+ }+ return "(none)"_utf16;+}++GC::Ref<WebIDL::Promise> Internals::writing_suggestion_settled()+{+ auto& realm = window().principal_realm();+ auto promise = WebIDL::create_promise_for(window());+ page().when_writing_suggestions_settled(GC::create_function(heap(), [&realm, promise] {+ HTML::TemporaryExecutionContext execution_context { realm };+ WebIDL::resolve_promise(promise);+ }));+ return promise;+}++GC::Ref<WebIDL::Promise> Internals::writing_suggestion_request_sent()+{+ auto& realm = window().principal_realm();+ auto promise = WebIDL::create_promise_for(window());+ page().when_writing_suggestion_requested(GC::create_function(heap(), [&realm, promise] {+ HTML::TemporaryExecutionContext execution_context { realm };+ WebIDL::resolve_promise(promise);+ }));+ return promise;+}+GC::Ref<WebIDL::Promise> Internals::activate_spelling_menu_item(Bindings::SpellingMenuItem item, WebIDL::UnsignedLong guess_index){auto& realm = window().principal_realm();diff --git a/Libraries/LibWeb/Internals/Internals.h b/Libraries/LibWeb/Internals/Internals.hindex c932a218930..0bede9b5234 100644--- a/Libraries/LibWeb/Internals/Internals.h+++ b/Libraries/LibWeb/Internals/Internals.h@@ -90,6 +90,9 @@ public:GC::Ref<WebIDL::Promise> spell_check_settled();GC::Ref<WebIDL::Promise> request_writing_suggestion_for_testing(Utf16String const& text, WebIDL::UnsignedLong caret_offset);+ Utf16String writing_suggestion();+ GC::Ref<WebIDL::Promise> writing_suggestion_settled();+ GC::Ref<WebIDL::Promise> writing_suggestion_request_sent();GC::Ref<WebIDL::Promise> activate_spelling_menu_item(Bindings::SpellingMenuItem, WebIDL::UnsignedLong guess_index);void send_text(HTML::HTMLElement&, Utf16String const&, WebIDL::UnsignedShort modifiers);diff --git a/Libraries/LibWeb/Internals/Internals.idl b/Libraries/LibWeb/Internals/Internals.idlindex d1fa0ac1824..d82c7923395 100644--- a/Libraries/LibWeb/Internals/Internals.idl+++ b/Libraries/LibWeb/Internals/Internals.idl@@ -53,6 +53,9 @@ interface Internals {// Writing suggestionsPromise<DOMString> requestWritingSuggestionForTesting(DOMString text, unsigned long caretOffset);+ DOMString writingSuggestion();+ Promise<undefined> writingSuggestionSettled();+ Promise<undefined> writingSuggestionRequestSent();Promise<DOMString> activateSpellingMenuItem(SpellingMenuItem item, optional unsigned long guessIndex = 0);const unsigned short MOD_NONE = 0;diff --git a/Libraries/LibWeb/Page/Page.cpp b/Libraries/LibWeb/Page/Page.cppindex 7ffbd0373cb..742031f3f88 100644--- a/Libraries/LibWeb/Page/Page.cpp+++ b/Libraries/LibWeb/Page/Page.cpp@@ -20,6 +20,7 @@#include <LibWeb/DOM/Range.h>#include <LibWeb/Editing/SpellCheckController.h>#include <LibWeb/Editing/SpellingMarkers.h>+#include <LibWeb/Editing/WritingSuggestionController.h>#include <LibWeb/HTML/BrowsingContext.h>#include <LibWeb/HTML/EventLoop/EventLoop.h>#include <LibWeb/HTML/EventNames.h>@@ -148,6 +149,8 @@ void Page::visit_edges(JS::Cell::Visitor& visitor)visitor.visit(m_pending_spell_check_requests);visitor.visit(m_spell_checking_settled_callbacks);visitor.visit(m_pending_writing_suggestion_requests);+ visitor.visit(m_writing_suggestions_settled_callbacks);+ visitor.visit(m_writing_suggestion_requested_callbacks);visitor.visit(m_on_spelling_menu_action_for_testing);visitor.visit(m_emulated_position_data);visitor.visit(m_emulated_position_data_observers);@@ -1346,12 +1349,49 @@ void Page::request_writing_suggestion(Utf16String const& text, u32 caret_offset,auto request_id = m_next_writing_suggestion_request_id++;m_pending_writing_suggestion_requests.set(request_id, request);client().page_did_request_writing_suggestion(request_id, text, caret_offset);+ GC::RootVector callbacks { exchange(m_writing_suggestion_requested_callbacks, {}) };+ for (auto& callback : callbacks)+ callback->function()();}void Page::did_get_writing_suggestion(u64 request_id, Optional<WritingSuggestion> suggestion){if (auto request = m_pending_writing_suggestion_requests.take(request_id); request.has_value())(*request)->function()(move(suggestion));+ notify_writing_suggestion_progress();+}++void Page::when_writing_suggestion_requested(GC::Ref<GC::Function<void()>> callback)+{+ m_writing_suggestion_requested_callbacks.append(callback);+}++static bool writing_suggestions_are_settled(Page& page)+{+ if (page.has_pending_writing_suggestions())+ return false;+ for (auto const& navigable : page.hosted_navigables()) {+ if (auto document = navigable->active_document()) {+ if (auto* controller = document->writing_suggestion_controller_if_exists(); controller && !controller->is_settled())+ return false;+ }+ }+ return true;+}++void Page::when_writing_suggestions_settled(GC::Ref<GC::Function<void()>> callback)+{+ m_writing_suggestions_settled_callbacks.append(callback);+ notify_writing_suggestion_progress();+}++void Page::notify_writing_suggestion_progress()+{+ if (m_writing_suggestions_settled_callbacks.is_empty() || !writing_suggestions_are_settled(*this))+ return;+ GC::RootVector callbacks { exchange(m_writing_suggestions_settled_callbacks, {}) };+ for (auto& callback : callbacks)+ callback->function()();}static bool spell_checking_is_settled(Page& page)diff --git a/Libraries/LibWeb/Page/Page.h b/Libraries/LibWeb/Page/Page.hindex 06cc84aae3d..c56fc81071f 100644--- a/Libraries/LibWeb/Page/Page.h+++ b/Libraries/LibWeb/Page/Page.h@@ -328,6 +328,12 @@ public:void did_get_writing_suggestion(u64 request_id, Optional<WritingSuggestion>);bool has_pending_writing_suggestions() const { return !m_pending_writing_suggestion_requests.is_empty(); }+ // For tests: Calls the callback once no document of the page has a writing suggestion request queued or in flight.+ void when_writing_suggestions_settled(GC::Ref<GC::Function<void()>>);+ void notify_writing_suggestion_progress();+ // For tests: Calls the callback when the next writing suggestion request goes to the UI process.+ void when_writing_suggestion_requested(GC::Ref<GC::Function<void()>>);+using GeolocationPositionResult = Variant<Geolocation::CoordinatesData, Geolocation::GeolocationPositionError::ErrorCode>;using GeolocationPositionCallback = GC::Ref<GC::Function<void(GeolocationPositionResult)>>;enum class GeolocationRequestType : u8 {@@ -564,6 +570,8 @@ private:bool m_writing_suggestions_available { false };HashMap<u64, WritingSuggestionRequest> m_pending_writing_suggestion_requests;u64 m_next_writing_suggestion_request_id { 0 };+ Vector<GC::Ref<GC::Function<void()>>> m_writing_suggestions_settled_callbacks;+ Vector<GC::Ref<GC::Function<void()>>> m_writing_suggestion_requested_callbacks;struct PendingGeolocationRequest {GeolocationPositionCallback callback;diff --git a/Services/WebContent/PageClient.cpp b/Services/WebContent/PageClient.cppindex 4e4ceee64a0..1086505a6e1 100644--- a/Services/WebContent/PageClient.cpp+++ b/Services/WebContent/PageClient.cpp@@ -34,6 +34,7 @@#include <LibWeb/DOM/MutationType.h>#include <LibWeb/DOM/Node.h>#include <LibWeb/DOM/NodeList.h>+#include <LibWeb/Editing/WritingSuggestionController.h>#include <LibWeb/Fetch/Infrastructure/FetchController.h>#include <LibWeb/Fetch/Infrastructure/HTTP/Bodies.h>#include <LibWeb/Geolocation/GeolocationCoordinates.h>@@ -208,6 +209,9 @@ void PageClient::set_has_focus(bool has_focus)continue;if (has_focus && navigable->is_local_root())document->reset_cursor_blink_cycle();+ // A writing suggestion is for the user typing in the window, so leaving the window drops it.+ if (auto* controller = document->writing_suggestion_controller_if_exists(); controller && !has_focus)+ controller->dismiss();// Focus changes can arrive while layout is invalidated. We only need to invalidate cached paint// on the current paintable tree here, without requiring layout to be up to date first.if (document->has_committed_viewport_box())diff --git a/Tests/LibWeb/Text/expected/Editing/writing-suggestion-dismissal.txt b/Tests/LibWeb/Text/expected/Editing/writing-suggestion-dismissal.txtnew file mode 100644index 00000000000..cc280c458d9--- /dev/null+++ b/Tests/LibWeb/Text/expected/Editing/writing-suggestion-dismissal.txt@@ -0,0 +1,6 @@+showing: ction+caret moved: (none)+text selected: (none)+focus moved: (none)+composition started: (none)+composition continued: (none)diff --git a/Tests/LibWeb/Text/expected/Editing/writing-suggestion-eligibility.txt b/Tests/LibWeb/Text/expected/Editing/writing-suggestion-eligibility.txtnew file mode 100644index 00000000000..1835be26700--- /dev/null+++ b/Tests/LibWeb/Text/expected/Editing/writing-suggestion-eligibility.txt@@ -0,0 +1,14 @@+text: ction+search: ction+url: ction+email: ction+tel: ction+password: (none)+number: (none)+readonly: (none)+textarea: ction+editable: ction+off: (none)+autocomplete-off: (none)+inherited-off: (none)+iframe: ctiondiff --git a/Tests/LibWeb/Text/expected/Editing/writing-suggestion-script-edits.txt b/Tests/LibWeb/Text/expected/Editing/writing-suggestion-script-edits.txtnew file mode 100644index 00000000000..a5a292ea435--- /dev/null+++ b/Tests/LibWeb/Text/expected/Editing/writing-suggestion-script-edits.txt@@ -0,0 +1,5 @@+showing: ction+text inserted before the caret by script: (none)+text replaced by script while the request was out: (none)+made read-only while the request was out: (none)+caret in the middle of the predicted word: (none)diff --git a/Tests/LibWeb/Text/expected/Editing/writing-suggestion-stale-reply.txt b/Tests/LibWeb/Text/expected/Editing/writing-suggestion-stale-reply.txtnew file mode 100644index 00000000000..549d03c2e01--- /dev/null+++ b/Tests/LibWeb/Text/expected/Editing/writing-suggestion-stale-reply.txt@@ -0,0 +1 @@+typed past the request: (none)diff --git a/Tests/LibWeb/Text/expected/Editing/writing-suggestion-typing.txt b/Tests/LibWeb/Text/expected/Editing/writing-suggestion-typing.txtnew file mode 100644index 00000000000..f06d74a072d--- /dev/null+++ b/Tests/LibWeb/Text/expected/Editing/writing-suggestion-typing.txt@@ -0,0 +1,12 @@+predi: ction+value: predi+typed through, without waiting: tion+typed through, settled: tion+diverged: (none)+several words: bird browser+a correction: (none)+contenteditable: ction+no further mutations: true+no further input events: true+selection collapsed: true+textContent: predidiff --git a/Tests/LibWeb/Text/input/Editing/writing-suggestion-dismissal.html b/Tests/LibWeb/Text/input/Editing/writing-suggestion-dismissal.htmlnew file mode 100644index 00000000000..cacf6170eec--- /dev/null+++ b/Tests/LibWeb/Text/input/Editing/writing-suggestion-dismissal.html@@ -0,0 +1,37 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<textarea id="area"></textarea>+<input id="other">+<script>+ promiseTest(async () => {+ const area = document.getElementById("area");+ const showSuggestion = async () => {+ area.value = "";+ internals.sendText(area, "predi");+ await internals.writingSuggestionSettled();+ return internals.writingSuggestion();+ };+ const show = async label => {+ await internals.writingSuggestionSettled();+ println(`${label}: ${internals.writingSuggestion()}`);+ };++ println(`showing: ${await showSuggestion()}`);+ area.setSelectionRange(0, 0);+ await show("caret moved");++ await showSuggestion();+ area.setSelectionRange(0, 3);+ await show("text selected");++ await showSuggestion();+ document.getElementById("other").focus();+ await show("focus moved");++ await showSuggestion();+ internals.setMarkedTextFromInputMethod("p");+ await show("composition started");+ internals.setMarkedTextFromInputMethod("pr");+ await show("composition continued");+ });+</script>diff --git a/Tests/LibWeb/Text/input/Editing/writing-suggestion-eligibility.html b/Tests/LibWeb/Text/input/Editing/writing-suggestion-eligibility.htmlnew file mode 100644index 00000000000..2a6f4e39f9b--- /dev/null+++ b/Tests/LibWeb/Text/input/Editing/writing-suggestion-eligibility.html@@ -0,0 +1,43 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<input id="text" type="text">+<input id="search" type="search">+<input id="url" type="url">+<input id="email" type="email">+<input id="tel" type="tel">+<input id="password" type="password">+<input id="number" type="number">+<input id="readonly" type="text" readonly>+<textarea id="textarea"></textarea>+<div id="editable" contenteditable></div>+<div id="off" contenteditable writingsuggestions="false"></div>+<div writingsuggestions="false"><div contenteditable><span id="inherited-off">x</span></div></div>+<textarea id="autocomplete-off" autocomplete="off"></textarea>+<iframe id="frame" srcdoc="<body contenteditable></body>"></iframe>+<script>+ promiseTest(async () => {+ await new Promise(resolve => {+ if (frame.contentDocument?.readyState === "complete")+ resolve();+ else+ frame.onload = resolve;+ });+ const show = async (label, target) => {+ internals.sendText(target, "predi");+ await internals.writingSuggestionSettled();+ println(`${label}: ${internals.writingSuggestion()}`);+ internals.sendText(target, " ");+ await internals.writingSuggestionSettled();+ };++ for (const id of ["text", "search", "url", "email", "tel", "password", "number", "readonly", "textarea", "editable", "off", "autocomplete-off"])+ await show(id, document.getElementById(id));++ const span = document.getElementById("inherited-off");+ span.parentElement.focus();+ getSelection().collapse(span.firstChild, 1);+ await show("inherited-off", span.parentElement);++ await show("iframe", frame.contentDocument.body);+ });+</script>diff --git a/Tests/LibWeb/Text/input/Editing/writing-suggestion-script-edits.html b/Tests/LibWeb/Text/input/Editing/writing-suggestion-script-edits.htmlnew file mode 100644index 00000000000..07d1b746392--- /dev/null+++ b/Tests/LibWeb/Text/input/Editing/writing-suggestion-script-edits.html@@ -0,0 +1,40 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<div id="editable" contenteditable></div>+<textarea id="area"></textarea>+<textarea id="readonly"></textarea>+<textarea id="mid-word"></textarea>+<script>+ promiseTest(async () => {+ const show = async label => {+ await internals.writingSuggestionSettled();+ println(`${label}: ${internals.writingSuggestion()}`);+ };++ const editable = document.getElementById("editable");+ internals.sendText(editable, "predi");+ await show("showing");+ editable.firstChild.insertData(0, "AB");+ await show("text inserted before the caret by script");++ const area = document.getElementById("area");+ let requestSent = internals.writingSuggestionRequestSent();+ internals.sendText(area, "predi");+ await requestSent;+ area.value = "xxxxx";+ await show("text replaced by script while the request was out");++ const readonly = document.getElementById("readonly");+ requestSent = internals.writingSuggestionRequestSent();+ internals.sendText(readonly, "predi");+ await requestSent;+ readonly.readOnly = true;+ await show("made read-only while the request was out");++ const midWord = document.getElementById("mid-word");+ internals.sendText(midWord, "prdi");+ midWord.setSelectionRange(2, 2);+ internals.sendText(midWord, "e");+ await show("caret in the middle of the predicted word");+ });+</script>diff --git a/Tests/LibWeb/Text/input/Editing/writing-suggestion-stale-reply.html b/Tests/LibWeb/Text/input/Editing/writing-suggestion-stale-reply.htmlnew file mode 100644index 00000000000..c570f83ce72--- /dev/null+++ b/Tests/LibWeb/Text/input/Editing/writing-suggestion-stale-reply.html@@ -0,0 +1,15 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<textarea id="area"></textarea>+<script>+ promiseTest(async () => {+ const area = document.getElementById("area");+ const requestSent = internals.writingSuggestionRequestSent();+ internals.sendText(area, "predi");+ // The answer to this request can't arrive before the next keystroke.+ await requestSent;+ internals.sendText(area, "x");+ await internals.writingSuggestionSettled();+ println(`typed past the request: ${internals.writingSuggestion()}`);+ });+</script>diff --git a/Tests/LibWeb/Text/input/Editing/writing-suggestion-typing.html b/Tests/LibWeb/Text/input/Editing/writing-suggestion-typing.htmlnew file mode 100644index 00000000000..dab3f0c1470--- /dev/null+++ b/Tests/LibWeb/Text/input/Editing/writing-suggestion-typing.html@@ -0,0 +1,48 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<textarea id="area"></textarea>+<textarea id="lady"></textarea>+<textarea id="correction"></textarea>+<div id="editable" contenteditable></div>+<script>+ promiseTest(async () => {+ const show = label => println(`${label}: ${internals.writingSuggestion()}`);+ const settle = () => internals.writingSuggestionSettled();++ const area = document.getElementById("area");+ internals.sendText(area, "predi");+ await settle();+ show("predi");+ println(`value: ${area.value}`);+ internals.sendText(area, "c");+ show("typed through, without waiting");+ await settle();+ show("typed through, settled");+ internals.sendText(area, "x");+ await settle();+ show("diverged");++ internals.sendText(document.getElementById("lady"), "Lady");+ await settle();+ show("several words");++ internals.sendText(document.getElementById("correction"), "teh");+ await settle();+ show("a correction");++ const editable = document.getElementById("editable");+ let inputEvents = 0;+ editable.addEventListener("input", () => ++inputEvents);+ const observer = new MutationObserver(() => {});+ observer.observe(editable, { subtree: true, characterData: true, childList: true });+ internals.sendText(editable, "predi");+ const recordsWhileTyping = observer.takeRecords().length;+ const inputEventsWhileTyping = inputEvents;+ await settle();+ show("contenteditable");+ println(`no further mutations: ${observer.takeRecords().length === 0 && recordsWhileTyping > 0}`);+ println(`no further input events: ${inputEvents === inputEventsWhileTyping}`);+ println(`selection collapsed: ${getSelection().isCollapsed}`);+ println(`textContent: ${editable.textContent}`);+ });+</script>