Skip to content

Truly independent web browser

LibWeb: Render a writing suggestion after the caret

sideshowbarkerbb6b1be11e8a
diff --git a/Libraries/LibWeb/Editing/WritingSuggestionController.cpp b/Libraries/LibWeb/Editing/WritingSuggestionController.cpp
index 56aa14c04dc..e38daf8c584 100644
--- a/Libraries/LibWeb/Editing/WritingSuggestionController.cpp
+++ b/Libraries/LibWeb/Editing/WritingSuggestionController.cpp
@@ -14,6 +14,7 @@
#include <LibWeb/HTML/HTMLInputElement.h>
#include <LibWeb/HTML/HTMLTextAreaElement.h>
#include <LibWeb/HTML/Window.h>
+#include <LibWeb/Layout/LayoutRustBridge.h>
#include <LibWeb/Page/Page.h>
namespace Web::Editing {
@@ -117,12 +118,12 @@ void WritingSuggestionController::set_showing(Optional<ShowingSuggestion> showin
};
invalidate(m_showing);
m_showing = move(showing);
- if (m_showing.has_value()) {
- if (auto text = m_showing->text.ptr()) {
- m_showing_text_length = text->length_in_utf16_code_units();
- m_showing_prefix = Utf16String::from_utf16(text_before(*text, m_showing->offset));
- }
+ GC::Ptr<DOM::Text> text = m_showing.has_value() ? m_showing->text.ptr() : nullptr;
+ if (text) {
+ m_showing_text_length = text->length_in_utf16_code_units();
+ m_showing_prefix = Utf16String::from_utf16(text_before(*text, m_showing->offset));
}
+ Layout::publish_writing_suggestion(m_document, text.ptr(), text ? m_showing->offset : 0, text ? m_showing->remainder.utf16_view() : Utf16View {});
invalidate(m_showing);
}
diff --git a/Libraries/LibWeb/Layout/LayoutRustBridge.cpp b/Libraries/LibWeb/Layout/LayoutRustBridge.cpp
index 7e918edff02..350c7caa5a3 100644
--- a/Libraries/LibWeb/Layout/LayoutRustBridge.cpp
+++ b/Libraries/LibWeb/Layout/LayoutRustBridge.cpp
@@ -357,6 +357,20 @@ void publish_element_scroll_offset(DOM::Element const& element)
RustFFI::render_state_set_element_scroll_offset(document.layout_node_arena().host(), element.style_node_id().value(), offset);
}
+void publish_writing_suggestion(DOM::Document& document, DOM::Text const* text, size_t offset, Utf16View remainder)
+{
+ // A text node without a style node identity has no box to show a suggestion in, so it publishes that none shows.
+ auto identity = text ? text->style_node_id().value() : 0;
+ // Nothing is published before a layout tree exists, so there's nothing to withdraw.
+ if (identity == 0 && !document.layout_node_arena_if_created())
+ return;
+ Vector<u16> code_units;
+ code_units.ensure_capacity(remainder.length_in_code_units());
+ for (size_t i = 0; i < remainder.length_in_code_units(); ++i)
+ code_units.unchecked_append(remainder.code_unit_at(i));
+ RustFFI::render_state_set_writing_suggestion(document.layout_node_arena().host(), identity, offset, code_units.data(), code_units.size());
+}
+
void publish_table_spans(DOM::Element const& element)
{
if (element.style_node_id().value() == 0)
diff --git a/Libraries/LibWeb/Layout/LayoutRustBridge.h b/Libraries/LibWeb/Layout/LayoutRustBridge.h
index 4b825ceb06a..762dd6528a4 100644
--- a/Libraries/LibWeb/Layout/LayoutRustBridge.h
+++ b/Libraries/LibWeb/Layout/LayoutRustBridge.h
@@ -61,6 +61,10 @@ void publish_element_scroll_offset(DOM::Element const&);
// before the build that stamps the element's row is over. Every other element spans one of each and publishes nothing.
void publish_table_spans(DOM::Element const&);
+// Publishes the writing suggestion showing after the caret, at offset in text, or that none shows when text is null.
+// The tree build splits the text's box around it.
+void publish_writing_suggestion(DOM::Document&, DOM::Text const* text, size_t offset, Utf16View remainder);
+
inline RustFFI::FfiSvgNumberPercentage to_ffi_number_percentage(SVG::NumberPercentage value)
{
return { .value = value.value(), .is_percentage = value.is_percentage() };
diff --git a/Libraries/LibWeb/Rust/src/css/style/layout_style.rs b/Libraries/LibWeb/Rust/src/css/style/layout_style.rs
index ba6f825b706..4b85cf7fba6 100644
--- a/Libraries/LibWeb/Rust/src/css/style/layout_style.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/layout_style.rs
@@ -33,6 +33,8 @@ pub(crate) enum AnonymousStyleKind {
ButtonContentBox,
FieldsetContentWrapper,
InlineStyleWrapper,
+ /// The inline box a writing suggestion's text renders in after the caret.
+ WritingSuggestion,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
@@ -191,6 +193,23 @@ impl LayoutStyle {
);
}
+ /// Draws text in its color at half its alpha, i.e. `color-mix(in srgb, currentColor 50%, transparent)`, which
+ /// reads as a suggestion in light and dark color schemes alike.
+ fn fade_text_color(&mut self) {
+ let fade = |color: u32| (color >> 24).div_ceil(2) << 24 | (color & 0x00ff_ffff);
+ let index = group_index::INHERITED_TEXT;
+ // SAFETY: The clone is uniquely owned and is the inherited text group.
+ let payload = SharedPayload::new(unsafe { clone_group_payload(index, self.payloads[index].as_ptr()) });
+ // SAFETY: As above; the colors are plain values the payload doesn't retain.
+ unsafe {
+ let values = &mut *payload.cast::<InheritedTextValues>().cast_mut();
+ values.color = fade(values.color);
+ values.webkit_text_fill_color = fade(values.webkit_text_fill_color);
+ }
+ release_group_payload(index, std::mem::replace(&mut self.payloads[index], payload).as_ptr());
+ self.changed = true;
+ }
+
pub(crate) fn is_unchanged(&self) -> bool {
!self.changed
}
@@ -448,11 +467,12 @@ impl LayoutStyle {
});
style.set_overflow(overrides.overflow_x, overrides.overflow_y);
}
- AnonymousStyleKind::InlineStyleWrapper => style.set_display(FfiDisplay::outside_and_inside(
- display_outside::INLINE,
- display_inside::FLOW,
- false,
- )),
+ AnonymousStyleKind::InlineStyleWrapper | AnonymousStyleKind::WritingSuggestion => style.set_display(
+ FfiDisplay::outside_and_inside(display_outside::INLINE, display_inside::FLOW, false),
+ ),
+ }
+ if kind == AnonymousStyleKind::WritingSuggestion {
+ style.fade_text_color();
}
if kind == AnonymousStyleKind::MissingTableCell {
style.edit::<BoxValues>(|values| {
diff --git a/Libraries/LibWeb/Rust/src/layout/layout_changes.rs b/Libraries/LibWeb/Rust/src/layout/layout_changes.rs
index ddde2ace287..2db6b78840e 100644
--- a/Libraries/LibWeb/Rust/src/layout/layout_changes.rs
+++ b/Libraries/LibWeb/Rust/src/layout/layout_changes.rs
@@ -63,6 +63,8 @@ pub(crate) enum LayoutChange {
element: StyleNodeID,
offset: CssPixelPoint,
},
+ /// The writing suggestion showing after the caret, or none.
+ SetWritingSuggestion(Option<super::layout_node_arena::PublishedWritingSuggestion>),
/// What the pseudo-element of kind `generated_for` on `generator` has scrolled to.
SetPseudoElementScrollOffset {
generator: StyleNodeID,
@@ -173,6 +175,7 @@ impl LayoutChange {
| Self::RecordPartialRelayoutEscape
| Self::SetAnchorNameElements { .. }
| Self::SetElementScrollOffset { .. }
+ | Self::SetWritingSuggestion(_)
| Self::SetPseudoElementScrollOffset { .. }
| Self::SetIdentityInFocusedTextControl { .. }
| Self::SvgAttributeFacts { .. }
@@ -259,6 +262,7 @@ impl LayoutChange {
elements,
} => arena.set_anchor_name_elements(scope_host, anchor_name, elements.iter().copied()),
Self::SetElementScrollOffset { element, offset } => arena.set_element_scroll_offset(element, offset),
+ Self::SetWritingSuggestion(suggestion) => arena.set_writing_suggestion(suggestion),
Self::SetPseudoElementScrollOffset {
generator,
generated_for,
@@ -548,6 +552,37 @@ pub extern "C" fn render_state_set_element_scroll_offset(host: &DocumentHost, el
queue(host, LayoutChange::SetElementScrollOffset { element, offset });
}
+/// Publishes the writing suggestion showing after the caret: `remainder` is what it would add at `offset` in the text
+/// node `text`. A zero `text` publishes that none shows.
+///
+/// # Safety
+///
+/// `host` must be a live document host, on the document's thread, and `remainder` must point at `length` readable code
+/// units.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn render_state_set_writing_suggestion(
+ host: &DocumentHost,
+ text: u32,
+ offset: usize,
+ remainder: *const u16,
+ length: usize,
+) {
+ let suggestion = StyleNodeID::from_raw(text).map(|text| {
+ let remainder: &[u16] = if length == 0 {
+ &[]
+ } else {
+ // SAFETY: Guaranteed by the caller.
+ unsafe { ak::slice_from_raw_parts(remainder, length) }
+ };
+ super::layout_node_arena::PublishedWritingSuggestion {
+ text,
+ offset,
+ remainder: remainder.to_vec(),
+ }
+ });
+ queue(host, LayoutChange::SetWritingSuggestion(suggestion));
+}
+
#[unsafe(no_mangle)]
pub extern "C" fn render_state_set_pseudo_element_scroll_offset(
host: &DocumentHost,
diff --git a/Libraries/LibWeb/Rust/src/layout/layout_node_arena.rs b/Libraries/LibWeb/Rust/src/layout/layout_node_arena.rs
index 9322edf920f..b1c1c7757d5 100644
--- a/Libraries/LibWeb/Rust/src/layout/layout_node_arena.rs
+++ b/Libraries/LibWeb/Rust/src/layout/layout_node_arena.rs
@@ -606,12 +606,16 @@ impl TextSlots {
PublishedTextSlot {
generation: slot.generation,
first_letter: state.first_letter,
+ precedes_writing_suggestion: state.precedes_writing_suggestion,
rendered: state.content.as_ref().map(|content| content.rendered().clone()),
}
})
.unwrap_or_default();
if self.published.get(index).is_none() {
- if published.rendered.is_none() && published.first_letter.is_invalid() {
+ if published.rendered.is_none()
+ && published.first_letter.is_invalid()
+ && !published.precedes_writing_suggestion
+ {
return;
}
self.published.grow_to(index + 1);
@@ -650,6 +654,8 @@ impl Drop for TextStateMut<'_> {
struct TextNodeState {
source_range: Option<FfiTextSourceRange>,
first_letter: NodeSlotId,
+ /// Whether the slice ends where a writing suggestion shows. See [`LayoutNodeArena::set_writing_suggestion_slices`].
+ precedes_writing_suggestion: bool,
content: Option<TextContent>,
/// What a generated text row renders. Generated content has no DOM text node whose characters
/// the style mirror could hold, so the row keeps the characters it was made with.
@@ -1129,6 +1135,18 @@ struct StyleNodeTables {
/// What each element's pseudo-elements have scrolled to, held against the element's identity,
/// since a pseudo-element has none of its own, and published the way the element's offset is.
pseudo_element_scroll_offsets: RefCell<HashMap<StyleNodeID, PseudoElementScrollOffsets>>,
+ /// The writing suggestion showing after the caret, if any: at most one per document, held
+ /// against the identity of the text node the caret is in.
+ writing_suggestion: RefCell<Option<PublishedWritingSuggestion>>,
+}
+
+/// A writing suggestion as the document publishes it: the text node the caret is in, where the
+/// caret is in it, and the text the suggestion would add there, in UTF-16 code units.
+#[derive(Clone)]
+pub(crate) struct PublishedWritingSuggestion {
+ pub text: StyleNodeID,
+ pub offset: usize,
+ pub remainder: Vec<u16>,
}
/// What an element's synthetic pseudo-elements have scrolled to, by kind.
@@ -2227,6 +2245,14 @@ impl LayoutNodeArena {
self.set_node_flag(slot, NodeFlag::HasScrollOffset, has_scroll_offset);
}
+ pub(crate) fn set_writing_suggestion(&self, suggestion: Option<PublishedWritingSuggestion>) {
+ *self.style_node_tables.writing_suggestion.borrow_mut() = suggestion;
+ }
+
+ pub(crate) fn writing_suggestion(&self) -> Option<PublishedWritingSuggestion> {
+ self.style_node_tables.writing_suggestion.borrow().clone()
+ }
+
/// Records what the element has scrolled to, for every row built for it. A rebuild can leave
/// an old row and its replacement both built for the element until the commit that retires the
/// old one, and both answer for the element meanwhile.
@@ -2333,6 +2359,7 @@ impl LayoutNodeArena {
identities_in_focused_text_control,
element_scroll_offsets,
pseudo_element_scroll_offsets,
+ writing_suggestion,
} = &self.style_node_tables;
counters_sets.borrow_mut().forget(style_node);
generated_content.borrow_mut().forget(style_node);
@@ -2349,6 +2376,14 @@ impl LayoutNodeArena {
identities_in_focused_text_control.borrow_mut().remove(&style_node);
element_scroll_offsets.borrow_mut().remove(&style_node);
pseudo_element_scroll_offsets.borrow_mut().remove(&style_node);
+ let mut writing_suggestion = writing_suggestion.borrow_mut();
+ if writing_suggestion
+ .as_ref()
+ .is_some_and(|suggestion| suggestion.text == style_node)
+ {
+ *writing_suggestion = None;
+ }
+ drop(writing_suggestion);
// A retired shadow host takes its tree scope with it. The registry withdraws no names from a
// scope it can no longer name.
anchor_name_elements
@@ -3721,14 +3756,23 @@ impl LayoutNodeArena {
self.reinherit_anonymous_descendants(host_calls, child);
self.notify_shell_of_style_change(host_calls, child, true);
} else {
- let column_source = self
- .anonymous_box_column_source(child)
- .map(|source| self.node_style_record(source));
- let derived = self.reinherit_anonymous_style_record(
- self.node_style_record(child),
- parent_style_record,
- column_source,
- );
+ // A writing suggestion's box is derived from its parent again, so its text stays faded.
+ let derived = if self.is_writing_suggestion_box(child) {
+ self.derive_anonymous_style_record(
+ parent_style_record,
+ AnonymousStyleKind::WritingSuggestion,
+ AnonymousStyleOverrides::default(),
+ )
+ } else {
+ let column_source = self
+ .anonymous_box_column_source(child)
+ .map(|source| self.node_style_record(source));
+ self.reinherit_anonymous_style_record(
+ self.node_style_record(child),
+ parent_style_record,
+ column_source,
+ )
+ };
self.apply_reinherited_style_record(host_calls, child, derived);
self.reinherit_anonymous_children(host_calls, child, derived.record);
}
@@ -5340,6 +5384,32 @@ impl LayoutNodeArena {
self.invalidate_text_content(remainder);
}
+ /// Splits a text node's box at the caret for a writing suggestion, the way a `::first-letter`
+ /// split divides it at the end of the letter: The leading slice renders the text before the
+ /// caret, and the trailing slice (the one the node is bound to) renders the rest.
+ pub(super) fn set_writing_suggestion_slices(
+ &mut self,
+ leading: NodeSlotId,
+ trailing: NodeSlotId,
+ caret: usize,
+ source_length: usize,
+ ) {
+ self.set_first_letter_slices(leading, trailing, caret, source_length);
+ self.text_node_state_mut(leading).precedes_writing_suggestion = true;
+ }
+
+ pub(crate) fn text_precedes_writing_suggestion(&self, id: NodeSlotId) -> bool {
+ self.text_node_state(id)
+ .is_some_and(|state| state.precedes_writing_suggestion)
+ }
+
+ /// Whether a box is the inline box that renders a writing suggestion, i.e. the one right after the text slice in
+ /// front of the suggestion.
+ fn is_writing_suggestion_box(&self, id: NodeSlotId) -> bool {
+ let previous_sibling = self.data(id).previous_sibling.get();
+ !previous_sibling.is_invalid() && self.text_precedes_writing_suggestion(previous_sibling)
+ }
+
pub(crate) fn text_source_range(&self, id: NodeSlotId, source_length: usize) -> FfiTextSourceRange {
self.data(id);
let Some(range) = self.text_node_state(id).and_then(|state| state.source_range) else {
diff --git a/Libraries/LibWeb/Rust/src/layout/rendered_text.rs b/Libraries/LibWeb/Rust/src/layout/rendered_text.rs
index 2e5f7888f06..af253609d86 100644
--- a/Libraries/LibWeb/Rust/src/layout/rendered_text.rs
+++ b/Libraries/LibWeb/Rust/src/layout/rendered_text.rs
@@ -53,6 +53,8 @@ pub(crate) struct RenderedText {
pub(crate) struct PublishedTextSlot {
pub(crate) generation: u8,
pub(crate) first_letter: NodeSlotId,
+ /// Whether the slice ends where a writing suggestion shows — so a caret at the slice's end paints in front of it.
+ pub(crate) precedes_writing_suggestion: bool,
pub(crate) rendered: Option<Arc<RenderedText>>,
}
@@ -61,6 +63,7 @@ impl Default for PublishedTextSlot {
Self {
generation: 0,
first_letter: NodeSlotId::INVALID,
+ precedes_writing_suggestion: false,
rendered: None,
}
}
@@ -72,6 +75,7 @@ impl PartialEq for PublishedTextSlot {
fn eq(&self, other: &Self) -> bool {
self.generation == other.generation
&& self.first_letter == other.first_letter
+ && self.precedes_writing_suggestion == other.precedes_writing_suggestion
&& crate::cow_column::same_payload(self.rendered.as_ref(), other.rendered.as_ref(), |_, _| false)
}
}
diff --git a/Libraries/LibWeb/Rust/src/layout/tree_builder.rs b/Libraries/LibWeb/Rust/src/layout/tree_builder.rs
index 2580f382b92..4280ad1789e 100644
--- a/Libraries/LibWeb/Rust/src/layout/tree_builder.rs
+++ b/Libraries/LibWeb/Rust/src/layout/tree_builder.rs
@@ -2275,6 +2275,8 @@ fn update_principal_node_descendants(
create_first_letter_boxes(host, update.mirror_identity, target);
}
}
+
+ create_writing_suggestion_boxes(host, update.mirror_identity, layout_node);
}
wrap_fieldset_contents_if_needed(host, layout_node);
@@ -4634,6 +4636,86 @@ fn create_first_letter_boxes(host: &mut TreeBuilderHost<'_>, element: StyleNodeI
host.free_subtree(text_node);
}
+/// Splits the box of the text node the caret is in at the caret, around an inline box that renders the writing
+/// suggestion showing there, so the suggestion takes up space in the line as text would. It's never in the DOM: The
+/// slices on either side keep rendering the DOM text, with source ranges that map its offsets as they do for a
+/// `::first-letter` split.
+fn create_writing_suggestion_boxes(host: &mut TreeBuilderHost<'_>, element: StyleNodeID, layout_node: LayoutNode) {
+ let Some(suggestion) = host.arena().writing_suggestion() else {
+ return;
+ };
+ let is_child_text = host.arena().with_style_store(|engine| {
+ if engine.tree().text_parent(suggestion.text) != Some(element) {
+ return false;
+ }
+ // Text that a `::first-letter` may already split is left alone, so the two splits never meet.
+ let mut ancestor = Some(element);
+ while let Some(current) = ancestor {
+ if engine.has_published_first_letter_style(current) {
+ return false;
+ }
+ ancestor = engine
+ .tree()
+ .parent(current)
+ .map(|parent| engine.tree().host_of(parent).unwrap_or(parent));
+ }
+ true
+ });
+ if !is_child_text {
+ return;
+ }
+ let text_node = host.arena().bound_row(suggestion.text);
+ if text_node.is_invalid()
+ || host.data(text_node).kind.get() != NodeKind::TextNode
+ || host.arena().text_has_source_range(text_node)
+ || !is_inclusive_layout_ancestor_of(host, layout_node, text_node)
+ {
+ return;
+ }
+ let source_length = host
+ .arena()
+ .published_text_source(text_node, false)
+ .data
+ .to_utf16()
+ .len();
+ if suggestion.offset > source_length || suggestion.remainder.is_empty() {
+ return;
+ }
+
+ // The trailing slice takes over the text node's rows, and the leading slice renders the same node without
+ // becoming the row the node is bound to.
+ let trailing_slice = host.stamp_dom_box(NodeKind::TextNode, Some(suggestion.text));
+ let leading_slice = host.arena.allocate_unbound();
+ host.arena()
+ .stamp_dom_row(leading_slice, NodeKind::TextNode, Some(suggestion.text));
+ host.arena().note_rows_share_dom_node(trailing_slice, leading_slice);
+ for slice in [leading_slice, trailing_slice] {
+ host.stamp_text_row_facts(slice, suggestion.text);
+ }
+ host.arena
+ .set_writing_suggestion_slices(leading_slice, trailing_slice, suggestion.offset, source_length);
+ let leading_slice = host.created(leading_slice);
+ let trailing_slice = host.created(trailing_slice);
+
+ let parent = host.parent(text_node);
+ assert!(!parent.is_invalid());
+ let wrapper = host.create_anonymous_box(
+ parent,
+ AnonymousStyleKind::WritingSuggestion,
+ AnonymousStyleOverrides::default(),
+ NodeKind::InlineNode,
+ );
+ let wrapper_slot = wrapper.slot();
+ host.set_children_are_inline(wrapper_slot, true);
+ let suggestion_text = host.stamp_generated_text_box(&suggestion.remainder);
+ host.attach_child(wrapper_slot, host.created(suggestion_text), NodeSlotId::INVALID);
+ host.attach_child(parent, leading_slice, text_node);
+ host.attach_child(parent, wrapper, text_node);
+ host.attach_child(parent, trailing_slice, text_node);
+ host.arena().detach_child(parent, text_node);
+ host.free_subtree(text_node);
+}
+
fn is_marker_content(data: &NodeData) -> bool {
data.kind.get() == NodeKind::ListItemMarkerBox || data.generated_for.get() == GENERATED_FOR_MARKER
}
diff --git a/Libraries/LibWeb/Rust/src/painting/caret.rs b/Libraries/LibWeb/Rust/src/painting/caret.rs
index 6b4d9a70776..0b9b453190d 100644
--- a/Libraries/LibWeb/Rust/src/painting/caret.rs
+++ b/Libraries/LibWeb/Rust/src/painting/caret.rs
@@ -55,7 +55,15 @@ pub(crate) fn caret_rect_for_position(
let mut fallback: Option<(NodeSlotId, u32)> = None;
let mut direct: Option<(NodeSlotId, u32)> = None;
text_fragment::for_each_fragment_of_nodes(layout_arena, node_slots, |block, index, fragment| {
- match text_fragment::caret_match(fragment, offset, affinity_is_downstream) {
+ // A caret at the end of the text in front of a writing suggestion is in front of the suggestion, whichever way
+ // it leans: The text after the caret starts only after the suggestion.
+ let caret_match = match text_fragment::caret_match(fragment, offset, affinity_is_downstream) {
+ CaretMatch::SoftWrapFallback if layout_arena.text_precedes_writing_suggestion(fragment.layout_node) => {
+ CaretMatch::Direct
+ }
+ caret_match => caret_match,
+ };
+ match caret_match {
CaretMatch::None => true,
CaretMatch::SoftWrapFallback => {
if fallback.is_none() {
diff --git a/Libraries/LibWeb/Rust/src/painting/paint_read.rs b/Libraries/LibWeb/Rust/src/painting/paint_read.rs
index 837429d8446..d335f0304cd 100644
--- a/Libraries/LibWeb/Rust/src/painting/paint_read.rs
+++ b/Libraries/LibWeb/Rust/src/painting/paint_read.rs
@@ -216,6 +216,8 @@ pub(crate) trait PaintRead: GeometryRead {
/// The rows a text node is painted in: its first-letter row, if any, then its own.
fn text_fragments(&self, primary: NodeSlotId) -> TextFragments;
+ /// Whether a text row is the slice in front of a writing suggestion, whose end is where the caret is.
+ fn text_precedes_writing_suggestion(&self, id: NodeSlotId) -> bool;
fn replaced_paint_facts(&self, id: NodeSlotId) -> Option<ReplacedPaintFacts>;
fn layer_image_paint_facts(
&self,
@@ -406,6 +408,10 @@ impl<Live: AsRef<LayoutNodeArena>> PaintRead for Live {
self.as_ref().text_fragments(primary)
}
+ fn text_precedes_writing_suggestion(&self, id: NodeSlotId) -> bool {
+ self.as_ref().text_precedes_writing_suggestion(id)
+ }
+
fn published_svg_filter(&self, slot: NodeSlotId, kind: SvgPaintResourceKind) -> Option<Arc<PublishedSvgFilter>> {
self.as_ref().svg_paint_resources().published_filter(slot, kind)
}
@@ -589,6 +595,12 @@ impl PaintRead for PaintSource<'_> {
fragments
}
+ fn text_precedes_writing_suggestion(&self, id: NodeSlotId) -> bool {
+ self.rows()
+ .text(id)
+ .is_some_and(|text| text.precedes_writing_suggestion)
+ }
+
fn published_svg_filter(&self, slot: NodeSlotId, kind: SvgPaintResourceKind) -> Option<Arc<PublishedSvgFilter>> {
published_filter_in(&self.rows().paint_facts.svg_paint_resources, slot, kind)
}
diff --git a/Tests/LibWeb/Crash/Editing/writing-suggestion-first-letter.html b/Tests/LibWeb/Crash/Editing/writing-suggestion-first-letter.html
new file mode 100644
index 00000000000..69908ca89f7
--- /dev/null
+++ b/Tests/LibWeb/Crash/Editing/writing-suggestion-first-letter.html
@@ -0,0 +1,16 @@
+<!DOCTYPE html>
+<html class="test-wait">
+<style>
+ div::first-letter { color: red; }
+</style>
+<div id="editable" contenteditable></div>
+<script>
+ const editable = document.getElementById("editable");
+ internals.sendText(editable, "p");
+ internals.sendText(editable, "redi");
+ internals.writingSuggestionSettled().then(() => {
+ editable.offsetWidth;
+ document.documentElement.classList.remove("test-wait");
+ });
+</script>
+</html>
diff --git a/Tests/LibWeb/Crash/Editing/writing-suggestion-text-node-removed.html b/Tests/LibWeb/Crash/Editing/writing-suggestion-text-node-removed.html
new file mode 100644
index 00000000000..c77d832a25e
--- /dev/null
+++ b/Tests/LibWeb/Crash/Editing/writing-suggestion-text-node-removed.html
@@ -0,0 +1,13 @@
+<!DOCTYPE html>
+<html class="test-wait">
+<div id="editable" contenteditable></div>
+<script>
+ const editable = document.getElementById("editable");
+ internals.sendText(editable, "predi");
+ internals.writingSuggestionSettled().then(() => {
+ editable.innerHTML = "replaced";
+ editable.offsetWidth;
+ document.documentElement.classList.remove("test-wait");
+ });
+</script>
+</html>
diff --git a/Tests/LibWeb/Ref/expected/writing-suggestion-color-change-ref.html b/Tests/LibWeb/Ref/expected/writing-suggestion-color-change-ref.html
new file mode 100644
index 00000000000..b82a031c02e
--- /dev/null
+++ b/Tests/LibWeb/Ref/expected/writing-suggestion-color-change-ref.html
@@ -0,0 +1,11 @@
+<!DOCTYPE html>
+<style>
+ div { font: 20px/1.5 sans-serif; color: blue; caret-color: transparent; }
+ span { color: rgb(0 0 255 / 50%); }
+</style>
+<div id="editable" contenteditable>I like predi<span>ction</span></div>
+<script>
+ const editable = document.getElementById("editable");
+ editable.focus();
+ getSelection().collapse(editable.firstChild, 12);
+</script>
diff --git a/Tests/LibWeb/Ref/expected/writing-suggestion-dark-ref.html b/Tests/LibWeb/Ref/expected/writing-suggestion-dark-ref.html
new file mode 100644
index 00000000000..464bce7d19f
--- /dev/null
+++ b/Tests/LibWeb/Ref/expected/writing-suggestion-dark-ref.html
@@ -0,0 +1,13 @@
+<!DOCTYPE html>
+<style>
+ div { font: 20px/1.5 sans-serif; }
+ span { color: rgb(0 0 0 / 50%); }
+ :root { color-scheme: dark; }
+ span { color: rgb(255 255 255 / 50%); }
+</style>
+<div id="editable" contenteditable>I like predi<span>ction</span></div>
+<script>
+ const editable = document.getElementById("editable");
+ editable.focus();
+ getSelection().collapse(editable.firstChild, 12);
+</script>
diff --git a/Tests/LibWeb/Ref/expected/writing-suggestion-end-of-text-ref.html b/Tests/LibWeb/Ref/expected/writing-suggestion-end-of-text-ref.html
new file mode 100644
index 00000000000..b5954348629
--- /dev/null
+++ b/Tests/LibWeb/Ref/expected/writing-suggestion-end-of-text-ref.html
@@ -0,0 +1,11 @@
+<!DOCTYPE html>
+<style>
+ div { font: 20px/1.5 sans-serif; }
+ span { color: rgb(0 0 0 / 50%); }
+</style>
+<div id="editable" contenteditable>I like predi<span>ction</span></div>
+<script>
+ const editable = document.getElementById("editable");
+ editable.focus();
+ getSelection().collapse(editable.firstChild, 12);
+</script>
diff --git a/Tests/LibWeb/Ref/expected/writing-suggestion-mid-line-ref.html b/Tests/LibWeb/Ref/expected/writing-suggestion-mid-line-ref.html
new file mode 100644
index 00000000000..be1cb5552d0
--- /dev/null
+++ b/Tests/LibWeb/Ref/expected/writing-suggestion-mid-line-ref.html
@@ -0,0 +1,11 @@
+<!DOCTYPE html>
+<style>
+ div { font: 20px/1.5 sans-serif; }
+ span { color: rgb(0 0 0 / 50%); }
+</style>
+<div id="editable" contenteditable>predi<span>ction</span>-xyz</div>
+<script>
+ const editable = document.getElementById("editable");
+ editable.focus();
+ getSelection().collapse(editable.firstChild, 5);
+</script>
diff --git a/Tests/LibWeb/Ref/input/writing-suggestion-color-change.html b/Tests/LibWeb/Ref/input/writing-suggestion-color-change.html
new file mode 100644
index 00000000000..c12471ccd7c
--- /dev/null
+++ b/Tests/LibWeb/Ref/input/writing-suggestion-color-change.html
@@ -0,0 +1,20 @@
+<!DOCTYPE html>
+<html class="reftest-wait">
+<link rel="match" href="../expected/writing-suggestion-color-change-ref.html">
+<style>
+ div { font: 20px/1.5 sans-serif; caret-color: transparent; }
+</style>
+<div id="editable" contenteditable></div>
+<script>
+ const editable = document.getElementById("editable");
+ editable.focus();
+
+ internals.sendText(editable, "I like predi");
+ internals.writingSuggestionSettled().then(() => {
+ // Restyling the editable while the suggestion shows keeps the suggestion faded.
+ editable.offsetWidth;
+ editable.style.color = "blue";
+ requestAnimationFrame(() => requestAnimationFrame(() => internals.signalTestIsDone("PASS")));
+ });
+</script>
+</html>
diff --git a/Tests/LibWeb/Ref/input/writing-suggestion-dark.html b/Tests/LibWeb/Ref/input/writing-suggestion-dark.html
new file mode 100644
index 00000000000..317765389db
--- /dev/null
+++ b/Tests/LibWeb/Ref/input/writing-suggestion-dark.html
@@ -0,0 +1,16 @@
+<!DOCTYPE html>
+<html class="reftest-wait">
+<link rel="match" href="../expected/writing-suggestion-dark-ref.html">
+<style>
+ div { font: 20px/1.5 sans-serif; }
+ :root { color-scheme: dark; }
+</style>
+<div id="editable" contenteditable></div>
+<script>
+ const editable = document.getElementById("editable");
+ editable.focus();
+
+ internals.sendText(editable, "I like predi");
+ internals.writingSuggestionSettled().then(() => internals.signalTestIsDone("PASS"));
+</script>
+</html>
diff --git a/Tests/LibWeb/Ref/input/writing-suggestion-end-of-text.html b/Tests/LibWeb/Ref/input/writing-suggestion-end-of-text.html
new file mode 100644
index 00000000000..83c47e7d174
--- /dev/null
+++ b/Tests/LibWeb/Ref/input/writing-suggestion-end-of-text.html
@@ -0,0 +1,15 @@
+<!DOCTYPE html>
+<html class="reftest-wait">
+<link rel="match" href="../expected/writing-suggestion-end-of-text-ref.html">
+<style>
+ div { font: 20px/1.5 sans-serif; }
+</style>
+<div id="editable" contenteditable></div>
+<script>
+ const editable = document.getElementById("editable");
+ editable.focus();
+
+ internals.sendText(editable, "I like predi");
+ internals.writingSuggestionSettled().then(() => internals.signalTestIsDone("PASS"));
+</script>
+</html>
diff --git a/Tests/LibWeb/Ref/input/writing-suggestion-mid-line.html b/Tests/LibWeb/Ref/input/writing-suggestion-mid-line.html
new file mode 100644
index 00000000000..1bb26be511c
--- /dev/null
+++ b/Tests/LibWeb/Ref/input/writing-suggestion-mid-line.html
@@ -0,0 +1,15 @@
+<!DOCTYPE html>
+<html class="reftest-wait">
+<link rel="match" href="../expected/writing-suggestion-mid-line-ref.html">
+<style>
+ div { font: 20px/1.5 sans-serif; }
+</style>
+<div id="editable" contenteditable>-xyz</div>
+<script>
+ const editable = document.getElementById("editable");
+ editable.focus();
+ getSelection().collapse(editable.firstChild, 0);
+ internals.sendText(editable, "predi");
+ internals.writingSuggestionSettled().then(() => internals.signalTestIsDone("PASS"));
+</script>
+</html>
diff --git a/Tests/LibWeb/Text/expected/Editing/writing-suggestion-accessibility.txt b/Tests/LibWeb/Text/expected/Editing/writing-suggestion-accessibility.txt
new file mode 100644
index 00000000000..6e04d7376a8
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/Editing/writing-suggestion-accessibility.txt
@@ -0,0 +1,2 @@
+suggestion: ction
+text leaves: ["predi"]
diff --git a/Tests/LibWeb/Text/expected/Editing/writing-suggestion-geometry.txt b/Tests/LibWeb/Text/expected/Editing/writing-suggestion-geometry.txt
new file mode 100644
index 00000000000..d16b8be49e9
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/Editing/writing-suggestion-geometry.txt
@@ -0,0 +1,2 @@
+suggestion: ction
+text after the caret moved over: true
diff --git a/Tests/LibWeb/Text/expected/Editing/writing-suggestion-text-queries.txt b/Tests/LibWeb/Text/expected/Editing/writing-suggestion-text-queries.txt
new file mode 100644
index 00000000000..0a6731262d9
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/Editing/writing-suggestion-text-queries.txt
@@ -0,0 +1,7 @@
+suggestion: ction
+innerText: predi
+textContent: predi
+selection: ""
+find: false
+input suggestion: ction
+value: predi
diff --git a/Tests/LibWeb/Text/input/Editing/writing-suggestion-accessibility.html b/Tests/LibWeb/Text/input/Editing/writing-suggestion-accessibility.html
new file mode 100644
index 00000000000..88771ffdb4b
--- /dev/null
+++ b/Tests/LibWeb/Text/input/Editing/writing-suggestion-accessibility.html
@@ -0,0 +1,21 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<div id="editable" contenteditable></div>
+<script>
+ promiseTest(async () => {
+ const editable = document.getElementById("editable");
+ internals.sendText(editable, "predi");
+ await internals.writingSuggestionSettled();
+ // Read before anything is printed, so the output itself isn't in the tree.
+ const tree = internals.dumpAccessibilityTree();
+ const leaves = [];
+ const collect = node => {
+ if (node.type === "text")
+ leaves.push(node.name);
+ (node.children || []).forEach(collect);
+ };
+ collect(JSON.parse(tree));
+ println(`suggestion: ${internals.writingSuggestion()}`);
+ println(`text leaves: ${JSON.stringify(leaves)}`);
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/Editing/writing-suggestion-geometry.html b/Tests/LibWeb/Text/input/Editing/writing-suggestion-geometry.html
new file mode 100644
index 00000000000..0f219bb68d2
--- /dev/null
+++ b/Tests/LibWeb/Text/input/Editing/writing-suggestion-geometry.html
@@ -0,0 +1,18 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<div id="editable" contenteditable>-xyz</div>
+<script>
+ promiseTest(async () => {
+ const editable = document.getElementById("editable");
+ editable.focus();
+ getSelection().collapse(editable.firstChild, 0);
+ internals.sendText(editable, "predi");
+ const textAfterCaret = document.createRange();
+ textAfterCaret.setStart(editable.firstChild, 5);
+ textAfterCaret.setEnd(editable.firstChild, 9);
+ const leftWhileTyping = textAfterCaret.getBoundingClientRect().left;
+ await internals.writingSuggestionSettled();
+ println(`suggestion: ${internals.writingSuggestion()}`);
+ println(`text after the caret moved over: ${textAfterCaret.getBoundingClientRect().left > leftWhileTyping}`);
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/Editing/writing-suggestion-text-queries.html b/Tests/LibWeb/Text/input/Editing/writing-suggestion-text-queries.html
new file mode 100644
index 00000000000..2614c47943b
--- /dev/null
+++ b/Tests/LibWeb/Text/input/Editing/writing-suggestion-text-queries.html
@@ -0,0 +1,25 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<div id="editable" contenteditable></div>
+<input id="field">
+<script>
+ promiseTest(async () => {
+ // Printed only at the end, so the output itself isn't in the page that find() searches.
+ const lines = [];
+ const editable = document.getElementById("editable");
+ internals.sendText(editable, "predi");
+ await internals.writingSuggestionSettled();
+ lines.push(`suggestion: ${internals.writingSuggestion()}`);
+ lines.push(`innerText: ${editable.innerText}`);
+ lines.push(`textContent: ${editable.textContent}`);
+ lines.push(`selection: "${getSelection().toString()}"`);
+ lines.push(`find: ${window.find("ction")}`);
+
+ const field = document.getElementById("field");
+ internals.sendText(field, "predi");
+ await internals.writingSuggestionSettled();
+ lines.push(`input suggestion: ${internals.writingSuggestion()}`);
+ lines.push(`value: ${field.value}`);
+ lines.forEach(line => println(line));
+ });
+</script>