Skip to content

Truly independent web browser

LibWeb: Select a whole word across the inline elements it spans

sideshowbarker916fcde1c4e7
diff --git a/Libraries/LibWeb/Page/EventHandler.cpp b/Libraries/LibWeb/Page/EventHandler.cpp
index 34c4e5a1837..bb5119afdaa 100644
--- a/Libraries/LibWeb/Page/EventHandler.cpp
+++ b/Libraries/LibWeb/Page/EventHandler.cpp
@@ -4433,6 +4433,32 @@ Optional<Editing::ContextMenuMisspelling> EventHandler::select_context_menu_miss
return Editing::ContextMenuMisspelling { *text, marker->start, marker->end, move(word) };
}
+// The word at `offset` in `hit_node`, whose layout node is `layout_text_node`. A word runs on through inline elements
+// into the text of other text nodes, as in super<span>cali</span>fragilistic.
+struct WordBoundaries {
+ GC::Ref<DOM::Text> start_node;
+ size_t start_offset;
+ GC::Ref<DOM::Text> end_node;
+ size_t end_offset;
+};
+
+static WordBoundaries word_boundaries_at(DOM::Document& document, DOM::Text& hit_node, Layout::TextNode const& layout_text_node, size_t offset)
+{
+ Layout::RustFFI::FfiDomTextRange range {};
+ if (Layout::RustFFI::layout_text_inline_word_range(layout_text_node.document_host(), Layout::Node::slot_id(&layout_text_node), offset, &range)) {
+ auto text_node = [&](u32 identity) {
+ return as_if<DOM::Text>(document.style_computer().node_for_style_node(CSS::StyleNodeID { identity }).ptr());
+ };
+ auto* start = text_node(range.start_text_node);
+ auto* end = text_node(range.end_text_node);
+ if (start && end && &start->root() == &end->root() && start->is_connected() && end->is_connected()
+ && range.start_offset <= start->length() && range.end_offset <= end->length() && end->is_following(*start))
+ return { *start, range.start_offset, *end, range.end_offset };
+ }
+ auto word_range = layout_text_node.word_range_at(offset);
+ return { hit_node, word_range.start, hit_node, word_range.start + word_range.length };
+}
+
bool EventHandler::initiate_word_selection(Layout::BegunRead const& read, DOM::Document& document, Painting::CaretPosition const& caret_position, CSS::UserSelect user_select)
{
auto* boundary_node = as_if<DOM::Text>(caret_position.boundary_node().ptr());
@@ -4445,20 +4471,18 @@ bool EventHandler::initiate_word_selection(Layout::BegunRead const& read, DOM::D
if (!hit_layout_text_node)
return false;
- auto word_range = hit_layout_text_node->word_range_at(hit_index);
- auto previous_boundary = word_range.start;
- auto next_boundary = word_range.start + word_range.length;
+ auto word = word_boundaries_at(document, hit_node, *hit_layout_text_node, hit_index);
m_selection_mode = SelectionMode::Word;
- m_selection_origin = DOM::Range::create(hit_node, previous_boundary, hit_node, next_boundary);
+ m_selection_origin = DOM::Range::create(word.start_node, word.start_offset, word.end_node, word.end_offset);
if (auto* target = document.active_input_events_target(&hit_node)) {
m_mouse_selection_target = target;
- target->set_selection_anchor(hit_node, previous_boundary);
- target->set_selection_focus(hit_node, next_boundary);
+ target->set_selection_anchor(word.start_node, word.start_offset);
+ target->set_selection_focus(word.end_node, word.end_offset);
} else if (auto selection = document.get_selection()) {
m_mouse_selection_target = nullptr;
- set_user_selection(hit_node, previous_boundary, hit_node, next_boundary, selection, user_select);
+ set_user_selection(word.start_node, word.start_offset, word.end_node, word.end_offset, selection, user_select);
}
m_selection_mode = SelectionMode::Word;
@@ -4669,9 +4693,7 @@ void EventHandler::apply_mouse_selection(Layout::BegunRead const& read, CSSPixel
auto const* text_layout_node = as_if<Layout::TextNode>(focus_boundary.node.bound_layout_node(read, *caret_position->arena));
if (!text_layout_node)
return;
- auto word_range = text_layout_node->word_range_at(focus_index);
- auto word_start = word_range.start;
- auto word_end = word_range.start + word_range.length;
+ auto word = word_boundaries_at(document, as<DOM::Text>(*focus_node), *text_layout_node, focus_index);
// Determine cursor position relative to anchor.
auto position = m_selection_origin->compare_point(*focus_node, focus_index);
@@ -4680,12 +4702,14 @@ void EventHandler::apply_mouse_selection(Layout::BegunRead const& read, CSSPixel
// Cursor is before anchor: select from anchor end to current word start.
anchor_node = m_selection_origin->end_container();
anchor_offset = m_selection_origin->end_offset();
- focus_index = word_start;
+ focus_node = word.start_node;
+ focus_index = word.start_offset;
} else if (position.value() > 0) {
// Cursor is after anchor: select from anchor start to current word end.
anchor_node = m_selection_origin->start_container();
anchor_offset = m_selection_origin->start_offset();
- focus_index = word_end;
+ focus_node = word.end_node;
+ focus_index = word.end_offset;
} else {
// Cursor is within anchor: keep original word selected.
anchor_node = m_selection_origin->start_container();
diff --git a/Libraries/LibWeb/Rust/src/layout/text_queries.rs b/Libraries/LibWeb/Rust/src/layout/text_queries.rs
index ed571dae34b..9d9f7315243 100644
--- a/Libraries/LibWeb/Rust/src/layout/text_queries.rs
+++ b/Libraries/LibWeb/Rust/src/layout/text_queries.rs
@@ -258,6 +258,110 @@ pub(crate) fn text_word_range(
}
}
+/// The box whose inline content the text row `node` is part of.
+fn containing_box(arena: &LayoutNodeArena, node: NodeSlotId) -> NodeSlotId {
+ let mut current = arena.data(node).parent.get();
+ while !current.is_invalid() && !kind_is_box(arena.data(current).kind.get()) {
+ current = arena.data(current).parent.get();
+ }
+ current
+}
+
+/// The DOM range of the word at `dom_offset` in the text node whose primary row is `primary`, read across the inline
+/// boxes around it: A word runs on through inline elements, but not past a box, a line break or generated content
+/// within the same inline content. None where the word lies in that one text node anyway.
+pub(crate) fn inline_word_range(
+ arena: &mut LayoutNodeArena,
+ primary: NodeSlotId,
+ dom_offset: usize,
+) -> Option<FfiDomTextRange> {
+ if arena
+ .text_content(primary)
+ .is_some_and(|content| content.is_password_input())
+ {
+ return None;
+ }
+ let container = containing_box(arena, primary);
+ if container.is_invalid() {
+ return None;
+ }
+ // NB: The rows of the inline content, split into runs where something other than inline text and inline boxes
+ // comes between them.
+ let mut nodes = Vec::new();
+ arena.for_each_node_in_layout_subtree_in_pre_order(container, |node| nodes.push(node));
+ let mut runs: Vec<Vec<NodeSlotId>> = vec![Vec::new()];
+ let mut primary_run = None;
+ for node in nodes {
+ if node == container {
+ continue;
+ }
+ let data = arena.data(node);
+ let kind = data.kind.get();
+ let pseudo = data.generated_for.get();
+ if node_style_view(data).is_some_and(|style| style.display().is_none()) {
+ continue;
+ }
+ let breaks_run = kind == NodeKind::BreakNode
+ || (kind_is_box(kind) && pseudo != GENERATED_FOR_FIRST_LETTER)
+ || (pseudo != 0 && pseudo != GENERATED_FOR_FIRST_LETTER);
+ if breaks_run {
+ if !runs.last().expect("there is always a run").is_empty() {
+ runs.push(Vec::new());
+ }
+ continue;
+ }
+ // NB: A ::first-letter row is read with the rest of its text node, through that node's primary row.
+ if kind != NodeKind::TextNode
+ || pseudo == GENERATED_FOR_FIRST_LETTER
+ || arena.node_style_node(node).is_none()
+ || containing_box(arena, node) != container
+ {
+ continue;
+ }
+ if node == primary {
+ primary_run = Some(runs.len() - 1);
+ }
+ runs.last_mut().expect("there is always a run").push(node);
+ }
+ let run = std::mem::take(&mut runs[primary_run?]);
+ if run.len() < 2 {
+ return None;
+ }
+
+ let mut text = MappedText::default();
+ let mut hit_offset = None;
+ for node in run {
+ ensure_text_fragments(arena, node);
+ for &fragment in arena.text_fragments(node).as_slice() {
+ let content = arena.text_content(fragment).expect("fragment was refreshed");
+ let dom_range = content.dom_range();
+ if node == primary && hit_offset.is_none() && dom_offset >= dom_range.start && dom_offset <= dom_range.end {
+ hit_offset = Some(text.text.len() + content.rendered_text_offset_for_dom_offset(dom_offset, Start));
+ }
+ text.append(
+ &content.text,
+ TextPosition {
+ node: fragment,
+ offset: 0,
+ },
+ TextPosition {
+ node: fragment,
+ offset: content.text.len(),
+ },
+ );
+ }
+ }
+ if text.text.is_empty() {
+ return None;
+ }
+ let range = super::text_chunker::word_boundaries(&text.text, hit_offset?);
+ let dom_range = text.dom_range(arena, range)?;
+ if dom_range.start_text_node == dom_range.end_text_node {
+ return None;
+ }
+ Some(dom_range)
+}
+
#[derive(Default)]
struct SearchTextBuilder {
blocks: Vec<MappedText>,
@@ -477,6 +581,26 @@ pub extern "C" fn layout_text_word_range(
})
}
+/// The DOM range of the word at `dom_offset` in the text node whose primary row is `primary`, where the word runs on
+/// into the text of other DOM text nodes through inline elements. False, leaving `range` alone, where it doesn't.
+#[unsafe(no_mangle)]
+pub extern "C" fn layout_text_inline_word_range(
+ host: &crate::render_state::DocumentHost,
+ primary: NodeSlotId,
+ dom_offset: usize,
+ range: &mut FfiDomTextRange,
+) -> bool {
+ host.ask(node_read(), |state| {
+ match inline_word_range(state.arena_mut(), primary, dom_offset) {
+ Some(found) => {
+ *range = found;
+ true
+ }
+ None => false,
+ }
+ })
+}
+
#[cfg(test)]
mod tests {
use super::*;
diff --git a/Tests/LibWeb/Text/expected/word-selection-across-inline-elements.txt b/Tests/LibWeb/Text/expected/word-selection-across-inline-elements.txt
new file mode 100644
index 00000000000..98b71d100dd
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/word-selection-across-inline-elements.txt
@@ -0,0 +1,2 @@
+split word: supercalifragilisticexpialidocious
+per-letter word: word
diff --git a/Tests/LibWeb/Text/input/word-selection-across-inline-elements.html b/Tests/LibWeb/Text/input/word-selection-across-inline-elements.html
new file mode 100644
index 00000000000..0a6d992a336
--- /dev/null
+++ b/Tests/LibWeb/Text/input/word-selection-across-inline-elements.html
@@ -0,0 +1,19 @@
+<!DOCTYPE html>
+<style>
+ body { font: 20px serif; }
+ .rainbow span:nth-child(odd) { color: red; }
+</style>
+<p id="split">super<span id="middle">califragilistic</span>expialidocious and more</p>
+<p id="rainbow" class="rainbow"><span>w</span><span>o</span><span>r</span><span>d</span> next</p>
+<script src="include.js"></script>
+<script>
+ test(() => {
+ const selectWordAt = (element) => {
+ const rect = element.getBoundingClientRect();
+ internals.click(rect.left + rect.width / 2, rect.top + rect.height / 2, 2);
+ return getSelection().toString();
+ };
+ println(`split word: ${selectWordAt(document.getElementById("middle"))}`);
+ println(`per-letter word: ${selectWordAt(document.querySelector("#rainbow span:nth-child(2)"))}`);
+ });
+</script>