LibWeb: Add Document helpers to move its cursor to word boundaries

This implementation is based on the same feature I added to Serenity's
TextEditor:

https://github.com/SerenityOS/serenity/pull/17477
This commit is contained in:
Timothy Flynn 2024-09-05 12:10:25 -04:00 committed by Andreas Kling
commit ecf2cc600b
Notes: github-actions[bot] 2024-09-06 05:44:05 +00:00
6 changed files with 92 additions and 0 deletions

View file

@ -6,6 +6,7 @@
*/
#include <AK/Utf8View.h>
#include <LibUnicode/CharacterTypes.h>
#include <LibUnicode/Segmenter.h>
#include <LibWeb/DOM/Node.h>
#include <LibWeb/DOM/Position.h>
@ -66,6 +67,60 @@ bool Position::decrement_offset()
return false;
}
static bool should_continue_beyond_word(Utf8View const& word)
{
for (auto code_point : word) {
if (!Unicode::code_point_has_punctuation_general_category(code_point) && !Unicode::code_point_has_separator_general_category(code_point))
return false;
}
return true;
}
bool Position::increment_offset_to_next_word()
{
if (!is<DOM::Text>(*m_node) || offset_is_at_end_of_node())
return false;
auto& node = static_cast<DOM::Text&>(*m_node);
while (true) {
if (auto offset = node.word_segmenter().next_boundary(m_offset); offset.has_value()) {
auto word = node.data().code_points().substring_view(m_offset, *offset - m_offset);
m_offset = *offset;
if (should_continue_beyond_word(word))
continue;
}
break;
}
return true;
}
bool Position::decrement_offset_to_previous_word()
{
if (!is<DOM::Text>(*m_node) || m_offset == 0)
return false;
auto& node = static_cast<DOM::Text&>(*m_node);
while (true) {
if (auto offset = node.word_segmenter().previous_boundary(m_offset); offset.has_value()) {
auto word = node.data().code_points().substring_view(*offset, m_offset - *offset);
m_offset = *offset;
if (should_continue_beyond_word(word))
continue;
}
break;
}
return true;
}
bool Position::offset_is_at_end_of_node() const
{
if (!is<DOM::Text>(*m_node))