Skip to content

armgit / moli

Public Imported from GitHub
0

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

fix(selection): synchronize endpoints after live Range mutations

ldm04bb110f56cdc
diff --git a/moli-renderer-v8/src/native_bridge/context_host/range_records.rs b/moli-renderer-v8/src/native_bridge/context_host/range_records.rs
index 9e6593cd1..952333e8e 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/range_records.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/range_records.rs
@@ -289,7 +289,7 @@ impl RangeRecordRegistry {
.map(|record| record.boundary(side).container())
}
- fn boundary_point(
+ pub(super) fn boundary_point(
&self,
handle: RangeRecordHandle,
side: RangeBoundarySide,
@@ -753,6 +753,14 @@ impl JsContextHost {
let ids = self
.range_record_registry
.live_record_ids_for_boundary_container(scope, target);
+ if ids.is_empty() {
+ return;
+ }
+ let selection_links = self.selection_record_registry.linked_range_boundaries(
+ dom_host,
+ &self.range_record_registry,
+ true,
+ );
self.range_record_registry.update_for_character_data_edit(
dom_host,
&ids,
@@ -761,6 +769,11 @@ impl JsContextHost {
removed_count,
inserted_count,
);
+ self.selection_record_registry.sync_linked_range_boundaries(
+ dom_host,
+ &self.range_record_registry,
+ selection_links,
+ );
}
pub(crate) fn update_live_range_records_for_child_removal(
@@ -776,6 +789,16 @@ impl JsContextHost {
let ids = self
.range_record_registry
.live_record_ids_for_child_removal(scope, dom_host, removed_child);
+ if ids.is_empty() {
+ return;
+ }
+ // Composed removal boundaries have their own shadow-including
+ // rescoping step. Synchronize only the observable endpoints here.
+ let selection_links = self.selection_record_registry.linked_range_boundaries(
+ dom_host,
+ &self.range_record_registry,
+ false,
+ );
self.range_record_registry.update_for_child_removal(
dom_host,
&ids,
@@ -784,6 +807,11 @@ impl JsContextHost {
index,
previous_sibling,
);
+ self.selection_record_registry.sync_linked_range_boundaries(
+ dom_host,
+ &self.range_record_registry,
+ selection_links,
+ );
}
pub(crate) fn update_live_range_records_for_text_split(
@@ -798,8 +826,21 @@ impl JsContextHost {
let ids = self
.range_record_registry
.live_record_ids_for_text_split(scope, dom_host, original);
+ if ids.is_empty() {
+ return;
+ }
+ let selection_links = self.selection_record_registry.linked_range_boundaries(
+ dom_host,
+ &self.range_record_registry,
+ true,
+ );
self.range_record_registry
.update_for_text_split(dom_host, &ids, original, new_text, offset);
+ self.selection_record_registry.sync_linked_range_boundaries(
+ dom_host,
+ &self.range_record_registry,
+ selection_links,
+ );
}
pub(crate) fn range_record_is_collapsed(&mut self, handle: RangeRecordHandle) -> Option<bool> {
diff --git a/moli-renderer-v8/src/native_bridge/context_host/selection_records.rs b/moli-renderer-v8/src/native_bridge/context_host/selection_records.rs
index 870f66901..0252e3985 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/selection_records.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/selection_records.rs
@@ -1,4 +1,6 @@
+use super::range_records::RangeRecordRegistry;
use super::*;
+use crate::dom::native::{DomHost, NodeType};
use crate::range_boundary::RangeBoundaryPoint;
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
@@ -74,7 +76,106 @@ struct SelectionRecord {
composed_end: Option<RangeBoundaryPoint>,
}
+pub(super) struct SelectionRangeBoundaryLink {
+ selection: SelectionRecordHandle,
+ range: RangeRecordHandle,
+ role: SelectionBoundaryRole,
+ side: RangeBoundarySide,
+}
+
+fn same_boundary_position(dom: &DomHost, a: RangeBoundaryPoint, b: RangeBoundaryPoint) -> bool {
+ if a.container() != b.container() {
+ return false;
+ }
+ if dom.node(a.container()).is_some_and(|node| {
+ matches!(
+ node.node_type(),
+ NodeType::Text
+ | NodeType::CDataSection
+ | NodeType::ProcessingInstruction
+ | NodeType::Comment
+ )
+ }) {
+ let (mut a, mut b) = (a, b);
+ a.offset(dom) == b.offset(dom)
+ } else {
+ // The child may already have left its parent when a removal hook
+ // runs. Compare stable child anchors, not a now-unresolvable offset.
+ a.child_before() == b.child_before()
+ }
+}
+
impl SelectionRecordRegistry {
+ pub(super) fn linked_range_boundaries(
+ &self,
+ dom: &DomHost,
+ ranges: &RangeRecordRegistry,
+ include_composed: bool,
+ ) -> Vec<SelectionRangeBoundaryLink> {
+ let mut links = Vec::new();
+ for (&selection, record) in &self.records {
+ let Some(range) = record.associated_range else {
+ continue;
+ };
+ let start = ranges.boundary_point(range, RangeBoundarySide::Start);
+ let end = ranges.boundary_point(range, RangeBoundarySide::End);
+ for (role, point) in [
+ (SelectionBoundaryRole::Anchor, record.anchor),
+ (SelectionBoundaryRole::Focus, record.focus),
+ (SelectionBoundaryRole::ComposedStart, record.composed_start),
+ (SelectionBoundaryRole::ComposedEnd, record.composed_end),
+ ] {
+ if !include_composed
+ && matches!(
+ role,
+ SelectionBoundaryRole::ComposedStart | SelectionBoundaryRole::ComposedEnd
+ )
+ {
+ continue;
+ }
+ let Some(point) = point else { continue };
+ let side = if start.is_some_and(|start| same_boundary_position(dom, point, start)) {
+ RangeBoundarySide::Start
+ } else if end.is_some_and(|end| same_boundary_position(dom, point, end)) {
+ RangeBoundarySide::End
+ } else {
+ // Focus and cross-tree selections may retain separate
+ // composed boundaries. Do not overwrite their projection.
+ continue;
+ };
+ links.push(SelectionRangeBoundaryLink {
+ selection,
+ range,
+ role,
+ side,
+ });
+ }
+ }
+ links
+ }
+
+ pub(super) fn sync_linked_range_boundaries(
+ &mut self,
+ dom: &DomHost,
+ ranges: &RangeRecordRegistry,
+ links: Vec<SelectionRangeBoundaryLink>,
+ ) {
+ for link in links {
+ if let Some(point) = ranges.boundary_point(link.range, link.side)
+ && let Some(record) = self.records.get_mut(&link.selection)
+ {
+ *record.boundary_slot_mut(link.role) = Some(point);
+ }
+ }
+ for record in self.records.values_mut() {
+ if let (Some(anchor), Some(focus)) = (record.anchor, record.focus)
+ && same_boundary_position(dom, anchor, focus)
+ {
+ record.direction = SelectionDirection::None;
+ }
+ }
+ }
+
pub(super) fn new() -> Self {
Self {
next_id: 1,
diff --git a/moli-renderer-v8/src/runtime/phase_one/tests/extracted/dom_mutation_state.rs b/moli-renderer-v8/src/runtime/phase_one/tests/extracted/dom_mutation_state.rs
index 45d67d1c6..268e40b9b 100644
--- a/moli-renderer-v8/src/runtime/phase_one/tests/extracted/dom_mutation_state.rs
+++ b/moli-renderer-v8/src/runtime/phase_one/tests/extracted/dom_mutation_state.rs
@@ -2477,7 +2477,7 @@ JSON.stringify(window.parserSelectionStates)
assert_eq!(
result.get("value").and_then(serde_json::Value::as_str),
Some(
- r#"{"jsRemove":{"rangeCount":1,"anchor":"target-text","anchorOffset":0,"focus":"target-text","focusOffset":6,"start":"parser-selection-remove-parent","startOffset":0,"end":"parser-selection-remove-parent","endOffset":0,"text":""},"jsMove":{"rangeCount":1,"anchor":"target-text","anchorOffset":0,"focus":"target-text","focusOffset":4,"start":"parser-selection-move-parent","startOffset":0,"end":"parser-selection-move-parent","endOffset":0,"text":""},"parserRemove":{"rangeCount":1,"anchor":"target-text","anchorOffset":0,"focus":"target-text","focusOffset":6,"start":"parser-selection-remove-parent","startOffset":0,"end":"parser-selection-remove-parent","endOffset":0,"text":""},"parserMove":{"rangeCount":1,"anchor":"target-text","anchorOffset":0,"focus":"target-text","focusOffset":4,"start":"parser-selection-move-parent","startOffset":0,"end":"parser-selection-move-parent","endOffset":0,"text":""}}"#
+ r#"{"jsRemove":{"rangeCount":1,"anchor":"parser-selection-remove-parent","anchorOffset":0,"focus":"parser-selection-remove-parent","focusOffset":0,"start":"parser-selection-remove-parent","startOffset":0,"end":"parser-selection-remove-parent","endOffset":0,"text":""},"jsMove":{"rangeCount":1,"anchor":"parser-selection-move-parent","anchorOffset":0,"focus":"parser-selection-move-parent","focusOffset":0,"start":"parser-selection-move-parent","startOffset":0,"end":"parser-selection-move-parent","endOffset":0,"text":""},"parserRemove":{"rangeCount":1,"anchor":"parser-selection-remove-parent","anchorOffset":0,"focus":"parser-selection-remove-parent","focusOffset":0,"start":"parser-selection-remove-parent","startOffset":0,"end":"parser-selection-remove-parent","endOffset":0,"text":""},"parserMove":{"rangeCount":1,"anchor":"parser-selection-move-parent","anchorOffset":0,"focus":"parser-selection-move-parent","focusOffset":0,"start":"parser-selection-move-parent","startOffset":0,"end":"parser-selection-move-parent","endOffset":0,"text":""}}"#
),
"parser remove/reparent should update the selected live range like JS DOM mutation"
);
diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/events_selection_storage/event_dispatch_and_targets.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/events_selection_storage/event_dispatch_and_targets.rs
index 5604c1b8a..a321ec653 100644
--- a/moli-renderer-v8/src/script_vm/tests/browser_api/events_selection_storage/event_dispatch_and_targets.rs
+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/events_selection_storage/event_dispatch_and_targets.rs
@@ -1654,3 +1654,15 @@ fn relative_range_boundaries_share_selection_updates() {
.unwrap();
assert_eq!(result, "true");
}
+
+#[test]
+fn selection_endpoints_follow_associated_live_range_mutations() {
+ let mut vm = new_storage_test_vm("https://selection-live-mutations.test/");
+ assert_eq!(
+ vm.eval(include_str!(
+ "../../../../../tests/fixtures/selection-live-range-mutations.js"
+ ))
+ .expect("Selection endpoints should follow their live Range"),
+ ""
+ );
+}
diff --git a/moli-renderer-v8/tests/fixtures/selection-live-range-mutations.js b/moli-renderer-v8/tests/fixtures/selection-live-range-mutations.js
new file mode 100644
index 000000000..fa7d5b723
--- /dev/null
+++ b/moli-renderer-v8/tests/fixtures/selection-live-range-mutations.js
@@ -0,0 +1,50 @@
+(() => {
+ const root = document.documentElement || document.appendChild(document.createElement('html'));
+ const body = document.body || root.appendChild(document.createElement('body'));
+ const fixture = body.appendChild(document.createElement('div'));
+ const selection = getSelection();
+ const failures = [];
+ const check = (condition, label) => { if (!condition) failures.push(label); };
+ function endpoints(s, r, backward, label) {
+ check(s.rangeCount === 1 && s.getRangeAt(0) === r, label + ': range identity');
+ const a = backward && !r.collapsed ? 'end' : 'start';
+ const f = backward && !r.collapsed ? 'start' : 'end';
+ check(s.anchorNode === r[a + 'Container'] && s.anchorOffset === r[a + 'Offset'] &&
+ s.focusNode === r[f + 'Container'] && s.focusOffset === r[f + 'Offset'], label + ': observable endpoints');
+ check(s.isCollapsed === r.collapsed && s.direction === (r.collapsed ? 'none' : backward ? 'backward' : 'forward'),
+ label + ': direction and collapsed state');
+ const c = s.getComposedRanges()[0];
+ check(c.startContainer === r.startContainer && c.startOffset === r.startOffset &&
+ c.endContainer === r.endContainer && c.endOffset === r.endOffset, label + ': composed endpoints');
+ }
+ for (const backward of [false, true]) {
+ for (const action of ['delete-data', 'insert-data', 'reset-data', 'split-text', 'remove-text', 'remove-before']) {
+ fixture.innerHTML = '<div><span>abcdef</span><span>xyz</span><span>last</span></div>';
+ const editor = fixture.firstChild;
+ const text = editor.firstChild.firstChild;
+ if (action === 'remove-before') selection.collapse(editor, 2);
+ else selection.setBaseAndExtent(text, backward ? 5 : 1, text, backward ? 1 : 5);
+ const range = selection.getRangeAt(0);
+ if (action === 'delete-data') text.deleteData(0, 2);
+ if (action === 'insert-data') text.insertData(0, 'XY');
+ if (action === 'reset-data') text.data = 'new';
+ if (action === 'split-text') text.splitText(2);
+ if (action === 'remove-text') editor.firstChild.remove();
+ if (action === 'remove-before') editor.children[1].remove();
+ endpoints(selection, range, backward, action + ':' + backward);
+ }
+ }
+ fixture.innerHTML = '<p>parent</p><iframe></iframe>';
+ selection.setBaseAndExtent(fixture.firstChild.firstChild, 1, fixture.firstChild.firstChild, 4);
+ const retained = selection.getRangeAt(0);
+ const other = fixture.lastChild.contentWindow;
+ const text = other.document.body.appendChild(other.document.createTextNode('abcdef'));
+ const childSelection = other.getSelection();
+ childSelection.setBaseAndExtent(text, 5, text, 1);
+ const childRange = childSelection.getRangeAt(0);
+ CharacterData.prototype.deleteData.call(text, 0, 2);
+ endpoints(childSelection, childRange, true, 'borrowed CharacterData mutation in child realm');
+ endpoints(selection, retained, false, 'unrelated parent selection');
+ fixture.remove();
+ return failures.join('\n');
+})()