Skip to content

armgit / moli

Public Imported from GitHub
0

Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust

fix(forms): isolate empty editor carets from placeholder styling

ldm086762e488a04
diff --git a/moli-layout/src/form.rs b/moli-layout/src/form.rs
index afe8976c9..37e85e97b 100644
--- a/moli-layout/src/form.rs
+++ b/moli-layout/src/form.rs
@@ -43,28 +43,39 @@ where
}
let owner_label = world.boxes[control.index()].source_label.clone();
let placeholder_style = if placeholder {
- styles.placeholder_style(owner)?
+ styles.placeholder_style(owner)?.map(|style| {
+ let mut style = style.into_style();
+ style.force_layout_display(LayoutDisplay::Block);
+ style
+ })
} else {
None
};
- let wrapper_style = if let Some(style) = placeholder_style {
- let mut style = style.into_style();
- style.force_layout_display(LayoutDisplay::Block);
- style
- } else {
- styles.anonymous_style(
- owner,
- &world.boxes[control.index()].style,
- LayoutDisplay::Block,
- )?
- };
- let text_style = ResolvedLayoutStyle::text_leaf_from(&wrapper_style);
+ let editor_style = styles.anonymous_style(
+ owner,
+ &world.boxes[control.index()].style,
+ LayoutDisplay::Block,
+ )?;
let selection = world.boxes[control.index()].text_selection;
- let caret_color = world.boxes[control.index()].style.caret_color();
if texts.is_empty() && selection.is_some() {
texts.push(Arc::from(""));
}
- for (row, text) in texts.into_iter().enumerate() {
+ // Blink keeps the placeholder and inner editor as siblings. The
+ // placeholder precedes the empty editor, which retains its own
+ // font metrics and selection outside the placeholder's effect layers.
+ // Both remain descendants of the control's effects and clipping.
+ let contents = texts
+ .into_iter()
+ .map(|text| (text, placeholder))
+ .chain(placeholder.then(|| (Arc::from(""), false)));
+ for (row, (text, is_placeholder)) in contents.enumerate() {
+ let wrapper_style = if is_placeholder {
+ placeholder_style.as_ref().unwrap_or(&editor_style)
+ } else {
+ &editor_style
+ };
+ let text_style = ResolvedLayoutStyle::text_leaf_from(wrapper_style);
+ let selection = if is_placeholder { None } else { selection };
let mut wrapper = LayoutWorld::new_box(
None,
Some(owner),
@@ -79,7 +90,6 @@ where
);
wrapper.inline_formatting_context = true;
wrapper.text_selection = selection;
- wrapper.selection_caret_color = Some(caret_color);
let wrapper_id = world.allocate(wrapper);
let text_id = world.allocate(LayoutWorld::new_box(
None,
@@ -94,7 +104,6 @@ where
Some(text),
));
world.boxes[text_id.index()].text_selection = selection;
- world.boxes[text_id.index()].selection_caret_color = Some(caret_color);
world.append_synthesized_child(wrapper_id, text_id)?;
world.append_synthesized_child(control, wrapper_id)?;
}
diff --git a/moli-layout/src/inline.rs b/moli-layout/src/inline.rs
index 631748879..945a04ce5 100644
--- a/moli-layout/src/inline.rs
+++ b/moli-layout/src/inline.rs
@@ -2079,11 +2079,7 @@ impl InlineBuildInput {
.filter(|selection| selection.is_caret())
.map(|_| InlineSelection::Caret {
offset: 0,
- color: world.boxes[self.root_style.index()]
- .selection_caret_color
- .unwrap_or_else(|| {
- world.boxes[self.root_style.index()].style.caret_color()
- }),
+ color: world.boxes[self.root_style.index()].style.caret_color(),
})
});
let mut root_text_style = world.boxes[self.root_style.index()]
@@ -2281,11 +2277,7 @@ where
caret_output_offset(source_map, entry.box_id, selection.start).map(|offset| {
(
offset,
- world.boxes[entry.box_id.index()]
- .selection_caret_color
- .unwrap_or_else(|| {
- world.boxes[entry.box_id.index()].style.caret_color()
- }),
+ world.boxes[entry.box_id.index()].style.caret_color(),
)
});
}
diff --git a/moli-layout/src/world.rs b/moli-layout/src/world.rs
index bac4cbb31..2b8651402 100644
--- a/moli-layout/src/world.rs
+++ b/moli-layout/src/world.rs
@@ -247,7 +247,6 @@ pub struct LayoutBox<N> {
pub(crate) style: ResolvedLayoutStyle,
pub(crate) text: Option<Arc<str>>,
pub(crate) text_selection: Option<crate::LayoutTextSelection>,
- pub(crate) selection_caret_color: Option<crate::PaintColor>,
/// Shared text/inline layout owned by this formatting-context root.
pub(crate) inline_layout: Option<InlineFormattingContext>,
/// Outermost IFC that consumes this box as a flattened or atomic item.
@@ -1186,7 +1185,6 @@ where
style,
text,
text_selection: None,
- selection_caret_color: None,
inline_layout: None,
inline_context_owner: None,
inline_flattened: false,
diff --git a/moli-renderer-v8/src/runtime/page_vm/tests/rendering_update/form_controls.rs b/moli-renderer-v8/src/runtime/page_vm/tests/rendering_update/form_controls.rs
index b465d94a4..6ea451e87 100644
--- a/moli-renderer-v8/src/runtime/page_vm/tests/rendering_update/form_controls.rs
+++ b/moli-renderer-v8/src/runtime/page_vm/tests/rendering_update/form_controls.rs
@@ -1,5 +1,172 @@
use super::*;
+#[tokio::test(flavor = "current_thread")]
+async fn empty_text_control_caret_keeps_control_opacity_transform_and_clip() {
+ run_page_vm_async_test(async move {
+ let loader = crate::network::ResourceRequestClient::new(&FetchConfig::default())?;
+ let mut page = test_page_vm_with_loader_and_document_url(
+ &loader,
+ Vec::new(),
+ Url::parse("https://example.com/control-caret-effects.html")?,
+ );
+ page.vm_mut().eval(
+ r#"
+document.head.innerHTML=`<style>
+html,body{margin:0;background:white}
+input{display:block;box-sizing:border-box;width:220px;height:100px;border:0;
+ padding:8px;outline:none;background:white;caret-color:red;font:20px sans-serif}
+::placeholder{font-size:48px;opacity:0}
+</style>`;
+document.body.innerHTML='<input id=field placeholder=Example>';
+document.getElementById('field').focus();
+'installed'
+"#,
+ )?;
+ page.vm_mut().sync_live_document_style_sources();
+ let mut reference: Option<moli_layout::PaintRect> = None;
+ for (state, styles) in [
+ ("normal", ""),
+ ("translated", "transform:translate(17px,11px)"),
+ ("translucent", "opacity:0.5"),
+ ("transparent", "opacity:0"),
+ ("clipped", "clip-path:inset(0 0 0 50%)"),
+ ] {
+ page.vm_mut().eval(&format!(
+ "document.getElementById('field').style.cssText={};'updated'",
+ serde_json::to_string(styles)?,
+ ))?;
+ let snapshot = page
+ .vm_mut()
+ .screenshot_layout_snapshot(moli_layout::PaintViewport::new(260, 140, 1.0))?
+ .expect("control caret effects layout");
+ if matches!(state, "normal" | "translated") {
+ let caret = snapshot
+ .fragments
+ .iter()
+ .find_map(|fragment| match fragment {
+ moli_layout::PaintFragment::Fill {
+ shape: moli_layout::PaintShape::Rect(rect),
+ brush: moli_layout::PaintBrush::Solid(color),
+ transform,
+ } if *color == moli_layout::PaintColor::new(1.0, 0.0, 0.0, 1.0)
+ && rect.width == 1.5 =>
+ {
+ Some(transform.map_rect(*rect).bounding_rect())
+ }
+ _ => None,
+ })
+ .expect("editor caret paint");
+ if let Some(reference) = reference {
+ assert_eq!(
+ caret,
+ moli_layout::PaintRect::new(
+ reference.x + 17.0,
+ reference.y + 11.0,
+ reference.width,
+ reference.height
+ )
+ );
+ } else {
+ reference = Some(caret);
+ }
+ }
+ let image = moli_paint::raster_snapshot(&snapshot)?;
+ let pixels = image.rgba.chunks_exact(4);
+ match state {
+ "transparent" | "clipped" => assert!(
+ !pixels
+ .clone()
+ .any(|p| i16::from(p[0]) - i16::from(p[1]) > 25),
+ "{state}: the control's effects also apply to the caret",
+ ),
+ "translucent" => assert!(
+ pixels
+ .clone()
+ .any(|p| p[0] > 240 && (100..=160).contains(&p[1]) && p[1] == p[2]),
+ "the caret must be composited with the control's opacity",
+ ),
+ _ => assert!(pixels.clone().any(|p| p[0] > 200 && p[1] < 50 && p[2] < 50)),
+ }
+ }
+ Ok::<_, anyhow::Error>(())
+ })
+ .await
+ .expect("control caret effects fixture");
+}
+
+#[tokio::test(flavor = "current_thread")]
+async fn placeholder_opacity_does_not_hide_empty_text_control_carets() {
+ assert_placeholder_style_keeps_empty_editor_caret(&["opacity:1", "opacity:0"]).await;
+}
+
+#[tokio::test(flavor = "current_thread")]
+async fn placeholder_font_metrics_do_not_change_empty_text_control_carets() {
+ assert_placeholder_style_keeps_empty_editor_caret(&[
+ "font-size:20px;line-height:normal",
+ "font-size:48px;line-height:96px",
+ ])
+ .await;
+}
+
+async fn assert_placeholder_style_keeps_empty_editor_caret(
+ placeholder_styles: &'static [&'static str],
+) {
+ run_page_vm_async_test(async move {
+ let loader = crate::network::ResourceRequestClient::new(&FetchConfig::default())?;
+ let mut page = test_page_vm_with_loader_and_document_url(
+ &loader,
+ Vec::new(),
+ Url::parse("https://example.com/placeholder-caret.html")?,
+ );
+ page.vm_mut().eval(r#"
+document.head.innerHTML=`<style>
+html,body{margin:0;background:white}
+input,textarea{display:block;box-sizing:border-box;width:220px;height:100px;
+ border:0;padding:8px;outline:none;background:white;color:black;
+ caret-color:red;font:20px sans-serif}
+</style><style id=placeholder-style></style>`;
+'installed'
+"#)?;
+ for tag in ["input", "textarea"] {
+ page.vm_mut().eval(&format!(
+ "document.body.innerHTML='<{tag} id=field></{tag}>';document.getElementById('field').focus();'focused'"
+ ))?;
+ page.vm_mut().sync_live_document_style_sources();
+ let mut reference = None;
+ // Blink keeps the empty inner editor separate from the placeholder
+ // sibling (TextControlInnerEditorElement / UpdatePlaceholderText).
+ for placeholder_style in std::iter::once(None)
+ .chain(placeholder_styles.iter().copied().map(Some))
+ {
+ let script = if let Some(style) = placeholder_style {
+ format!(
+ "document.getElementById('field').placeholder='Example';document.getElementById('placeholder-style').textContent={};'updated'",
+ serde_json::to_string(&format!("::placeholder{{color:black;{style}}}"))?,
+ )
+ } else {
+ "document.getElementById('placeholder-style').textContent='';'reference'".to_owned()
+ };
+ page.vm_mut().eval(&script)?;
+ let snapshot = page.vm_mut().screenshot_layout_snapshot(
+ moli_layout::PaintViewport::new(260, 140, 1.0),
+ )?.expect("placeholder caret layout");
+ let image = moli_paint::raster_snapshot(&snapshot)?;
+ let red_pixels = image.rgba.chunks_exact(4).enumerate().filter_map(|(index, pixel)| {
+ (pixel[0] > 200 && pixel[1] < 50 && pixel[2] < 50 && pixel[3] > 200)
+ .then_some((index as u32 % image.width, index as u32 / image.width))
+ }).collect::<Vec<_>>();
+ assert!(!red_pixels.is_empty(), "{tag}/{placeholder_style:?}: the caret must remain visible after compositing");
+ if let Some(reference) = &reference {
+ assert_eq!(&red_pixels, reference, "{tag}/{placeholder_style:?}: placeholder styling must not change caret position or size");
+ } else {
+ reference = Some(red_pixels);
+ }
+ }
+ }
+ Ok::<_, anyhow::Error>(())
+ }).await.expect("placeholder caret independence fixture");
+}
+
#[tokio::test(flavor = "current_thread")]
async fn focused_text_controls_paint_utf16_selection_and_empty_carets() {
run_page_vm_async_test(async move {