From 0b6671ef823a61ae7ed49f2eeb44611dd1c19668 Mon Sep 17 00:00:00 2001 From: ldm0 Date: Sat, 26 Sep 2026 11:47:09 +0800 Subject: [PATCH] fix(selection): restore focused text control ranges after clearing Restore the owning Document's Selection after successful text selection setters, including unchanged cached offsets. Reuse the existing projection in the owner realm and reset the focused control's cached offsets when clearing its Document Selection. Cover parent/child realms, shadow trees, cleared/replaced ranges, argument conversion side effects, and isolated background controls. --- .../context_host/selection_records.rs | 10 ++ .../element/forms/text_control/selection.rs | 38 +++--- .../event_dispatch_and_targets.rs | 12 ++ .../text-control-selection-restoration.js | 125 ++++++++++++++++++ 4 files changed, 170 insertions(+), 15 deletions(-) create mode 100644 moli-renderer-v8/tests/fixtures/text-control-selection-restoration.js 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 85efdf83ab4..54d60aa6a2d 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 @@ -525,6 +525,16 @@ impl PageScriptHost { } pub(crate) fn clear_selection_record(&mut self, handle: SelectionRecordHandle) { + if self.selection_record_registry.has_range(handle) + && let Some(document) = self.selection_record_registry.owner_document(handle) + && let Some(control) = self.active_element_handle() + && self.dom_host().owner_document_handle(control) == Some(document) + && crate::native_bridge::element::is_text_control(self, control) + { + // A focused text control exposes the document selection, including + // its empty position. An unfocused control retains its cached range. + let _ = self.set_selection_range(control, 0, 0); + } self.selection_record_registry.clear_record(handle); } diff --git a/moli-renderer-v8/src/native_bridge/element/forms/text_control/selection.rs b/moli-renderer-v8/src/native_bridge/element/forms/text_control/selection.rs index 174917f00d5..ecbfe938361 100644 --- a/moli-renderer-v8/src/native_bridge/element/forms/text_control/selection.rs +++ b/moli-renderer-v8/src/native_bridge/element/forms/text_control/selection.rs @@ -109,14 +109,28 @@ pub(crate) fn text_control_set_selection_range_with_direction_internal( (end, end) }; let changed = runtime.set_selection_range_with_direction(handle, start, end, direction); - if runtime.active_element_handle() == Some(handle) { - runtime.note_text_control_selection(handle); + finish_text_control_selection_update(scope, runtime_ptr, handle, changed); + changed +} + +fn finish_text_control_selection_update( + scope: &mut v8::PinScope<'_, '_>, + runtime_ptr: *mut PageScriptHost, + handle: DomHandle, + changed: bool, +) { + // The control's cached offsets and the Document's Selection are separate. + // Even an unchanged setter restores a cleared/replaced Selection while the + // control is focused. Background changes must only update the cache. + if unsafe { &*runtime_ptr }.active_element_handle() == Some(handle) + && crate::context_bootstrap::focus_element_selection(scope, runtime_ptr, handle).is_some() + { + unsafe { &mut *runtime_ptr }.note_text_control_selection(handle); } if changed { queue_text_control_select_event(scope, runtime_ptr, handle); queue_text_control_selection_change_event(scope, runtime_ptr, handle); } - changed } pub(crate) fn replace_text_control_selection( @@ -523,10 +537,8 @@ pub(in crate::native_bridge) fn text_control_selection_start_setter_function<'s> }; let runtime = unsafe { &mut *runtime_ptr }; let next = clamp_text_control_offset(runtime, handle, next); - if runtime.set_selection_start(handle, next) { - queue_text_control_select_event(scope, runtime_ptr, handle); - queue_text_control_selection_change_event(scope, runtime_ptr, handle); - } + let changed = runtime.set_selection_start(handle, next); + finish_text_control_selection_update(scope, runtime_ptr, handle, changed); rv.set_undefined(); } @@ -578,10 +590,8 @@ pub(in crate::native_bridge) fn text_control_selection_end_setter_function<'s>( }; let runtime = unsafe { &mut *runtime_ptr }; let next = clamp_text_control_offset(runtime, handle, next); - if runtime.set_selection_end(handle, next) { - queue_text_control_select_event(scope, runtime_ptr, handle); - queue_text_control_selection_change_event(scope, runtime_ptr, handle); - } + let changed = runtime.set_selection_end(handle, next); + finish_text_control_selection_update(scope, runtime_ptr, handle, changed); rv.set_undefined(); } @@ -631,10 +641,8 @@ pub(in crate::native_bridge) fn text_control_selection_direction_setter_function else { return; }; - if unsafe { &mut *runtime_ptr }.set_selection_direction(handle, &direction) { - queue_text_control_select_event(scope, runtime_ptr, handle); - queue_text_control_selection_change_event(scope, runtime_ptr, handle); - } + let changed = unsafe { &mut *runtime_ptr }.set_selection_direction(handle, &direction); + finish_text_control_selection_update(scope, runtime_ptr, handle, changed); rv.set_undefined(); } 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 64e1f56ec45..7800893596f 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 @@ -1804,3 +1804,15 @@ fn selection_shadow_direction_and_composed_boundaries_follow_native_mutations() "" ); } + +#[test] +fn text_control_selection_setters_restore_the_focused_document_selection() { + let mut vm = new_storage_test_vm("https://text-control-selection-restoration.test/"); + assert_eq!( + vm.eval(include_str!( + "../../../../../tests/fixtures/text-control-selection-restoration.js" + )) + .expect("text control selection updates should restore only their focused document"), + "" + ); +} diff --git a/moli-renderer-v8/tests/fixtures/text-control-selection-restoration.js b/moli-renderer-v8/tests/fixtures/text-control-selection-restoration.js new file mode 100644 index 00000000000..aaafb1c0d99 --- /dev/null +++ b/moli-renderer-v8/tests/fixtures/text-control-selection-restoration.js @@ -0,0 +1,125 @@ +(() => { + 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 frame = fixture.appendChild(document.createElement('iframe')); + const other = frame.contentWindow; + const otherRoot = other.document.documentElement || other.document.appendChild(other.document.createElement('html')); + const otherBody = other.document.body || otherRoot.appendChild(other.document.createElement('body')); + const failures = []; + const check = (condition, label) => { if (!condition) failures.push(label); }; + const at = (range, node, start, end = start) => range.startContainer === node && + range.startOffset === start && range.endContainer === node && range.endOffset === end; + const roots = [window, other].map(owner => { + const holder = (owner === window ? fixture : otherBody).appendChild(owner.document.createElement('div')); + const button = holder.appendChild(owner.document.createElement('button')); + const text = holder.appendChild(owner.document.createTextNode('document text')); + return {owner, holder, button, text, selection: owner.getSelection()}; + }); + const methods = ['setSelectionRange', 'selectionStart', 'selectionEnd', 'selectionDirection', 'select']; + for (const state of roots) for (const caller of [window, other]) { + const {owner, holder, button, text, selection} = state; + const unrelated = roots.find(entry => entry !== state); + for (const tag of ['text', 'textarea']) { + for (const mode of ['light', 'open', 'closed']) { + const box = holder.appendChild(owner.document.createElement('div')); + const parent = mode === 'light' ? box : box.appendChild(owner.document.createElement('div')).attachShadow({mode}); + const control = parent.appendChild(owner.document.createElement(tag === 'textarea' ? 'textarea' : 'input')); + if (tag !== 'textarea') control.type = tag; + control.value = 'A😀BC'; + const proto = tag === 'textarea' ? caller.HTMLTextAreaElement.prototype : caller.HTMLInputElement.prototype; + const invoke = (name, value) => { + if (name === 'setSelectionRange') proto[name].call(control, 1, 3, 'backward'); + else if (name === 'select') proto[name].call(control); + else Object.getOwnPropertyDescriptor(proto, name).set.call(control, value); + }; + for (const method of methods) for (const clear of ['removeAllRanges', 'empty', 'removeRange', 'collapse', 'superseded']) { + const label = [owner === window ? 'parent' : 'child', caller === window ? 'parent' : 'child', tag, mode, method, clear].join(':'); + button.focus(); + control.focus(); + control.setSelectionRange(1, 3, 'backward'); + const original = selection.getRangeAt(0); + unrelated.selection.setBaseAndExtent(unrelated.text, 0, unrelated.text, 13); + const untouched = unrelated.selection.getRangeAt(0); + if (clear === 'superseded') selection.setBaseAndExtent(text, 0, text, 13); + else if (clear === 'removeRange') caller.Selection.prototype.removeRange.call(selection, original); + else if (clear === 'collapse') caller.Selection.prototype.collapse.call(selection, null); + else caller.Selection.prototype[clear].call(selection); + if (clear !== 'superseded') { + check(selection.rangeCount === 0, label + ': selection cleared'); + check(control.selectionStart === 0 && control.selectionEnd === 0, label + ': focused offsets cleared'); + } + invoke(method, method === 'selectionDirection' ? 'backward' : method === 'selectionStart' ? 0 : 3); + check(selection.rangeCount === 1, label + ': projection restored'); + if (selection.rangeCount) { + check(at(selection.getRangeAt(0), box, 0), label + ': projected position'); + check(at(selection.getComposedRanges({shadowRoots: mode === 'light' ? [] : [parent]})[0], parent, 0, 1), label + ': composed position'); + } + check(at(original, box, 0), label + ': retained range unchanged'); + check(unrelated.selection.getRangeAt(0) === untouched && at(untouched, unrelated.text, 0, 13), label + ': unrelated document unchanged'); + } + for (const method of methods.filter(name => name !== 'select')) { + control.focus(); + control.setSelectionRange(1, 3, 'backward'); + button.focus(); + selection.removeAllRanges(); + check(control.selectionStart === 1 && control.selectionEnd === 3, tag + ': blurred cache retained'); + invoke(method, method === 'selectionDirection' ? 'forward' : 2); + check(selection.rangeCount === 0 && owner.document.activeElement === button, tag + ':' + method + ': background setter does not restore or focus'); + } + // Conversion can move focus. The post-conversion native state decides + // whether this control may replace the document selection. + control.focus(); + selection.removeAllRanges(); + invoke('selectionEnd', {valueOf() { button.focus(); return 4; }}); + check(selection.rangeCount === 0 && owner.document.activeElement === button, tag + ': conversion blur respected'); + control.focus(); + selection.removeAllRanges(); + const sentinel = new Error('conversion'); + let caught; + try { invoke('selectionStart', {valueOf() { throw sentinel; }}); } catch (error) { caught = error; } + check(caught === sentinel && selection.rangeCount === 0, tag + ': failed conversion keeps selection empty'); + box.remove(); + } + } + } + const {holder, selection, button, text} = roots[0]; + const control = holder.appendChild(document.createElement('input')); + control.value = 'abcdef'; + control.focus(); + control.setSelectionRange(1, 4, 'backward'); + selection.removeAllRanges(); + let calls = 0; + const forbidden = () => { calls++; throw new Error('author hook'); }; + const originalCreateRange = document.createRange, originalGetSelection = window.getSelection; + const originalCollapse = Selection.prototype.collapse; + try { + document.createRange = forbidden; + window.getSelection = forbidden; + Selection.prototype.collapse = forbidden; + for (const key of ['ownerDocument', 'parentNode', 'selectionStart', 'selectionEnd']) { + Object.defineProperty(control, key, {configurable: true, get: forbidden}); + } + control.setSelectionRange(1, 4); + check(calls === 0 && selection.rangeCount === 1, 'restoration ignores author relationship and selection getters'); + } finally { + document.createRange = originalCreateRange; + window.getSelection = originalGetSelection; + Selection.prototype.collapse = originalCollapse; + for (const key of ['ownerDocument', 'parentNode', 'selectionStart', 'selectionEnd']) delete control[key]; + } + button.focus(); + selection.setBaseAndExtent(text, 0, text, 13); + const untouched = selection.getRangeAt(0); + for (const location of ['fragment', 'windowless']) { + const doc = location === 'windowless' ? document.implementation.createHTMLDocument('') : document; + const input = doc.createElement('input'); + input.value = 'abcdef'; + (location === 'windowless' ? doc.body : doc.createDocumentFragment()).appendChild(input); + input.setSelectionRange(1, 4); + input.selectionEnd = 3; + check(selection.getRangeAt(0) === untouched && at(untouched, text, 0, 13), location + ': setter retains live document selection'); + } + fixture.remove(); + return failures.join('\n'); +})()