Truly independent web browser
LibWeb: Paint text fragment indications
Sam Atkins6ca82099953f
diff --git a/Libraries/LibWeb/DOM/Document.cpp b/Libraries/LibWeb/DOM/Document.cppindex 4d6a9785b7e..53bd7449fdd 100644--- a/Libraries/LibWeb/DOM/Document.cpp+++ b/Libraries/LibWeb/DOM/Document.cpp@@ -4278,8 +4278,25 @@ Document::IndicatedPart Document::determine_the_indicated_part()// 1. Let ranges be a list that is the result of running the invoke text directives steps// with text directives and the document.auto ranges = HTML::invoke_text_directives(*text_directives, *this);++ // Text-fragment indication spans are generated while recording foreground paint commands.+ // Invalidate both sets of paintables so cached commands cannot retain the old indication or+ // omit the new one.+ auto invalidate_text_fragment_range_paint = [](Vector<GC::Ref<Range>> const& ranges) {+ for (auto const& range : ranges) {+ range->common_ancestor_container()->for_each_in_inclusive_subtree_of_type<Text>([&](Text& text) {+ if (range->intersects_node(text)) {+ if (auto* layout_text = as_if<Layout::TextNode>(text.unsafe_layout_node()))+ layout_text->set_needs_repaint(InvalidateDisplayList::Yes);+ }+ return TraversalDecision::Continue;+ });+ }+ };+ invalidate_text_fragment_range_paint(m_text_fragment_ranges);m_text_fragment_ranges.clear();m_text_fragment_ranges.extend(ranges);+ invalidate_text_fragment_range_paint(m_text_fragment_ranges);// 2. If ranges is non-empty, then:if (!ranges.is_empty()) {diff --git a/Libraries/LibWeb/DOM/Document.h b/Libraries/LibWeb/DOM/Document.hindex 62b1575a5cf..28c6402abc7 100644--- a/Libraries/LibWeb/DOM/Document.h+++ b/Libraries/LibWeb/DOM/Document.h@@ -840,6 +840,11 @@ public:}void clear_pending_text_directives() { m_pending_text_directives.clear(); }ReadonlySpan<GC::Ref<Range>> text_fragment_ranges() const { return m_text_fragment_ranges; }+ void dismiss_text_fragment_indication()+ {+ m_text_fragment_ranges.clear();+ m_pending_text_directives.clear();+ }bool pending_text_directive_scroll_allowed() const { return m_pending_text_directive_scroll_allowed; }bool check_if_a_text_directive_can_be_scrolled(Optional<URL::Origin> const&, Optional<HTML::UserNavigationInvolvement>);bool text_directive_user_activation() const { return m_text_directive_user_activation; }diff --git a/Libraries/LibWeb/Page/EventHandler.cpp b/Libraries/LibWeb/Page/EventHandler.cppindex ab710c269f5..5353abfb753 100644--- a/Libraries/LibWeb/Page/EventHandler.cpp+++ b/Libraries/LibWeb/Page/EventHandler.cpp@@ -1852,6 +1852,14 @@ EventResult EventHandler::handle_keydown(UIEvents::KeyCode key, u32 modifiers, u// 9. Alternative processing: Otherwise, there was nothing watching for a close request. The user agent may// instead interpret this interaction as some other action, instead of interpreting it as a close request.+ // https://wicg.github.io/scroll-to-text-fragment/#indicating-the-text-match+ // The UA should provide to the user some method of dismissing the match, such that the+ // matched text no longer appears visually indicated.+ if (!document->text_fragment_ranges().is_empty()) {+ document->dismiss_text_fragment_indication();+ document->set_needs_repaint(Badge<EventHandler> {});+ return EventResult::Handled;+ }}// https://w3c.github.io/clipboard-apis/#clipboard-actionsdiff --git a/Libraries/LibWeb/Painting/PaintingRustBridge.cpp b/Libraries/LibWeb/Painting/PaintingRustBridge.cppindex a48005793cf..ec052e3f2bd 100644--- a/Libraries/LibWeb/Painting/PaintingRustBridge.cpp+++ b/Libraries/LibWeb/Painting/PaintingRustBridge.cpp@@ -24,7 +24,9 @@#include <LibWeb/DOM/Document.h>#include <LibWeb/DOM/Element.h>#include <LibWeb/DOM/Node.h>+#include <LibWeb/DOM/Range.h>#include <LibWeb/DOM/ShadowRoot.h>+#include <LibWeb/DOM/Text.h>#include <LibWeb/HTML/FormAssociatedElement.h>#include <LibWeb/HTML/HTMLBRElement.h>#include <LibWeb/HTML/HTMLCanvasElement.h>@@ -518,6 +520,37 @@ Optional<DisplayListRecording> start_rust_display_list_recording(Layout::BegunReauto device_viewport_rect = document.page().css_to_device_rect(document.viewport_rect());auto wheel_event_region_state = document.paint_state().collect_root_blocking_wheel_event_regions(document);Layout::RustFFI::FfiRecordingInputs inputs {};+ Vector<Layout::RustFFI::FfiTextFragmentIndicationRange> text_fragment_indications;+ if (!document.text_fragment_ranges().is_empty()) {+ document.for_each_shadow_including_inclusive_descendant([&](DOM::Node& node) {+ auto* text = as_if<DOM::Text>(&node);+ if (!text)+ return TraversalDecision::Continue;+ auto* layout_text = as_if<Layout::TextNode>(text->unsafe_layout_node(read));+ if (!layout_text)+ return TraversalDecision::Continue;++ for (auto const& range : document.text_fragment_ranges()) {+ if (!range->intersects_node(*text))+ continue;+ auto start = range->start_container().ptr() == text ? static_cast<size_t>(range->start_offset()) : 0;+ auto end = range->end_container().ptr() == text ? static_cast<size_t>(range->end_offset()) : text->length();+ if (start < end) {+ text_fragment_indications.append({+ .text_node = committed_row_slot(*layout_text),+ .start = start,+ .end = end,+ });+ }+ }+ return TraversalDecision::Continue;+ });+ }+ inputs.text_fragment_indications = text_fragment_indications.data();+ inputs.text_fragment_indication_count = text_fragment_indications.size();+ auto mark_color_scheme = document.page().preferred_color_scheme();+ inputs.mark_color = CSS::SystemColor::mark(mark_color_scheme);+ inputs.mark_text_color = CSS::SystemColor::mark_text(mark_color_scheme);if (overlay_inputs.highlighted_layout_node) {inputs.has_inspector_highlight = true;inputs.inspector_highlight_paintable = committed_row_slot(*overlay_inputs.highlighted_layout_node);diff --git a/Libraries/LibWeb/Rust/src/painting/ffi.rs b/Libraries/LibWeb/Rust/src/painting/ffi.rsindex ca3db1fc334..6d5e46bb3f0 100644--- a/Libraries/LibWeb/Rust/src/painting/ffi.rs+++ b/Libraries/LibWeb/Rust/src/painting/ffi.rs@@ -536,6 +536,24 @@ pub struct FfiImageMapArea {pub coords_count: u32,}+/// # Safety+///+/// `sink` must be the pointer handed to the callback, used synchronously.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn layout_arena_paint_push_text_fragment_indication_range(+ sink: *mut c_void,+ start: usize,+ end: usize,+) {+ abort_on_panic(|| {+ // SAFETY: `sink` is the Vec pointer handed out by+ // FfiPaintHostCallbacks::text_fragment_indication_facts.+ let ranges =+ unsafe { &mut *sink.cast::<Vec<crate::painting::record::paint::text::TextFragmentIndicationRange>>() };+ ranges.push(crate::painting::record::paint::text::TextFragmentIndicationRange { start, end });+ });+}+/// # Safety////// `sink` must be the pointer handed to the callback, used synchronously.diff --git a/Libraries/LibWeb/Rust/src/painting/host/paint.rs b/Libraries/LibWeb/Rust/src/painting/host/paint.rsindex 956eb6e2c7c..0f86833bf6f 100644--- a/Libraries/LibWeb/Rust/src/painting/host/paint.rs+++ b/Libraries/LibWeb/Rust/src/painting/host/paint.rs@@ -63,6 +63,18 @@ pub struct FfiRecordingInputs {pub focused_area_outline: FfiFocusedAreaOutline,pub inspector_highlight_label: FfiInspectorHighlightLabel,pub grid_label_fonts: FfiOverlayLabelFonts,+ pub text_fragment_indications: *const FfiTextFragmentIndicationRange,+ pub text_fragment_indication_count: usize,+ pub mark_color: Color,+ pub mark_text_color: Color,+}++#[derive(Clone, Copy, Debug)]+#[repr(C)]+pub struct FfiTextFragmentIndicationRange {+ pub text_node: crate::layout::node_data::NodeSlotId,+ pub start: usize,+ pub end: usize,}impl FfiRecordingInputs {@@ -83,7 +95,7 @@ impl FfiRecordingInputs {use libcompositing_rust::ffi::ffi_slice;// SAFETY: The caller lends these arrays and buffers for this call.- let (grid_overlays, flex_overlays, outline_path) = unsafe {+ let (grid_overlays, flex_overlays, outline_path, text_fragment_indications) = unsafe {(ffi_slice(self.grid_overlays, self.grid_overlay_count),ffi_slice(self.flex_overlays, self.flex_overlay_count),@@ -91,6 +103,7 @@ impl FfiRecordingInputs {self.focused_area_outline.path_bytes,self.focused_area_outline.path_byte_count,),+ ffi_slice(self.text_fragment_indications, self.text_fragment_indication_count),)};let caret = self.caret;@@ -195,6 +208,9 @@ impl FfiRecordingInputs {image: self.focused_area_outline.image,path_bytes: outline_path.into(),}),+ text_fragment_indications: text_fragment_indications.to_vec().into(),+ mark_color: self.mark_color,+ mark_text_color: self.mark_text_color,})}}diff --git a/Libraries/LibWeb/Rust/src/painting/record/inputs.rs b/Libraries/LibWeb/Rust/src/painting/record/inputs.rsindex e87bee07f0b..0c97c0bf8e0 100644--- a/Libraries/LibWeb/Rust/src/painting/record/inputs.rs+++ b/Libraries/LibWeb/Rust/src/painting/record/inputs.rs@@ -95,6 +95,9 @@ pub(crate) struct RecordingInputs {pub caret: Option<CaretPaint>,pub focused_text_control: Option<FocusedTextControlSelection>,pub focused_area_outline: Option<FocusedAreaOutline>,+ pub text_fragment_indications: Box<[crate::painting::host::FfiTextFragmentIndicationRange]>,+ pub mark_color: Color,+ pub mark_text_color: Color,}#[derive(Clone, Copy, PartialEq, Eq)]diff --git a/Libraries/LibWeb/Rust/src/painting/record/paint/text.rs b/Libraries/LibWeb/Rust/src/painting/record/paint/text.rsindex ff0da3bc81b..d0a9d2580ba 100644--- a/Libraries/LibWeb/Rust/src/painting/record/paint/text.rs+++ b/Libraries/LibWeb/Rust/src/painting/record/paint/text.rs@@ -60,6 +60,7 @@ pub(crate) struct RenderSpan {/// The highlight's color when it has one of its own, which its redraw of the text's original/// decorations takes as well.pub decoration_color: Option<u32>,+ pub text_fragment_indication_background_color: Option<u32>,}impl RenderSpan {@@ -68,6 +69,8 @@ impl RenderSpan {.iter().map(|overlay| overlay.highlight).eq(other.highlights.iter().map(|overlay| overlay.highlight))+ && self.text_fragment_indication_background_color == other.text_fragment_indication_background_color+ && self.text_color == other.text_color}}@@ -246,7 +249,22 @@ fn compute_render_spans<O: Observer>(highlights.push((highlight, ranges, answer));}}- if highlights.is_empty() {+ let indication_offsets: Vec<SelectionOffsets> = recorder+ .inputs+ .text_fragment_indications+ .iter()+ .filter(|range| range.text_node == fragment.layout_node)+ .filter_map(|range| {+ text_fragment::selection_offsets_for_dom_range(+ arena,+ fragment,+ range.start,+ range.end,+ )+ })+ .filter(|offsets| offsets.start != offsets.end)+ .collect();+ if highlights.is_empty() && indication_offsets.is_empty() {spans.push(RenderSpan {fragment_index,start_code_unit: 0,@@ -255,11 +273,13 @@ fn compute_render_spans<O: Observer>(shadow_layers: base_shadows(),highlights: Vec::new(),decoration_color: None,+ text_fragment_indication_background_color: None,});continue;}let mut boundaries = vec![0, fragment.length_in_code_units];+ boundaries.extend(indication_offsets.iter().flat_map(|offsets| [offsets.start, offsets.end]));for (_, ranges, _) in &highlights {boundaries.extend(ranges.iter().flat_map(|offsets| [offsets.start, offsets.end]));}@@ -279,7 +299,15 @@ fn compute_render_spans<O: Observer>(shadow_layers: base_shadows(),highlights: Vec::new(),decoration_color: None,+ text_fragment_indication_background_color: None,};+ if indication_offsets+ .iter()+ .any(|offsets| start >= offsets.start && end <= offsets.end)+ {+ span.text_color = recorder.inputs.mark_text_color.0;+ span.text_fragment_indication_background_color = Some(recorder.inputs.mark_color.0);+ }for ((highlight, ranges, answer), next_range) in highlights.iter().zip(&mut next_ranges) {while ranges.get(*next_range).is_some_and(|offsets| offsets.end <= start) {*next_range += 1;@@ -425,6 +453,16 @@ pub(crate) fn paint_fragments<O: Observer>(recorder: &mut PaintRecorder<'_, O>,for span in &spans {paint_text_shadow(recorder, block, span, &span.shadow_layers);}+ for span in spans.iter().filter(|span| span.text_fragment_indication_background_color.is_some()) {+ let background_color = span.text_fragment_indication_background_color.unwrap();+ let indication_rect = highlight_rect(recorder, block, span);+ let converter = recorder.converter;+ recorder.recorder.fill_rect(+ converter.rounded_device_rect(indication_rect),+ Color(background_color),+ ForceDarkRole::Selection,+ );+ }for span in spans.iter().filter(|span| span.highlights.is_empty()) {let sets = crate::painting::record::paint::text_decoration::decoration_sets_for_span(recorder, block, span);paint_text_fragment(recorder, block, span, &sets);diff --git a/Tests/LibWeb/Ref/expected/scroll-to-text-fragment-indication-ref.html b/Tests/LibWeb/Ref/expected/scroll-to-text-fragment-indication-ref.htmlnew file mode 100644index 00000000000..a343f1982d9--- /dev/null+++ b/Tests/LibWeb/Ref/expected/scroll-to-text-fragment-indication-ref.html@@ -0,0 +1,12 @@+<!DOCTYPE html>+<style>+p {+ font: 20px sans-serif;+ line-height: 1.5;+}+.indication {+ color: black;+ background: yellow;+}+</style>+<p>Before <span class="indication">Highlighted passage</span> after</p>diff --git a/Tests/LibWeb/Ref/input/scroll-to-text-fragment-indication.html b/Tests/LibWeb/Ref/input/scroll-to-text-fragment-indication.htmlnew file mode 100644index 00000000000..a118fc711c6--- /dev/null+++ b/Tests/LibWeb/Ref/input/scroll-to-text-fragment-indication.html@@ -0,0 +1,27 @@+<!DOCTYPE html>+<html class="reftest-wait">+<link rel="match" href="../expected/scroll-to-text-fragment-indication-ref.html">+<link rel="help" href="https://wicg.github.io/scroll-to-text-fragment/#indicating-the-text-match">+<style>+p {+ font: 20px sans-serif;+ line-height: 1.5;+}+</style>+<p>Before Highlighted passage after</p>+<script>+if (!location.hash.includes(":~:"))+ location.replace("#:~:text=Highlighted");++requestAnimationFrame(() => {+ requestAnimationFrame(() => {+ location.replace("#:~:text=Highlighted%20passage");+ requestAnimationFrame(() => {+ requestAnimationFrame(() => {+ document.documentElement.classList.remove("reftest-wait");+ });+ });+ });+});+</script>+</html>