diff --git a/Cargo.lock b/Cargo.lock index 5a5b62d8964..a274452b717 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3431,6 +3431,7 @@ dependencies = [ "html5ever 0.40.1", "http", "httpdate", + "icu_segmenter", "idna", "indexmap", "kurbo", diff --git a/moli-dom/src/forms/mod.rs b/moli-dom/src/forms/mod.rs index 9d035bd5158..25dda94c285 100644 --- a/moli-dom/src/forms/mod.rs +++ b/moli-dom/src/forms/mod.rs @@ -40,7 +40,7 @@ pub use option::{ }; pub use text::{ apply_textarea_wrapping_transformation, normalize_custom_validation_message, - normalize_form_submission_newlines, parse_html_integer_prefix, + normalize_form_submission_newlines, normalize_textarea_api_value, parse_html_integer_prefix, parse_non_negative_integer_prefix, parse_non_negative_length_attribute, parse_positive_integer_prefix, text_control_suffers_too_long, text_control_suffers_too_short, text_control_value_length, diff --git a/moli-dom/src/forms/text.rs b/moli-dom/src/forms/text.rs index 7e80b36da50..891f112a63a 100644 --- a/moli-dom/src/forms/text.rs +++ b/moli-dom/src/forms/text.rs @@ -1,3 +1,19 @@ +pub fn normalize_textarea_api_value(value: &str) -> String { + let mut output = String::with_capacity(value.len()); + let mut chars = value.chars().peekable(); + while let Some(ch) = chars.next() { + if ch == '\r' { + if chars.peek() == Some(&'\n') { + let _ = chars.next(); + } + output.push('\n'); + } else { + output.push(ch); + } + } + output +} + pub fn normalize_custom_validation_message(message: &str) -> String { message.replace("\r\n", "\n").replace('\r', "\n") } diff --git a/moli-dom/src/native/host.rs b/moli-dom/src/native/host.rs index 05f9d5bde92..6076d40f609 100644 --- a/moli-dom/src/native/host.rs +++ b/moli-dom/src/native/host.rs @@ -36,8 +36,8 @@ pub use self::mutation::{ DomMutationRecord, DomMutationRecordBatch, DomMutationRecordKind, DomScriptMutationEffects, DomSlotAssignmentChange, DomSlotMutationEffects, DomStyleInvalidationInputs, DomStylesheetOwnerChange, DomStylesheetOwnerChangeKind, DomStylesheetOwnerTransitions, - DomStylesheetOwnerTreeScopes, DomTreeMutationEffects, ScriptPrepareTrigger, - ScriptPrepareTriggerKind, + DomStylesheetOwnerTreeScopes, DomTextareaValueChange, DomTreeMutationEffects, + ScriptPrepareTrigger, ScriptPrepareTriggerKind, }; use self::query_index::ElementQueryIndex; diff --git a/moli-dom/src/native/host/mutation.rs b/moli-dom/src/native/host/mutation.rs index 049211090d7..12536f78ca8 100644 --- a/moli-dom/src/native/host/mutation.rs +++ b/moli-dom/src/native/host/mutation.rs @@ -4,6 +4,7 @@ mod attributes; mod effects; mod owner_lifecycle; mod state; +mod text_control; mod tree; pub use effects::{ @@ -11,8 +12,8 @@ pub use effects::{ DomMutationRecord, DomMutationRecordBatch, DomMutationRecordKind, DomScriptMutationEffects, DomSlotAssignmentChange, DomSlotMutationEffects, DomStyleInvalidationInputs, DomStylesheetOwnerChange, DomStylesheetOwnerChangeKind, DomStylesheetOwnerTransitions, - DomStylesheetOwnerTreeScopes, DomTreeMutationEffects, ScriptPrepareTrigger, - ScriptPrepareTriggerKind, + DomStylesheetOwnerTreeScopes, DomTextareaValueChange, DomTreeMutationEffects, + ScriptPrepareTrigger, ScriptPrepareTriggerKind, }; impl Deref for DomHost { diff --git a/moli-dom/src/native/host/mutation/effects/mod.rs b/moli-dom/src/native/host/mutation/effects/mod.rs index 3cbc659d73b..4e00199bbf4 100644 --- a/moli-dom/src/native/host/mutation/effects/mod.rs +++ b/moli-dom/src/native/host/mutation/effects/mod.rs @@ -7,6 +7,7 @@ mod script; mod slot; mod style; mod stylesheet; +mod text_control; mod tree; pub use observer::{DomMutationRecord, DomMutationRecordBatch, DomMutationRecordKind}; @@ -17,6 +18,7 @@ pub use stylesheet::{ DomStylesheetOwnerChange, DomStylesheetOwnerChangeKind, DomStylesheetOwnerTransitions, DomStylesheetOwnerTreeScopes, }; +pub use text_control::DomTextareaValueChange; pub use tree::DomTreeMutationEffects; /// One synchronous DOM mutation result, partitioned by semantic followup @@ -31,6 +33,7 @@ pub struct DomMutationEffects { style: DomStyleInvalidationInputs, stylesheet_owners: DomStylesheetOwnerTransitions, observer_records: DomMutationRecordBatch, + textarea_values: Vec, } /// Result of an attribute operation that shares the captured pre-mutation @@ -99,6 +102,10 @@ impl DomMutationEffects { &self.observer_records } + pub fn textarea_values(&self) -> &[DomTextareaValueChange] { + &self.textarea_values + } + pub fn coalesce_child_list_replacement( &mut self, target: DomHandle, @@ -194,6 +201,7 @@ impl DomMutationEffects { self.style.merge(other.style); self.stylesheet_owners.merge(other.stylesheet_owners); self.observer_records.merge(other.observer_records); + self.textarea_values.extend(other.textarea_values); } } diff --git a/moli-dom/src/native/host/mutation/effects/text_control.rs b/moli-dom/src/native/host/mutation/effects/text_control.rs new file mode 100644 index 00000000000..2a99881ee24 --- /dev/null +++ b/moli-dom/src/native/host/mutation/effects/text_control.rs @@ -0,0 +1,39 @@ +use super::{DomHandle, DomMutationEffects}; + +/// A change to a non-dirty textarea's normalized API value. These changes +/// retain intermediate lengths even when observer records are disabled or +/// coalesced: replacing all text first clamps selection to the empty value. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct DomTextareaValueChange { + target: DomHandle, + length: u32, +} + +impl DomTextareaValueChange { + pub fn target(&self) -> DomHandle { + self.target + } + + pub fn length(&self) -> u32 { + self.length + } +} + +impl DomMutationEffects { + pub(in crate::native::host::mutation) fn record_textarea_value_change( + &mut self, + target: DomHandle, + before: Option<&str>, + after: Option<&str>, + ) { + if let (Some(before), Some(after)) = (before, after) + && before != after + { + self.changed = true; + self.textarea_values.push(DomTextareaValueChange { + target, + length: after.encode_utf16().count() as u32, + }); + } + } +} diff --git a/moli-dom/src/native/host/mutation/text_control.rs b/moli-dom/src/native/host/mutation/text_control.rs new file mode 100644 index 00000000000..28787bc1725 --- /dev/null +++ b/moli-dom/src/native/host/mutation/text_control.rs @@ -0,0 +1,103 @@ +use super::*; +use crate::forms::normalize_textarea_api_value; + +impl DomHost { + pub(super) fn textarea_value_excluding_children( + &self, + parent: DomHandle, + excluded: &[DomHandle], + ) -> Option { + let element = self.node(parent)?.as_element()?; + if !element.is_html_textarea() || element.input_value_dirty() { + return None; + } + let mut value = String::new(); + for child in self.child_handles(parent) { + if excluded.contains(&child) { + continue; + } + let Some(node) = self.node(child) else { + continue; + }; + if node.is_text() || node.is_cdata_section() { + value.push_str(node.node_value().unwrap_or_default()); + } + } + Some(normalize_textarea_api_value(&value)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn host_and_textarea() -> (DomHost, DomHandle, DomHandle) { + let mut host = DomHost::from_dom(NativeDom::new_html( + url::Url::parse("https://textarea-values.test/").unwrap(), + )); + let textarea = host.create_element("textarea"); + let first = host.create_text_node("A๐Ÿ˜€"); + let last = host.create_text_node("B\nC"); + assert!(host.append_child(textarea, first)); + assert!(host.append_child(textarea, last)); + (host, textarea, first) + } + + #[test] + fn textarea_replacement_retains_intermediate_lengths_without_observer_records() { + for observe in [false, true] { + let (mut host, textarea, _) = host_and_textarea(); + host.set_mutation_observer_records_enabled(observe); + let effects = host.set_text_content_effects(textarea, "A๐Ÿ˜€B\nC"); + assert_eq!( + effects + .textarea_values() + .iter() + .map(|change| (change.target(), change.length())) + .collect::>(), + vec![(textarea, 3), (textarea, 0), (textarea, 6)], + "observer enabled: {observe}", + ); + assert_eq!(effects.observer_records().records().is_empty(), !observe); + } + } + + #[test] + fn textarea_character_data_changes_use_normalized_utf16_lengths_and_respect_dirty_values() { + for observe in [false, true] { + let (mut host, textarea, first) = host_and_textarea(); + host.set_mutation_observer_records_enabled(observe); + let effects = host.set_text_content_effects(first, "๐Ÿ˜€\r\n"); + assert_eq!(effects.textarea_values().len(), 1); + assert_eq!(effects.textarea_values()[0].length(), 6); + assert!( + host.set_text_content_effects(first, "๐Ÿ˜€\n") + .textarea_values() + .is_empty() + ); + host.set_input_value(textarea, "dirty"); + assert!( + host.set_text_content_effects(first, "replacement") + .textarea_values() + .is_empty() + ); + } + } + + #[test] + fn moving_text_retains_the_removal_length_even_when_the_final_value_is_unchanged() { + for observe in [false, true] { + let (mut host, textarea, first) = host_and_textarea(); + host.set_mutation_observer_records_enabled(observe); + let effects = host.insert_before_effects(textarea, first, Some(first)); + assert_eq!( + effects + .textarea_values() + .iter() + .map(|change| change.length()) + .collect::>(), + vec![3, 6], + ); + } + } +} diff --git a/moli-dom/src/native/host/mutation/tree.rs b/moli-dom/src/native/host/mutation/tree.rs index 7e05d233eb3..772405a4481 100644 --- a/moli-dom/src/native/host/mutation/tree.rs +++ b/moli-dom/src/native/host/mutation/tree.rs @@ -114,6 +114,7 @@ impl DomHost { .unwrap_or_default(); let previous_sibling = self.node(child).and_then(Node::prev_sibling); let next_sibling = self.node(child).and_then(Node::next_sibling); + let previous_textarea_value = self.textarea_value_excluding_children(parent, &[]); let candidate_changes = if is_atomic_move { self.dom .remove_child_preserving_state_with_stylesheet_candidate_changes(parent, child) @@ -126,6 +127,12 @@ impl DomHost { self.prune_disconnected_hovered_elements(); self.reset_parser_form_owners_after_subtree_removal(child, &parser_form_owner_resets); let mut effects = DomMutationEffects::changed(); + effects.record_textarea_value_change( + parent, + previous_textarea_value.as_deref(), + self.textarea_value_excluding_children(parent, &[]) + .as_deref(), + ); effects.extend_stylesheet_candidate_changes(candidate_changes); self.clear_popover_open_states(&removal_context.open_popovers, &mut effects); if !is_atomic_move { @@ -184,12 +191,16 @@ impl DomHost { if self.node(child).and_then(Node::parent_node) != Some(parent) { return DomMutationEffects::default(); } + let mut effects = DomMutationEffects::default(); + let value = self.textarea_value_excluding_children(parent, &[]); + let after_removal = self.textarea_value_excluding_children(parent, &[child]); + effects.record_textarea_value_change(parent, value.as_deref(), after_removal.as_deref()); + effects.record_textarea_value_change(parent, after_removal.as_deref(), value.as_deref()); if !self.mutation_records_enabled() { - return DomMutationEffects::default(); + return effects; } let previous_sibling = self.node(child).and_then(Node::prev_sibling); let next_sibling = self.node(child).and_then(Node::next_sibling); - let mut effects = DomMutationEffects::default(); effects.mark_child_list_mutation( parent, &[], @@ -384,6 +395,17 @@ impl DomHost { let inserted_shadow_slot_assignment_snapshots = self.slot_assignment_snapshots_for_inserted_shadow_tree_slots(parent, &inserted_roots); let previous_shadow_root = self.containing_shadow_root(child); + let removed_textarea_value = removal_record.as_ref().map(|(old_parent, removed, _, _)| { + ( + *old_parent, + self.textarea_value_excluding_children(*old_parent, &[]), + self.textarea_value_excluding_children(*old_parent, removed), + ) + }); + let previous_textarea_value = match &removed_textarea_value { + Some((old_parent, _, after)) if *old_parent == parent => after.clone(), + _ => self.textarea_value_excluding_children(parent, &[]), + }; let candidate_changes = if is_atomic_move { self.dom .insert_before_preserving_state_with_stylesheet_candidate_changes( @@ -464,6 +486,19 @@ impl DomHost { self.tree_insertion_effects(parent, child, &inserted_fragment_children); effects.extend_stylesheet_candidate_changes(candidate_changes); effects.extend_stylesheet_owner_changes(shadow_stylesheet_owner_changes); + if let Some((old_parent, before, after)) = removed_textarea_value { + effects.record_textarea_value_change( + old_parent, + before.as_deref(), + after.as_deref(), + ); + } + effects.record_textarea_value_change( + parent, + previous_textarea_value.as_deref(), + self.textarea_value_excluding_children(parent, &[]) + .as_deref(), + ); if single_child_was_connected_before_insert && !self.is_connected(child) { effects.mark_disconnected_root(child); if let Some((_, _, removal_context, _)) = implicit_removal_slot_state.as_ref() { @@ -702,6 +737,10 @@ impl DomHost { match node_type { NodeType::Text | NodeType::CDataSection => { + let textarea = self.parent_node(handle).and_then(|parent| { + self.textarea_value_excluding_children(parent, &[]) + .map(|value| (parent, value)) + }); let records_enabled = self.mutation_records_enabled(); let old_value = if records_enabled { self.node(handle) @@ -744,7 +783,17 @@ impl DomHost { if !changed { return DomMutationEffects::default(); } - self.text_data_mutation_effects(handle, records_enabled, old_value) + let mut effects = + self.text_data_mutation_effects(handle, records_enabled, old_value); + if let Some((parent, before)) = textarea { + effects.record_textarea_value_change( + parent, + Some(&before), + self.textarea_value_excluding_children(parent, &[]) + .as_deref(), + ); + } + effects } NodeType::Element | NodeType::DocumentFragment => { let children = self.child_handles(handle).collect::>(); diff --git a/moli-dom/src/native/mod.rs b/moli-dom/src/native/mod.rs index aee45dad346..c1e961f88f1 100644 --- a/moli-dom/src/native/mod.rs +++ b/moli-dom/src/native/mod.rs @@ -32,8 +32,9 @@ pub use host::{ DomMutationEffects, DomMutationRecord, DomMutationRecordBatch, DomMutationRecordKind, DomScriptMutationEffects, DomSlotAssignmentChange, DomSlotMutationEffects, DomStyleInvalidationInputs, DomStylesheetOwnerChange, DomStylesheetOwnerChangeKind, - DomStylesheetOwnerTransitions, DomStylesheetOwnerTreeScopes, DomTreeMutationEffects, - ScriptPrepareTrigger, ScriptPrepareTriggerKind, StylesheetCandidateTreeScopeSnapshots, + DomStylesheetOwnerTransitions, DomStylesheetOwnerTreeScopes, DomTextareaValueChange, + DomTreeMutationEffects, ScriptPrepareTrigger, ScriptPrepareTriggerKind, + StylesheetCandidateTreeScopeSnapshots, }; pub use host::{ HostElementSnapshot, ShadowRootBindingSnapshot, ShadowRootInclusion, ShadowRootInit, diff --git a/moli-renderer-v8/Cargo.toml b/moli-renderer-v8/Cargo.toml index 27381644ecb..3175491ff5a 100644 --- a/moli-renderer-v8/Cargo.toml +++ b/moli-renderer-v8/Cargo.toml @@ -34,6 +34,7 @@ encoding_rs = "0.8" euclid = "0.22" kurbo = "0.13.1" futures-util = "0.3.31" +icu_segmenter = { version = "2.1.2", default-features = false, features = ["compiled_data"] } precomputed-hash = "0.1" read-fonts = "0.41.0" percent-encoding = "2.3" diff --git a/moli-renderer-v8/src/context_bootstrap/selection.rs b/moli-renderer-v8/src/context_bootstrap/selection.rs index 08008c70f65..0a6707004fb 100644 --- a/moli-renderer-v8/src/context_bootstrap/selection.rs +++ b/moli-renderer-v8/src/context_bootstrap/selection.rs @@ -20,4 +20,5 @@ pub(super) use values::{ selection_owner_document, selection_range, selection_range_belongs_to_document, selection_range_update_states, selection_set_collapsed, selection_store, selection_store_with_composed_boundaries, selection_sync_associated_range, + selection_text_control_text, selection_type, }; diff --git a/moli-renderer-v8/src/context_bootstrap/selection/focus.rs b/moli-renderer-v8/src/context_bootstrap/selection/focus.rs index 3c243ba96a4..a80703e4ea7 100644 --- a/moli-renderer-v8/src/context_bootstrap/selection/focus.rs +++ b/moli-renderer-v8/src/context_bootstrap/selection/focus.rs @@ -6,7 +6,6 @@ use super::{ }; use crate::context_bootstrap::selection_value_for_window; use crate::document_runtime::DomHandle; -use crate::dom::forms::InputType; use crate::native_bridge::element::{ contenteditable_editing_host, queue_text_control_selection_change_event, }; @@ -20,20 +19,8 @@ pub(crate) fn focus_element_selection( target: DomHandle, ) -> Option<()> { let runtime = unsafe { &mut *runtime_ptr }; - let element = runtime.dom_host().node(target)?.as_element()?; // Picker controls have a separate focus behavior from text fields. - let text_field = element.is_html_textarea() - || (element.is_html_input() - && matches!( - element.input_type(), - InputType::Text - | InputType::Search - | InputType::Tel - | InputType::Url - | InputType::Email - | InputType::Password - | InputType::Number - )); + let text_field = runtime.text_control_has_selection_editor(target); if !text_field && contenteditable_editing_host(runtime, target) != Some(target) { return None; } diff --git a/moli-renderer-v8/src/context_bootstrap/selection/values.rs b/moli-renderer-v8/src/context_bootstrap/selection/values.rs index d7bf55dc39b..fd654377893 100644 --- a/moli-renderer-v8/src/context_bootstrap/selection/values.rs +++ b/moli-renderer-v8/src/context_bootstrap/selection/values.rs @@ -203,16 +203,25 @@ pub(in crate::context_bootstrap) fn selection_is_collapsed_internal<'s>( .unwrap_or(true) } -pub(in crate::context_bootstrap) fn selection_spans_dom_roots<'s>( +pub(in crate::context_bootstrap) fn selection_type<'s>( scope: &mut v8::PinScope<'s, '_>, selection: v8::Local<'s, v8::Object>, -) -> bool { +) -> &'static str { selection_record_handle(scope, selection) .and_then(|handle| { context_host_ptr_from_global_bridge(scope) - .map(|host_ptr| unsafe { &*host_ptr }.selection_record_spans_dom_roots(handle)) + .map(|host_ptr| unsafe { &mut *host_ptr }.selection_record_type(handle)) }) - .unwrap_or(false) + .unwrap_or("None") +} + +pub(in crate::context_bootstrap) fn selection_text_control_text<'s>( + scope: &mut v8::PinScope<'s, '_>, + selection: v8::Local<'s, v8::Object>, +) -> Option { + let handle = selection_record_handle(scope, selection)?; + let host = context_host_ptr_from_global_bridge(scope)?; + unsafe { &*host }.selection_record_text_control_text(handle) } pub(in crate::context_bootstrap) fn selection_store<'s>( diff --git a/moli-renderer-v8/src/context_bootstrap/selection_callbacks.rs b/moli-renderer-v8/src/context_bootstrap/selection_callbacks.rs index b2e58f1d9d8..e42c83a5e53 100644 --- a/moli-renderer-v8/src/context_bootstrap/selection_callbacks.rs +++ b/moli-renderer-v8/src/context_bootstrap/selection_callbacks.rs @@ -9,8 +9,8 @@ use super::selection::{ selection_composed_start_node, selection_composed_start_offset, selection_direction, selection_dispatch_change, selection_focus_node, selection_focus_offset, selection_has_range, selection_is_collapsed_internal, selection_owner_document, selection_range, - selection_range_belongs_to_document, selection_set_collapsed, selection_spans_dom_roots, - selection_store, selection_store_with_composed_boundaries, + selection_range_belongs_to_document, selection_set_collapsed, selection_store, + selection_store_with_composed_boundaries, selection_type, }; use super::selection_modify::selection_modify_target; use super::*; diff --git a/moli-renderer-v8/src/context_bootstrap/selection_callbacks/accessors.rs b/moli-renderer-v8/src/context_bootstrap/selection_callbacks/accessors.rs index 3fa1d955a91..ce75fe68091 100644 --- a/moli-renderer-v8/src/context_bootstrap/selection_callbacks/accessors.rs +++ b/moli-renderer-v8/src/context_bootstrap/selection_callbacks/accessors.rs @@ -69,15 +69,7 @@ fn selection_attribute_value<'s>( v8::Integer::new(scope, count).into() } SelectionAttribute::Type => { - let value = if !selection_has_range(scope, selection) { - "None" - } else if selection_is_collapsed_internal(scope, selection) - && !selection_spans_dom_roots(scope, selection) - { - "Caret" - } else { - "Range" - }; + let value = selection_type(scope, selection); v8str(scope, value).into() } SelectionAttribute::IsCollapsed => { diff --git a/moli-renderer-v8/src/context_bootstrap/selection_surface.rs b/moli-renderer-v8/src/context_bootstrap/selection_surface.rs index 556ed13c58b..4bb026b3c05 100644 --- a/moli-renderer-v8/src/context_bootstrap/selection_surface.rs +++ b/moli-renderer-v8/src/context_bootstrap/selection_surface.rs @@ -1,7 +1,7 @@ use super::range_algorithms::{range_clipboard_string_contents, range_selection_string_contents}; use super::selection::{ new_selection_runtime_object, selection_bind_owner_document, selection_owner_document, - selection_range, + selection_range, selection_text_control_text, }; use super::selection_callbacks::{ selection_add_range_callback, selection_attribute_getter_callback, selection_collapse_callback, @@ -153,7 +153,9 @@ fn selection_to_string_callback<'s>( rv.set(v8str(scope, "").into()); return; }; - let value = range_selection_string_contents(scope, range).unwrap_or_default(); + let value = selection_text_control_text(scope, args.this()) + .or_else(|| range_selection_string_contents(scope, range)) + .unwrap_or_default(); match v8_string(scope, &value) { Some(value) => rv.set(value.into()), None => rv.set(v8str(scope, "").into()), diff --git a/moli-renderer-v8/src/document_runtime/mutation_commands.rs b/moli-renderer-v8/src/document_runtime/mutation_commands.rs index 53586f63204..cb1bc041de1 100644 --- a/moli-renderer-v8/src/document_runtime/mutation_commands.rs +++ b/moli-renderer-v8/src/document_runtime/mutation_commands.rs @@ -362,7 +362,6 @@ impl DocumentRuntime { prepublished_removals, ); if changed { - self.reset_non_dirty_textarea_selection_after_child_list_change(handle); for root in disconnected_lifecycle_roots { if self.dom_host.is_connected(root) || custom_elements::is_shadow_including_rooted_in_document(&self.dom_host, root) @@ -408,17 +407,6 @@ impl DocumentRuntime { ) } - fn reset_non_dirty_textarea_selection_after_child_list_change(&mut self, handle: DomHandle) { - let should_reset = self - .dom_host - .node(handle) - .and_then(Node::as_element) - .is_some_and(|element| element.is_html_textarea() && !element.input_value_dirty()); - if should_reset { - let _ = self.dom_host.set_selection_range(handle, 0, 0); - } - } - pub(crate) fn split_text( &mut self, scope: &mut v8::PinScope<'_, '_>, @@ -1707,18 +1695,6 @@ impl DocumentRuntime { .set_selection_range_with_direction(handle, start, end, direction) } - pub(crate) fn set_selection_start(&mut self, handle: DomHandle, start: u32) -> bool { - self.dom_host.set_selection_start(handle, start) - } - - pub(crate) fn set_selection_end(&mut self, handle: DomHandle, end: u32) -> bool { - self.dom_host.set_selection_end(handle, end) - } - - pub(crate) fn set_selection_direction(&mut self, handle: DomHandle, direction: &str) -> bool { - self.dom_host.set_selection_direction(handle, direction) - } - pub(crate) fn set_media_paused(&mut self, handle: DomHandle, paused: bool) -> bool { self.dom_host.set_media_paused(handle, paused) } @@ -1955,6 +1931,8 @@ impl DocumentRuntime { options: RuntimeMutationOptions, prepublished_removals: Vec, ) -> RuntimeMutationApplyResult { + let changed_text_controls = + unsafe { &mut *host_ptr }.reconcile_text_control_selection_dom_mutations(&effects); self.apply_base_url_csp_mutation_steps(scope, host_ptr, &effects); let mut result = apply_runtime_mutation_effects_to_dom_host( &mut self.mutations, @@ -1967,6 +1945,7 @@ impl DocumentRuntime { effects, options, ); + result.changed_text_controls = changed_text_controls; devtools_mutations::attach_prepublished_removals( &mut result.devtools_dom_mutations, prepublished_removals, @@ -1986,6 +1965,7 @@ pub(crate) struct RuntimeMutationApplyResult { stylesheet_owner_changes: Vec, inline_style_attribute_csp_mutations: Vec, connected_style_csp_roots: Vec, + changed_text_controls: Vec<(DomHandle, bool)>, } impl RuntimeMutationApplyResult { @@ -2029,8 +2009,20 @@ pub(super) fn finish_runtime_mutation_effects( stylesheet_owner_changes, inline_style_attribute_csp_mutations, connected_style_csp_roots, + changed_text_controls, } = result; + for (control, selection_changed) in changed_text_controls { + crate::native_bridge::element::restore_focused_text_control_selection( + scope, host_ptr, control, + ); + if selection_changed || unsafe { &*host_ptr }.active_element_handle() == Some(control) { + crate::native_bridge::element::queue_text_control_selection_change_event( + scope, host_ptr, control, + ); + } + } + runtime.queue_devtools_dom_mutations(devtools_dom_mutations); if !document_followups_deferred_to_parser_owner { @@ -2410,6 +2402,7 @@ pub(super) fn prepare_runtime_mutation_effects( stylesheet_owner_changes, inline_style_attribute_csp_mutations, connected_style_csp_roots, + changed_text_controls: Vec::new(), } } diff --git a/moli-renderer-v8/src/document_runtime/mutation_commands/tree/insertion_followups.rs b/moli-renderer-v8/src/document_runtime/mutation_commands/tree/insertion_followups.rs index 29463e665e3..80c9a824807 100644 --- a/moli-renderer-v8/src/document_runtime/mutation_commands/tree/insertion_followups.rs +++ b/moli-renderer-v8/src/document_runtime/mutation_commands/tree/insertion_followups.rs @@ -57,7 +57,6 @@ impl DocumentRuntime { host_ptr: *mut PageScriptHost, insertion_plan: &TreeInsertionPlan<'_>, ) { - self.reset_non_dirty_textarea_selection_after_child_list_change(insertion_plan.parent); if let Some(live_range_plan) = insertion_plan.live_range_plan.as_ref() { self.apply_live_range_pre_insert_plan(scope, host_ptr, live_range_plan); apply_live_ranges_child_insertion( diff --git a/moli-renderer-v8/src/document_runtime/mutation_commands/tree/parser.rs b/moli-renderer-v8/src/document_runtime/mutation_commands/tree/parser.rs index 49474cde489..9aa89cc119c 100644 --- a/moli-renderer-v8/src/document_runtime/mutation_commands/tree/parser.rs +++ b/moli-renderer-v8/src/document_runtime/mutation_commands/tree/parser.rs @@ -177,8 +177,10 @@ impl DocumentRuntime { ); } self.assert_active_parser_document_incarnation(); + let changed_text_controls = + unsafe { &mut *host_ptr }.reconcile_text_control_selection_dom_mutations(&effects); self.apply_base_url_csp_mutation_steps(scope, host_ptr, &effects); - let result = { + let mut result = { let dom_host = self.dom_host.borrow_mut(); apply_runtime_mutation_effects_to_dom_host( &mut self.mutations, @@ -192,6 +194,7 @@ impl DocumentRuntime { mutation_options, ) }; + result.changed_text_controls = changed_text_controls; let changed = finish_runtime_mutation_effects(self, scope, host_ptr, result); if !changed { return; @@ -358,8 +361,10 @@ impl DocumentRuntime { let effects = self.parser_remove_child_effects_in_structural_scope(parent, child); self.apply_tree_removal_node_iterator_plan_if_changed(host_ptr, &removal_plan, &effects); self.assert_active_parser_document_incarnation(); + let changed_text_controls = + unsafe { &mut *host_ptr }.reconcile_text_control_selection_dom_mutations(&effects); self.apply_base_url_csp_mutation_steps(scope, host_ptr, &effects); - let result = { + let mut result = { let dom_host = self.dom_host.borrow_mut(); apply_runtime_mutation_effects_to_dom_host( &mut self.mutations, @@ -373,6 +378,7 @@ impl DocumentRuntime { mutation_options, ) }; + result.changed_text_controls = changed_text_controls; let changed = finish_runtime_mutation_effects(self, scope, host_ptr, result); if changed { self.dispatch_tree_removal_side_effects_after_change( diff --git a/moli-renderer-v8/src/document_runtime/mutation_commands/tree/removal_followups.rs b/moli-renderer-v8/src/document_runtime/mutation_commands/tree/removal_followups.rs index c372e39cc39..c9e94edf9ae 100644 --- a/moli-renderer-v8/src/document_runtime/mutation_commands/tree/removal_followups.rs +++ b/moli-renderer-v8/src/document_runtime/mutation_commands/tree/removal_followups.rs @@ -59,7 +59,6 @@ impl DocumentRuntime { host_ptr: *mut PageScriptHost, removal_plan: &TreeRemovalPlan, ) { - self.reset_non_dirty_textarea_selection_after_child_list_change(removal_plan.parent); if let Some(removal_index) = removal_plan.live_range_removal_index { context_bootstrap::live_ranges_child_removal( scope, diff --git a/moli-renderer-v8/src/document_runtime/mutation_commands/tree/replacement.rs b/moli-renderer-v8/src/document_runtime/mutation_commands/tree/replacement.rs index 968cacf50ed..c5659c2e3b1 100644 --- a/moli-renderer-v8/src/document_runtime/mutation_commands/tree/replacement.rs +++ b/moli-renderer-v8/src/document_runtime/mutation_commands/tree/replacement.rs @@ -139,102 +139,82 @@ impl DocumentRuntime { inserted_was_connected, ); let removal_plan = self.tree_removal_plan(host_ptr, parent, old_child); - let (inserted, removed, prepublished_removals) = if unsafe { &*host_ptr } - .has_dom_debugger_dom_breakpoints() - { - // Blink's replace algorithm removes an attached non-fragment new - // child first, removes oldChild second, then drains a fragment (if - // present) before the single WillInsertDOMNode probe. - let reference_child = self - .dom_host - .node(old_child) - .and_then(Node::next_sibling) - .and_then(|next| { - if next == new_child { - self.dom_host.node(new_child).and_then(Node::next_sibling) - } else { - Some(next) - } - }); - let lifecycle_connected_before = insertion_plan - .insertion_roots - .iter() - .copied() - .filter(|root| self.is_custom_element_lifecycle_connected(*root)) - .collect::>(); - let mut inserted = crate::dom::native::DomMutationEffects::default(); - let mut prepublished_removals = Vec::new(); - if fragment_children.is_none() - && !self.remove_tree_insertion_roots_with_dom_debugger( - host_ptr, - insertion_plan.insertion_roots, - &mut inserted, - &mut prepublished_removals, - false, - ) - { - return false; - } - - prepublished_removals.extend( - self.break_on_dom_debugger_before_tree_removal(host_ptr, parent, old_child), - ); - let removed = self.remove_child_effects_in_structural_scope(parent, old_child); - if !removed.did_change() { - return false; - } - - if fragment_children.is_some() - && !self.remove_tree_insertion_roots_with_dom_debugger( - host_ptr, - insertion_plan.insertion_roots, - &mut inserted, - &mut prepublished_removals, - false, - ) - { - return false; - } - if !insertion_plan.insertion_roots.is_empty() { - unsafe { &mut *host_ptr }.break_on_dom_debugger_will_insert_dom_node(parent); - for &root in insertion_plan.insertion_roots { - let root_effects = self.insert_before_effects_in_structural_scope( - parent, - root, - reference_child, - ); - if !root_effects.did_change() { - return false; - } - inserted.merge(root_effects); + // DOM replacement removes an attached new node, then oldChild, then + // inserts the replacement. The intermediate values are observable in + // text-control selections even without a DOM debugger breakpoint. + let reference_child = self + .dom_host + .node(old_child) + .and_then(Node::next_sibling) + .and_then(|next| { + if next == new_child { + self.dom_host.node(new_child).and_then(Node::next_sibling) + } else { + Some(next) } - self.finish_split_tree_insertion_effects( - parent, - new_child, - insertion_plan.insertion_roots, - &lifecycle_connected_before, - &mut inserted, - ); - } - (inserted, removed, prepublished_removals) - } else { - let inserted = - self.insert_before_effects_in_structural_scope(parent, new_child, Some(old_child)); - if !inserted.did_change() { - return false; - } - let removed = self.remove_child_effects_in_structural_scope(parent, old_child); - (inserted, removed, Vec::new()) - }; - if inserted.did_change() { - self.apply_node_iterator_pre_remove_plans(host_ptr, &insertion_plan.node_iterator_plan); + }); + let lifecycle_connected_before = insertion_plan + .insertion_roots + .iter() + .copied() + .filter(|root| self.is_custom_element_lifecycle_connected(*root)) + .collect::>(); + let mut before_removal = crate::dom::native::DomMutationEffects::default(); + let mut prepublished_removals = Vec::new(); + if fragment_children.is_none() + && !self.remove_tree_insertion_roots_with_dom_debugger( + host_ptr, + insertion_plan.insertion_roots, + &mut before_removal, + &mut prepublished_removals, + false, + ) + { + return false; } - self.apply_tree_removal_node_iterator_plan_if_changed(host_ptr, &removal_plan, &removed); + prepublished_removals + .extend(self.break_on_dom_debugger_before_tree_removal(host_ptr, parent, old_child)); + let removed = self.remove_child_effects_in_structural_scope(parent, old_child); if !removed.did_change() { return false; } - let mut effects = inserted; + let mut inserted = crate::dom::native::DomMutationEffects::default(); + if fragment_children.is_some() + && !self.remove_tree_insertion_roots_with_dom_debugger( + host_ptr, + insertion_plan.insertion_roots, + &mut inserted, + &mut prepublished_removals, + false, + ) + { + return false; + } + if !insertion_plan.insertion_roots.is_empty() { + unsafe { &mut *host_ptr }.break_on_dom_debugger_will_insert_dom_node(parent); + for &root in insertion_plan.insertion_roots { + let effects = + self.insert_before_effects_in_structural_scope(parent, root, reference_child); + if !effects.did_change() { + return false; + } + inserted.merge(effects); + } + } + if before_removal.did_change() || inserted.did_change() { + self.apply_node_iterator_pre_remove_plans(host_ptr, &insertion_plan.node_iterator_plan); + } + self.apply_tree_removal_node_iterator_plan_if_changed(host_ptr, &removal_plan, &removed); + let mut effects = before_removal; effects.merge(removed); + effects.merge(inserted); + self.finish_split_tree_insertion_effects( + parent, + new_child, + insertion_plan.insertion_roots, + &lifecycle_connected_before, + &mut effects, + ); if self.dom_host.mutation_records_enabled() { let previous_sibling = insertion_plan .insertion_roots diff --git a/moli-renderer-v8/src/native_bridge/context_host/host_environment.rs b/moli-renderer-v8/src/native_bridge/context_host/host_environment.rs index 9bdb61283bf..760fee4b486 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/host_environment.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/host_environment.rs @@ -2281,6 +2281,7 @@ impl PageScriptHost { let changed = unsafe { DocumentRuntime::set_input_value(&mut *self.document_runtime, handle, value) }; if changed { + self.reconcile_text_control_selection_value(handle); self.note_input_value_state_style_activity(handle, old_state, &container_old_states); } changed @@ -2304,6 +2305,7 @@ impl PageScriptHost { ) }; if changed { + self.reconcile_text_control_selection_value(handle); self.note_input_value_state_style_activity(handle, old_state, &container_old_states); } changed @@ -2324,6 +2326,7 @@ impl PageScriptHost { ) }; if changed { + self.reconcile_text_control_selection_value(handle); self.note_input_value_state_style_activity(handle, old_state, &container_old_states); } changed 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 54d60aa6a2d..74415a3406c 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 @@ -3,6 +3,9 @@ use super::*; use crate::dom::native::{DomHost, NodeType}; use crate::range_boundary::RangeBoundaryPoint; +mod text_control; +use text_control::SelectedTextControl; + #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub(crate) struct SelectionRecordHandle(u64); @@ -88,7 +91,7 @@ pub(super) struct SelectionRecordRegistry { records: HashMap, // A text control's selection survives focus moving to another document. // Explicit DOM Selection changes supersede it in its own document. - text_controls: HashMap, + text_controls: HashMap, } struct SelectionRecord { @@ -264,6 +267,9 @@ impl SelectionRecordRegistry { .and_then(|previous| dom.child_index(parent, previous)) .and_then(|previous_index| u32::try_from(previous_index + 1).ok()) .unwrap_or(index); + self.text_controls.retain(|_, selected| { + !shadow_including_descendant_or_self(dom, selected.control, removed_child) + }); for record in self.records.values_mut() { // Preserve the editing-host caret projection when its host is // removed across a shadow boundary. Ordinary observable endpoints @@ -505,36 +511,11 @@ impl SelectionRecord { } impl PageScriptHost { - pub(crate) fn note_text_control_selection(&mut self, control: DomHandle) { - if let Some(document) = self.dom_host().owner_document_handle(control) { - self.selection_record_registry - .text_controls - .insert(document, control); - } - } - - pub(crate) fn document_selected_text_control(&self, document: DomHandle) -> Option { - self.selection_record_registry - .text_controls - .get(&document) - .copied() - } - pub(crate) fn create_selection_record(&mut self) -> Option { self.selection_record_registry.create_record() } 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); } @@ -587,9 +568,34 @@ impl PageScriptHost { &self, handle: SelectionRecordHandle, ) -> Option<&'static str> { + if let Some(selection) = self.selection_record_text_control(handle) { + return Some(if selection.start == selection.end { + "none" + } else { + selection.direction + }); + } self.selection_record_registry.direction(handle) } + pub(crate) fn selection_record_type(&mut self, handle: SelectionRecordHandle) -> &'static str { + if !self.selection_record_registry.has_range(handle) { + "None" + } else if let Some(selection) = self.selection_record_text_control(handle) { + if selection.start == selection.end { + "Caret" + } else { + "Range" + } + } else if self.selection_record_is_collapsed(handle) + && !self.selection_record_spans_dom_roots(handle) + { + "Caret" + } else { + "Range" + } + } + pub(crate) fn selection_record_boundary( &mut self, handle: SelectionRecordHandle, diff --git a/moli-renderer-v8/src/native_bridge/context_host/selection_records/text_control.rs b/moli-renderer-v8/src/native_bridge/context_host/selection_records/text_control.rs new file mode 100644 index 00000000000..ae2bc00d433 --- /dev/null +++ b/moli-renderer-v8/src/native_bridge/context_host/selection_records/text_control.rs @@ -0,0 +1,292 @@ +use super::{PageScriptHost, SelectionDirection, SelectionRecordHandle}; +use crate::document_runtime::DomHandle; +use crate::dom::forms::InputType; +use crate::dom::native::{Element, Node}; +use crate::native_bridge::element::text_control_value; +use icu_segmenter::GraphemeClusterSegmenter; + +mod mutations; + +#[derive(Clone, Copy, PartialEq, Eq)] +pub(crate) struct TextControlSelection { + pub(crate) start: u32, + pub(crate) end: u32, + pub(crate) direction: &'static str, +} + +impl TextControlSelection { + fn cached(element: &Element) -> Self { + Self { + start: element.selection_start(), + end: element.selection_end(), + direction: match element.selection_direction() { + "backward" => "backward", + "forward" => "forward", + _ => "none", + }, + } + } + + fn caret(offset: u32) -> Self { + Self { + start: offset, + end: offset, + direction: "forward", + } + } + + fn clamp(mut self, length: u32) -> Self { + self.end = self.end.min(length); + self.start = self.start.min(self.end); + self + } +} + +pub(super) struct SelectedTextControl { + pub(super) control: DomHandle, + selection: TextControlSelection, + // This is the text underlying the Document's selection. Cached control + // offsets may change independently while the control is not focused. + value: String, +} + +impl SelectedTextControl { + fn text(&self, password: bool) -> String { + let mut result = String::new(); + let mut previous = 0; + let mut offset = 0; + for boundary in GraphemeClusterSegmenter::new() + .segment_str(&self.value) + .skip(1) + { + if offset >= self.selection.end { + break; + } + let cluster = &self.value[previous..boundary]; + if offset >= self.selection.start { + if password { + result.push('\u{2022}'); + } else { + result.push_str(cluster); + } + } + offset += cluster.encode_utf16().count() as u32; + previous = boundary; + } + result + } +} + +impl PageScriptHost { + pub(crate) fn cached_text_control_selection( + &self, + control: DomHandle, + ) -> Option { + let element = self.dom_host().node(control)?.as_element()?; + let mut selection = TextControlSelection::cached(element); + selection.direction = self.text_control_selection_direction(control, selection.direction); + Some(selection) + } + + pub(crate) fn set_text_control_selection( + &mut self, + control: DomHandle, + start: u32, + end: u32, + direction: &str, + ) -> bool { + let before = self.cached_text_control_selection(control); + let direction = self.text_control_selection_direction(control, direction); + let changed = self.set_selection_range_with_direction(control, start, end, direction); + // A real Document's default direction is already forward. Materializing + // that default in the cache must not manufacture a selectionchange. + changed + && before + != Some(TextControlSelection { + start, + end, + direction, + }) + } + + pub(crate) fn text_control_selection_direction( + &self, + control: DomHandle, + direction: &str, + ) -> &'static str { + match direction { + "backward" => "backward", + "forward" => "forward", + _ if self.owner_dispatch_scope_for_node(control).is_some() => "forward", + _ => "none", + } + } + + pub(crate) fn text_control_has_selection_editor(&self, control: DomHandle) -> bool { + self.dom_host() + .node(control) + .and_then(Node::as_element) + .is_some_and(|element| { + element.is_html_textarea() + || element.is_html_input() + && matches!( + element.input_type(), + InputType::Text + | InputType::Search + | InputType::Tel + | InputType::Url + | InputType::Email + | InputType::Password + | InputType::Number + ) + }) + } + + pub(crate) fn note_text_control_selection(&mut self, control: DomHandle) { + if !self.text_control_has_selection_editor(control) { + return; + } + let Some(document) = self.dom_host().owner_document_handle(control) else { + return; + }; + let Some(element) = self.dom_host().node(control).and_then(Node::as_element) else { + return; + }; + let mut selection = TextControlSelection::cached(element); + // Text field selections are directional even when the caller omitted + // a direction. A collapsed Document Selection still reports "none". + if selection.direction == "none" { + selection.direction = "forward"; + } + if let Some(selected) = self + .selection_record_registry + .text_controls + .get_mut(&document) + && selected.control == control + { + selected.selection = selection.clamp(selected.value.encode_utf16().count() as u32); + return; + } + let value = text_control_value(self, control); + let selection = selection.clamp(value.encode_utf16().count() as u32); + self.selection_record_registry.text_controls.insert( + document, + SelectedTextControl { + control, + selection, + value, + }, + ); + } + + pub(crate) fn document_selected_text_control(&self, document: DomHandle) -> Option { + self.selected_text_control(document) + .map(|selected| selected.control) + } + + fn selected_text_control(&self, document: DomHandle) -> Option<&SelectedTextControl> { + let selected = self + .selection_record_registry + .text_controls + .get(&document)?; + (self.dom_host().is_connected(selected.control) + && self.dom_host().owner_document_handle(selected.control) == Some(document) + && self.text_control_has_selection_editor(selected.control)) + .then_some(selected) + } + + pub(crate) fn text_control_selection( + &self, + control: DomHandle, + ) -> Option { + if self.active_element_handle() != Some(control) { + return self.cached_text_control_selection(control); + } + let document = self.dom_host().owner_document_handle(control)?; + if let Some(selected) = self.selected_text_control(document) + && selected.control == control + { + return Some(selected.selection); + } + // Focusing does not make the cached range authoritative. An explicit + // Document Selection can be empty or lie outside the focused control. + let direction = self + .selection_record_registry + .records + .values() + .find(|record| record.owner_document == Some(document)) + .map_or("forward", |record| match record.direction { + SelectionDirection::Backward => "backward", + _ => "forward", + }); + Some(TextControlSelection { + direction, + ..TextControlSelection::caret(0) + }) + } + + pub(crate) fn selection_record_text_control( + &self, + handle: SelectionRecordHandle, + ) -> Option { + let record = self.selection_record_registry.records.get(&handle)?; + if !record.has_range() { + return None; + } + Some( + self.selected_text_control(record.owner_document?)? + .selection, + ) + } + + pub(crate) fn selection_record_text_control_text( + &self, + handle: SelectionRecordHandle, + ) -> Option { + let record = self.selection_record_registry.records.get(&handle)?; + if !record.has_range() { + return None; + } + self.document_text_control_selection_text(record.owner_document?) + } + + pub(crate) fn document_text_control_selection_text( + &self, + document: DomHandle, + ) -> Option { + let selected = self.selected_text_control(document)?; + let element = self.dom_host().node(selected.control)?.as_element()?; + let password = element.is_html_input() && element.input_type() == InputType::Password; + Some(selected.text(password)) + } + + pub(crate) fn reconcile_text_control_selection_value(&mut self, control: DomHandle) { + let Some(document) = self.dom_host().owner_document_handle(control) else { + return; + }; + if !self + .selection_record_registry + .text_controls + .get(&document) + .is_some_and(|selected| selected.control == control) + { + return; + } + if !self.text_control_has_selection_editor(control) { + self.selection_record_registry + .text_controls + .remove(&document); + return; + } + let value = text_control_value(self, control); + let selected = self + .selection_record_registry + .text_controls + .get_mut(&document) + .expect("selected control checked"); + if selected.value != value { + selected.selection = TextControlSelection::caret(0); + selected.value = value; + } + } +} diff --git a/moli-renderer-v8/src/native_bridge/context_host/selection_records/text_control/mutations.rs b/moli-renderer-v8/src/native_bridge/context_host/selection_records/text_control/mutations.rs new file mode 100644 index 00000000000..e5d3136f2f2 --- /dev/null +++ b/moli-renderer-v8/src/native_bridge/context_host/selection_records/text_control/mutations.rs @@ -0,0 +1,67 @@ +use super::{PageScriptHost, TextControlSelection, text_control_value}; +use crate::document_runtime::DomHandle; +use crate::dom::native::DomMutationEffects; + +impl PageScriptHost { + pub(crate) fn reconcile_text_control_selection_dom_mutations( + &mut self, + effects: &DomMutationEffects, + ) -> Vec<(DomHandle, bool)> { + for mutation in effects.style().attribute_mutations() { + self.reconcile_text_control_selection_value(mutation.target()); + } + let mut changed = Vec::new(); + for change in effects.textarea_values() { + let control = change.target(); + let Some(selection) = self.text_control_selection(control) else { + continue; + }; + let mut selection = selection.clamp(change.length()); + selection.direction = self.text_control_selection_direction(control, "none"); + let selection_changed = self.set_text_control_selection( + control, + selection.start, + selection.end, + selection.direction, + ); + let focused = self.active_element_handle() == Some(control); + let document = self.dom_host().owner_document_handle(control); + if let Some(selected) = document + .and_then(|document| { + self.selection_record_registry + .text_controls + .get_mut(&document) + }) + .filter(|selected| selected.control == control) + { + selected.selection = if focused { + selection + } else { + TextControlSelection::caret(0) + }; + } + if let Some((_, changed_selection)) = + changed.iter_mut().find(|(handle, _)| *handle == control) + { + *changed_selection |= selection_changed; + } else { + changed.push((control, selection_changed)); + } + } + for &(control, _) in &changed { + let value = text_control_value(self, control); + let document = self.dom_host().owner_document_handle(control); + if let Some(selected) = document + .and_then(|document| { + self.selection_record_registry + .text_controls + .get_mut(&document) + }) + .filter(|selected| selected.control == control) + { + selected.value = value; + } + } + changed + } +} diff --git a/moli-renderer-v8/src/native_bridge/document/lifecycle.rs b/moli-renderer-v8/src/native_bridge/document/lifecycle.rs index 30e6d1b7187..bac7b9f3337 100644 --- a/moli-renderer-v8/src/native_bridge/document/lifecycle.rs +++ b/moli-renderer-v8/src/native_bridge/document/lifecycle.rs @@ -9,7 +9,7 @@ use crate::native_bridge::element::{ document_copy_command_supported, form_control_is_effectively_disabled, is_text_control, queue_text_control_document_selection_change_event, replace_contenteditable_selection, replace_text_control_selection, replace_text_control_selection_for_insert_html, - run_document_copy_command, text_control_value, + restore_focused_text_control_selection, run_document_copy_command, text_control_value, }; use crate::{ custom_elements, @@ -1102,12 +1102,10 @@ fn exec_command_delete_text_control( let value_units = utf16_units(&value); let value_len = value_units.len() as u32; let (start, end) = runtime - .dom_host() - .node(handle) - .and_then(|node| node.as_element()) - .map(|element| { - let start = element.selection_start().min(value_len); - let end = element.selection_end().min(value_len); + .text_control_selection(handle) + .map(|selection| { + let start = selection.start.min(value_len); + let end = selection.end.min(value_len); if start <= end { (start, end) } else { @@ -1148,9 +1146,11 @@ fn exec_command_delete_text_control( if changed { runtime.mark_text_control_change_pending(handle, &value); } + let direction = runtime.text_control_selection_direction(handle, "none"); let selection_changed = - runtime.set_selection_range_with_direction(handle, caret, caret, "none"); + runtime.set_selection_range_with_direction(handle, caret, caret, direction); if changed || selection_changed { + restore_focused_text_control_selection(scope, runtime_ptr, handle); dispatch_text_control_event(scope, runtime_ptr, handle, "input"); queue_text_control_document_selection_change_event(scope, runtime_ptr, handle); } diff --git a/moli-renderer-v8/src/native_bridge/element.rs b/moli-renderer-v8/src/native_bridge/element.rs index 11c5efa2fd6..4a38b8d89c1 100644 --- a/moli-renderer-v8/src/native_bridge/element.rs +++ b/moli-renderer-v8/src/native_bridge/element.rs @@ -331,7 +331,7 @@ pub(crate) use focus::focus_live_element_for_inspector; pub(crate) use focus::is_disabled_form_control; use focus::is_focusable; pub(crate) use focus::{ - contenteditable_editing_host, focus_element, + contenteditable_editing_host, focus_element, focus_text_control_preserving_selection, perform_access_key_default_action_for_dispatched_event, perform_hover_interest_default_action_for_dispatched_event, perform_tab_focus_default_action_for_dispatched_event, post_parse_autofocus_is_pending, @@ -451,7 +451,7 @@ pub(crate) use forms::{control_label_handles, v8_pattern_is_usable}; pub(crate) use forms::{ dispatch_text_control_event, is_text_control, queue_text_control_document_selection_change_event, queue_text_control_selection_change_event, replace_text_control_selection, - replace_text_control_selection_for_insert_html, text_control_value, + replace_text_control_selection_for_insert_html, restore_focused_text_control_selection, text_control_value, }; pub(crate) use forms::{form_control_is_effectively_disabled, input_files_for_object}; pub(in crate::native_bridge) use forms::{ diff --git a/moli-renderer-v8/src/native_bridge/element/activation/clipboard_copy.rs b/moli-renderer-v8/src/native_bridge/element/activation/clipboard_copy.rs index c590f158a6f..2e4a8dbb301 100644 --- a/moli-renderer-v8/src/native_bridge/element/activation/clipboard_copy.rs +++ b/moli-renderer-v8/src/native_bridge/element/activation/clipboard_copy.rs @@ -3,7 +3,6 @@ use crate::context_bootstrap::selection_text_for_clipboard; use crate::dom::{forms::InputType, native::Node}; use crate::native_bridge::element::*; use crate::runtime::ClipboardSnapshot; -use crate::util::utf16_units; pub(crate) fn document_copy_command_supported( runtime: &PageScriptHost, @@ -72,15 +71,12 @@ fn copy_selection_text( document: DomHandle, ) -> Option { if runtime.document_selected_text_control(document).is_some() { - let control = selected_control(runtime, document)?; - let element = runtime.dom_host().node(control)?.as_element()?; if selected_password(runtime, document) { return None; } - let units = utf16_units(&text_control_value(runtime, control)); - let start = (element.selection_start() as usize).min(units.len()); - let end = (element.selection_end() as usize).min(units.len()); - return (start < end).then(|| String::from_utf16_lossy(&units[start..end])); + return runtime + .document_text_control_selection_text(document) + .filter(|text| !text.is_empty()); } let selection = runtime.document_selection_snapshot(document)?; if selection.start == selection.end { diff --git a/moli-renderer-v8/src/native_bridge/element/focus.rs b/moli-renderer-v8/src/native_bridge/element/focus.rs index 8063e1b3e80..4a34a86831f 100644 --- a/moli-renderer-v8/src/native_bridge/element/focus.rs +++ b/moli-renderer-v8/src/native_bridge/element/focus.rs @@ -29,12 +29,6 @@ struct SequentialFocusEntry { handles: Vec, } -#[derive(Clone, Copy, PartialEq, Eq)] -enum FocusSelection { - Initialize, - Preserve, -} - #[derive(Clone, Copy, PartialEq, Eq)] enum ReadingFlowMode { SourceOrder, @@ -446,7 +440,7 @@ pub(crate) fn reset_document_navigation_focus( viewport, None, Some(document), - FocusSelection::Preserve, + SelectionBehaviorOnFocus::Preserve, ); } unsafe { &mut *runtime_ptr }.set_sequential_focus_starting_point(document, focus_target); @@ -642,7 +636,7 @@ pub(crate) fn update_focus( next, None, None, - FocusSelection::Initialize, + SelectionBehaviorOnFocus::Restore, ); } @@ -662,7 +656,34 @@ pub(crate) fn update_focus_preserving_selection( next, None, None, - FocusSelection::Preserve, + SelectionBehaviorOnFocus::Preserve, + ); +} + +#[derive(Clone, Copy)] +enum SelectionBehaviorOnFocus { + Restore, + Preserve, +} + +pub(crate) fn focus_text_control_preserving_selection( + scope: &mut v8::PinScope<'_, '_>, + runtime_ptr: *mut PageScriptHost, + target: DomHandle, +) { + let runtime = unsafe { &*runtime_ptr }; + if !is_focusable(runtime, target) { + return; + } + let previous = runtime.active_element_handle(); + update_focus_from_previous_with_previous_focus_within( + scope, + runtime_ptr, + previous, + Some(target), + None, + None, + SelectionBehaviorOnFocus::Preserve, ); } @@ -678,7 +699,7 @@ pub(crate) fn reset_focus_from_previous_handle( None, None, None, - FocusSelection::Preserve, + SelectionBehaviorOnFocus::Preserve, ); } @@ -695,7 +716,7 @@ pub(crate) fn reset_focus_from_previous_handle_with_previous_focus_within( None, Some(previous_focus_within), None, - FocusSelection::Preserve, + SelectionBehaviorOnFocus::Preserve, ); } @@ -706,7 +727,7 @@ fn update_focus_from_previous_with_previous_focus_within( next: Option, previous_focus_within: Option>, viewport_document: Option, - selection: FocusSelection, + selection_behavior: SelectionBehaviorOnFocus, ) { // A viewport has no element handle. Its Document must stay explicit: // clearing a parent's focus does not clear its inactive child's focused area. @@ -831,7 +852,9 @@ fn update_focus_from_previous_with_previous_focus_within( runtime.mark_focus_changed(previous, next); } runtime.note_focus_style_activity(None, next); - if let Some(handle) = next { + if let Some(handle) = next + && matches!(selection_behavior, SelectionBehaviorOnFocus::Restore) + { let _ = crate::context_bootstrap::focus_element_selection(scope, runtime_ptr, handle); let runtime = unsafe { &mut *runtime_ptr }; if is_text_control(runtime, handle) { diff --git a/moli-renderer-v8/src/native_bridge/element/forms.rs b/moli-renderer-v8/src/native_bridge/element/forms.rs index 24e74af9602..7b355c403c8 100644 --- a/moli-renderer-v8/src/native_bridge/element/forms.rs +++ b/moli-renderer-v8/src/native_bridge/element/forms.rs @@ -244,7 +244,7 @@ pub(crate) use self::text_control::replace_text_control_selection_after_beforein pub(crate) use self::text_control::{ dispatch_text_control_event, is_text_control, queue_text_control_document_selection_change_event, queue_text_control_selection_change_event, replace_text_control_selection, - replace_text_control_selection_for_insert_html, text_control_value, + replace_text_control_selection_for_insert_html, restore_focused_text_control_selection, text_control_value, }; #[cfg(feature = "devtools")] pub(crate) use self::text_control::{ diff --git a/moli-renderer-v8/src/native_bridge/element/forms/input/value.rs b/moli-renderer-v8/src/native_bridge/element/forms/input/value.rs index 5e5df3c82c9..df51ca9f486 100644 --- a/moli-renderer-v8/src/native_bridge/element/forms/input/value.rs +++ b/moli-renderer-v8/src/native_bridge/element/forms/input/value.rs @@ -184,6 +184,16 @@ pub(in crate::native_bridge) fn input_value_setter_function<'s>( ); return; } + set_input_value_and_selection(scope, runtime_ptr, handle, &next_value); + rv.set_undefined(); +} + +fn set_input_value_and_selection( + scope: &mut v8::PinScope<'_, '_>, + runtime_ptr: *mut PageScriptHost, + handle: DomHandle, + next_value: &str, +) { let previous_value: String = unsafe { &*runtime_ptr } .dom_host() .node(handle) @@ -191,7 +201,7 @@ pub(in crate::native_bridge) fn input_value_setter_function<'s>( .map(Element::input_value) .unwrap_or_default(); let runtime = unsafe { &mut *runtime_ptr }; - let _ = runtime.set_input_value(handle, &next_value); + let _ = runtime.set_input_value(handle, next_value); let current_value = runtime .dom_host() .node(handle) @@ -199,22 +209,30 @@ pub(in crate::native_bridge) fn input_value_setter_function<'s>( .map(Element::input_value) .unwrap_or_default(); if current_value != previous_value { - reset_input_selection_to_end(runtime, handle); + let selection_changed = reset_input_selection_to_end(runtime, handle); + if runtime.text_control_has_selection_editor(handle) { + restore_focused_text_control_selection(scope, runtime_ptr, handle); + if selection_changed || unsafe { &*runtime_ptr }.active_element_handle() == Some(handle) + { + queue_text_control_selection_change_event(scope, runtime_ptr, handle); + } + } } - rv.set_undefined(); } -fn reset_input_selection_to_end(runtime: &mut PageScriptHost, handle: DomHandle) { +fn reset_input_selection_to_end(runtime: &mut PageScriptHost, handle: DomHandle) -> bool { + if !runtime.text_control_has_selection_editor(handle) { + return false; + } let Some(end) = runtime .dom_host() .node(handle) .and_then(Node::as_element) - .filter(|element| element.input_type().supports_variable_length_selection()) .map(|element| utf16_len(&element.input_value()) as u32) else { - return; + return false; }; - let _ = runtime.set_selection_range(handle, end, end); + runtime.set_text_control_selection(handle, end, end, "none") } pub(in crate::native_bridge) fn input_value_as_number_getter_function<'s>( @@ -304,7 +322,7 @@ fn input_value_as_number_setter_on_object<'s>( } else { moli_dom::forms::input_number_to_value_string(input_type, number).unwrap_or_default() }; - let _ = runtime.set_input_value(handle, &next_value); + set_input_value_and_selection(scope, runtime_ptr, handle, &next_value); } pub(in crate::native_bridge) fn input_value_as_date_getter_function<'s>( @@ -395,7 +413,7 @@ fn input_value_as_date_setter_on_object<'s>( }; input_date_value_from_milliseconds(input_type, date.value_of()).unwrap_or_default() }; - let _ = unsafe { &mut *runtime_ptr }.set_input_value(handle, &next_value); + set_input_value_and_selection(scope, runtime_ptr, handle, &next_value); } pub(in crate::native_bridge) fn input_step_up_callback<'s>( @@ -475,8 +493,7 @@ fn input_step_by( match outcome { Ok(InputStepOutcome::Set(value)) => { - let runtime = unsafe { &mut *runtime_ptr }; - let _ = runtime.set_input_value(handle, &value); + set_input_value_and_selection(scope, runtime_ptr, handle, &value); } Ok(InputStepOutcome::NoChange) => {} Err(InputStepError::Unsupported) => { diff --git a/moli-renderer-v8/src/native_bridge/element/forms/submission.rs b/moli-renderer-v8/src/native_bridge/element/forms/submission.rs index 24bdd6059d9..ec2bc217987 100644 --- a/moli-renderer-v8/src/native_bridge/element/forms/submission.rs +++ b/moli-renderer-v8/src/native_bridge/element/forms/submission.rs @@ -487,6 +487,7 @@ pub(in crate::native_bridge) fn reset_form_default_action( }; let runtime = unsafe { &mut *runtime_ptr }; let mut did_change = false; + let mut changed_text_controls = Vec::new(); for plan in plans { match plan { FormResetPlan::InputValue { handle, value } => { @@ -494,8 +495,13 @@ pub(in crate::native_bridge) fn reset_form_default_action( did_change |= runtime.set_input_value_with_dirty(handle, &value, false); let next_value = text_control_value(runtime, handle); if next_value != previous_value { - let end = next_value.chars().count() as u32; - did_change |= runtime.dom_host_mut().set_selection_range(handle, end, end); + let end = next_value.encode_utf16().count() as u32; + let selection_changed = + runtime.set_text_control_selection(handle, end, end, "none"); + did_change |= selection_changed; + if runtime.text_control_has_selection_editor(handle) { + changed_text_controls.push((handle, selection_changed)); + } } } FormResetPlan::Checked { handle, checked } => { @@ -529,6 +535,12 @@ pub(in crate::native_bridge) fn reset_form_default_action( } } } + for (handle, selection_changed) in changed_text_controls { + restore_focused_text_control_selection(scope, runtime_ptr, handle); + if selection_changed || unsafe { &*runtime_ptr }.active_element_handle() == Some(handle) { + queue_text_control_selection_change_event(scope, runtime_ptr, handle); + } + } match callback_timing { FormAssociatedResetCallbackTiming::Sync => { crate::custom_elements::dispatch_form_reset_callbacks_for_form( diff --git a/moli-renderer-v8/src/native_bridge/element/forms/text_control.rs b/moli-renderer-v8/src/native_bridge/element/forms/text_control.rs index 44d03b0b426..81a11cd5bd8 100644 --- a/moli-renderer-v8/src/native_bridge/element/forms/text_control.rs +++ b/moli-renderer-v8/src/native_bridge/element/forms/text_control.rs @@ -16,7 +16,7 @@ pub(crate) use selection::{ text_control_set_selection_range_with_direction_internal, }; pub(crate) use selection::{ - replace_text_control_selection, replace_text_control_selection_for_insert_html, + replace_text_control_selection, replace_text_control_selection_for_insert_html, restore_focused_text_control_selection, }; pub(in crate::native_bridge) use selection::{ text_control_select_callback, text_control_selection_direction_getter_function, 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 ecbfe938361..ad3bcb03d45 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 @@ -108,7 +108,7 @@ pub(crate) fn text_control_set_selection_range_with_direction_internal( } else { (end, end) }; - let changed = runtime.set_selection_range_with_direction(handle, start, end, direction); + let changed = runtime.set_text_control_selection(handle, start, end, direction); finish_text_control_selection_update(scope, runtime_ptr, handle, changed); changed } @@ -118,6 +118,18 @@ fn finish_text_control_selection_update( runtime_ptr: *mut PageScriptHost, handle: DomHandle, changed: bool, +) { + restore_focused_text_control_selection(scope, runtime_ptr, handle); + if changed { + queue_text_control_select_event(scope, runtime_ptr, handle); + queue_text_control_selection_change_event(scope, runtime_ptr, handle); + } +} + +pub(crate) fn restore_focused_text_control_selection( + scope: &mut v8::PinScope<'_, '_>, + runtime_ptr: *mut PageScriptHost, + handle: DomHandle, ) { // The control's cached offsets and the Document's Selection are separate. // Even an unchanged setter restores a cleared/replaced Selection while the @@ -127,10 +139,6 @@ fn finish_text_control_selection_update( { 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); - } } pub(crate) fn replace_text_control_selection( @@ -290,12 +298,10 @@ fn replace_text_control_selection_with_events( let value = text_control_value(runtime, handle); let value_units = utf16_units(&value); let (start, end) = runtime - .dom_host() - .node(handle) - .and_then(Node::as_element) - .map(|element| { - let start = element.selection_start(); - let end = element.selection_end(); + .text_control_selection(handle) + .map(|selection| { + let start = selection.start; + let end = selection.end; if start <= end { (start, end) } else { @@ -474,12 +480,10 @@ fn current_selection_or_end( value_len: u32, ) -> (u32, u32) { runtime - .dom_host() - .node(handle) - .and_then(Node::as_element) - .map(|element| { - let start = element.selection_start().min(value_len); - let end = element.selection_end().min(value_len); + .text_control_selection(handle) + .map(|selection| { + let start = selection.start.min(value_len); + let end = selection.end.min(value_len); if start <= end { (start, end) } else { @@ -506,10 +510,8 @@ pub(in crate::native_bridge) fn text_control_selection_start_getter_function<'s> return; } let value = runtime - .dom_host() - .node(handle) - .and_then(Node::as_element) - .map(Element::selection_start) + .text_control_selection(handle) + .map(|selection| selection.start) .unwrap_or(0); rv.set_uint32(value); } @@ -535,10 +537,18 @@ pub(in crate::native_bridge) fn text_control_selection_start_setter_function<'s> else { return; }; - let runtime = unsafe { &mut *runtime_ptr }; + let runtime = unsafe { &*runtime_ptr }; let next = clamp_text_control_offset(runtime, handle, next); - let changed = runtime.set_selection_start(handle, next); - finish_text_control_selection_update(scope, runtime_ptr, handle, changed); + if let Some(current) = runtime.text_control_selection(handle) { + text_control_set_selection_range_with_direction_internal( + scope, + runtime_ptr, + handle, + next, + next.max(current.end), + current.direction, + ); + } rv.set_undefined(); } @@ -559,10 +569,8 @@ pub(in crate::native_bridge) fn text_control_selection_end_getter_function<'s>( return; } let value = runtime - .dom_host() - .node(handle) - .and_then(Node::as_element) - .map(Element::selection_end) + .text_control_selection(handle) + .map(|selection| selection.end) .unwrap_or(0); rv.set_uint32(value); } @@ -588,10 +596,18 @@ pub(in crate::native_bridge) fn text_control_selection_end_setter_function<'s>( else { return; }; - let runtime = unsafe { &mut *runtime_ptr }; + let runtime = unsafe { &*runtime_ptr }; let next = clamp_text_control_offset(runtime, handle, next); - let changed = runtime.set_selection_end(handle, next); - finish_text_control_selection_update(scope, runtime_ptr, handle, changed); + if let Some(current) = runtime.text_control_selection(handle) { + text_control_set_selection_range_with_direction_internal( + scope, + runtime_ptr, + handle, + current.start.min(next), + next, + current.direction, + ); + } rv.set_undefined(); } @@ -611,10 +627,8 @@ pub(in crate::native_bridge) fn text_control_selection_direction_getter_function return; } let direction = unsafe { &*runtime_ptr } - .dom_host() - .node(handle) - .and_then(Node::as_element) - .map(Element::selection_direction) + .text_control_selection(handle) + .map(|selection| selection.direction) .unwrap_or("none"); rv.set(v8str(scope, direction).into()); } @@ -641,8 +655,16 @@ pub(in crate::native_bridge) fn text_control_selection_direction_setter_function else { return; }; - let changed = unsafe { &mut *runtime_ptr }.set_selection_direction(handle, &direction); - finish_text_control_selection_update(scope, runtime_ptr, handle, changed); + if let Some(current) = unsafe { &*runtime_ptr }.text_control_selection(handle) { + text_control_set_selection_range_with_direction_internal( + scope, + runtime_ptr, + handle, + current.start, + current.end, + &direction, + ); + } rv.set_undefined(); } @@ -729,6 +751,7 @@ pub(in crate::native_bridge) fn text_control_set_range_text_callback<'s>( let runtime = unsafe { &mut *runtime_ptr }; let _ = runtime.set_input_value(handle, &next_value); + let value_changed = text_control_value(runtime, handle) != value; let replacement_end = start + replacement_len; let (next_start, next_end) = match mode { "select" => (start, replacement_end), @@ -747,6 +770,9 @@ pub(in crate::native_bridge) fn text_control_set_range_text_callback<'s>( }; let _ = text_control_set_selection_range_internal(scope, runtime_ptr, handle, next_start, next_end); + if value_changed && unsafe { &*runtime_ptr }.active_element_handle() == Some(handle) { + queue_text_control_selection_change_event(scope, runtime_ptr, handle); + } rv.set_undefined(); } @@ -781,9 +807,19 @@ pub(in crate::native_bridge) fn text_control_select_callback( rv.set_undefined(); return; }; - let len = text_control_value(unsafe { &*runtime_ptr }, handle) - .encode_utf16() - .count() as u32; - let _ = text_control_set_selection_range_internal(scope, runtime_ptr, handle, 0, len); + if unsafe { &*runtime_ptr }.text_control_has_selection_editor(handle) { + let len = text_control_value(unsafe { &*runtime_ptr }, handle) + .encode_utf16() + .count() as u32; + let _ = text_control_set_selection_range_internal(scope, runtime_ptr, handle, 0, len); + } + crate::native_bridge::element::focus_text_control_preserving_selection( + scope, + runtime_ptr, + handle, + ); + // Focus listeners may redirect focus, replace the value, or set a different + // cached selection. Restore only the state left by those listeners. + restore_focused_text_control_selection(scope, runtime_ptr, handle); rv.set_undefined(); } diff --git a/moli-renderer-v8/src/native_bridge/element/forms/text_control/value.rs b/moli-renderer-v8/src/native_bridge/element/forms/text_control/value.rs index 34d3ef3d146..cf3bc404c36 100644 --- a/moli-renderer-v8/src/native_bridge/element/forms/text_control/value.rs +++ b/moli-renderer-v8/src/native_bridge/element/forms/text_control/value.rs @@ -1,6 +1,7 @@ use super::*; use crate::native_bridge::document::detached_native_handle_for_runtime; use crate::util::utf16_len; +pub(in crate::native_bridge) use moli_dom::forms::normalize_textarea_api_value; pub(crate) fn text_control_value(runtime: &PageScriptHost, handle: DomHandle) -> String { let Some(element) = runtime.dom_host().node(handle).and_then(Node::as_element) else { @@ -19,22 +20,6 @@ pub(crate) fn text_control_value(runtime: &PageScriptHost, handle: DomHandle) -> String::new() } -pub(in crate::native_bridge) fn normalize_textarea_api_value(value: &str) -> String { - let mut output = String::with_capacity(value.len()); - let mut chars = value.chars().peekable(); - while let Some(ch) = chars.next() { - if ch == '\r' { - if chars.peek() == Some(&'\n') { - let _ = chars.next(); - } - output.push('\n'); - } else { - output.push(ch); - } - } - output -} - pub(super) fn clamp_text_control_offset( runtime: &PageScriptHost, handle: DomHandle, @@ -144,7 +129,11 @@ pub(in crate::native_bridge) fn textarea_value_setter_function<'s>( let current_value = text_control_value(runtime, handle); if current_value != previous_value { let end = utf16_len(¤t_value) as u32; - let _ = runtime.set_selection_range(handle, end, end); + let selection_changed = runtime.set_text_control_selection(handle, end, end, "none"); + restore_focused_text_control_selection(scope, runtime_ptr, handle); + if selection_changed || unsafe { &*runtime_ptr }.active_element_handle() == Some(handle) { + queue_text_control_selection_change_event(scope, runtime_ptr, handle); + } } rv.set_undefined(); } diff --git a/moli-renderer-v8/src/runtime/page_vm/tests/user_interaction.rs b/moli-renderer-v8/src/runtime/page_vm/tests/user_interaction.rs index ed9798bfbcb..2f94d34a5b0 100644 --- a/moli-renderer-v8/src/runtime/page_vm/tests/user_interaction.rs +++ b/moli-renderer-v8/src/runtime/page_vm/tests/user_interaction.rs @@ -548,12 +548,14 @@ getSelection().collapse(text, 1); !page_vm.vm().has_ready_timeout(), "user-interaction tasks must not acquire PageTimer descriptors" ); + // The value setter already queued selectionchange before the range + // setter queues select; later selection changes coalesce with it. let expected_after_each_turn = [ - "input:select|microtask:select", - "input:select|microtask:select|input:selectionchange|microtask:selectionchange", - "input:select|microtask:select|input:selectionchange|microtask:selectionchange|data-transfer:alpha|microtask:data-transfer", - "input:select|microtask:select|input:selectionchange|microtask:selectionchange|data-transfer:alpha|microtask:data-transfer|dialog:close|microtask:close", - "input:select|microtask:select|input:selectionchange|microtask:selectionchange|data-transfer:alpha|microtask:data-transfer|dialog:close|microtask:close|document:selectionchange|microtask:document", + "input:selectionchange|microtask:selectionchange", + "input:selectionchange|microtask:selectionchange|input:select|microtask:select", + "input:selectionchange|microtask:selectionchange|input:select|microtask:select|data-transfer:alpha|microtask:data-transfer", + "input:selectionchange|microtask:selectionchange|input:select|microtask:select|data-transfer:alpha|microtask:data-transfer|dialog:close|microtask:close", + "input:selectionchange|microtask:selectionchange|input:select|microtask:select|data-transfer:alpha|microtask:data-transfer|dialog:close|microtask:close|document:selectionchange|microtask:document", ]; for expected in expected_after_each_turn { assert!( 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 873a1bc48b0..e188d07a61b 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 @@ -2433,167 +2433,7 @@ JSON.stringify(window.parserSelectionStates) ); })); } -#[test] -fn parser_textarea_child_list_mutations_reset_selection_like_js() { - let runtime = tokio::runtime::Builder::new_current_thread() - .enable_all() - .build() - .expect("current-thread runtime should build"); - runtime.block_on(tokio::task::LocalSet::new().run_until(async move { - let mut page_vm = new_phase_one_page_vm_for_test(); - create_connected_html_body_for_test(&mut page_vm); - - page_vm - .evaluate_expression( - r#" -window.parserTextareaSelectionStates = {}; -function textareaState(textarea) { - return { - value: textarea.value, - text: textarea.textContent, - start: textarea.selectionStart, - end: textarea.selectionEnd - }; -} -function makeTextarea(id, text, start, end) { - const textarea = document.createElement('textarea'); - textarea.id = id; - textarea.textContent = text; - document.body.appendChild(textarea); - textarea.setSelectionRange(start, end); - return textarea; -} - -const jsAppend = makeTextarea('js-textarea-append', 'abc', 2, 3); -const parserAppend = makeTextarea('parser-textarea-append', 'abc', 2, 3); -jsAppend.appendChild(document.createTextNode('d')); -window.parserTextareaSelectionStates.jsAppend = textareaState(jsAppend); - -const jsBefore = makeTextarea('js-textarea-before', 'bc', 1, 2); -const parserBefore = makeTextarea('parser-textarea-before', 'bc', 1, 2); -jsBefore.insertBefore(document.createTextNode('a'), jsBefore.firstChild); -window.parserTextareaSelectionStates.jsInsertBefore = textareaState(jsBefore); - -const jsRemove = makeTextarea('js-textarea-remove', 'abc', 2, 3); -const parserRemove = makeTextarea('parser-textarea-remove', 'abc', 2, 3); -jsRemove.removeChild(jsRemove.firstChild); -window.parserTextareaSelectionStates.jsRemove = textareaState(jsRemove); -"#, - ) - .expect("textarea selection setup should evaluate"); - - let (parser_append, parser_before, parser_remove) = { - let runtime = &page_vm.vm().document_runtime; - ( - runtime - .get_element_by_id("parser-textarea-append") - .expect("parser append textarea should exist"), - runtime - .get_element_by_id("parser-textarea-before") - .expect("parser insertBefore textarea should exist"), - runtime - .get_element_by_id("parser-textarea-remove") - .expect("parser remove textarea should exist"), - ) - }; - let (parser_before_reference, parser_remove_child) = { - let dom_host = page_vm.vm().document_runtime.dom_host(); - ( - dom_host - .child_handles(parser_before) - .next() - .expect("parser insertBefore textarea should have a text child"), - dom_host - .child_handles(parser_remove) - .next() - .expect("parser remove textarea should have a text child"), - ) - }; - - let (parser_append_text, parser_before_text) = { - let dom_host = page_vm.vm_mut().document_runtime.dom_host_mut(); - ( - dom_host.create_text_node("d"), - dom_host.create_text_node("a"), - ) - }; - - let append_reaction_roots = apply_parser_dom_mutation_for_test( - &mut page_vm, - ParserDomMutation::AppendChild { - parent: parser_append, - child: parser_append_text, - }, - "parser textarea append should apply", - ); - assert!( - append_reaction_roots.is_empty(), - "plain textarea text append should not queue custom element reactions" - ); - let before_reaction_roots = apply_parser_dom_mutation_for_test( - &mut page_vm, - ParserDomMutation::InsertBefore { - parent: parser_before, - child: parser_before_text, - reference_child: Some(parser_before_reference), - }, - "parser textarea insertBefore should apply", - ); - assert!( - before_reaction_roots.is_empty(), - "plain textarea text insertBefore should not queue custom element reactions" - ); - let remove_reaction_roots = apply_parser_dom_mutation_for_test( - &mut page_vm, - ParserDomMutation::RemoveChild { - parent: parser_remove, - child: parser_remove_child, - }, - "parser textarea remove should apply", - ); - if !remove_reaction_roots.is_empty() { - page_vm - .vm_mut() - .queue_and_run_pending_parser_post_step_runtime_work_in_default_context_for_test(remove_reaction_roots) - .expect("parser textarea remove followups should dispatch"); - } - - let result = page_vm - .evaluate_expression( - r#" -window.parserTextareaSelectionStates.parserAppend = - textareaState(document.getElementById('parser-textarea-append')); -window.parserTextareaSelectionStates.parserInsertBefore = - textareaState(document.getElementById('parser-textarea-before')); -window.parserTextareaSelectionStates.parserRemove = - textareaState(document.getElementById('parser-textarea-remove')); -JSON.stringify({ - jsAppend: window.parserTextareaSelectionStates.jsAppend, - parserAppend: window.parserTextareaSelectionStates.parserAppend, - appendSame: JSON.stringify(window.parserTextareaSelectionStates.jsAppend) === - JSON.stringify(window.parserTextareaSelectionStates.parserAppend), - jsInsertBefore: window.parserTextareaSelectionStates.jsInsertBefore, - parserInsertBefore: window.parserTextareaSelectionStates.parserInsertBefore, - insertBeforeSame: JSON.stringify(window.parserTextareaSelectionStates.jsInsertBefore) === - JSON.stringify(window.parserTextareaSelectionStates.parserInsertBefore), - jsRemove: window.parserTextareaSelectionStates.jsRemove, - parserRemove: window.parserTextareaSelectionStates.parserRemove, - removeSame: JSON.stringify(window.parserTextareaSelectionStates.jsRemove) === - JSON.stringify(window.parserTextareaSelectionStates.parserRemove) -}) -"#, - ) - .expect("textarea selection result should evaluate"); - assert_eq!( - result.get("value").and_then(serde_json::Value::as_str), - Some( - r#"{"jsAppend":{"value":"abcd","text":"abcd","start":0,"end":0},"parserAppend":{"value":"abcd","text":"abcd","start":0,"end":0},"appendSame":true,"jsInsertBefore":{"value":"abc","text":"abc","start":0,"end":0},"parserInsertBefore":{"value":"abc","text":"abc","start":0,"end":0},"insertBeforeSame":true,"jsRemove":{"value":"","text":"","start":0,"end":0},"parserRemove":{"value":"","text":"","start":0,"end":0},"removeSame":true}"# - ), - "parser textarea append/insertBefore/remove should reset non-dirty selection like JS child-list mutations" - ); - })); -} #[test] fn parser_inserted_nonce_attribute_is_hidden_like_js_insertion() { let runtime = tokio::runtime::Builder::new_current_thread() @@ -2970,3 +2810,165 @@ JSON.stringify({ ); })); } + +#[test] +fn parser_textarea_child_list_mutations_adjust_selection_like_js() { + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .expect("current-thread runtime should build"); + + runtime.block_on(tokio::task::LocalSet::new().run_until(async move { + let mut page_vm = new_phase_one_page_vm_for_test(); + create_connected_html_body_for_test(&mut page_vm); + + page_vm + .evaluate_expression( + r#" +window.parserTextareaSelectionStates = {}; +function textareaState(textarea) { + return { + value: textarea.value, + text: textarea.textContent, + start: textarea.selectionStart, + end: textarea.selectionEnd + }; +} +function makeTextarea(id, text, start, end) { + const textarea = document.createElement('textarea'); + textarea.id = id; + textarea.textContent = text; + document.body.appendChild(textarea); + textarea.setSelectionRange(start, end); + return textarea; +} + +const jsAppend = makeTextarea('js-textarea-append', 'abc', 2, 3); +const parserAppend = makeTextarea('parser-textarea-append', 'abc', 2, 3); +jsAppend.appendChild(document.createTextNode('d')); +window.parserTextareaSelectionStates.jsAppend = textareaState(jsAppend); + +const jsBefore = makeTextarea('js-textarea-before', 'bc', 1, 2); +const parserBefore = makeTextarea('parser-textarea-before', 'bc', 1, 2); +jsBefore.insertBefore(document.createTextNode('a'), jsBefore.firstChild); +window.parserTextareaSelectionStates.jsInsertBefore = textareaState(jsBefore); + +const jsRemove = makeTextarea('js-textarea-remove', 'abc', 2, 3); +const parserRemove = makeTextarea('parser-textarea-remove', 'abc', 2, 3); +jsRemove.removeChild(jsRemove.firstChild); +window.parserTextareaSelectionStates.jsRemove = textareaState(jsRemove); +"#, + ) + .expect("textarea selection setup should evaluate"); + + let (parser_append, parser_before, parser_remove) = { + let runtime = &page_vm.vm().document_runtime; + ( + runtime + .get_element_by_id("parser-textarea-append") + .expect("parser append textarea should exist"), + runtime + .get_element_by_id("parser-textarea-before") + .expect("parser insertBefore textarea should exist"), + runtime + .get_element_by_id("parser-textarea-remove") + .expect("parser remove textarea should exist"), + ) + }; + let (parser_before_reference, parser_remove_child) = { + let dom_host = page_vm.vm().document_runtime.dom_host(); + ( + dom_host + .child_handles(parser_before) + .next() + .expect("parser insertBefore textarea should have a text child"), + dom_host + .child_handles(parser_remove) + .next() + .expect("parser remove textarea should have a text child"), + ) + }; + + let (parser_append_text, parser_before_text) = { + let dom_host = page_vm.vm_mut().document_runtime.dom_host_mut(); + ( + dom_host.create_text_node("d"), + dom_host.create_text_node("a"), + ) + }; + + let append_reaction_roots = apply_parser_dom_mutation_for_test( + &mut page_vm, + ParserDomMutation::AppendChild { + parent: parser_append, + child: parser_append_text, + }, + "parser textarea append should apply", + ); + assert!( + append_reaction_roots.is_empty(), + "plain textarea text append should not queue custom element reactions" + ); + let before_reaction_roots = apply_parser_dom_mutation_for_test( + &mut page_vm, + ParserDomMutation::InsertBefore { + parent: parser_before, + child: parser_before_text, + reference_child: Some(parser_before_reference), + }, + "parser textarea insertBefore should apply", + ); + assert!( + before_reaction_roots.is_empty(), + "plain textarea text insertBefore should not queue custom element reactions" + ); + let remove_reaction_roots = apply_parser_dom_mutation_for_test( + &mut page_vm, + ParserDomMutation::RemoveChild { + parent: parser_remove, + child: parser_remove_child, + }, + "parser textarea remove should apply", + ); + if !remove_reaction_roots.is_empty() { + page_vm + .vm_mut() + .queue_and_run_pending_parser_post_step_runtime_work_in_default_context_for_test(remove_reaction_roots) + .expect("parser textarea remove followups should dispatch"); + } + + let result = page_vm + .evaluate_expression( + r#" +window.parserTextareaSelectionStates.parserAppend = + textareaState(document.getElementById('parser-textarea-append')); +window.parserTextareaSelectionStates.parserInsertBefore = + textareaState(document.getElementById('parser-textarea-before')); +window.parserTextareaSelectionStates.parserRemove = + textareaState(document.getElementById('parser-textarea-remove')); +JSON.stringify({ + jsAppend: window.parserTextareaSelectionStates.jsAppend, + parserAppend: window.parserTextareaSelectionStates.parserAppend, + appendSame: JSON.stringify(window.parserTextareaSelectionStates.jsAppend) === + JSON.stringify(window.parserTextareaSelectionStates.parserAppend), + jsInsertBefore: window.parserTextareaSelectionStates.jsInsertBefore, + parserInsertBefore: window.parserTextareaSelectionStates.parserInsertBefore, + insertBeforeSame: JSON.stringify(window.parserTextareaSelectionStates.jsInsertBefore) === + JSON.stringify(window.parserTextareaSelectionStates.parserInsertBefore), + jsRemove: window.parserTextareaSelectionStates.jsRemove, + parserRemove: window.parserTextareaSelectionStates.parserRemove, + removeSame: JSON.stringify(window.parserTextareaSelectionStates.jsRemove) === + JSON.stringify(window.parserTextareaSelectionStates.parserRemove) +}) +"#, + ) + .expect("textarea selection result should evaluate"); + assert_eq!( + result.get("value").and_then(serde_json::Value::as_str), + Some( + r#"{"jsAppend":{"value":"abcd","text":"abcd","start":2,"end":3},"parserAppend":{"value":"abcd","text":"abcd","start":2,"end":3},"appendSame":true,"jsInsertBefore":{"value":"abc","text":"abc","start":1,"end":2},"parserInsertBefore":{"value":"abc","text":"abc","start":1,"end":2},"insertBeforeSame":true,"jsRemove":{"value":"","text":"","start":0,"end":0},"parserRemove":{"value":"","text":"","start":0,"end":0},"removeSame":true}"# + ), + "parser textarea append/insertBefore/remove should clamp non-dirty selection like JS child-list mutations" + ); + })); +} diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/clipboard_exec_copy.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/clipboard_exec_copy.rs index 73788ebba1e..5467ee90ac8 100644 --- a/moli-renderer-v8/src/script_vm/tests/browser_api/clipboard_exec_copy.rs +++ b/moli-renderer-v8/src/script_vm/tests/browser_api/clipboard_exec_copy.rs @@ -120,6 +120,24 @@ fn exec_copy_preserves_unfocused_selections_and_respects_passwords_and_empty_sel ("control.readOnly=true", true, "๐ŸฆŠ", 3), ("control.disabled=true", true, "๐ŸฆŠ", 3), ("control.blur()", true, "๐ŸฆŠ", 3), + ( + "control.blur();control.setSelectionRange(3,5)", + true, + "๐ŸฆŠ", + 3, + ), + ( + "getSelection().removeAllRanges();control.blur();control.focus()", + true, + "๐ŸฆŠ", + 3, + ), + ( + "control.blur();control.value='xyz';control.value='A๐ŸฆŠBC'", + false, + "seed", + 3, + ), ("control.blur();control.select()", true, "A๐ŸฆŠBC", 3), ("control.type='password'", false, "seed", 0), ("control.setSelectionRange(1,1)", false, "seed", 3), 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 7800893596f..c8cbb48e11a 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 @@ -1816,3 +1816,27 @@ fn text_control_selection_setters_restore_the_focused_document_selection() { "" ); } + +#[test] +fn document_selection_tracks_visible_text_controls_independently_of_cached_offsets() { + let mut vm = new_storage_test_vm("https://text-control-visible-selection.test/"); + assert_eq!( + vm.eval(include_str!( + "../../../../../tests/fixtures/text-control-visible-selection.js" + )) + .expect("visible text control selections should follow their document and focus lifecycle"), + "" + ); +} + +#[test] +fn text_control_selections_follow_value_default_value_and_form_reset() { + let mut vm = new_storage_test_vm("https://text-control-selection-values.test/"); + assert_eq!( + vm.eval(include_str!( + "../../../../../tests/fixtures/text-control-selection-values.js" + )) + .expect("value mutations should reconcile both cached and visible selections"), + "" + ); +} diff --git a/moli-renderer-v8/src/script_vm/tests/dom_elements/text_controls.rs b/moli-renderer-v8/src/script_vm/tests/dom_elements/text_controls.rs index 43d29b65a12..0a75c1d7660 100644 --- a/moli-renderer-v8/src/script_vm/tests/dom_elements/text_controls.rs +++ b/moli-renderer-v8/src/script_vm/tests/dom_elements/text_controls.rs @@ -221,7 +221,7 @@ fn text_control_selection_methods_parse_webidl_arguments() { assert_eq!( result, - "0,3,none|throw:TypeError|throw:TypeError|0,3,none|0,1,backward|0,1,forward|2,2,none" + "0,3,forward|throw:TypeError|throw:TypeError|0,3,forward|0,1,backward|0,1,forward|2,2,forward" ); } @@ -360,7 +360,7 @@ fn text_control_value_setters_reset_selection_only_when_api_value_changes() { ) .expect("text control value selection reset should evaluate"); - assert_eq!(result, "1:3:backward|6:6:none|1:3:backward|6:6:none"); + assert_eq!(result, "1:3:backward|6:6:forward|1:3:backward|6:6:forward"); } #[test] fn text_control_default_value_type_and_reset_paths_clamp_selection() { @@ -898,6 +898,126 @@ async fn text_control_selection_mutations_queue_select_event() { "" ); } +#[tokio::test] +async fn unchanged_background_text_control_selections_do_not_queue_change_events() { + let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).expect("loader"); + let mut vm = new_storage_page_task_executor_test_vm_with_loader( + "https://forms-selection-unchanged-events.test/", + &loader, + ); + vm.eval( + r#" +if (!document.documentElement) document.appendChild(document.createElement('html')); +if (!document.body) document.documentElement.appendChild(document.createElement('body')); +globalThis.controls = []; +for (const tag of ['input', 'textarea']) for (const connected of [true, false]) { + const control = document.createElement(tag); + if (connected) document.body.append(control); + control.value = 'abcdef'; + control.setSelectionRange(0, 0); + controls.push(control); +} +'ready' +"#, + ) + .unwrap(); + for _ in 0..32 { + if !vm + .run_one_oldest_ready_page_task_executor_turn(&loader) + .await + .unwrap() + { + break; + } + } + assert_eq!( + vm.eval( + r#" +globalThis.changes = []; +controls.forEach((control, index) => { + control.addEventListener('selectionchange', () => changes.push(index)); + control.setSelectionRange(0, 0); + control.selectionDirection = 'none'; + control.value = ''; + control.setRangeText('foo'); +}); +JSON.stringify(controls.map(c => [c.value, c.selectionStart, c.selectionEnd, c.selectionDirection])) +"# + ) + .unwrap(), + r#"[["foo",0,0,"forward"],["foo",0,0,"forward"],["foo",0,0,"forward"],["foo",0,0,"forward"]]"# + ); + for _ in 0..32 { + if !vm + .run_one_oldest_ready_page_task_executor_turn(&loader) + .await + .unwrap() + { + break; + } + } + assert_eq!(vm.eval("JSON.stringify(changes)").unwrap(), "[]"); + + vm.eval("controls[0].focus(); controls[0].setSelectionRange(3, 3)") + .unwrap(); + for _ in 0..32 { + if !vm + .run_one_oldest_ready_page_task_executor_turn(&loader) + .await + .unwrap() + { + break; + } + } + // A focused editor's value replacement changes the live selection even + // when the cached caret offset remains the same. + vm.eval("changes.length = 0; controls[0].value = 'bar'") + .unwrap(); + assert_eq!(vm.eval("JSON.stringify(changes)").unwrap(), "[]"); + for _ in 0..32 { + if !vm + .run_one_oldest_ready_page_task_executor_turn(&loader) + .await + .unwrap() + { + break; + } + } + assert_eq!(vm.eval("JSON.stringify(changes)").unwrap(), "[0]"); + + vm.eval( + r#" +globalThis.untouched = document.createElement('input'); +untouched.defaultValue = 'abc'; +document.body.append(untouched); +untouched.focus(); +"ready" +"#, + ) + .unwrap(); + for _ in 0..32 { + if !vm + .run_one_oldest_ready_page_task_executor_turn(&loader) + .await + .unwrap() + { + break; + } + } + // Marking the value dirty without changing its text is not a value change. + vm.eval("changes.length = 0; untouched.addEventListener('selectionchange', () => changes.push('untouched')); untouched.setRangeText('')").unwrap(); + for _ in 0..32 { + if !vm + .run_one_oldest_ready_page_task_executor_turn(&loader) + .await + .unwrap() + { + break; + } + } + assert_eq!(vm.eval("JSON.stringify(changes)").unwrap(), "[]"); +} + #[tokio::test] async fn text_control_clone_resets_selection_but_still_queues_select_event() { let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).expect("loader"); @@ -970,7 +1090,7 @@ async fn text_control_clone_resets_selection_but_still_queues_select_event() { ) .expect("text control clone setup should evaluate"); - assert_eq!(result, "foobar:0:0:0:6:none|foobar:0:0:0:6:none|0|"); + assert_eq!(result, "foobar:0:0:0:6:forward|foobar:0:0:0:6:forward|0|"); for _ in 0..8 { if vm .eval("globalThis.__textControlCloneSelectEvents.length") @@ -1064,7 +1184,9 @@ async fn shadow_text_control_selectionchange_and_exec_delete_target_document() { "globalThis.__shadowTextControlInputEvents.join(',') + '|' + globalThis.__shadowTextControlDocumentEvents.join(',')", ) .expect("shadow selectionchange event log should evaluate"), - "|document" + // value was set before insertion into the shadow tree, so its queued + // control event precedes the document selectionchange from focus. + "true|document" ); let result = vm diff --git a/moli-renderer-v8/tests/fixtures/text-control-selection-values.js b/moli-renderer-v8/tests/fixtures/text-control-selection-values.js new file mode 100644 index 00000000000..ef22ec5a7cb --- /dev/null +++ b/moli-renderer-v8/tests/fixtures/text-control-selection-values.js @@ -0,0 +1,141 @@ +(() => { + 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 button = fixture.appendChild(document.createElement('button')); + const selection = getSelection(), failures = []; + const check = (actual, expected, label) => { + if (JSON.stringify(actual) !== JSON.stringify(expected)) { + failures.push(label + ': ' + JSON.stringify(actual) + ' expected ' + JSON.stringify(expected)); + } + }; + const offsets = control => [control.selectionStart, control.selectionEnd, control.selectionDirection]; + const selected = () => [selection.rangeCount, selection.type, selection.direction, String(selection)]; + const original = 'A๐Ÿ˜€B\nC'; + // Expected offsets include the intermediate removal step of replacements. + // DOM nodes do not stand in for the text control's internal selection nodes. + const cases = [ + ['append', c => c.append('XY'), original + 'XY', 4, '๐Ÿ˜€B'], + ['prepend', c => c.prepend('XY'), 'XY' + original, 4, 'YA๐Ÿ˜€'], + ['fragment', c => { const f = document.createDocumentFragment(); f.append('XY', 'Z'); c.append(f); }, original + 'XYZ', 4, '๐Ÿ˜€B'], + ['same textContent', c => c.textContent = c.textContent, original, 0, ''], + ['same defaultValue', c => c.defaultValue = c.defaultValue, original, 0, ''], + ['empty', c => c.textContent = '', '', 0, ''], + ['replace', c => c.replaceChild(document.createTextNode('uvwxyz'), c.firstChild), 'uvwxyzB\nC', 3, 'vw'], + ['same replacement', c => c.replaceChild(document.createTextNode(c.firstChild.data), c.firstChild), original, 3, '๐Ÿ˜€'], + ['replace self', c => c.replaceChild(c.firstChild, c.firstChild), original, 3, '๐Ÿ˜€'], + ['insert before self', c => c.insertBefore(c.firstChild, c.firstChild), original, 3, '๐Ÿ˜€'], + ['remove first', c => c.firstChild.remove(), 'B\nC', 3, '\nC'], + ['remove last', c => c.lastChild.remove(), 'A๐Ÿ˜€', 3, '๐Ÿ˜€'], + ['move first', c => c.append(c.firstChild), 'B\nCA๐Ÿ˜€', 3, '\nC'], + ['data', c => c.firstChild.data = 'Q', 'QB\nC', 4, 'B\nC'], + ['appendData', c => c.firstChild.appendData('XY'), 'A๐Ÿ˜€XYB\nC', 4, '๐Ÿ˜€X'], + ['split', c => c.firstChild.splitText(1), original, 4, '๐Ÿ˜€B'], + ['normalize', c => c.normalize(), original, 4, '๐Ÿ˜€B'], + ['replaceChildren', c => c.replaceChildren('A๐Ÿ˜€', 'B\nC'), original, 0, ''], + ['same data', c => c.firstChild.data = c.firstChild.data, original, 4, '๐Ÿ˜€B', false], + ['empty text node', c => c.append(''), original, 4, '๐Ÿ˜€B', false], + ['comment', c => c.append(document.createComment('ignored')), original, 4, '๐Ÿ˜€B', false], + ['descendant text', c => { const e = document.createElement('b'); e.textContent = 'ignored'; c.append(e); }, original, 4, '๐Ÿ˜€B', false], + ]; + for (const focused of [true, false]) for (const dirty of [false, true]) for (const cleared of [false, true]) { + for (const [name, mutate, value, end, text, changes = true] of cases) { + const control = fixture.appendChild(document.createElement('textarea')); + control.append('A๐Ÿ˜€', 'B\nC'); + if (dirty) control.value = control.value; + control.focus(); + control.setSelectionRange(1, 4, 'backward'); + if (cleared) selection.removeAllRanges(); + if (!focused) button.focus(); + mutate(control); + const label = [name, focused, dirty, cleared].join('/'); + const changed = changes && !dirty; + const cache = changed + ? [cleared && focused ? 0 : Math.min(1, end), cleared && focused ? 0 : end, 'forward'] + : [1, 4, 'backward']; + const restored = [1, cache[0] === cache[1] ? 'Caret' : 'Range', cache[0] === cache[1] ? 'none' : cache[2], cache[0] === cache[1] ? '' : changed ? text : '๐Ÿ˜€B']; + const visible = changed && focused ? restored + : cleared ? [0, 'None', 'none', ''] + : changed ? [1, 'Caret', 'none', ''] + : [1, 'Range', 'backward', '๐Ÿ˜€B']; + check(control.value, dirty ? original : value, label + '/value'); + check(offsets(control), focused && cleared && !changed ? [0, 0, 'forward'] : cache, label + '/offsets'); + check(selected(), visible, label + '/visible selection'); + control.blur(); + check(offsets(control), cache, label + '/blurred cache'); + check(selected(), visible, label + '/blurred selection'); + control.focus(); + check(offsets(control), cache, label + '/restored offsets'); + check(selected(), restored, label + '/restored selection'); + control.remove(); + } + } + for (const tag of ['input', 'textarea']) for (const focused of [true, false]) { + for (const mutation of ['reset', 'same reset', 'default', 'value', 'same value', 'roundtrip']) { + const form = fixture.appendChild(document.createElement('form')); + const control = form.appendChild(document.createElement(tag)); + control.defaultValue = 'A๐Ÿ˜€BC'; + if (mutation === 'reset') control.value = 'dirty'; + control.focus(); + control.setSelectionRange(1, 3, 'backward'); + if (!focused) button.focus(); + if (mutation.includes('reset')) form.reset(); + else if (mutation === 'default') control.defaultValue = 'xyz'; + else if (mutation === 'same value') control.value = 'A๐Ÿ˜€BC'; + else if (mutation === 'value') control.value = 'X๐Ÿ˜€Y'; + else { control.value = 'xyz'; control.value = 'A๐Ÿ˜€BC'; } + const label = [tag, focused, mutation].join('/'); + const unchanged = mutation.startsWith('same'); + const cache = unchanged || mutation === 'default' && tag === 'input' ? [1, 3, 'backward'] + : mutation === 'default' ? [0, 0, 'forward'] + : mutation === 'value' ? [4, 4, 'forward'] : [5, 5, 'forward']; + check(offsets(control), focused && mutation === 'default' && tag === 'input' ? [0, 0, 'forward'] : cache, label + '/offsets'); + check(selected(), unchanged ? [1, 'Range', 'backward', '๐Ÿ˜€'] : [1, 'Caret', 'none', ''], label + '/selection'); + control.blur(); + check(offsets(control), cache, label + '/blur'); + control.focus(); + check(selected(), unchanged ? [1, 'Range', 'backward', '๐Ÿ˜€'] + : mutation === 'default' && tag === 'input' ? [1, 'Range', 'backward', 'yz'] + : [1, 'Caret', 'none', ''], label + '/refocus'); + form.remove(); + } + } + // Observer bookkeeping must not control value/selection synchronization. + for (const observe of [false, true]) { + const control = fixture.appendChild(document.createElement('textarea')); + control.append('A\r'); + const observer = new MutationObserver(() => {}); + if (observe) observer.observe(control, {subtree: true, childList: true, characterData: true}); + control.focus(); + control.setSelectionRange(1, 2, 'backward'); + control.append('\n'); + check(offsets(control), [1, 2, 'backward'], 'CRLF normalization preserves unchanged API selection/' + observe); + check(selected(), [1, 'Range', 'backward', '\n'], 'normalized value/' + observe); + control.firstChild.data = 'A๐Ÿ˜€'; + check(offsets(control), [1, 2, 'forward'], 'character data changes selection without observers/' + observe); + check(selected(), [1, 'Range', 'forward', '๐Ÿ˜€'], 'character data updates selected text/' + observe); + observer.disconnect(); + control.remove(); + } + for (const focused of [true, false]) for (const action of ['number', 'same', 'nan', 'up', 'down', 'zero']) { + const control = fixture.appendChild(document.createElement('input')); + control.type = 'number'; + control.value = '123'; + control.select(); + if (!focused) button.focus(); + if (action === 'number') control.valueAsNumber = 4567; + if (action === 'same') control.valueAsNumber = 123; + if (action === 'nan') control.valueAsNumber = NaN; + if (action === 'up') control.stepUp(); + if (action === 'down') control.stepDown(); + if (action === 'zero') control.stepUp(0); + const expected = ['same', 'zero'].includes(action) ? [1, 'Range', 'forward', '123'] : [1, 'Caret', 'none', '']; + check(selected(), expected, 'numeric setter/' + [focused, action].join('/')); + control.blur(); + control.focus(); + check(selected(), expected, 'numeric setter refocus/' + [focused, action].join('/')); + control.remove(); + } + fixture.remove(); + return failures.join('\n'); +})() diff --git a/moli-renderer-v8/tests/fixtures/text-control-visible-selection.js b/moli-renderer-v8/tests/fixtures/text-control-visible-selection.js new file mode 100644 index 00000000000..8e56146d960 --- /dev/null +++ b/moli-renderer-v8/tests/fixtures/text-control-visible-selection.js @@ -0,0 +1,149 @@ +(() => { + 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 other = fixture.appendChild(document.createElement('iframe')).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 = (actual, expected, label) => { + if (JSON.stringify(actual) !== JSON.stringify(expected)) { + failures.push(label + ': ' + JSON.stringify(actual) + ' expected ' + JSON.stringify(expected)); + } + }; + const selected = selection => [selection.rangeCount, selection.type, selection.direction, String(selection)]; + const offsets = control => [control.selectionStart, control.selectionEnd, control.selectionDirection]; + for (const owner of [window, other]) { + const doc = owner.document, selection = owner.getSelection(); + const holder = (owner === window ? fixture : otherBody).appendChild(doc.createElement('div')); + const button = holder.appendChild(doc.createElement('button')); + const outside = holder.appendChild(doc.createTextNode('outside')); + for (const kind of ['text', 'search', 'tel', 'url', 'password', 'email', 'number', 'textarea']) { + for (const mode of ['light', 'open', 'closed']) { + const box = holder.appendChild(doc.createElement('div')); + const parent = mode === 'light' ? box : box.appendChild(doc.createElement('div')).attachShadow({mode}); + const control = parent.appendChild(doc.createElement(kind === 'textarea' ? 'textarea' : 'input')); + if (kind !== 'textarea') control.type = kind; + if (!['email', 'number'].includes(kind)) { + check(offsets(control), [0, 0, 'forward'], kind + '/' + mode + '/initial cache direction'); + } + control.value = kind === 'number' ? '12345' : 'A๐Ÿ˜€BC'; + const label = [owner === window ? 'parent' : 'child', kind, mode].join('/'); + // Call through the other realm's function to exercise owner-document routing. + const caller = owner === window ? other : window; + const proto = kind === 'textarea' ? caller.HTMLTextAreaElement.prototype : caller.HTMLInputElement.prototype; + proto.select.call(control); + check(selected(selection), [1, 'Range', 'forward', kind === 'password' ? 'โ€ขโ€ขโ€ขโ€ข' : control.value], label + '/select'); + check(selection.isCollapsed, true, label + '/public projection stays collapsed'); + const projected = selection.getRangeAt(0); + check([projected.startContainer === box, projected.startOffset, projected.collapsed], [true, 0, true], label + '/range projection'); + const composed = selection.getComposedRanges({shadowRoots: mode === 'light' ? [] : [parent]})[0]; + check([composed.startContainer === parent, composed.startOffset, composed.endContainer === parent, composed.endOffset], [true, 0, true, 1], label + '/composed range'); + if (!['email', 'number'].includes(kind)) { + const setRange = (...args) => proto.setSelectionRange.call(control, ...args); + setRange(1, 3, 'backward'); + check(selected(selection), [1, 'Range', 'backward', kind === 'password' ? 'โ€ข' : '๐Ÿ˜€'], label + '/backward'); + button.focus(); + setRange(0, 1, 'forward'); + check(selected(selection), [1, 'Range', 'backward', kind === 'password' ? 'โ€ข' : '๐Ÿ˜€'], label + '/background cache is independent'); + control.focus(); + check(selected(selection), [1, 'Range', 'forward', kind === 'password' ? 'โ€ข' : 'A'], label + '/restore background cache'); + setRange(1, 3, 'backward'); + selection.removeAllRanges(); + check(offsets(control), [0, 0, 'forward'], label + '/focused empty selection'); + control.blur(); + check(offsets(control), [1, 3, 'backward'], label + '/blur exposes preserved cache'); + control.focus(); + check(selected(selection), [1, 'Range', 'backward', kind === 'password' ? 'โ€ข' : '๐Ÿ˜€'], label + '/refocus after clear'); + selection.setBaseAndExtent(outside, 0, outside, 4); + check(offsets(control), [0, 0, 'forward'], label + '/selection outside editor'); + control.blur(); + check(offsets(control), [1, 3, 'backward'], label + '/outside selection preserves cache'); + control.focus(); + check(selected(selection), [1, 'Range', 'backward', kind === 'password' ? 'โ€ข' : '๐Ÿ˜€'], label + '/refocus after outside selection'); + control.value = 'X๐Ÿ˜€Y'; + check(offsets(control), [4, 4, 'forward'], label + '/value setter uses UTF-16 end'); + check(selected(selection), [1, 'Caret', 'none', ''], label + '/value setter collapses selection'); + setRange(1, 3); + button.focus(); + control.value = 'A๐Ÿ˜€BC'; + control.value = 'X๐Ÿ˜€Y'; + check(selected(selection), [1, 'Caret', 'none', ''], label + '/background value roundtrip invalidates visible range'); + } + box.remove(); + check(String(selection), '', label + '/removed editor has no selected text'); + } + } + holder.remove(); + } + + const selection = window.getSelection(); + const holder = fixture.appendChild(document.createElement('div')); + const control = holder.appendChild(document.createElement('input')); + const button = holder.appendChild(document.createElement('button')); + const peer = holder.appendChild(document.createElement('input')); + peer.value = 'XYZ'; + for (const action of ['none', 'range', 'value', 'clear', 'redirect', 'remove']) { + holder.prepend(control); + control.value = 'abcdef'; + peer.select(); + control.addEventListener('focus', () => { + check(selected(selection), [1, 'Range', 'forward', 'XYZ'], action + '/select focus event preserves previous selection'); + if (action === 'range') control.setSelectionRange(2, 3, 'backward'); + if (action === 'value') control.value = 'X๐Ÿ˜€Y'; + if (action === 'clear') selection.removeAllRanges(); + if (action === 'redirect') peer.focus(); + if (action === 'remove') control.remove(); + }, {once: true}); + control.select(); + if (action === 'remove') check(document.activeElement === control, false, 'select respects removal during focus'); + else if (action === 'redirect') check(selected(selection), [1, 'Range', 'forward', 'XYZ'], 'select respects focus redirection'); + else if (action === 'value') check(selected(selection), [1, 'Caret', 'none', ''], 'select respects value changes during focus'); + else if (action === 'range') check(selected(selection), [1, 'Range', 'backward', 'c'], 'select respects cache changes during focus'); + else check(selected(selection), [1, 'Range', 'forward', 'abcdef'], action + '/select restores cached selection after focus event'); + } + holder.prepend(control); + control.value = 'abcdef'; + button.focus(); + control.addEventListener('focus', () => selection.removeAllRanges(), {once: true}); + control.focus(); + check(selection.rangeCount, 0, 'normal focus does not overwrite listener selection'); + + for (const [value, start, end, expected] of [ + ['A๐Ÿ˜€BC', 1, 2, '๐Ÿ˜€'], ['A๐Ÿ˜€BC', 2, 3, ''], ['A๐Ÿ˜€BC', 2, 4, 'B'], + ['e\u0301X', 0, 1, 'e\u0301'], ['e\u0301X', 1, 2, ''], + ['๐Ÿ‘ฉโ€๐Ÿ‘ฉโ€๐Ÿ‘งโ€๐Ÿ‘ฆX', 0, 1, '๐Ÿ‘ฉโ€๐Ÿ‘ฉโ€๐Ÿ‘งโ€๐Ÿ‘ฆ'], ['๐Ÿ‘ฉโ€๐Ÿ‘ฉโ€๐Ÿ‘งโ€๐Ÿ‘ฆX', 1, 11, ''], + ['๐Ÿ‘๐ŸฝX', 0, 2, '๐Ÿ‘๐Ÿฝ'], ['ืื‘ื’', 1, 3, 'ื‘ื’'] + ]) { + control.type = 'text'; + control.value = value; + control.focus(); + control.setSelectionRange(start, end); + check(String(selection), expected, 'visible grapheme ' + [value, start, end].join('/')); + } + control.type = 'password'; + control.value = 'A๐Ÿ‘ฉโ€๐Ÿ‘ฉโ€๐Ÿ‘งโ€๐Ÿ‘ฆe\u0301X'; + control.select(); + check(String(selection), 'โ€ขโ€ขโ€ขโ€ข', 'password masks each selected grapheme'); + + control.type = 'text'; + control.value = 'A๐Ÿ˜€BC'; + control.setSelectionRange(1, 3, 'backward'); + const segmenter = Object.getOwnPropertyDescriptor(Intl, 'Segmenter'); + let authorCalls = 0; + const forbidden = () => { authorCalls++; throw new Error('author hook'); }; + try { + Object.defineProperty(Intl, 'Segmenter', {configurable: true, get: forbidden}); + for (const name of ['value', 'type', 'selectionStart', 'selectionEnd', 'selectionDirection', 'ownerDocument']) { + Object.defineProperty(control, name, {configurable: true, get: forbidden}); + } + check(selected(selection), [1, 'Range', 'backward', '๐Ÿ˜€'], 'Selection uses native state'); + check(authorCalls, 0, 'Selection ignores author getters and Intl'); + } finally { + if (segmenter) Object.defineProperty(Intl, 'Segmenter', segmenter); + else delete Intl.Segmenter; + for (const name of ['value', 'type', 'selectionStart', 'selectionEnd', 'selectionDirection', 'ownerDocument']) delete control[name]; + } + fixture.remove(); + return failures.join('\n'); +})()