Skip to content

Truly independent web browser

LibWeb: Return rendered text from the selection stringifier

sideshowbarker80f2f0ebebf4
diff --git a/Libraries/LibWeb/Editing/ClipboardSerializer.cpp b/Libraries/LibWeb/Editing/ClipboardSerializer.cpp
index 85d6e28ddf4..eec0f6d6701 100644
--- a/Libraries/LibWeb/Editing/ClipboardSerializer.cpp
+++ b/Libraries/LibWeb/Editing/ClipboardSerializer.cpp
@@ -24,44 +24,61 @@
#include <LibWeb/HTML/HTMLImageElement.h>
#include <LibWeb/HTML/HTMLLIElement.h>
#include <LibWeb/HTML/HTMLOListElement.h>
-#include <LibWeb/HTML/HTMLParagraphElement.h>
#include <LibWeb/HTML/HTMLUListElement.h>
#include <LibWeb/HTML/Parser/HTMLParser.h>
+#include <LibWeb/HTML/TagNames.h>
#include <LibWeb/HTML/XMLSerializer.h>
#include <LibWeb/Layout/Node.h>
+#include <LibWeb/Layout/TextNode.h>
#include <LibWeb/Namespace.h>
+#include <LibWeb/SVG/SVGTextElement.h>
#include <LibWeb/Editing/StyledMarkupSerializer.h>
namespace Web::Editing {
+enum class TextDestination {
+ Clipboard,
+ Selection,
+};
+
// INTEROP: The Clipboard API does not define how a DOM range becomes text/plain. Blink and WebKit use a rendered-text
// iterator which emits paragraph boundaries, replaced-element text, and explicit line breaks without exposing
// the DOM's formatting whitespace. Keep that policy separate from DOM serialization so both clipboard
// representations can evolve without coupling their traversal rules.
-class ClipboardTextSerializer {
+class RangeTextSerializer {
public:
- explicit ClipboardTextSerializer(DOM::Range const& range)
+ RangeTextSerializer(DOM::Range const& range, TextDestination destination)
: m_range(GC::Root<DOM::Range const>::create(&range))
+ , m_destination(destination)
{
}
Utf16String serialize(Layout::BegunRead const& read)
{
- collect(read, m_range->common_ancestor_container(), false);
+ SelectedTableParts table;
+ collect(read, m_range->common_ancestor_container(), false, table);
if (m_pending_break_is_explicit)
flush_pending_breaks();
return m_builder.to_string();
}
private:
+ struct SelectedTableParts {
+ bool visited_row { false };
+ bool visited_cell { false };
+ size_t trailing_hidden_cells { 0 };
+ };
+
void request_line_breaks(size_t count)
{
+ m_pending_space = false;
m_pending_line_breaks = max(m_pending_line_breaks, count);
}
void request_explicit_line_break()
{
+ m_pending_space = false;
flush_pending_breaks();
m_pending_line_breaks = 1;
m_pending_break_is_explicit = true;
@@ -129,21 +146,176 @@ private:
callback(*child, child != child_on_path_to_start && child != child_on_path_to_end);
}
- void collect(Layout::BegunRead const& read, DOM::Node const& node, bool node_is_fully_contained)
+ bool has_visible_table_content(Layout::BegunRead const& read, DOM::Node const& node, bool node_is_fully_contained)
+ {
+ if (auto const* box = as_if<Layout::NodeWithStyle>(node.layout_node(read)); box && box->visibility() == CSS::Visibility::Visible && box->user_select_used_value() != CSS::UserSelect::None)
+ return true;
+ bool visible = false;
+ for_each_child_intersecting_range(node, node_is_fully_contained, [&](auto const& child, bool fully_contained) {
+ visible = visible || has_visible_table_content(read, child, fully_contained);
+ });
+ return visible;
+ }
+
+ void append_selected_text(Layout::TextNode const& layout_text, DOM::Text const& text)
+ {
+ auto const* parent = layout_text.parent();
+ if (!parent || parent->visibility() != CSS::Visibility::Visible)
+ return;
+ auto collapse = CSS::white_space_collapse_from_inherited_bits(parent->inherited_set_values().bits);
+ bool collapses_spaces = first_is_one_of(collapse, CSS::WhiteSpaceCollapse::Collapse, CSS::WhiteSpaceCollapse::PreserveBreaks);
+ size_t range_start = &text == m_range->start_container().ptr() ? m_range->start_offset() : 0;
+ size_t range_end = &text == m_range->end_container().ptr() ? m_range->end_offset() : text.length_in_utf16_code_units();
+ if (range_start >= range_end)
+ return;
+ auto source = text.data().utf16_view();
+ auto is_collapsible_space = [&](size_t offset) {
+ auto unit = source.code_unit_at(offset);
+ return collapses_spaces && (first_is_one_of(unit, ' ', '\t', '\r') || (unit == '\n' && collapse == CSS::WhiteSpaceCollapse::Collapse));
+ };
+ auto slot = Layout::Node::slot_id(&layout_text);
+ Layout::RustFFI::FfiVisualLine bounds {};
+ bool preserves_breaks = first_is_one_of(collapse, CSS::WhiteSpaceCollapse::Preserve, CSS::WhiteSpaceCollapse::PreserveBreaks, CSS::WhiteSpaceCollapse::BreakSpaces);
+ size_t first_offset = range_start;
+ size_t last_offset = range_end;
+ if (Layout::RustFFI::render_state_text_line_bounds(layout_text.document_host(), slot, &bounds)) {
+ first_offset = bounds.start_offset;
+ last_offset = bounds.end_offset;
+ } else if (first_is_one_of(parent->kind(), Layout::RustFFI::NodeKind::SVGTextBox, Layout::RustFFI::NodeKind::SVGTextPathBox)) {
+ // SVG text content has no inline line boxes. Its layout text still carries rendered text and DOM offsets.
+ first_offset = 0;
+ last_offset = source.length_in_code_units();
+ while (first_offset < last_offset && is_collapsible_space(first_offset))
+ ++first_offset;
+ while (last_offset > first_offset && is_collapsible_space(last_offset - 1))
+ --last_offset;
+ } else {
+ auto selected = source.substring_view(range_start, range_end - range_start);
+ if (!preserves_breaks || !all_of(selected, [](u32 code_point) { return code_point == '\n'; })) {
+ if (selected.is_ascii_whitespace() && is_collapsible_space(range_start))
+ m_pending_space = true;
+ return;
+ }
+ }
+ // A caret boundary can skip a preserved line feed and the collapsible spaces beside it. Include each
+ // selected line feed and the whitespace between it and the rendered text.
+ if (preserves_breaks) {
+ for (auto offset = first_offset; offset > range_start; --offset) {
+ if (source.code_unit_at(offset - 1) == '\n')
+ first_offset = offset - 1;
+ else if (!is_collapsible_space(offset - 1))
+ break;
+ }
+ for (auto offset = last_offset; offset < range_end; ++offset) {
+ if (source.code_unit_at(offset) == '\n')
+ last_offset = offset + 1;
+ else if (!is_collapsible_space(offset))
+ break;
+ }
+ }
+ auto start = max(first_offset, range_start);
+ auto end = min(last_offset, range_end);
+ if (range_start < first_offset && is_collapsible_space(range_start))
+ m_pending_space = true;
+ bool ends_in_trimmed_space = last_offset < range_end && is_collapsible_space(range_end - 1);
+ if (start >= end) {
+ m_pending_space |= ends_in_trimmed_space;
+ return;
+ }
+
+ Utf16String rendered;
+ if (start == 0 && end == text.length_in_utf16_code_units()) {
+ rendered = layout_text.rendered_text_for_dom();
+ } else {
+ auto mapped = layout_text.rendered_text_for_dom_with_offset_mapping();
+ size_t from = 0;
+ while (from < mapped.offset_mapping.size() && mapped.offset_mapping[from].dom_end_offset <= start)
+ ++from;
+ size_t to = from;
+ while (to < mapped.offset_mapping.size() && mapped.offset_mapping[to].dom_start_offset < end)
+ ++to;
+ rendered = Utf16String::from_utf16(mapped.text.utf16_view().substring_view(from, to - from));
+ }
+
+ auto units = rendered.utf16_view();
+ if (units.is_empty())
+ return;
+ // A soft wrap can trim a space from both painted lines. Keep one separator when the selection includes text
+ // on both sides, and drop it at a paragraph or explicit line break.
+ if (m_pending_space && !m_builder.is_empty() && !m_pending_line_breaks && !m_builder.view().ends_with(u' ') && !units.starts_with(u' '))
+ m_builder.append_ascii(' ');
+ m_pending_space = ends_in_trimmed_space;
+ flush_pending_breaks();
+ if (!collapses_spaces) {
+ m_builder.append(units);
+ return;
+ }
+
+ size_t run_start = 0;
+ for (size_t i = 1; i < units.length_in_code_units(); ++i) {
+ if (units.code_unit_at(i) != ' ' || units.code_unit_at(i - 1) != ' ')
+ continue;
+ m_builder.append(units.substring_view(run_start, i - run_start));
+ while (i + 1 < units.length_in_code_units() && units.code_unit_at(i + 1) == ' ')
+ ++i;
+ run_start = i + 1;
+ }
+ m_builder.append(units.substring_view(run_start));
+ }
+
+ void collect(Layout::BegunRead const& read, DOM::Node const& node, bool node_is_fully_contained, SelectedTableParts& table)
{
auto const* layout_node = node.layout_node(read);
- bool is_rendered_block = false;
+ SelectedTableParts nested_table;
+ bool starts_table = false;
+ size_t block_line_breaks = 0;
if (layout_node && is<Layout::NodeWithStyle>(*layout_node)) {
- auto display = as<Layout::NodeWithStyle>(*layout_node).display();
- is_rendered_block = display.is_block_outside() || display.is_table_caption();
+ auto const& styled_node = as<Layout::NodeWithStyle>(*layout_node);
+ auto display = styled_node.display();
+ if (display.is_block_outside() || display.is_table_caption()
+ || (m_destination == TextDestination::Selection && is<SVG::SVGTextElement>(node))) {
+ auto const* element = as_if<HTML::HTMLElement>(node);
+ block_line_breaks = element && element->local_name() == HTML::TagNames::p ? 2 : 1;
+ }
+ starts_table = display.is_table_inside();
+ if (m_destination == TextDestination::Selection && (display.is_table_row() || display.is_table_cell())) {
+ if (layout_node->user_select_used_value() != CSS::UserSelect::None) {
+ if (styled_node.visibility() != CSS::Visibility::Visible && !has_visible_table_content(read, node, node_is_fully_contained)) {
+ if (display.is_table_cell() && table.visited_cell)
+ ++table.trailing_hidden_cells;
+ return;
+ }
+ // Hidden cells still occupy columns between visible parts of the selection.
+ if (table.trailing_hidden_cells && !m_pending_break_is_explicit) {
+ flush_pending_breaks();
+ m_builder.append_repeated_ascii('\t', table.trailing_hidden_cells);
+ }
+ table.trailing_hidden_cells = 0;
+ if (display.is_table_row()) {
+ if (table.visited_row)
+ request_explicit_line_break();
+ table.visited_row = true;
+ table.visited_cell = false;
+ } else {
+ if (table.visited_cell && !m_pending_break_is_explicit)
+ append("\t"_utf16);
+ table.visited_cell = true;
+ m_pending_space = false;
+ }
+ }
+ }
}
- if (is_rendered_block)
- request_line_breaks(is<HTML::HTMLParagraphElement>(node) ? 2 : 1);
+ if (block_line_breaks)
+ request_line_breaks(block_line_breaks);
if (auto const* text = as_if<DOM::Text>(node)) {
if (!layout_node || layout_node->user_select_used_value() == CSS::UserSelect::None)
return;
+ if (m_destination == TextDestination::Selection) {
+ append_selected_text(as<Layout::TextNode>(*layout_node), *text);
+ return;
+ }
// Source formatting whitespace between blocks has a layout node but produces no painted text. TextIterator
// based engines omit it from the plain-text clipboard representation.
if (!Layout::RustFFI::render_state_text_has_lines(layout_node->document_host(), Layout::Node::slot_id(layout_node)))
@@ -160,18 +332,20 @@ private:
data = text->data();
append(data);
} else if (is<HTML::HTMLBRElement>(node)) {
- if (node_is_fully_contained)
+ auto const* box = as_if<Layout::NodeWithStyle>(layout_node);
+ bool selectable = box && box->visibility() == CSS::Visibility::Visible && box->user_select_used_value() != CSS::UserSelect::None;
+ if (node_is_fully_contained && (m_destination == TextDestination::Clipboard || selectable))
request_explicit_line_break();
} else if (auto const* image = as_if<HTML::HTMLImageElement>(node)) {
- if (node_is_fully_contained && layout_node && layout_node->user_select_used_value() != CSS::UserSelect::None)
+ if (m_destination == TextDestination::Clipboard && node_is_fully_contained && layout_node && layout_node->user_select_used_value() != CSS::UserSelect::None)
append(image->alt());
} else {
for_each_child_intersecting_range(node, node_is_fully_contained, [&](DOM::Node const& child, bool child_is_fully_contained) {
- collect(read, child, child_is_fully_contained);
+ collect(read, child, child_is_fully_contained, starts_table ? nested_table : table);
});
}
- if (layout_node && is<Layout::NodeWithStyle>(*layout_node)) {
+ if (m_destination == TextDestination::Clipboard && layout_node && is<Layout::NodeWithStyle>(*layout_node)) {
auto display = as<Layout::NodeWithStyle>(*layout_node).display();
if (display.is_table_cell() && node.next_sibling())
append("\t"_utf16);
@@ -179,20 +353,30 @@ private:
request_explicit_line_break();
}
- if (is_rendered_block)
- request_line_breaks(is<HTML::HTMLParagraphElement>(node) ? 2 : 1);
+ if (block_line_breaks)
+ request_line_breaks(block_line_breaks);
}
GC::Root<DOM::Range const> m_range;
Utf16StringBuilder m_builder;
+ TextDestination m_destination;
size_t m_pending_line_breaks { 0 };
bool m_pending_break_is_explicit { false };
+ bool m_pending_space { false };
};
Utf16String serialize_range_as_plain_text_for_clipboard(DOM::Range const& range)
{
Layout::ForcedReadScope read { range.start_container()->document() };
- return ClipboardTextSerializer { range }.serialize(read);
+ return RangeTextSerializer { range, TextDestination::Clipboard }.serialize(read);
+}
+
+Utf16String serialize_selection_as_plain_text(DOM::Range const& range)
+{
+ auto& document = range.start_container()->document();
+ document.update_layout(DOM::UpdateLayoutReason::NavigableSelectedText);
+ Layout::ForcedReadScope read { document };
+ return RangeTextSerializer { range, TextDestination::Selection }.serialize(read);
}
Utf16String serialize_range_as_html_for_clipboard(DOM::Range& range)
diff --git a/Libraries/LibWeb/Editing/ClipboardSerializer.h b/Libraries/LibWeb/Editing/ClipboardSerializer.h
index b9e4555e8b9..557e8c39250 100644
--- a/Libraries/LibWeb/Editing/ClipboardSerializer.h
+++ b/Libraries/LibWeb/Editing/ClipboardSerializer.h
@@ -11,6 +11,7 @@
namespace Web::Editing {
+Utf16String serialize_selection_as_plain_text(DOM::Range const&);
Utf16String serialize_range_as_plain_text_for_clipboard(DOM::Range const&);
Utf16String serialize_range_as_html_for_clipboard(DOM::Range&);
diff --git a/Libraries/LibWeb/Rust/src/layout/inline_content.rs b/Libraries/LibWeb/Rust/src/layout/inline_content.rs
index b95a7eff516..d51ba865c43 100644
--- a/Libraries/LibWeb/Rust/src/layout/inline_content.rs
+++ b/Libraries/LibWeb/Rust/src/layout/inline_content.rs
@@ -55,7 +55,10 @@ impl PartialEq for GlyphInkOfLines {
/// The indices of each node's fragments in its line root's content, which queries that start from a node look up in a
/// line root with many fragments. Most line roots are never asked, so the index is built the first time one is.
#[derive(Default)]
-pub struct TextFragmentIndex(std::sync::OnceLock<InlineBoxIndex>);
+pub struct TextFragmentIndex {
+ fragments: std::sync::OnceLock<InlineBoxIndex>,
+ fragmentless_break_lines: std::sync::OnceLock<Box<InlineBoxIndex>>,
+}
// NB: The index follows from the fragments, so a copy builds its own, and it does not tell two contents apart.
impl Clone for TextFragmentIndex {
@@ -696,11 +699,25 @@ impl InlineContent {
/// The indices of the fragments of `node`, in fragment order.
pub(crate) fn fragment_indices_of(&self, node: NodeSlotId) -> &[u32] {
self.text_fragments
- .0
+ .fragments
.get_or_init(|| InlineBoxIndex::of_nodes(self.fragments.iter().map(|fragment| fragment.layout_node)))
.piece_indices_of(node)
}
+ /// Lines with a preserved break owned by this node and no fragments to identify the line by.
+ pub(crate) fn fragmentless_break_lines_of(&self, node: NodeSlotId) -> &[u32] {
+ self.text_fragments
+ .fragmentless_break_lines
+ .get_or_init(|| {
+ Box::new(InlineBoxIndex::of_nodes(self.lines.iter().map(|line| {
+ line.forced_break
+ .filter(|_| line.fragment_count == 0)
+ .map_or(NodeSlotId::INVALID, |position| position.node)
+ })))
+ })
+ .piece_indices_of(node)
+ }
+
fn drop_repeated_placeholder_pieces(&mut self) {
// NB: An inline box that's empty within one fragment has a piece there with no fragment of its content,
// which is a placeholder unless the box is empty in every fragment it's laid out in.
diff --git a/Libraries/LibWeb/Rust/src/layout/query/inline_cursor.rs b/Libraries/LibWeb/Rust/src/layout/query/inline_cursor.rs
index 172fc70950f..db6660c0f6f 100644
--- a/Libraries/LibWeb/Rust/src/layout/query/inline_cursor.rs
+++ b/Libraries/LibWeb/Rust/src/layout/query/inline_cursor.rs
@@ -1010,33 +1010,27 @@ impl<'a, A: PaintRead> InlineCursor<'a, A> {
}
true
});
- let mut roots: Vec<NodeSlotId> = nodes
- .iter()
- .filter_map(|&node| text_fragment::containing_block_paintable_of_node(arena, node))
- .collect();
- roots.dedup();
- for root in roots {
- for (index, record) in arena.committed_side_data(root).lines().iter().enumerate() {
- if let Some(position) = record.forced_break
- && record.fragment_count == 0
- && nodes.contains(&position.node)
- {
- let offset = arena.dom_offset_for_rendered_text_offset(
- position.node,
- position.rendered_offset as usize,
- RenderedTextBoundary::Start,
- );
- lines.push(TextLine {
- line: InlineLine {
- root,
- index: index as u32,
- },
- start_offset: offset,
- end_offset: offset,
- end_offset_with_trailing_whitespace: offset,
- has_fragments: false,
- });
- }
+ for &node in nodes {
+ let Some(root) = text_fragment::containing_block_paintable_of_node(arena, node) else {
+ continue;
+ };
+ let content = arena.committed_side_data(root);
+ for &index in content.fragmentless_break_lines_of(node) {
+ let position = content.lines()[index as usize]
+ .forced_break
+ .expect("indexed forced break");
+ let offset = arena.dom_offset_for_rendered_text_offset(
+ node,
+ position.rendered_offset as usize,
+ RenderedTextBoundary::Start,
+ );
+ lines.push(TextLine {
+ line: InlineLine { root, index },
+ start_offset: offset,
+ end_offset: offset,
+ end_offset_with_trailing_whitespace: offset,
+ has_fragments: false,
+ });
}
}
lines.sort_by_key(|line| line.start_offset);
diff --git a/Libraries/LibWeb/Rust/src/painting/ffi.rs b/Libraries/LibWeb/Rust/src/painting/ffi.rs
index 18cb841dade..050f899fd5e 100644
--- a/Libraries/LibWeb/Rust/src/painting/ffi.rs
+++ b/Libraries/LibWeb/Rust/src/painting/ffi.rs
@@ -719,6 +719,40 @@ pub extern "C" fn render_state_text_has_lines(host: &DocumentHost, primary: Node
})
}
+/// The first and last DOM offsets on lines belonging to this text, including fragmentless preserved breaks.
+#[unsafe(no_mangle)]
+pub extern "C" fn render_state_text_line_bounds(
+ host: &DocumentHost,
+ primary: NodeSlotId,
+ bounds: &mut FfiVisualLine,
+) -> bool {
+ fn line_bounds(rows: &impl PaintRead, primary: NodeSlotId) -> Option<FfiVisualLine> {
+ let lines = InlineCursor::new(rows).lines_of_text(primary);
+ Some(FfiVisualLine {
+ start_offset: lines.first()?.start_offset,
+ end_offset: lines.last()?.end_offset,
+ })
+ }
+
+ // A fragmentless break maps its rendered offset back to the DOM through the text of its row.
+ let known = host.read_known_rows(|snapshot, rows| {
+ snapshot
+ .text_awaiting_render()
+ .is_empty()
+ .then(|| line_bounds(rows, primary))
+ });
+ let result = known.flatten().unwrap_or_else(|| {
+ read_arena(host, node_read(), primary, |arena, primary| {
+ line_bounds(&arena.paintable_rows(), primary)
+ })
+ });
+ if let Some(result) = result {
+ *bounds = result;
+ return true;
+ }
+ false
+}
+
/// The caret position at the start of the first line of the DOM text whose layout node is `primary`, or at the end of
/// its last line.
#[unsafe(no_mangle)]
diff --git a/Libraries/LibWeb/Rust/src/painting/paintable_data.rs b/Libraries/LibWeb/Rust/src/painting/paintable_data.rs
index e2338f4b4f3..f9af09f4377 100644
--- a/Libraries/LibWeb/Rust/src/painting/paintable_data.rs
+++ b/Libraries/LibWeb/Rust/src/painting/paintable_data.rs
@@ -283,6 +283,11 @@ impl CommittedSideData {
.as_ref()
.map_or(&[], |content| content.fragment_indices_of(node))
}
+ pub(crate) fn fragmentless_break_lines_of(&self, node: NodeSlotId) -> &[u32] {
+ self.inline_content
+ .as_ref()
+ .map_or(&[], |content| content.fragmentless_break_lines_of(node))
+ }
pub(crate) fn inline_box_pieces(&self) -> &[InlineBoxPieceRecord] {
self.inline_content
.as_ref()
diff --git a/Libraries/LibWeb/Selection/Selection.cpp b/Libraries/LibWeb/Selection/Selection.cpp
index 016d73ed44c..e3f6d6151e7 100644
--- a/Libraries/LibWeb/Selection/Selection.cpp
+++ b/Libraries/LibWeb/Selection/Selection.cpp
@@ -13,6 +13,7 @@
#include <LibWeb/DOM/Position.h>
#include <LibWeb/DOM/Range.h>
#include <LibWeb/DOM/Text.h>
+#include <LibWeb/Editing/ClipboardSerializer.h>
#include <LibWeb/Editing/EditingHistory.h>
#include <LibWeb/HTML/FormAssociatedElement.h>
#include <LibWeb/Layout/Box.h>
@@ -539,11 +540,9 @@ Utf16String Selection::to_string() const
if (auto form_text = try_form_control_selected_text_for_stringifier(); form_text.has_value())
return form_text.release_value();
- // FIXME: This needs more work to be compatible with other engines.
- // See https://www.w3.org/Bugs/Public/show_bug.cgi?id=10583
- if (!m_range)
+ if (!m_range || m_range->collapsed())
return {};
- return m_range->to_string();
+ return Editing::serialize_selection_as_plain_text(*m_range);
}
GC::Ref<DOM::Document> Selection::document() const
diff --git a/Tests/LibWeb/Text/expected/HTML/frame-in-flight/clock-lane-drag-selection-beside-a-task.txt b/Tests/LibWeb/Text/expected/HTML/frame-in-flight/clock-lane-drag-selection-beside-a-task.txt
index 3f3207bec70..f1703c800a6 100644
--- a/Tests/LibWeb/Text/expected/HTML/frame-in-flight/clock-lane-drag-selection-beside-a-task.txt
+++ b/Tests/LibWeb/Text/expected/HTML/frame-in-flight/clock-lane-drag-selection-beside-a-task.txt
@@ -3,6 +3,6 @@ selection after the tick: ""
the lane shows something: true
the host paints nothing new: true
selection changes from the lane: 0
-selection after the host handled the move: "irst line of plain text\nsecond line of "
+selection after the host handled the move: "irst line of plain text\n\nsecond line of "
the host paints what the lane showed: true
a drag ends when the button goes up: true
diff --git a/Tests/LibWeb/Text/expected/select-all-respects-user-select-none.txt b/Tests/LibWeb/Text/expected/select-all-respects-user-select-none.txt
index c5b8126cf4c..27d6b6db089 100644
--- a/Tests/LibWeb/Text/expected/select-all-respects-user-select-none.txt
+++ b/Tests/LibWeb/Text/expected/select-all-respects-user-select-none.txt
@@ -1,2 +1,3 @@
-selection.toString(): "hiddenvisiblealso hiddenalso visible"
+range.toString(): "hiddenvisiblealso hiddenalso visible"
+selection.toString(): "visible\n\nalso visible"
clipboard text: "visible\n\nalso visible"
diff --git a/Tests/LibWeb/Text/expected/select-text.txt b/Tests/LibWeb/Text/expected/select-text.txt
index cd002c00087..9afaa90d2b1 100644
--- a/Tests/LibWeb/Text/expected/select-text.txt
+++ b/Tests/LibWeb/Text/expected/select-text.txt
@@ -4,4 +4,5 @@ dolor
dolor s
dolor sit
First paragraph for triple-click test.
- Second paragraph with a link inside.
+
+Second paragraph with a link inside.
diff --git a/Tests/LibWeb/Text/expected/selection-drag-below-line-with-side-content.txt b/Tests/LibWeb/Text/expected/selection-drag-below-line-with-side-content.txt
index 6de21f8aa58..3b7c7980b1b 100644
--- a/Tests/LibWeb/Text/expected/selection-drag-below-line-with-side-content.txt
+++ b/Tests/LibWeb/Text/expected/selection-drag-below-line-with-side-content.txt
@@ -1,3 +1,3 @@
selected previous text: false
-selected rest of line: false
+selected rest of line: true
selected sidebar text: false
diff --git a/Tests/LibWeb/Text/expected/selection-stringifier-rendered-text.txt b/Tests/LibWeb/Text/expected/selection-stringifier-rendered-text.txt
new file mode 100644
index 00000000000..ba539c00c6d
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/selection-stringifier-rendered-text.txt
@@ -0,0 +1,31 @@
+ab
+a.hidden { display: none; }scripthiddeninvisibleb
+Y Z
+aaa inside
+""
+"\n"
+"\n\n"
+"x"
+"a \nb"
+"a \n"
+"a"
+"a"
+"a"
+"a\t\tb"
+"a\t\tb\nc"
+"a\t\t"
+""
+"c"
+"b"
+""
+"v"
+"a\t\tb\nc"
+"c"
+"a \n b"
+"\n"
+"a \n b"
+"\n"
+"abcdef"
+"bcde"
+"cd"
+""
diff --git a/Tests/LibWeb/Text/expected/wpt-import/selection/toString-ff-bug-001.txt b/Tests/LibWeb/Text/expected/wpt-import/selection/toString-ff-bug-001.txt
new file mode 100644
index 00000000000..57db53109c2
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/selection/toString-ff-bug-001.txt
@@ -0,0 +1,6 @@
+Harness status: OK
+
+Found 1 tests
+
+1 Pass
+Pass Can serialize a range which starts at the end of an element
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/selection/toString-user-select-none.txt b/Tests/LibWeb/Text/expected/wpt-import/selection/toString-user-select-none.txt
new file mode 100644
index 00000000000..8435df28166
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/selection/toString-user-select-none.txt
@@ -0,0 +1,8 @@
+Harness status: OK
+
+Found 3 tests
+
+3 Pass
+Pass Selection.toString() excludes basic user-select: none content
+Pass Selection.toString() excludes nested user-select: none content
+Pass Selection.toString() includes selectable children in unselectable container
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/input/select-all-respects-user-select-none.html b/Tests/LibWeb/Text/input/select-all-respects-user-select-none.html
index dd4a95f5cab..3eb8d8b48d6 100644
--- a/Tests/LibWeb/Text/input/select-all-respects-user-select-none.html
+++ b/Tests/LibWeb/Text/input/select-all-respects-user-select-none.html
@@ -5,12 +5,9 @@
test(() => {
getSelection().selectAllChildren(document.getElementById("container"));
- // Per the Selection API spec, the Range itself still spans the whole container, including user-select:none
- // subtrees — so Selection.toString() returns everything.
+ println(`range.toString(): "${getSelection().getRangeAt(0).toString()}"`);
println(`selection.toString(): "${getSelection().toString().replace(/\n/g, "\\n")}"`);
- // But the clipboard/visible-selection path must exclude user-select: none content, per
- // https://drafts.csswg.org/css-ui/#valdef-user-select-none.
println(`clipboard text: "${internals.selectedTextForClipboard().replace(/\n/g, "\\n")}"`);
});
</script>
diff --git a/Tests/LibWeb/Text/input/selection-drag-below-line-with-side-content.html b/Tests/LibWeb/Text/input/selection-drag-below-line-with-side-content.html
index 467d0166f7c..42e59d2cabc 100644
--- a/Tests/LibWeb/Text/input/selection-drag-below-line-with-side-content.html
+++ b/Tests/LibWeb/Text/input/selection-drag-below-line-with-side-content.html
@@ -61,7 +61,7 @@
const selectedText = getSelection().toString();
println(`selected previous text: ${selectedText.includes("This")}`);
- println(`selected rest of line: ${selectedText.includes("comes with many new features") && selectedText.endsWith("including:")}`);
+ println(`selected rest of line: ${selectedText.includes("comes with many new features") && selectedText.trimEnd().endsWith("including:")}`);
println(`selected sidebar text: ${selectedText.includes("About Me")}`);
});
</script>
diff --git a/Tests/LibWeb/Text/input/selection-stringifier-rendered-text.html b/Tests/LibWeb/Text/input/selection-stringifier-rendered-text.html
new file mode 100644
index 00000000000..80603aeba6a
--- /dev/null
+++ b/Tests/LibWeb/Text/input/selection-stringifier-rendered-text.html
@@ -0,0 +1,98 @@
+<!doctype html>
+<script src="include.js"></script>
+<div id="target">a<style>.hidden { display: none; }</style><script type="text/plain">script</script><span class="hidden">hidden</span><span style="visibility: hidden">invisible</span><br hidden><br style="user-select:none"><img alt="image">b</div>
+<script>
+ test(() => {
+ const selection = getSelection();
+ selection.selectAllChildren(target);
+ println(selection.toString());
+ println(selection.getRangeAt(0).toString());
+
+ target.textContent = "xy z";
+ target.style.textTransform = "uppercase";
+ selection.setBaseAndExtent(target.firstChild, 1, target.firstChild, 5);
+ println(selection.toString());
+ target.style.cssText = "font: 20px monospace; width: 60px";
+ target.innerHTML = "aaa<span> </span>inside";
+ selection.selectAllChildren(target);
+ println(selection.toString());
+ selection.collapseToStart();
+ println(JSON.stringify(selection.toString()));
+
+ function printContents(node) {
+ const range = document.createRange();
+ range.selectNodeContents(node);
+ selection.removeAllRanges();
+ selection.addRange(range);
+ println(JSON.stringify(selection.toString()));
+ }
+ target.style.cssText = "";
+ target.innerHTML = '<span style="white-space: pre"></span>';
+ const text = target.firstChild.appendChild(document.createTextNode("\n"));
+ printContents(text);
+ text.data = "x\n\n";
+ selection.setBaseAndExtent(text, 1, text, 3);
+ println(JSON.stringify(selection.toString()));
+ target.firstChild.style.whiteSpace = "normal";
+ printContents(text);
+
+ target.innerHTML = '<span>a </span><span style="white-space: pre">\nb</span>';
+ printContents(target);
+ target.lastChild.textContent = "\n";
+ printContents(target);
+ target.lastChild.hidden = true;
+ printContents(target);
+ target.innerHTML = 'a<div style="content-visibility: hidden"><span style="white-space: pre">\n</span></div>';
+ printContents(target);
+ target.innerHTML = "<table><tbody><tr><td>a</td><td></td><td>b</td></tr><tr><td>c</td></tr></tbody></table>";
+ const table = target.firstChild;
+ printContents(table.rows[0].cells[0]);
+ printContents(table.rows[0]);
+ printContents(table);
+ selection.setBaseAndExtent(table.rows[0].cells[0].firstChild, 0, table.rows[0].cells[2].firstChild, 0);
+ println(JSON.stringify(selection.toString()));
+
+ table.style.userSelect = "none";
+ printContents(table);
+ table.rows[1].style.userSelect = "text";
+ printContents(table);
+ table.rows[1].style.userSelect = "";
+ table.rows[0].cells[2].innerHTML = '<span style="user-select: text">b</span>';
+ printContents(table);
+
+ table.style.userSelect = "";
+ table.rows[0].cells[2].textContent = "b";
+ table.style.visibility = "hidden";
+ printContents(table);
+ table.rows[0].cells[1].innerHTML = '<span style="visibility: visible">v</span>';
+ printContents(table);
+ table.style.visibility = "";
+ table.rows[0].cells[1].style.visibility = "hidden";
+ table.rows[0].cells[1].textContent = "hidden";
+ printContents(table);
+ table.rows[0].style.visibility = "hidden";
+ printContents(table);
+
+ target.style.whiteSpace = "pre-line";
+ target.innerHTML = "<span>a </span><span>\n b</span>";
+ printContents(target);
+ selection.setBaseAndExtent(target.lastChild.firstChild, 0, target.lastChild.firstChild, 1);
+ println(JSON.stringify(selection.toString()));
+ target.innerHTML = "<span>a \n</span><span> b</span>";
+ printContents(target);
+ selection.setBaseAndExtent(target.firstChild.firstChild, 2, target.firstChild.firstChild, 3);
+ println(JSON.stringify(selection.toString()));
+ target.style.whiteSpace = "";
+
+ target.innerHTML = '<svg><title>title</title><text y="20">ab<tspan>cd</tspan>ef</text></svg>';
+ const svgText = target.querySelector("text");
+ printContents(target);
+ selection.setBaseAndExtent(svgText.firstChild, 1, svgText.lastChild, 1);
+ println(JSON.stringify(selection.toString()));
+ svgText.style.visibility = "hidden";
+ svgText.firstElementChild.style.visibility = "visible";
+ printContents(target);
+ svgText.firstElementChild.style.display = "none";
+ printContents(target);
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/selection/toString-ff-bug-001.html b/Tests/LibWeb/Text/input/wpt-import/selection/toString-ff-bug-001.html
new file mode 100644
index 00000000000..5fd2f1aa384
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/selection/toString-ff-bug-001.html
@@ -0,0 +1,23 @@
+<!doctype html>
+<title>Can serialize a range which starts at the end of an element</title>
+<link rel="help" href="https://bugzilla.mozilla.org/show_bug.cgi?id=1571517">
+<link rel="author" title="Emilio Cobos Álvarez" href="mailto:[email protected]">
+<link rel="author" title="Mozilla" href="https://mozilla.org">
+<script src=../resources/testharness.js></script>
+<script src=../resources/testharnessreport.js></script>
+<table>
+ <tr>
+ <td id="left">Foo</td>
+ <td id="right">Hello</td>
+ </tr>
+</table>
+<script>
+test(function() {
+ let s = getSelection();
+ let r = new Range();
+ r.setStart(document.getElementById("left"), 1);
+ r.setEnd(document.getElementById("right").firstChild, 4);
+ s.addRange(r);
+ assert_equals(s.toString().trim(), "Hell");
+}, "Can serialize a range which starts at the end of an element");
+</script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/selection/toString-user-select-none.html b/Tests/LibWeb/Text/input/wpt-import/selection/toString-user-select-none.html
new file mode 100644
index 00000000000..5b34b5c8337
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/selection/toString-user-select-none.html
@@ -0,0 +1,54 @@
+<!DOCTYPE html>
+<meta charset="utf-8">
+<title>Selection.toString() with user-select: none elements</title>
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+
+<div id="test-content">
+ <!-- Test case 1: Basic user-select: none -->
+ <div id="basic">
+ a<span style="user-select: none;">b</span>c
+ </div>
+
+ <!-- Test case 2: Nested user-select: none -->
+ <div id="nested">
+ start <span style="user-select: none;">unselectable <strong>nested</strong>
+ text</span> end
+ </div>
+
+ <!-- Test case 3: Selectable children inside unselectable container -->
+ <div id="container" style="user-select: none;">
+ <span style="user-select: text;">selectable</span> unselectable
+ <span style="user-select: text;">text</span>
+ </div>
+</div>
+
+<script>
+function selectAllAndGetSelectionTextInElement(element) {
+ const selection = getSelection();
+ selection.removeAllRanges();
+ const range = document.createRange();
+ range.selectNodeContents(element);
+ selection.addRange(range);
+ return selection.toString();
+}
+
+test(() => {
+ const result = selectAllAndGetSelectionTextInElement(document.getElementById('basic'));
+ assert_equals(result, 'ac',
+ 'Basic user-select: none content should be excluded');
+}, 'Selection.toString() excludes basic user-select: none content');
+
+test(() => {
+ const result = selectAllAndGetSelectionTextInElement(document.getElementById('nested'));
+ assert_equals(result, 'start end',
+ 'Nested user-select: none content should be excluded');
+}, 'Selection.toString() excludes nested user-select: none content');
+
+test(() => {
+ const result = selectAllAndGetSelectionTextInElement(document.getElementById('container'));
+ assert_equals(result, 'selectabletext',
+ 'Selectable children should be included even in unselectable container');
+}, 'Selection.toString() includes selectable children in unselectable ' +
+ 'container');
+</script>