The headless browser for AI agents and web scraping
fix(dom): resolve caret positions from rendered text geometry
SGavrla430ca544b79
diff --git a/crates/obscura-js/js/bootstrap.js b/crates/obscura-js/js/bootstrap.jsindex 2d47383f..283aba3d 100644--- a/crates/obscura-js/js/bootstrap.js+++ b/crates/obscura-js/js/bootstrap.js@@ -16752,6 +16752,111 @@ if (typeof ShadowRoot !== 'undefined' && !ShadowRoot.prototype.elementFromPoint)};}+// Ops are bound after snapshot restoration, so probe the renderer at realm+// initialization, not while building the snapshot with an empty op table.+function _installCaretGeometry() {+ if (typeof __obscuraCore.ops.op_layout_caret !== 'function') return {};+ const positions = new WeakMap();+ function positionState(receiver) {+ const state = positions.get(receiver);+ if (!state) throw new TypeError('Illegal invocation');+ return state;+ }+ const CaretPosition = class CaretPosition {+ constructor() { throw new TypeError('Illegal constructor'); }+ get offsetNode() { return positionState(this).node; }+ get offset() { return positionState(this).offset; }+ getClientRect() {+ const { node, offset } = positionState(this);+ const raw = __obscuraCore.ops.op_layout_caret_rect(String(node._nid), offset, _realmFrameId);+ const rect = raw ? JSON.parse(raw) : null;+ return rect ? new DOMRect(rect.x, rect.y, rect.width, rect.height) : new DOMRect();+ }+ };+ Object.defineProperty(globalThis, 'CaretPosition', {+ value: CaretPosition, writable: true, configurable: true,+ });+ Object.defineProperty(CaretPosition.prototype, Symbol.toStringTag, { value: 'CaretPosition', configurable: true });+ for (const name of ['offsetNode', 'offset', 'getClientRect']) {+ const descriptor = Object.getOwnPropertyDescriptor(CaretPosition.prototype, name);+ descriptor.enumerable = true;+ Object.defineProperty(CaretPosition.prototype, name, descriptor);+ _markNative(descriptor.value || descriptor.get);+ }+ _markNative(CaretPosition);+ function nativeCaret(receiver, x, y) {+ if (receiver !== globalThis.document && !(receiver instanceof Document)) throw new TypeError('Illegal invocation');+ if (receiver._nid !== globalThis.document?._nid) return null;+ const raw = __obscuraCore.ops.op_layout_caret(x, y, _realmFrameId);+ if (!raw) return null;+ const [nid, offset] = JSON.parse(raw);+ const node = _wrap(nid);+ return node ? { node, offset } : null;+ }+ Document.prototype.caretRangeFromPoint = function caretRangeFromPoint(x = 0, y = 0) {+ const method = _documentRealmMember(this, 'caretRangeFromPoint');+ if (method) return Reflect.apply(method, this, [x, y]);+ // The legacy Chromium extension takes optional signed integer coordinates.+ const state = nativeCaret(this, +x | 0, +y | 0);+ if (!state) return null;+ const range = new Range();+ // Widget value offsets are not DOM Range boundaries. The legacy API+ // exposes the position before the control, not its internal editing text.+ for (let node = state.node; node; node = node.parentNode) {+ if (node instanceof HTMLInputElement || node instanceof HTMLTextAreaElement) {+ range.setStartBefore(node);+ range.collapse(true);+ return range;+ }+ }+ range.setStart(state.node, state.offset);+ range.collapse(true);+ return range;+ };+ Document.prototype.caretPositionFromPoint = function caretPositionFromPoint(x, y, options = {}) {+ const method = _documentRealmMember(this, 'caretPositionFromPoint');+ if (method) return Reflect.apply(method, this, arguments);+ if (arguments.length < 2) throw new TypeError('Two coordinates are required');+ x = +x; y = +y;+ if (!Number.isFinite(x) || !Number.isFinite(y)) throw new TypeError('Coordinates must be finite');+ if (options != null && typeof options !== 'object' && typeof options !== 'function') {+ throw new TypeError('Options must be a dictionary');+ }+ const shadowRoots = options?.shadowRoots;+ if (shadowRoots !== undefined && (shadowRoots == null || typeof shadowRoots[Symbol.iterator] !== 'function')) {+ throw new TypeError('Shadow roots must be iterable');+ }+ const roots = shadowRoots === undefined ? [] : Array.from(shadowRoots);+ for (const root of roots) {+ if (!(root instanceof ShadowRoot)) throw new TypeError('Expected a ShadowRoot');+ }+ const state = nativeCaret(this, x, y);+ if (!state) return null;+ let root = state.node.getRootNode();+ while (root instanceof ShadowRoot && !roots.some(allowed => {+ for (let current = allowed; current instanceof ShadowRoot; current = current.host.getRootNode()) {+ if (current === root) return true;+ }+ return false;+ })) {+ const host = root.host, parent = host.parentNode;+ if (!parent) return null;+ state.offset = Array.prototype.indexOf.call(parent.childNodes, host);+ state.node = parent;+ root = parent.getRootNode();+ }+ const position = Object.create(CaretPosition.prototype);+ positions.set(position, state);+ return position;+ };+ _markNative(Document.prototype.caretRangeFromPoint);+ _markNative(Document.prototype.caretPositionFromPoint);+ return {+ caretRangeFromPoint: Document.prototype.caretRangeFromPoint,+ caretPositionFromPoint: Document.prototype.caretPositionFromPoint,+ };+}+// Capture late-defined document members too, before page code can replace them.const _documentMembers = Object.freeze(Object.fromEntries(['URL', 'defaultView', 'readyState', 'getElementById', 'querySelector', 'querySelectorAll', 'open', 'close', 'elementFromPoint'].map(name => {@@ -16762,7 +16867,10 @@ const _documentMembers = Object.freeze(Object.fromEntries(globalThis.__obscura_init = function() {// The host sets __obscura_frameId on a frame realm before calling this._realmFrameId = globalThis.__obscura_frameId >>> 0;- __obscuraCore.ops.op_register_document_realm(_documentMembers, _realmFrameId);+ const caretMembers = _installCaretGeometry();+ __obscuraCore.ops.op_register_document_realm(+ Object.keys(caretMembers).length ? Object.freeze({ ..._documentMembers, ...caretMembers }) : _documentMembers,+ _realmFrameId);_browserPostedTaskWakePending = false;for (const queue of _browserPostedTaskQueues) _browserPostedTaskDiscardQueue(queue);_fpSeed = Date.now() ^ (Math.random() * 0xFFFFFFFF >>> 0);diff --git a/crates/obscura-js/src/ops.rs b/crates/obscura-js/src/ops.rsindex 5123c998..cb1c887c 100644--- a/crates/obscura-js/src/ops.rs+++ b/crates/obscura-js/src/ops.rs@@ -6570,6 +6570,8 @@ pub fn build_extension() -> Extension {ops.push(op_layout_geometry());ops.push(op_layout_box_metrics());ops.push(op_layout_hit_test());+ ops.push(op_layout_caret());+ ops.push(op_layout_caret_rect());ops.push(op_resize_observer_measurements());ops.push(op_intersection_observer_measurements());ops.push(op_computed_style());@@ -7628,6 +7630,40 @@ fn op_layout_hit_test(state: &OpState, x: f64, y: f64, frame_id: u32) -> i32 {.map_or(-1, |id| id.index() as i32)}+#[cfg(feature = "render")]+#[op2]+#[string]+fn op_layout_caret(state: &OpState, x: f64, y: f64, frame_id: u32) -> String {+ std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {+ let shared = frame_state(state, frame_id);+ let mut gs = shared.borrow_mut();+ sample_live_document_animations(&mut gs);+ ensure_resolved_scroll_for_geometry(&mut gs)?;+ let (_, scroll) = gs.resolved_scroll.as_ref()?;+ let prepared = gs.prepared_render.as_ref()?;+ let dom = gs.dom.as_ref()?;+ let (node, offset) = prepared.caret_from_point(dom, scroll, x as f32, y as f32)?;+ Some(serde_json::json!([node.raw(), offset]).to_string())+ })).ok().flatten().unwrap_or_default()+}++#[cfg(feature = "render")]+#[op2]+#[string]+fn op_layout_caret_rect(state: &OpState, #[string] nid: String, offset: u32, frame_id: u32) -> String {+ std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {+ let node = NodeId::new(nid.parse().ok()?);+ let shared = frame_state(state, frame_id);+ let mut gs = shared.borrow_mut();+ sample_live_document_animations(&mut gs);+ ensure_resolved_scroll_for_geometry(&mut gs)?;+ let (_, scroll) = gs.resolved_scroll.as_ref()?;+ let rect = gs.prepared_render.as_ref()?.caret_rect(gs.dom.as_ref()?, scroll, node, offset as usize)?;+ Some(serde_json::json!({"x": rect.x, "y": rect.y,+ "width": rect.width, "height": rect.height}).to_string())+ })).ok().flatten().unwrap_or_default()+}+/// Measure every target in one ResizeObserver rendering opportunity.////// ResizeObserver gathers all observations before it invokes any callback.diff --git a/crates/obscura-js/src/runtime.rs b/crates/obscura-js/src/runtime.rsindex 63b62b18..c82d4bf2 100644--- a/crates/obscura-js/src/runtime.rs+++ b/crates/obscura-js/src/runtime.rs@@ -5094,6 +5094,89 @@ mod tests {]));}+ #[cfg(feature = "render")]+ #[test]+ fn document_carets_use_shaped_text_and_utf16_offsets() {+ let mut rt = setup_runtime("<style>body{margin:0;font:20px/24px monospace}span{display:inline-block}</style><span id='text'>A😀BC</span>");+ assert_eq!(rt.evaluate(r#"(() => {+ if (typeof document.caretRangeFromPoint !== 'function' ||+ typeof document.caretPositionFromPoint !== 'function') return 'missing caret API';+ const element = document.getElementById('text'), text = element.firstChild;+ const r = element.getBoundingClientRect();+ const results = [];+ for (const name of ['caretRangeFromPoint', 'caretPositionFromPoint']) {+ for (const x of [r.left + .1, r.right - .1]) {+ const c = document[name](x, r.top + 12);+ results.push([(c.startContainer || c.offsetNode) === text,+ c.startOffset ?? c.offset]);+ }+ results.push(document[name](-1, 12) === null);+ }+ return results;+ })()"#).unwrap(), serde_json::json!([+ [true, 0], [true, 5], true, [true, 0], [true, 5], true+ ]));+ }++ #[cfg(feature = "render")]+ #[test]+ fn document_carets_find_flattened_mixed_content_runs() {+ let mut rt = setup_runtime("<style>body{margin:0;font:20px/24px monospace}</style><div>AAAA<div style='height:30px'></div><span id='text'>ABCD</span></div>");+ assert_eq!(rt.evaluate(r#"(() => {+ const text = document.getElementById('text').firstChild;+ const caret = document.caretPositionFromPoint(1, 66);+ return [caret.offsetNode === text, caret.offset];+ })()"#).unwrap(), serde_json::json!([true, 0]));+ }++ #[cfg(feature = "render")]+ #[test]+ fn document_carets_legacy_ranges_exclude_widget_internal_text() {+ let mut rt = setup_runtime("<style>body{margin:0}input,textarea{display:block;border:0;padding:0;font:20px/24px monospace;width:200px;height:24px}</style><div></div><input id='input'><textarea id='textarea'>ABCD</textarea>");+ assert_eq!(rt.evaluate(r#"(() => {+ const result = [];+ for (const id of ['input', 'textarea']) {+ const widget = document.getElementById(id);+ widget.value = 'A😀BC';+ const rect = widget.getBoundingClientRect();+ for (const x of [rect.left + .1, rect.right - .1]) {+ const range = document.caretRangeFromPoint(x, rect.top + 12);+ result.push([range.startContainer === document.body,+ range.startOffset, range.collapsed]);+ }+ }+ return result;+ })()"#).unwrap(), serde_json::json!([+ [true, 1, true], [true, 1, true], [true, 2, true], [true, 2, true]+ ]));+ }++ #[cfg(feature = "render")]+ #[test]+ fn document_carets_keep_receiver_realm_and_current_geometry() {+ let mut rt = setup_runtime("<style>body{margin:0;font:20px/24px monospace}#parent{display:inline-block}</style><span id='parent'>ABCD</span>");+ assert_eq!(rt.evaluate(r#"(() => {+ if (typeof document.caretPositionFromPoint !== 'function') return 'missing caret API';+ const iframe = document.createElement('iframe'); iframe.style.display = 'block'; document.body.appendChild(iframe);+ const d = iframe.contentDocument;+ d.body.innerHTML = '<style>body{margin:0;font:20px/24px monospace}#child{display:inline-block}</style><span id="child">WXYZ</span>';+ const child = d.getElementById('child'), parent = document.getElementById('parent');+ const foreign = iframe.contentWindow.Document.prototype;+ const borrowed = Document.prototype.caretPositionFromPoint.call(d, .1, 12);+ const reverse = foreign.caretPositionFromPoint.call(document, .1, 12);+ const position = document.caretPositionFromPoint(.1, 12);+ const before = position.getClientRect();+ parent.style.transform = 'translate(40px,50px)';+ const after = position.getClientRect();+ let invalid = false;+ try { document.caretPositionFromPoint(Infinity, 0); } catch (e) { invalid = e instanceof TypeError; }+ return [borrowed.offsetNode === child.firstChild, reverse.offsetNode === parent.firstChild,+ position.offset === 0, before.width === 0 && before.height > 0,+ Math.abs(after.x - before.x - 40) < .01, Math.abs(after.y - before.y - 50) < .01,+ new Document().caretPositionFromPoint(1, 12) === null, invalid];+ })()"#).unwrap(), serde_json::json!([true, true, true, true, true, true, true, true]));+ }+#[cfg(feature = "render")]#[test]fn borrowed_document_hit_testing_uses_the_receiver_realm() {diff --git a/crates/obscura-render/src/dom.rs b/crates/obscura-render/src/dom.rsindex 90245e84..26245530 100644--- a/crates/obscura-render/src/dom.rs+++ b/crates/obscura-render/src/dom.rs@@ -13955,7 +13955,7 @@ fn inline_wraps_only_in_flow_blocks(/// computed text styles, so removing these wrappers preserves shaping while/// exposing block-in-inline descendants early enough for anonymous block/// construction.-fn flatten_boxless_inline_children(+pub(crate) fn flatten_boxless_inline_children(tree: &DomTree,children: &[NodeId],styles: &HashMap<NodeId, crate::LayoutStyle>,diff --git a/crates/obscura-render/src/inline.rs b/crates/obscura-render/src/inline.rsindex 0897de55..9807a55a 100644--- a/crates/obscura-render/src/inline.rs+++ b/crates/obscura-render/src/inline.rs@@ -780,6 +780,9 @@ pub struct InlineItem {/// Empty for ordinary IFCs and for nested inlines that remain at their/// normal-flow position, so paint pays no provenance cost on that path.relative_owner_ranges: Vec<RelativeOwnerTextRange>,+ /// Mixed-content IFCs own only this sibling range. Caret queries replay+ /// the collector on demand rather than retaining a map for every glyph.+ caret_run: Option<(NodeId, NodeId)>,/// Exact measurement results retained across repeated Taffy probes.measured: Vec<(Option<u32>, Wrap, (f32, f32))>,}@@ -1468,7 +1471,7 @@ impl TextEngine {&self.loaded_families,);}- self.push_shaped_item(+ let index = self.push_shaped_item(base,line_height,spans,@@ -1476,7 +1479,9 @@ impl TextEngine {collector.owner_ranges,collector.owner_boxes,collector.boundary_events,- )+ )?;+ self.items[index].caret_run = Some((*run.first()?, *run.last()?));+ Some(index)}/// Shape generated text that owns a positioned pseudo box.@@ -1525,6 +1530,7 @@ impl TextEngine {&attrs,&mut spans,&mut collector,+ None,);self.push_shaped_item(style,@@ -1802,6 +1808,7 @@ impl TextEngine {owner_boxes,boundary_events,relative_owner_ranges: Vec::new(),+ caret_run: None,measured: Vec::new(),});Some(idx)@@ -2167,6 +2174,145 @@ impl TextEngine {}out}++ fn caret_source(+ &self,+ index: usize,+ parent: NodeId,+ tree: &DomTree,+ styles: &HashMap<NodeId, LayoutStyle>,+ ) -> Option<(String, Vec<CaretBoundary>)> {+ let item = self.items.get(index)?;+ let base = styles.get(&parent)?;+ let mut collector = Collector::new();+ collector.caret_boundaries = Some(Vec::new());+ let font = resolve_loaded_font(base.font_family.as_deref(),+ crate::style::used_font_weight(base), base.font_style_italic.unwrap_or(false),+ &self.loaded_families);+ let ctx = base_span_ctx(base, font, &mut collector);+ let mut spans = Vec::new();+ if let Some((first, last)) = item.caret_run {+ let mut children = crate::dom::rendered_children(tree, parent);+ if !children.contains(&first) || !children.contains(&last) {+ let mut flattened = Vec::new();+ crate::dom::flatten_boxless_inline_children(tree, &children, styles, &mut flattened);+ children = flattened;+ }+ let start = children.iter().position(|id| *id == first)?;+ let end = children.iter().position(|id| *id == last)?;+ for &id in children.get(start..=end)? {+ collect_node_spans(tree, id, styles, ctx.clone(), &mut spans,+ &mut collector, &self.loaded_families);+ }+ } else {+ collect_spans(tree, parent, styles, ctx, &mut spans,+ &mut collector, &self.loaded_families);+ }+ let mut source: String = spans.into_iter().map(|(text, _)| text).collect();+ if matches!(base.white_space.unwrap_or_default(),+ crate::WhiteSpace::Normal | crate::WhiteSpace::NoWrap | crate::WhiteSpace::PreLine)+ && source.ends_with(' ')+ {+ source.pop();+ }+ let mut boundaries = collector.caret_boundaries?;+ boundaries.retain(|boundary| boundary.byte <= source.len());+ Some((source, boundaries))+ }++ /// Use the retained glyph clusters for hit testing, then translate the+ /// shaped byte cursor into the original DOM node's UTF-16 boundary.+ pub(crate) fn caret_from_point(+ &self,+ index: usize,+ parent: NodeId,+ tree: &DomTree,+ styles: &HashMap<NodeId, LayoutStyle>,+ x: f32,+ y: f32,+ hit: NodeId,+ ) -> Option<(NodeId, usize, f32)> {+ let item = self.items.get(index)?;+ let (source, boundaries) = self.caret_source(index, parent, tree, styles)?;+ if hit != parent && !boundaries.iter().any(|boundary|+ boundary.node == hit || tree.ancestors(boundary.node).contains(&hit))+ { return None; }+ let starts = source_line_starts(&item.buffer, &source);+ let mut best: Option<(f32, usize, cosmic_text::Affinity)> = None;+ for (line_index, run) in item.buffer.layout_runs().enumerate() {+ if item.line_clamp.is_some_and(|limit| line_index >= limit) { break; }+ let start = *starts.get(run.line_i)?;+ let end = start + run.text.len();+ let indent = if line_index == 0 { item.first_line_offset } else { 0.0 };+ for glyph in run.glyphs {+ if glyph.w <= 0.0 || item.marker.is_some_and(|marker|+ marker.line_index == line_index && glyph.x + indent + glyph.w > marker.content_end)+ { continue; }+ let relative = glyph_relative_offset(&item.relative_owner_ranges, start, glyph.start, glyph.end);+ let dx = item.origin.0 + indent + relative.0+ + line_edge_alignment_shift(item, start, end)+ + line_advance_before_text(item, start + glyph.start, start, end);+ let dy = item.origin.1 + relative.1;+ let left = dx + glyph.x;+ let top = dy + run.line_top;+ let distance = (x - x.clamp(left, left + glyph.w)).powi(2)+ + (y - y.clamp(top, top + run.line_height)).powi(2);+ if best.as_ref().is_some_and(|(old, _, _)| *old <= distance) { continue; }+ // Buffer::hit already implements grapheme/ligature and bidi+ // boundaries. Remove the extra offsets applied by paint.+ let hit_x = (x - dx).clamp(glyph.x, glyph.x + glyph.w);+ let cursor = item.buffer.hit(hit_x, run.line_top + run.line_height * 0.5)?;+ best = Some((distance, start + cursor.index, cursor.affinity));+ }+ }+ let (distance, byte, affinity) = best?;+ let nearest = boundaries.iter().map(|boundary| boundary.byte.abs_diff(byte)).min()?;+ let matches = |boundary: &&CaretBoundary| boundary.byte.abs_diff(byte) == nearest;+ let boundary = if affinity == cosmic_text::Affinity::Before {+ boundaries.iter().find(matches)+ } else {+ boundaries.iter().rev().find(matches)+ }?;+ Some((boundary.node, boundary.offset, distance))+ }++ pub(crate) fn caret_rect(+ &self,+ index: usize,+ parent: NodeId,+ tree: &DomTree,+ styles: &HashMap<NodeId, LayoutStyle>,+ node: NodeId,+ offset: usize,+ ) -> Option<Rect> {+ let item = self.items.get(index)?;+ let (source, boundaries) = self.caret_source(index, parent, tree, styles)?;+ let boundary = boundaries.iter().filter(|boundary| boundary.node == node)+ .min_by_key(|boundary| boundary.offset.abs_diff(offset))?;+ let starts = source_line_starts(&item.buffer, &source);+ let style = tree.with_node(node, |node| node.parent)+ .flatten().and_then(|id| styles.get(&id)).or_else(|| styles.get(&parent))?;+ let (ascent, descent) = self.inline_font_box_metrics(style);+ for (line_index, run) in item.buffer.layout_runs().enumerate() {+ if item.line_clamp.is_some_and(|limit| line_index >= limit) { break; }+ let start = *starts.get(run.line_i)?;+ let byte = boundary.byte.checked_sub(start)?;+ let Some(glyph) = run.glyphs.iter().find(|glyph| glyph.start <= byte && byte <= glyph.end) else {+ continue;+ };+ let relative = glyph_relative_offset(&item.relative_owner_ranges, start, glyph.start, glyph.end);+ let indent = if line_index == 0 { item.first_line_offset } else { 0.0 };+ return Some(Rect {+ x: item.origin.0 + run_cursor_x(&run, byte) + indent + relative.0+ + line_edge_alignment_shift(item, start, start + run.text.len())+ + line_advance_before_text(item, start + glyph.start, start, start + run.text.len()),+ y: item.origin.1 + run.line_y + relative.1 - ascent,+ width: 0.0,+ height: ascent + descent,+ });+ }+ None+ }}/// A run of same-styled inline text.@@ -2330,6 +2476,14 @@ struct Collector {owner_boxes: Vec<InlineOwnerBox>,boundary_events: Vec<InlineBoundaryEvent>,text_len: usize,+ caret_boundaries: Option<Vec<CaretBoundary>>,+}++#[derive(Clone, Copy)]+struct CaretBoundary {+ byte: usize,+ node: NodeId,+ offset: usize,}impl Collector {@@ -2342,6 +2496,7 @@ impl Collector {owner_boxes: Vec::new(),boundary_events: Vec::new(),text_len: 0,+ caret_boundaries: None,}}@@ -2521,7 +2676,7 @@ fn collect_node_spans(overflow_wrap: ctx.overflow_wrap,word_break: ctx.word_break,};- push_text(contents, ctx.transform, ctx.white_space, &attrs, out, c);+ push_text(contents, ctx.transform, ctx.white_space, &attrs, out, c, Some(cid));}_ => {let Some(elem) = node.as_element() else {@@ -2654,9 +2809,44 @@ fn push_text(attrs: &SpanAttrs,out: &mut Vec<(String, SpanAttrs)>,c: &mut Collector,+ node: Option<NodeId>,) {+ let start = c.text_len;+ let buf = if let (Some(boundaries), Some(node)) = (&mut c.caret_boundaries, node) {+ normalize_text(raw, transform, white_space, &mut c.last_was_space, |byte, offset| {+ // Pre-line normalization can remove the space before a newline.+ while boundaries.last().is_some_and(|boundary| boundary.byte > start + byte) {+ boundaries.pop();+ }+ boundaries.push(CaretBoundary { byte: start + byte, node, offset });+ })+ } else {+ normalize_text(raw, transform, white_space, &mut c.last_was_space, |_, _| {})+ };+ if buf.is_empty() {+ return;+ }+ c.record_text(buf.len());+ if let Some((last_text, last_attrs)) = out.last_mut() {+ if last_attrs == attrs {+ last_text.push_str(&buf);+ return;+ }+ }+ out.push((buf, attrs.clone()));+}++fn normalize_text(+ raw: &str,+ transform: TextTransform,+ white_space: crate::WhiteSpace,+ last_was_space: &mut bool,+ mut boundary: impl FnMut(usize, usize),+) -> String {let mut buf = String::new();- let mut at_word_start = c.last_was_space;+ let mut at_word_start = *last_was_space;+ let mut offset = 0;+ boundary(0, 0);for ch in raw.chars() {if ch.is_whitespace() {match white_space {@@ -2669,10 +2859,10 @@ fn push_text(}buf.push('\n');}- _ if !c.last_was_space => buf.push(' '),+ _ if !*last_was_space => buf.push(' '),_ => {}}- c.last_was_space = true;+ *last_was_space = true;at_word_start = true;} else {match transform {@@ -2681,21 +2871,13 @@ fn push_text(TextTransform::Capitalize if at_word_start => buf.extend(ch.to_uppercase()),_ => buf.push(ch),}- c.last_was_space = false;+ *last_was_space = false;at_word_start = false;}+ offset += ch.len_utf16();+ boundary(buf.len(), offset);}- if buf.is_empty() {- return;- }- c.record_text(buf.len());- if let Some((last_text, last_attrs)) = out.last_mut() {- if last_attrs == attrs {- last_text.push_str(&buf);- return;- }- }- out.push((buf, attrs.clone()));+ buf}fn boundary_event_on_line(diff --git a/crates/obscura-render/src/paint.rs b/crates/obscura-render/src/paint.rsindex 7e676839..e2b1d0ff 100644--- a/crates/obscura-render/src/paint.rs+++ b/crates/obscura-render/src/paint.rs@@ -1625,6 +1625,64 @@ impl PreparedRender {best.map(|(_, _, _, _, id)| id)}+ /// Shaped-text caret in the viewport. Hit testing selects the painted+ /// owner first, so an occluding sibling cannot donate its text cursor.+ pub fn caret_from_point(+ &self,+ tree: &DomTree,+ scroll: &ResolvedScrollState,+ x: f32,+ y: f32,+ ) -> Option<(obscura_dom::tree::NodeId, usize)> {+ let hit = self.hit_test(tree, scroll, x, y)?;+ for parent in std::iter::successors(Some(hit), |id| crate::dom::rendered_parent(tree, *id))+ .take(tree.len() + 1)+ {+ let movement = scroll.movement_for(parent);+ let transform = self.layout.transforms.get(&parent).copied().unwrap_or_default();+ let Some(inverse) = transform.inverse() else { continue; };+ let (local_x, local_y) = inverse.map_point(x - movement.0, y - movement.1);+ let indices = self.layout.ifc_items.get(&parent).into_iter().copied()+ .chain(self.layout.run_ifc_items.get(&parent).into_iter().flatten().copied());+ let best = indices.filter_map(|index|+ self.layout.text_engine.caret_from_point(index, parent, tree,+ &self.layout.styles, local_x, local_y, hit))+ .min_by(|a, b| a.2.total_cmp(&b.2));+ if let Some((node, offset, _)) = best { return Some((node, offset)); }+ }+ // Empty rendered line boxes have an element boundary, not a fabricated+ // text node. This also preserves the caret of an empty editable block.+ Some((hit, 0))+ }++ /// Geometry for a previously obtained DOM caret, using current layout and+ /// scroll rather than the snapshot at the original mouse coordinates.+ pub fn caret_rect(+ &self,+ tree: &DomTree,+ scroll: &ResolvedScrollState,+ node: obscura_dom::tree::NodeId,+ offset: usize,+ ) -> Option<crate::Rect> {+ for parent in std::iter::successors(crate::dom::rendered_parent(tree, node),+ |id| crate::dom::rendered_parent(tree, *id)).take(tree.len() + 1)+ {+ let indices = self.layout.ifc_items.get(&parent).into_iter().copied()+ .chain(self.layout.run_ifc_items.get(&parent).into_iter().flatten().copied());+ for index in indices {+ let Some(rect) = self.layout.text_engine.caret_rect(index, parent,+ tree, &self.layout.styles, node, offset) else { continue; };+ let mut rect = self.layout.transforms.get(&parent).copied()+ .unwrap_or_default().map_rect(rect);+ let movement = scroll.movement_for(parent);+ rect.x += movement.0;+ rect.y += movement.1;+ return Some(rect);+ }+ }+ None+ }+/// A compact CSSOM snapshot derived from the same final cascade and/// layout used by paint and geometry. Keeping this on `PreparedRender`/// lets script fetch all high-traffic computed properties in one op,