Skip to content

Truly independent web browser

LibWeb: Spellcheck an editable’s text when it gets focus

sideshowbarker4f20588d39fa
diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txt
index 8e9c84ad28b..65670c11778 100644
--- a/Libraries/LibWeb/CMakeLists.txt
+++ b/Libraries/LibWeb/CMakeLists.txt
@@ -348,6 +348,7 @@ set(SOURCES
Editing/ReplacementFragment.cpp
Editing/ReplacementRangeCleanup.cpp
Editing/ReplacementStyleCleanup.cpp
+ Editing/SpellCheckController.cpp
Editing/SpellingMarkers.cpp
Editing/StyledMarkupAccumulator.cpp
Editing/StyledMarkupSelection.cpp
diff --git a/Libraries/LibWeb/DOM/Document.cpp b/Libraries/LibWeb/DOM/Document.cpp
index e7c5b506d79..aad43e3c6f3 100644
--- a/Libraries/LibWeb/DOM/Document.cpp
+++ b/Libraries/LibWeb/DOM/Document.cpp
@@ -129,6 +129,7 @@
#include <LibWeb/DOMURL/DOMURL.h>
#include <LibWeb/Dump.h>
#include <LibWeb/Editing/EditingHistory.h>
+#include <LibWeb/Editing/SpellCheckController.h>
#include <LibWeb/Editing/SpellingMarkers.h>
#include <LibWeb/Fetch/Fetching/Checks.h>
#include <LibWeb/Fetch/Infrastructure/FetchController.h>
@@ -923,6 +924,8 @@ void Document::visit_edges(Cell::Visitor& visitor)
m_query_selector_result_cache->visit_edges(visitor);
if (m_spelling_markers)
m_spelling_markers->visit_edges(visitor);
+ if (m_spell_check_controller)
+ m_spell_check_controller->visit_edges(visitor);
for (auto& event : m_pending_animation_event_queue) {
visitor.visit(event.event);
@@ -1146,6 +1149,13 @@ Editing::SpellingMarkers& Document::spelling_markers()
return *m_spelling_markers;
}
+Editing::SpellCheckController& Document::spell_check_controller()
+{
+ if (!m_spell_check_controller)
+ m_spell_check_controller = make<Editing::SpellCheckController>(*this);
+ return *m_spell_check_controller;
+}
+
bool Document::has_spelling_markers() const
{
return m_spelling_markers && !m_spelling_markers->is_empty();
@@ -3967,6 +3977,9 @@ void Document::set_focused_area(GC::Ptr<Node> node, InvalidateFocusPseudoClasses
set_needs_repaint(InvalidateDisplayList::PaintCommands);
update_active_element();
+
+ if (navigable() && page().spell_checking_available())
+ spell_check_controller().did_focus(m_focused_area);
}
Element const* Document::active_element() const
diff --git a/Libraries/LibWeb/DOM/Document.h b/Libraries/LibWeb/DOM/Document.h
index de2a594214c..05b75b0991d 100644
--- a/Libraries/LibWeb/DOM/Document.h
+++ b/Libraries/LibWeb/DOM/Document.h
@@ -339,6 +339,8 @@ public:
void remove_find_in_page_highlighted_matches_whose_text_changed();
Editing::SpellingMarkers& spelling_markers();
+ Editing::SpellCheckController& spell_check_controller();
+ Editing::SpellCheckController* spell_check_controller_if_exists() { return m_spell_check_controller.ptr(); }
bool has_spelling_markers() const;
void recompute_search_text_paint_states(Layout::BegunRead const&);
void note_spelling_markers_changed();
@@ -1996,6 +1998,7 @@ private:
Utf16String m_find_in_page_active_match_text;
Vector<GC::Ref<Range>> m_find_in_page_highlighted_matches;
OwnPtr<Editing::SpellingMarkers> m_spelling_markers;
+ OwnPtr<Editing::SpellCheckController> m_spell_check_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/Editing/Internal/Algorithms.cpp b/Libraries/LibWeb/Editing/Internal/Algorithms.cpp
index 92ecfce1c0a..ba019acd66f 100644
--- a/Libraries/LibWeb/Editing/Internal/Algorithms.cpp
+++ b/Libraries/LibWeb/Editing/Internal/Algorithms.cpp
@@ -5049,4 +5049,56 @@ bool value_contains_keyword(CSS::StyleValue const& value, CSS::Keyword keyword)
return value.to_keyword() == keyword;
}
+// 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)
+{
+ GC::Ptr<DOM::Node> start_node = text_node;
+ WebIDL::UnsignedLong start_offset = offset;
+ GC::Ptr<DOM::Node> end_node = text_node;
+ WebIDL::UnsignedLong end_offset = offset;
+
+ // Walk backwards to find the paragraph start (a block boundary point).
+ if (!is_block_start_point({ *start_node, start_offset })) {
+ do {
+ if (start_offset == 0) {
+ start_offset = start_node->index();
+ start_node = start_node->parent();
+ } else {
+ --start_offset;
+ }
+ } while (start_node && !is_block_boundary_point({ *start_node, start_offset }));
+ }
+
+ // Walk forwards to find the paragraph end (a block boundary point).
+ if (!is_block_end_point({ *end_node, end_offset })) {
+ do {
+ if (end_offset == end_node->length()) {
+ end_offset = end_node->index() + 1;
+ end_node = end_node->parent();
+ } else {
+ ++end_offset;
+ }
+ } while (end_node && !is_block_boundary_point({ *end_node, end_offset }));
+ }
+
+ // Fallback if we couldn't find boundaries.
+ if (!start_node) {
+ start_node = text_node;
+ start_offset = 0;
+ }
+ if (!end_node) {
+ end_node = text_node;
+ end_offset = text_node.length();
+ }
+
+ return { *start_node, start_offset, *end_node, end_offset };
+}
+
+GC::Ref<DOM::Range> paragraph_range_containing(DOM::Text& text_node, WebIDL::UnsignedLong offset)
+{
+ auto bounds = paragraph_bounds_containing(text_node, offset);
+ return DOM::Range::create(bounds.start_node, bounds.start_offset, bounds.end_node, bounds.end_offset);
+}
+
}
diff --git a/Libraries/LibWeb/Editing/Internal/Algorithms.h b/Libraries/LibWeb/Editing/Internal/Algorithms.h
index 6ff4e12e269..710f0d51e5a 100644
--- a/Libraries/LibWeb/Editing/Internal/Algorithms.h
+++ b/Libraries/LibWeb/Editing/Internal/Algorithms.h
@@ -74,6 +74,14 @@ bool is_allowed_child_of_node(Variant<GC::Ref<DOM::Node>, Utf16FlyString> child,
bool is_block_boundary_point(DOM::BoundaryPoint);
bool is_block_end_point(DOM::BoundaryPoint);
bool is_block_node(GC::Ref<DOM::Node>);
+struct ParagraphBounds {
+ GC::Ref<DOM::Node> start_node;
+ WebIDL::UnsignedLong start_offset { 0 };
+ GC::Ref<DOM::Node> end_node;
+ WebIDL::UnsignedLong end_offset { 0 };
+};
+ParagraphBounds paragraph_bounds_containing(DOM::Text&, WebIDL::UnsignedLong offset);
+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>);
bool is_collapsed_line_break(GC::Ref<DOM::Node>);
diff --git a/Libraries/LibWeb/Editing/SpellCheckController.cpp b/Libraries/LibWeb/Editing/SpellCheckController.cpp
new file mode 100644
index 00000000000..f1335205155
--- /dev/null
+++ b/Libraries/LibWeb/Editing/SpellCheckController.cpp
@@ -0,0 +1,357 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <AK/Utf16StringBuilder.h>
+#include <LibWeb/DOM/Document.h>
+#include <LibWeb/DOM/ShadowRoot.h>
+#include <LibWeb/DOM/Text.h>
+#include <LibWeb/Editing/Internal/Algorithms.h>
+#include <LibWeb/Editing/SpellCheckController.h>
+#include <LibWeb/Editing/SpellingMarkers.h>
+#include <LibWeb/HTML/FormAssociatedElement.h>
+#include <LibWeb/HTML/HTMLInputElement.h>
+#include <LibWeb/HTML/HTMLTextAreaElement.h>
+#include <LibWeb/Page/Page.h>
+
+namespace Web::Editing {
+
+// https://html.spec.whatwg.org/multipage/interaction.html#spelling-and-grammar-checking
+static bool is_checkable_text_control(HTML::HTMLElement& element)
+{
+ // User agents should only consider the following pieces of text as checkable for the purposes of this feature:
+ // - The value of input elements whose type attributes are in the Text, Search, URL, or Email states and that are
+ // mutable (i.e. that do not have the readonly attribute specified and that are not disabled).
+ if (auto* input = as_if<HTML::HTMLInputElement>(element)) {
+ using enum HTML::HTMLInputElement::TypeAttributeState;
+ if (!first_is_one_of(input->type_state(), Text, Search, URL, Email))
+ return false;
+ return input->is_mutable() && input->spellcheck();
+ }
+ // - The value of textarea elements that do not have a readonly attribute and that are not disabled.
+ if (auto* text_area = as_if<HTML::HTMLTextAreaElement>(element))
+ return text_area->is_mutable() && text_area->spellcheck();
+ return false;
+}
+
+// The editable a node's text belongs to for spellchecking: a checkable text control, for text in its user-agent shadow
+// tree, or else the node's editing host.
+static GC::Ptr<DOM::Node> checkable_editable_for(DOM::Node& node)
+{
+ GC::Ptr<DOM::Node> current = node;
+ while (auto shadow_root = current->containing_shadow_root()) {
+ if (!shadow_root->is_user_agent_internal())
+ break;
+ current = shadow_root->host();
+ }
+ if (auto* element = as_if<HTML::HTMLElement>(*current); element && is<HTML::FormAssociatedTextControlElement>(*element))
+ return is_checkable_text_control(*element) ? current : nullptr;
+ return current->editing_host();
+}
+
+static bool text_is_checkable(DOM::Text& text)
+{
+ auto editable = checkable_editable_for(text);
+ if (!editable)
+ return false;
+ // For the values of input and textarea elements, it is the element itself.
+ if (is<HTML::FormAssociatedTextControlElement>(*editable))
+ return true;
+ // - Text in Text nodes that are children of editing hosts or editable elements.
+ // For text that is part of a Text node, the element with which the text is associated is the element that is the
+ // immediate parent of the first character of the word, sentence, or other piece of text.
+ auto* parent = as_if<HTML::HTMLElement>(text.parent());
+ return parent && parent->is_editable_or_editing_host() && parent->spellcheck();
+}
+
+static bool is_separator(char16_t code_unit)
+{
+ return code_unit == ' ' || code_unit == '\t' || code_unit == '\n' || code_unit == '\r' || code_unit == 0xa0;
+}
+
+// The first node in tree order that comes after node and all of its descendants.
+static GC::Ptr<DOM::Node> next_after_subtree(DOM::Node& node)
+{
+ for (GC::Ptr<DOM::Node> current = node; current; current = current->parent()) {
+ if (auto* sibling = current->next_sibling())
+ return sibling;
+ }
+ return nullptr;
+}
+
+// The first node in tree order at or after a boundary point.
+static GC::Ptr<DOM::Node> node_at_boundary(DOM::Node& container, size_t offset)
+{
+ if (is<DOM::CharacterData>(container))
+ return container;
+ if (auto* child = container.child_at_index(offset))
+ return child;
+ return next_after_subtree(container);
+}
+
+SpellCheckController::SpellCheckController(DOM::Document& document)
+ : m_document(document)
+{
+}
+
+void SpellCheckController::visit_edges(GC::Cell::Visitor& visitor)
+{
+ visitor.visit(m_document);
+}
+
+// Text the document still holds. A node that left it, for another document or for none, gets no checks or answers here.
+bool SpellCheckController::owns(DOM::Text const& text) const
+{
+ return text.is_connected() && &text.document() == m_document.ptr();
+}
+
+SpellCheckController::Paragraph SpellCheckController::paragraph_containing(DOM::Text& text, size_t offset) const
+{
+ Paragraph paragraph;
+ auto editable = checkable_editable_for(text);
+ if (!editable)
+ return paragraph;
+
+ // A text control's value is one text node.
+ if (is<HTML::FormAssociatedTextControlElement>(*editable)) {
+ paragraph.append({ text, 0, text.length_in_utf16_code_units(), true });
+ return paragraph;
+ }
+
+ // Visit only the nodes between the paragraph's boundary points.
+ auto bounds = paragraph_bounds_containing(text, offset);
+ auto stop = is<DOM::CharacterData>(*bounds.end_node) ? next_after_subtree(bounds.end_node) : node_at_boundary(bounds.end_node, bounds.end_offset);
+ for (auto node = node_at_boundary(bounds.start_node, bounds.start_offset); node && node != stop; node = node->next_in_pre_order()) {
+ auto* piece_text = as_if<DOM::Text>(*node);
+ if (!piece_text || !editable->is_inclusive_ancestor_of(*piece_text))
+ continue;
+ size_t node_start = piece_text == bounds.start_node.ptr() ? bounds.start_offset : 0;
+ size_t node_end = piece_text == bounds.end_node.ptr() ? bounds.end_offset : piece_text->length_in_utf16_code_units();
+ if (node_start < node_end)
+ paragraph.append({ *piece_text, node_start, node_end, text_is_checkable(*piece_text) });
+ }
+ return paragraph;
+}
+
+// The first text node of each of an editable's paragraphs, in order.
+Vector<GC::Weak<DOM::Text>> SpellCheckController::paragraphs_of(DOM::Node& editable) const
+{
+ Vector<GC::Weak<DOM::Text>> paragraphs;
+ if (auto* text_control = as_if<HTML::FormAssociatedTextControlElement>(editable)) {
+ if (auto text = text_control->form_associated_element_to_text_node())
+ paragraphs.append(*text);
+ return paragraphs;
+ }
+ HashTable<DOM::Text const*> covered;
+ editable.for_each_in_inclusive_subtree_of_type<DOM::Text>([&](DOM::Text& text) {
+ if (covered.contains(&text))
+ return TraversalDecision::Continue;
+ auto paragraph = paragraph_containing(text, 0);
+ for (auto const& piece : paragraph)
+ covered.set(piece.text.ptr());
+ if (!paragraph.is_empty())
+ paragraphs.append(*paragraph.first().text);
+ return TraversalDecision::Continue;
+ });
+ return paragraphs;
+}
+
+// Builds the request for a window of a paragraph's text, widened to whitespace so no word is cut. Text whose checking
+// is disabled goes as spaces of the same length, so offsets stay put and the words on either side don't merge.
+SpellCheckController::Request SpellCheckController::make_request(Paragraph const& paragraph, size_t window_start, size_t window_end) const
+{
+ size_t length = 0;
+ for (auto const& piece : paragraph)
+ length += piece.node_end - piece.node_start;
+ auto code_unit_at = [&](size_t offset) -> char16_t {
+ for (auto const& piece : paragraph) {
+ auto piece_length = piece.node_end - piece.node_start;
+ if (offset < piece_length)
+ return piece.text->data().utf16_view().code_unit_at(piece.node_start + offset);
+ offset -= piece_length;
+ }
+ VERIFY_NOT_REACHED();
+ };
+ window_start = min(window_start, length);
+ window_end = min(window_end, length);
+ while (window_start > 0 && !is_separator(code_unit_at(window_start - 1)))
+ --window_start;
+ while (window_end < length && !is_separator(code_unit_at(window_end)))
+ ++window_end;
+
+ Request request;
+ request.window_end = window_end;
+ Utf16StringBuilder text;
+ size_t text_length = 0;
+ size_t paragraph_offset = 0;
+ for (auto const& piece : paragraph) {
+ auto piece_length = piece.node_end - piece.node_start;
+ auto overlap_start = max(paragraph_offset, window_start);
+ auto overlap_end = min(paragraph_offset + piece_length, window_end);
+ if (overlap_start < overlap_end) {
+ auto node_start = piece.node_start + (overlap_start - paragraph_offset);
+ auto node_end = piece.node_start + (overlap_end - paragraph_offset);
+ auto data = piece.text->data().utf16_view().substring_view(node_start, node_end - node_start);
+ request.pieces.append({
+ .text = *piece.text,
+ .snapshot = Utf16String::from_utf16(data),
+ .node_start = node_start,
+ .node_end = node_end,
+ .offset = text_length,
+ .checked = piece.checked,
+ });
+ if (piece.checked)
+ text.append(data);
+ else
+ text.append_repeated_ascii(' ', data.length_in_code_units());
+ text_length += data.length_in_code_units();
+ }
+ paragraph_offset += piece_length;
+ }
+ request.text = text.to_string();
+ return request;
+}
+
+void SpellCheckController::send(Request request)
+{
+ auto text = request.text;
+ ++m_requests_in_flight;
+ m_document->page().request_spell_check(text, GC::create_function(m_document->heap(), [document = GC::Weak<DOM::Document> { m_document }, request = move(request)](Vector<SpellingError> errors) {
+ auto strong_document = document.ptr();
+ if (!strong_document)
+ return;
+ strong_document->spell_check_controller().did_receive_answer(request, errors);
+ strong_document->page().notify_spell_check_progress();
+ }));
+}
+
+void SpellCheckController::did_receive_answer(Request const& request, Vector<SpellingError> const& errors)
+{
+ --m_requests_in_flight;
+ apply(request, errors);
+ m_existing_text_chunk_in_flight = false;
+ send_next_existing_text_chunk();
+}
+
+// Checking existing text goes one chunk at a time: The next chunk goes out once the previous one's answer is in.
+// A chunk takes as many paragraphs as fit, so a document of many short paragraphs doesn't take a round trip for each.
+void SpellCheckController::send_next_existing_text_chunk()
+{
+ if (!m_existing_text_pass.has_value() || m_existing_text_chunk_in_flight)
+ return;
+ auto& pass = *m_existing_text_pass;
+ auto next_paragraph = [&] {
+ ++pass.next_paragraph;
+ pass.next_offset = 0;
+ };
+
+ Request chunk;
+ Utf16StringBuilder chunk_text;
+ size_t chunk_length = 0;
+ while (pass.next_paragraph < pass.paragraphs.size() && chunk_length < EXISTING_TEXT_CHUNK_SIZE) {
+ auto anchor = pass.paragraphs[pass.next_paragraph].ptr();
+ if (!anchor || !owns(*anchor)) {
+ next_paragraph();
+ continue;
+ }
+ auto paragraph = paragraph_containing(*anchor, 0);
+ size_t length = 0;
+ for (auto const& piece : paragraph)
+ length += piece.node_end - piece.node_start;
+ if (pass.next_offset >= length) {
+ next_paragraph();
+ continue;
+ }
+ // A paragraph that doesn't fit in what's left of a chunk waits for the next one, unless the chunk is empty.
+ auto room = EXISTING_TEXT_CHUNK_SIZE - chunk_length;
+ if (chunk_length > 0 && length - pass.next_offset > room)
+ break;
+ auto request = make_request(paragraph, pass.next_offset, pass.next_offset + room);
+ if (request.window_end <= pass.next_offset) {
+ next_paragraph();
+ continue;
+ }
+ pass.next_offset = request.window_end;
+ if (pass.next_offset >= length)
+ next_paragraph();
+
+ // A line break keeps the paragraphs in one chunk apart, so their words don't run together.
+ if (chunk_length > 0) {
+ chunk_text.append_code_unit('\n');
+ ++chunk_length;
+ }
+ for (auto& piece : request.pieces) {
+ piece.offset += chunk_length;
+ chunk.pieces.append(move(piece));
+ }
+ chunk_text.append(request.text.utf16_view());
+ chunk_length += request.text.length_in_code_units();
+ }
+
+ if (chunk.pieces.is_empty()) {
+ if (pass.next_paragraph >= pass.paragraphs.size())
+ m_existing_text_pass.clear();
+ return;
+ }
+ chunk.text = chunk_text.to_string();
+ m_existing_text_chunk_in_flight = true;
+ send(move(chunk));
+}
+
+bool SpellCheckController::overlaps_exempt_word(DOM::Text const& text, size_t start, size_t end) const
+{
+ if (!m_exempt_word.has_value() || m_exempt_word->text.ptr().ptr() != &text)
+ return false;
+ return start <= m_exempt_word->end && m_exempt_word->start <= end;
+}
+
+void SpellCheckController::apply(Request const& request, Vector<SpellingError> const& errors)
+{
+ auto& markers = m_document->spelling_markers();
+ for (auto const& piece : request.pieces) {
+ auto text = piece.text.ptr();
+ // Text that left the document, or whose checking turned off, since the text was sent takes nothing from the
+ // answer.
+ if (!text || !piece.checked || !owns(*text) || !text_is_checkable(*text))
+ continue;
+ // A node edited since the text was sent is dirty again, and the next check takes it.
+ auto data = text->data().utf16_view();
+ if (piece.node_end > data.length_in_code_units()
+ || data.substring_view(piece.node_start, piece.node_end - piece.node_start) != piece.snapshot.utf16_view())
+ continue;
+ markers.remove_overlapping(*text, piece.node_start, piece.node_end);
+ auto piece_length = piece.node_end - piece.node_start;
+ for (auto const& error : errors) {
+ auto error_start = max<size_t>(error.offset, piece.offset);
+ auto error_end = min<size_t>(error.offset + error.length, piece.offset + piece_length);
+ if (error_start >= error_end)
+ continue;
+ auto start = piece.node_start + (error_start - piece.offset);
+ auto end = piece.node_start + (error_end - piece.offset);
+ if (!overlaps_exempt_word(*text, start, end))
+ markers.add(*text, start, end);
+ }
+ }
+}
+
+// Checking existing text: When a checkable editable gains focus, its whole text is checked, one chunk at a time.
+void SpellCheckController::did_focus(GC::Ptr<DOM::Node> node)
+{
+ m_existing_text_pass.clear();
+ if (!node || !m_document->page().spell_checking_available())
+ return;
+ auto editable = checkable_editable_for(*node);
+ if (!editable)
+ return;
+ m_existing_text_pass = ExistingTextPass { .paragraphs = paragraphs_of(*editable) };
+ send_next_existing_text_chunk();
+}
+
+bool SpellCheckController::is_settled() const
+{
+ return !m_existing_text_pass.has_value() && m_requests_in_flight == 0;
+}
+
+}
diff --git a/Libraries/LibWeb/Editing/SpellCheckController.h b/Libraries/LibWeb/Editing/SpellCheckController.h
new file mode 100644
index 00000000000..672cfb6eeca
--- /dev/null
+++ b/Libraries/LibWeb/Editing/SpellCheckController.h
@@ -0,0 +1,101 @@
+/*
+ * 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 <AK/Vector.h>
+#include <LibGC/Ptr.h>
+#include <LibGC/Weak.h>
+#include <LibWeb/Forward.h>
+#include <LibWebCommon/Page/SpellingError.h>
+
+namespace Web::Editing {
+
+// Decides what text of a document gets spellchecked and when, asks the UI process to check it, and applies the answers
+// to the document's spelling markers.
+// https://html.spec.whatwg.org/multipage/interaction.html#spelling-and-grammar-checking
+class SpellCheckController {
+ AK_MAKE_NONCOPYABLE(SpellCheckController);
+ AK_MAKE_NONMOVABLE(SpellCheckController);
+ AK_ALLOC_WITH_KMALLOC;
+
+public:
+ static constexpr size_t TYPING_WINDOW_SIZE = 1024;
+ static constexpr size_t EXISTING_TEXT_CHUNK_SIZE = 16384;
+
+ struct WordRange {
+ GC::Weak<DOM::Text> text;
+ size_t start { 0 };
+ size_t end { 0 };
+ };
+
+ explicit SpellCheckController(DOM::Document&);
+
+ void did_focus(GC::Ptr<DOM::Node>);
+
+ bool is_settled() const;
+
+ void visit_edges(GC::Cell::Visitor&);
+
+private:
+ struct ParagraphPiece {
+ GC::Ref<DOM::Text> text;
+ size_t node_start { 0 };
+ size_t node_end { 0 };
+ bool checked { false };
+ };
+ using Paragraph = Vector<ParagraphPiece>;
+
+ struct RequestPiece {
+ GC::Weak<DOM::Text> text;
+ // The node's data from node_start to node_end, as it was when the text was sent.
+ Utf16String snapshot;
+ size_t node_start { 0 };
+ size_t node_end { 0 };
+ // Where the piece starts in the text sent.
+ size_t offset { 0 };
+ bool checked { false };
+ };
+
+ struct Request {
+ Utf16String text;
+ Vector<RequestPiece> pieces;
+ // Where the window ended in the paragraph's text.
+ size_t window_end { 0 };
+ };
+
+ // The editable whose existing text is being checked, one chunk at a time. Each chunk is built from the text as
+ // it is when the chunk goes out, so edits made while the pass runs don't make later chunks stale.
+ struct ExistingTextPass {
+ // The first text node of each paragraph still to check.
+ Vector<GC::Weak<DOM::Text>> paragraphs;
+ size_t next_paragraph { 0 };
+ // Where the next chunk starts in the current paragraph's text.
+ size_t next_offset { 0 };
+ };
+
+ bool owns(DOM::Text const&) const;
+ Paragraph paragraph_containing(DOM::Text&, size_t offset) const;
+ Vector<GC::Weak<DOM::Text>> paragraphs_of(DOM::Node& editable) const;
+ Request make_request(Paragraph const&, size_t window_start, size_t window_end) const;
+ void send(Request);
+ void send_next_existing_text_chunk();
+ void did_receive_answer(Request const&, Vector<SpellingError> const&);
+ void apply(Request const&, Vector<SpellingError> const&);
+ bool overlaps_exempt_word(DOM::Text const&, size_t start, size_t end) const;
+
+ GC::Ref<DOM::Document> m_document;
+ Optional<ExistingTextPass> m_existing_text_pass;
+ bool m_existing_text_chunk_in_flight { false };
+ size_t m_requests_in_flight { 0 };
+ // The word the user is still typing, which no answer flags until the caret leaves it.
+ Optional<WordRange> m_exempt_word;
+};
+
+}
diff --git a/Libraries/LibWeb/Internals/Internals.cpp b/Libraries/LibWeb/Internals/Internals.cpp
index 28412131416..3f45c453f77 100644
--- a/Libraries/LibWeb/Internals/Internals.cpp
+++ b/Libraries/LibWeb/Internals/Internals.cpp
@@ -2630,6 +2630,17 @@ GC::Ref<WebIDL::Promise> Internals::check_spelling_for_testing(Utf16String const
return promise;
}
+GC::Ref<WebIDL::Promise> Internals::spell_check_settled()
+{
+ auto& realm = window().principal_realm();
+ auto promise = WebIDL::create_promise_for(window());
+ page().when_spell_checking_settled(GC::create_function(heap(), [&realm, promise] {
+ HTML::TemporaryExecutionContext execution_context { realm };
+ WebIDL::resolve_promise(promise);
+ }));
+ return promise;
+}
+
GC::Ptr<JS::Object> Internals::hit_test_result(double x, double y)
{
auto& realm = HTML::relevant_realm(window());
diff --git a/Libraries/LibWeb/Internals/Internals.h b/Libraries/LibWeb/Internals/Internals.h
index 6fd599f6009..05152afe514 100644
--- a/Libraries/LibWeb/Internals/Internals.h
+++ b/Libraries/LibWeb/Internals/Internals.h
@@ -85,6 +85,7 @@ public:
WebIDL::ExceptionOr<void> add_spelling_error_for_testing(GC::Ref<DOM::Node>, WebIDL::UnsignedLong start, WebIDL::UnsignedLong end);
Utf16String spelling_error_ranges(GC::Ref<DOM::Node>);
GC::Ref<WebIDL::Promise> check_spelling_for_testing(Utf16String const& text);
+ GC::Ref<WebIDL::Promise> spell_check_settled();
void send_text(HTML::HTMLElement&, Utf16String const&, WebIDL::UnsignedShort modifiers);
void send_text_through_ui_process(Utf16String const&);
diff --git a/Libraries/LibWeb/Internals/Internals.idl b/Libraries/LibWeb/Internals/Internals.idl
index 999ff9bd505..c0ae0d43efd 100644
--- a/Libraries/LibWeb/Internals/Internals.idl
+++ b/Libraries/LibWeb/Internals/Internals.idl
@@ -48,6 +48,7 @@ interface Internals {
undefined addSpellingErrorForTesting(Node node, unsigned long start, unsigned long end);
DOMString spellingErrorRanges(Node node);
Promise<DOMString> checkSpellingForTesting(DOMString text);
+ Promise<undefined> spellCheckSettled();
const unsigned short MOD_NONE = 0;
const unsigned short MOD_ALT = 1;
diff --git a/Libraries/LibWeb/Page/EventHandler.cpp b/Libraries/LibWeb/Page/EventHandler.cpp
index fc163c2f771..871d469cef8 100644
--- a/Libraries/LibWeb/Page/EventHandler.cpp
+++ b/Libraries/LibWeb/Page/EventHandler.cpp
@@ -3516,51 +3516,6 @@ bool EventHandler::initiate_word_selection(Layout::BegunRead const& read, DOM::D
return true;
}
-// Find paragraph boundaries for triple-click selection. A paragraph is delimited by block nodes or <br> elements.
-static GC::Ref<DOM::Range> find_paragraph_range(DOM::Text& text_node, WebIDL::UnsignedLong offset)
-{
- GC::Ptr<DOM::Node> start_node = text_node;
- WebIDL::UnsignedLong start_offset = offset;
- GC::Ptr<DOM::Node> end_node = text_node;
- WebIDL::UnsignedLong end_offset = offset;
-
- // Walk backwards to find the paragraph start (a block boundary point).
- if (!Editing::is_block_start_point({ *start_node, start_offset })) {
- do {
- if (start_offset == 0) {
- start_offset = start_node->index();
- start_node = start_node->parent();
- } else {
- --start_offset;
- }
- } while (start_node && !Editing::is_block_boundary_point({ *start_node, start_offset }));
- }
-
- // Walk forwards to find the paragraph end (a block boundary point).
- if (!Editing::is_block_end_point({ *end_node, end_offset })) {
- do {
- if (end_offset == end_node->length()) {
- end_offset = end_node->index() + 1;
- end_node = end_node->parent();
- } else {
- ++end_offset;
- }
- } while (end_node && !Editing::is_block_boundary_point({ *end_node, end_offset }));
- }
-
- // Fallback if we couldn't find boundaries.
- if (!start_node) {
- start_node = text_node;
- start_offset = 0;
- }
- if (!end_node) {
- end_node = text_node;
- end_offset = text_node.length();
- }
-
- return DOM::Range::create(*start_node, start_offset, *end_node, end_offset);
-}
-
bool EventHandler::initiate_paragraph_selection(DOM::Document& document, Painting::CaretPosition const& caret_position, CSS::UserSelect user_select)
{
auto* boundary_node = as_if<DOM::Text>(caret_position.boundary_node().ptr());
@@ -3583,7 +3538,7 @@ bool EventHandler::initiate_paragraph_selection(DOM::Document& document, Paintin
target->set_selection_focus(hit_node, line_end);
} else if (auto selection = document.get_selection()) {
// For regular content, find paragraph boundaries within the containing block.
- m_selection_origin = find_paragraph_range(hit_node, hit_index);
+ m_selection_origin = Editing::paragraph_range_containing(hit_node, hit_index);
m_selection_mode = SelectionMode::Paragraph;
m_mouse_selection_target = nullptr;
@@ -3777,7 +3732,7 @@ void EventHandler::apply_mouse_selection(Layout::BegunRead const& read, CSSPixel
GC::Ref<DOM::Range> paragraph_range = m_mouse_selection_target
? DOM::Range::create(focus_text_node, find_line_start(focus_text_node.data().utf16_view(), focus_index),
focus_text_node, find_line_end(focus_text_node.data().utf16_view(), focus_index))
- : find_paragraph_range(focus_text_node, focus_index);
+ : Editing::paragraph_range_containing(focus_text_node, focus_index);
// Determine cursor position relative to origin.
auto position = m_selection_origin->compare_point(*focus_node, focus_index);
diff --git a/Libraries/LibWeb/Page/Page.cpp b/Libraries/LibWeb/Page/Page.cpp
index 525fdf68d18..966e43b02aa 100644
--- a/Libraries/LibWeb/Page/Page.cpp
+++ b/Libraries/LibWeb/Page/Page.cpp
@@ -18,6 +18,7 @@
#include <LibWeb/DOM/Document.h>
#include <LibWeb/DOM/Element.h>
#include <LibWeb/DOM/Range.h>
+#include <LibWeb/Editing/SpellCheckController.h>
#include <LibWeb/HTML/BrowsingContext.h>
#include <LibWeb/HTML/EventLoop/EventLoop.h>
#include <LibWeb/HTML/EventNames.h>
@@ -132,6 +133,7 @@ void Page::visit_edges(JS::Cell::Visitor& visitor)
visitor.visit(m_on_pending_dialog_closed);
visitor.visit(m_pending_clipboard_requests);
visitor.visit(m_pending_spell_check_requests);
+ visitor.visit(m_spell_checking_settled_callbacks);
visitor.visit(m_emulated_position_data);
visitor.visit(m_emulated_position_data_observers);
visitor.visit(m_offscreen_canvases_pending_placeholder_commit);
@@ -1274,6 +1276,34 @@ void Page::did_check_spelling(u64 request_id, Vector<SpellingError> errors)
{
if (auto request = m_pending_spell_check_requests.take(request_id); request.has_value())
(*request)->function()(move(errors));
+ notify_spell_check_progress();
+}
+
+static bool spell_checking_is_settled(Page& page)
+{
+ if (page.has_pending_spell_checks())
+ return false;
+ for (auto const& navigable : page.hosted_navigables()) {
+ if (auto document = navigable->active_document()) {
+ if (auto* controller = document->spell_check_controller_if_exists(); controller && !controller->is_settled())
+ return false;
+ }
+ }
+ return true;
+}
+
+void Page::when_spell_checking_settled(GC::Ref<GC::Function<void()>> callback)
+{
+ m_spell_checking_settled_callbacks.append(callback);
+ notify_spell_check_progress();
+}
+
+void Page::notify_spell_check_progress()
+{
+ if (m_spell_checking_settled_callbacks.is_empty() || !spell_checking_is_settled(*this))
+ return;
+ for (auto& callback : exchange(m_spell_checking_settled_callbacks, {}))
+ callback->function()();
}
// https://w3c.github.io/geolocation/#dfn-emulated-position-data
diff --git a/Libraries/LibWeb/Page/Page.h b/Libraries/LibWeb/Page/Page.h
index 8500b87d164..806b5aaa081 100644
--- a/Libraries/LibWeb/Page/Page.h
+++ b/Libraries/LibWeb/Page/Page.h
@@ -306,6 +306,10 @@ public:
void did_check_spelling(u64 request_id, Vector<SpellingError>);
bool has_pending_spell_checks() const { return !m_pending_spell_check_requests.is_empty(); }
+ // For tests: Calls the callback once no document of the page has spellchecking queued or in flight.
+ void when_spell_checking_settled(GC::Ref<GC::Function<void()>>);
+ void notify_spell_check_progress();
+
using GeolocationPositionResult = Variant<Geolocation::CoordinatesData, Geolocation::GeolocationPositionError::ErrorCode>;
using GeolocationPositionCallback = GC::Ref<GC::Function<void(GeolocationPositionResult)>>;
enum class GeolocationRequestType : u8 {
@@ -516,6 +520,7 @@ private:
bool m_spell_checking_available { false };
HashMap<u64, SpellCheckRequest> m_pending_spell_check_requests;
u64 m_next_spell_check_request_id { 0 };
+ Vector<GC::Ref<GC::Function<void()>>> m_spell_checking_settled_callbacks;
struct PendingGeolocationRequest {
GeolocationPositionCallback callback;
diff --git a/Tests/LibWeb/Text/expected/Editing/spellcheck-adopted-node.txt b/Tests/LibWeb/Text/expected/Editing/spellcheck-adopted-node.txt
new file mode 100644
index 00000000000..06d232eefdf
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/Editing/spellcheck-adopted-node.txt
@@ -0,0 +1,4 @@
+flagged before the move: 0-4
+flagged after the move: (none)
+moved during its check: (none)
+painted without a crash
diff --git a/Tests/LibWeb/Text/expected/Editing/spellcheck-existing-text-on-focus.txt b/Tests/LibWeb/Text/expected/Editing/spellcheck-existing-text-on-focus.txt
new file mode 100644
index 00000000000..af07807c75b
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/Editing/spellcheck-existing-text-on-focus.txt
@@ -0,0 +1,13 @@
+area: 4-8
+text: 0-5
+password: (none)
+readonly: (none)
+disabled: (none)
+no-spellcheck: (none)
+astral: 3-7
+long: 20000-20004
+editable "Hel": (none)
+editable "lo": (none)
+editable " txet ": 1-5
+editable "txet": (none)
+unfocused: (none)
diff --git a/Tests/LibWeb/Text/expected/Editing/spellcheck-long-text-edited-while-checking.txt b/Tests/LibWeb/Text/expected/Editing/spellcheck-long-text-edited-while-checking.txt
new file mode 100644
index 00000000000..232c56e1311
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/Editing/spellcheck-long-text-edited-while-checking.txt
@@ -0,0 +1 @@
+edited while its text was being checked: 20001-20005
diff --git a/Tests/LibWeb/Text/expected/Editing/spellcheck-stale-and-removed.txt b/Tests/LibWeb/Text/expected/Editing/spellcheck-stale-and-removed.txt
new file mode 100644
index 00000000000..620ec12286e
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/Editing/spellcheck-stale-and-removed.txt
@@ -0,0 +1,3 @@
+edited before the reply: (none)
+removed during the check: (none)
+iframe: 0-4
diff --git a/Tests/LibWeb/Text/expected/Editing/spellcheck-turned-off-in-flight.txt b/Tests/LibWeb/Text/expected/Editing/spellcheck-turned-off-in-flight.txt
new file mode 100644
index 00000000000..a05e76265e7
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/Editing/spellcheck-turned-off-in-flight.txt
@@ -0,0 +1,2 @@
+turned off during its check: (none)
+moved out of the editable during its check: (none)
diff --git a/Tests/LibWeb/Text/input/Editing/spellcheck-adopted-node.html b/Tests/LibWeb/Text/input/Editing/spellcheck-adopted-node.html
new file mode 100644
index 00000000000..56366e629e5
--- /dev/null
+++ b/Tests/LibWeb/Text/input/Editing/spellcheck-adopted-node.html
@@ -0,0 +1,38 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<div id="flagged" contenteditable>txet</div>
+<div id="in-flight" contenteditable>one txet two</div>
+<iframe id="frame" srcdoc="<p id=target></p>"></iframe>
+<script>
+ promiseTest(async () => {
+ const clickOn = element => {
+ const rect = element.getBoundingClientRect();
+ internals.click(rect.left + rect.width / 2, rect.top + rect.height / 2);
+ };
+ const ranges = node => internals.spellingErrorRanges(node) || "(none)";
+ const frame = document.getElementById("frame");
+ if (!frame.contentDocument?.getElementById("target"))
+ await new Promise(resolve => frame.addEventListener("load", resolve, { once: true }));
+ const target = frame.contentDocument.getElementById("target");
+
+ // A flagged text node moved into another document takes no markers along.
+ const flagged = document.getElementById("flagged");
+ clickOn(flagged);
+ await internals.spellCheckSettled();
+ const moved = flagged.firstChild;
+ println(`flagged before the move: ${ranges(moved)}`);
+ target.append(moved);
+ println(`flagged after the move: ${ranges(moved)}`);
+
+ // A text node moved into another document while its check is in flight gets no markers.
+ const inFlight = document.getElementById("in-flight");
+ clickOn(inFlight);
+ const movedInFlight = inFlight.firstChild;
+ target.append(movedInFlight);
+ await internals.spellCheckSettled();
+ println(`moved during its check: ${ranges(movedInFlight)}`);
+
+ await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));
+ println("painted without a crash");
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/Editing/spellcheck-existing-text-on-focus.html b/Tests/LibWeb/Text/input/Editing/spellcheck-existing-text-on-focus.html
new file mode 100644
index 00000000000..3fcfce3d439
--- /dev/null
+++ b/Tests/LibWeb/Text/input/Editing/spellcheck-existing-text-on-focus.html
@@ -0,0 +1,28 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<textarea id="area">one txet two</textarea>
+<input id="text" value="quikc fox">
+<input id="password" type="password" value="txet">
+<input id="readonly" readonly value="txet">
+<input id="disabled" disabled value="txet">
+<textarea id="no-spellcheck" spellcheck="false">txet</textarea>
+<div id="editable" contenteditable>Hel<b>lo</b> txet <span spellcheck="false">txet</span></div>
+<div id="unfocused" contenteditable>txet</div>
+<textarea id="astral">😀 txet</textarea>
+<textarea id="long"></textarea>
+<script>
+ promiseTest(async () => {
+ document.getElementById("long").value = "word ".repeat(4000) + "txet";
+ const ids = ["area", "text", "password", "readonly", "disabled", "no-spellcheck", "astral", "long"];
+ for (const id of [...ids, "editable"]) {
+ document.getElementById(id).focus();
+ await internals.spellCheckSettled();
+ }
+ for (const id of ids)
+ println(`${id}: ${internals.spellingErrorRanges(document.getElementById(id)) || "(none)"}`);
+ const editable = document.getElementById("editable");
+ for (const node of [editable.childNodes[0], editable.childNodes[1].firstChild, editable.childNodes[2], editable.childNodes[3].firstChild])
+ println(`editable ${JSON.stringify(node.data)}: ${internals.spellingErrorRanges(node) || "(none)"}`);
+ println(`unfocused: ${internals.spellingErrorRanges(document.getElementById("unfocused").firstChild) || "(none)"}`);
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/Editing/spellcheck-long-text-edited-while-checking.html b/Tests/LibWeb/Text/input/Editing/spellcheck-long-text-edited-while-checking.html
new file mode 100644
index 00000000000..78fd0e26f13
--- /dev/null
+++ b/Tests/LibWeb/Text/input/Editing/spellcheck-long-text-edited-while-checking.html
@@ -0,0 +1,17 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<textarea id="long"></textarea>
+<script>
+ promiseTest(async () => {
+ const long = document.getElementById("long");
+ long.value = "word ".repeat(4000) + "txet";
+ long.setSelectionRange(0, 0);
+
+ // The existing text goes in chunks. An edit before a later chunk goes out doesn't make that chunk stale.
+ const rect = long.getBoundingClientRect();
+ internals.click(rect.left + 3, rect.top + 3);
+ internals.sendText(long, "x");
+ await internals.spellCheckSettled();
+ println(`edited while its text was being checked: ${internals.spellingErrorRanges(long) || "(none)"}`);
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/Editing/spellcheck-stale-and-removed.html b/Tests/LibWeb/Text/input/Editing/spellcheck-stale-and-removed.html
new file mode 100644
index 00000000000..a248cda8d72
--- /dev/null
+++ b/Tests/LibWeb/Text/input/Editing/spellcheck-stale-and-removed.html
@@ -0,0 +1,32 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<textarea id="edited">one txet two</textarea>
+<textarea id="removed">txet</textarea>
+<iframe id="frame" srcdoc="<div contenteditable>txet</div>"></iframe>
+<script>
+ promiseTest(async () => {
+ const frame = document.getElementById("frame");
+ if (!frame.contentDocument?.querySelector("div"))
+ await new Promise(resolve => frame.addEventListener("load", resolve, { once: true }));
+
+ // A reply that comes back after the text changed is dropped.
+ const edited = document.getElementById("edited");
+ edited.focus();
+ edited.value = "one text two";
+ await internals.spellCheckSettled();
+ println(`edited before the reply: ${internals.spellingErrorRanges(edited) || "(none)"}`);
+
+ // An editable removed while its check is in flight gets no markers, and nothing crashes.
+ const removed = document.getElementById("removed");
+ removed.focus();
+ removed.remove();
+ await internals.spellCheckSettled();
+ println(`removed during the check: ${internals.spellingErrorRanges(removed) || "(none)"}`);
+
+ // A contenteditable in a same-origin iframe is checked by its own document.
+ const frameEditable = frame.contentDocument.querySelector("div");
+ frameEditable.focus();
+ await internals.spellCheckSettled();
+ println(`iframe: ${internals.spellingErrorRanges(frameEditable.firstChild) || "(none)"}`);
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/Editing/spellcheck-turned-off-in-flight.html b/Tests/LibWeb/Text/input/Editing/spellcheck-turned-off-in-flight.html
new file mode 100644
index 00000000000..55976ad2057
--- /dev/null
+++ b/Tests/LibWeb/Text/input/Editing/spellcheck-turned-off-in-flight.html
@@ -0,0 +1,28 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<textarea id="area">one txet two</textarea>
+<div id="editable" contenteditable>one txet two</div>
+<div id="plain"></div>
+<script>
+ promiseTest(async () => {
+ const clickOn = element => {
+ const rect = element.getBoundingClientRect();
+ internals.click(rect.left + rect.width / 2, rect.top + rect.height / 2);
+ };
+
+ // Checking that turns off while a check is in flight takes the answer with it.
+ const area = document.getElementById("area");
+ clickOn(area);
+ area.spellcheck = false;
+ await internals.spellCheckSettled();
+ println(`turned off during its check: ${internals.spellingErrorRanges(area) || "(none)"}`);
+
+ // So does text that moves out of the editable while its check is in flight.
+ const editable = document.getElementById("editable");
+ clickOn(editable);
+ const text = editable.firstChild;
+ document.getElementById("plain").append(text);
+ await internals.spellCheckSettled();
+ println(`moved out of the editable during its check: ${internals.spellingErrorRanges(text) || "(none)"}`);
+ });
+</script>