fix(focus): initialize selections in contenteditable hosts

Initialize the native caret before focus events in the editing host owner realm, retaining existing host selections and their Range identity. Preserve UTF-16 offsets, whitespace and shadow projections, and queue document selectionchange through the existing task queue.
This commit is contained in:
ldm0
2026-11-02 06:02:26 +08:00
parent 49f2313778
commit 2bc5baeb66
9 changed files with 826 additions and 30 deletions
+1 -1
View File
@@ -236,7 +236,7 @@ pub(crate) use navigation_traversal_execution::{
};
pub(crate) use performance_runtime::PERFORMANCE_TIME_ORIGIN_SLOT;
pub(crate) use performance_runtime::performance_slot_number;
pub(crate) use selection::focus_text_control_selection;
pub(crate) use selection::focus_element_selection;
pub(crate) use selection_surface::{
selection_text_for_clipboard, selection_value_for_window,
sync_selection_owner_document_for_window,
@@ -2,13 +2,14 @@ use super::*;
mod composed;
mod dispatch;
mod editing_caret;
mod focus;
mod text;
mod values;
pub(super) use composed::selection_composed_boundary_order;
pub(super) use dispatch::{boundary_order, selection_dispatch_change};
pub(crate) use focus::focus_text_control_selection;
pub(crate) use focus::focus_element_selection;
pub(super) use text::{first_text_descendant, last_text_descendant, text_length};
pub(super) use values::{
SelectionRangeUpdateState, new_selection_runtime_object, selection_anchor_node,
@@ -0,0 +1,276 @@
use crate::document_runtime::DomHandle;
use crate::dom::forms::InputType;
use crate::dom::native::{Element, NodeType};
use crate::native_bridge::JsContextHost;
use crate::native_bridge::document::{MATHML_NS, XHTML_NS};
use crate::native_bridge::element::{StyleMode, style_property_value};
enum Visit {
Node { node: DomHandle, block: DomHandle },
EmptyBlock(DomHandle),
}
/// Resolve the initial DOM caret in an editing host. Walk editable content in
/// tree order, retaining block boundaries around non-editable islands and
/// element boundaries around line breaks and replaced content. This does not
/// use hit testing: the first DOM position need not be inside the viewport.
pub(super) fn initial_editing_caret(
runtime: &JsContextHost,
editing_host: DomHandle,
) -> Option<(DomHandle, u32)> {
let dom = runtime.dom_host();
let mut stack = vec![Visit::Node {
node: editing_host,
block: editing_host,
}];
while let Some(visit) = stack.pop() {
let (handle, block) = match visit {
Visit::Node { node, block } => (node, block),
Visit::EmptyBlock(node) => {
if node == editing_host || empty_block_has_caret_space(runtime, node) {
return Some((node, 0));
}
continue;
}
};
let node = dom.node(handle)?;
if matches!(node.node_type(), NodeType::Text | NodeType::CDataSection) {
let parent = dom.parent_node(handle)?;
if !is_visible(runtime, parent) {
continue;
}
let collapse = computed(runtime, parent, "white-space-collapse");
let preserve = matches!(collapse.as_str(), "preserve" | "break-spaces");
let preserve_breaks = collapse == "preserve-breaks";
let text = node.data_value()?;
let first = text.encode_utf16().enumerate().find(|&(_, unit)| {
preserve
|| !is_collapsible_space(unit)
|| (preserve_breaks && matches!(unit, 0x0a | 0x0d))
});
// An inline editing host can begin in the middle of a line. Its
// first collapsed space is visible when it separates surrounding
// inline content; the editing boundary itself is not a line break.
if !text.is_empty()
&& first.is_none_or(|(offset, unit)| {
offset != 0 && !(preserve_breaks && matches!(unit, 0x0a | 0x0d))
})
&& adjacent_inline_content(runtime, handle, false)
&& (first.is_some() || adjacent_inline_content(runtime, handle, true))
{
return Some((handle, 0));
}
if let Some((offset, _)) = first {
return Some((handle, u32::try_from(offset).ok()?));
}
continue;
}
let Some(element) = node.as_element() else {
continue;
};
let display = computed(runtime, handle, "display");
if display == "none"
|| (element.is_html_input() && element.input_type() == InputType::Hidden)
{
continue;
}
let visible = is_visible(runtime, handle);
// Every visited parent is editable in this host. False and inert
// subtrees are islands, not absent content. Do not walk ancestors
// again for each descendant of a deeply nested editor.
if element.namespace() == XHTML_NS
&& (element.has_attribute("inert")
|| element
.attribute("contenteditable")
.is_some_and(|value| value.eq_ignore_ascii_case("false")))
{
if visible {
return Some((block, 0));
}
continue;
}
if handle != editing_host
&& element.namespace() == XHTML_NS
&& (is_replaced_element(element)
|| matches!(element.local_name(), "br" | "hr" | "table"))
{
if visible {
let parent = dom.parent_node(handle)?;
return Some((
parent,
u32::try_from(dom.child_index(parent, handle)?).ok()?,
));
}
continue;
}
let is_block = display != "contents" && !display.starts_with("inline");
let block = if is_block { handle } else { block };
if visible && (is_block || handle == editing_host) {
stack.push(Visit::EmptyBlock(handle));
}
// Use an explicit stack so deeply nested author content cannot exhaust
// the Rust call stack during a synchronous focus operation.
stack.extend(
dom.child_handles(handle)
.collect::<Vec<_>>()
.into_iter()
.rev()
.map(|node| Visit::Node { node, block }),
);
}
None
}
fn computed(runtime: &JsContextHost, node: DomHandle, property: &str) -> String {
style_property_value(runtime, node, StyleMode::Computed, property)
}
fn is_collapsible_space(unit: u16) -> bool {
matches!(unit, 0x09 | 0x0a | 0x0c | 0x0d | 0x20)
}
fn is_replaced_element(element: &Element) -> bool {
element.namespace() == XHTML_NS
&& matches!(
element.local_name(),
"img"
| "input"
| "textarea"
| "select"
| "iframe"
| "object"
| "embed"
| "canvas"
| "audio"
| "video"
)
}
fn is_inline_container(display: &str) -> bool {
matches!(display, "inline" | "contents")
}
/// Inspect the neighboring inline stream, including content outside an inline
/// editor. Stop at formatting-context boundaries; skip comments and display:none
/// subtrees. Hidden text still participates in whitespace collapsing.
fn adjacent_inline_content(runtime: &JsContextHost, mut node: DomHandle, forward: bool) -> bool {
let dom = runtime.dom_host();
loop {
let mut adjacent = loop {
let sibling = if forward {
dom.next_sibling(node)
} else {
dom.previous_sibling(node)
};
if let Some(sibling) = sibling {
break sibling;
}
let Some(parent) = dom.parent_node(node) else {
return false;
};
// SVG and MathML have their own text layout; HTML's surrounding
// inline stream cannot preserve their leading collapsed space.
if dom
.node(parent)
.and_then(|node| node.as_element())
.is_none_or(|element| element.namespace() != XHTML_NS)
|| !is_inline_container(&computed(runtime, parent, "display"))
{
return false;
}
node = parent;
};
loop {
node = adjacent;
let Some(candidate) = dom.node(node) else {
return false;
};
if matches!(
candidate.node_type(),
NodeType::Text | NodeType::CDataSection
) {
let text = candidate.data_value().unwrap_or_default();
let Some(parent) = dom.parent_node(node) else {
return false;
};
let collapse = computed(runtime, parent, "white-space-collapse");
let preserve = matches!(collapse.as_str(), "preserve" | "break-spaces");
let preserve_breaks = preserve || collapse == "preserve-breaks";
if forward {
for unit in text.encode_utf16() {
if preserve_breaks && matches!(unit, 0x0a | 0x0d) {
return false;
}
if preserve || !is_collapsible_space(unit) {
return true;
}
}
} else if let Some(byte) = text.as_bytes().last() {
return (preserve && !matches!(byte, b'\n' | b'\r'))
|| !is_collapsible_space(u16::from(*byte));
}
break;
}
let Some(element) = candidate.as_element() else {
break;
};
let display = computed(runtime, node, "display");
if display == "none"
|| matches!(
computed(runtime, node, "position").as_str(),
"absolute" | "fixed"
)
{
break;
}
if element.is_html_element("br") {
return false;
}
if !is_inline_container(&display) {
return display.starts_with("inline");
}
// A foreign root occupies an inline box in the surrounding HTML,
// although an initial caret can enter its text descendants.
if is_replaced_element(element)
|| element.is_svg_element("svg")
|| (element.namespace() == MATHML_NS && element.local_name() == "math")
{
return true;
}
let child = if forward {
dom.first_child(node)
} else {
dom.last_child(node)
};
let Some(child) = child else {
break;
};
adjacent = child;
}
}
}
fn is_visible(runtime: &JsContextHost, node: DomHandle) -> bool {
!matches!(
computed(runtime, node, "visibility").as_str(),
"hidden" | "collapse"
)
}
fn empty_block_has_caret_space(runtime: &JsContextHost, node: DomHandle) -> bool {
[
"height",
"min-height",
"padding-top",
"padding-bottom",
"border-top-width",
"border-bottom-width",
]
.iter()
.any(|property| {
computed(runtime, node, property)
.strip_suffix("px")
.and_then(|value| value.parse::<f64>().ok())
.is_some_and(|value| value > 0.0)
})
}
@@ -1,22 +1,28 @@
use super::super::range::{native_range_boundary_handles, new_range_for_document};
use super::{selection_range, selection_store_with_composed_boundaries};
use super::editing_caret::initial_editing_caret;
use super::{
selection_composed_end_node, selection_composed_start_node, selection_direction,
selection_range, selection_store_with_composed_boundaries,
};
use crate::context_bootstrap::selection_value_for_window;
use crate::document_runtime::DomHandle;
use crate::dom::forms::InputType;
use crate::native_bridge::element::queue_text_control_selection_change_event;
use crate::native_bridge::{JsContextHost, OwnerDispatchScope};
use crate::native_bridge::element::{
contenteditable_editing_host, queue_text_control_selection_change_event,
};
use crate::native_bridge::{JsContextHost, OwnerDispatchScope, callback_value_dom_handle};
use crate::page_task_queue::RendererPageUserInteractionEventKind;
/// Project a text field's internal selection into its Document before focus
/// listeners run. Picker controls have separate focus behavior and are not
/// text fields, even when their values contain text.
pub(crate) fn focus_text_control_selection(
/// Update the focused area's selection in its owner realm before focus events.
pub(crate) fn focus_element_selection(
scope: &mut v8::PinScope<'_, '_>,
runtime_ptr: *mut JsContextHost,
control: DomHandle,
target: DomHandle,
) -> Option<()> {
let runtime = unsafe { &mut *runtime_ptr };
let element = runtime.dom_host().node(control)?.as_element()?;
if !(element.is_html_textarea()
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(),
@@ -27,12 +33,12 @@ pub(crate) fn focus_text_control_selection(
| InputType::Email
| InputType::Password
| InputType::Number
)))
{
));
if !text_field && contenteditable_editing_host(runtime, target) != Some(target) {
return None;
}
let document = runtime.dom_host().owner_document_handle(control)?;
let dispatch_scope = runtime.owner_dispatch_scope_for_node(control)?;
let document = runtime.dom_host().owner_document_handle(target)?;
let dispatch_scope = runtime.owner_dispatch_scope_for_node(target)?;
match dispatch_scope {
OwnerDispatchScope::Child(child) => {
runtime
@@ -50,7 +56,11 @@ pub(crate) fn focus_text_control_selection(
let (_, context) = runtime.window_execution_context(scope, owner, dispatch_scope)?;
let scope = &mut v8::ContextScope::new(scope, context);
let previous = dispatch_scope.enter(scope);
let result = focus_text_control_selection_in_context(scope, runtime_ptr, document, control);
let result = if text_field {
focus_text_control_selection_in_context(scope, runtime_ptr, document, target)
} else {
focus_editing_host_selection_in_context(scope, runtime_ptr, document, target)
};
dispatch_scope.restore(scope, previous);
result
}
@@ -68,14 +78,7 @@ fn focus_text_control_selection_in_context(
// getRangeAt() exposes the position before the control (or its outermost
// shadow host). getComposedRanges() instead encloses the internal editor's
// host, with author shadow roots rescoping through the existing API.
let (mut container, mut offset) = (parent, index);
let mut root = dom.root_node_handle(container)?;
while dom.is_shadow_root(root) {
let host = dom.shadow_root_host(root)?;
container = dom.parent_node(host)?;
offset = u32::try_from(dom.child_index(container, host)?).ok()?;
root = dom.root_node_handle(container)?;
}
let (container, offset) = project_caret_out_of_shadow_trees(runtime, parent, index)?;
let window = scope.get_current_context().global(scope);
let selection = selection_value_for_window(scope, window)?;
@@ -124,6 +127,78 @@ fn focus_text_control_selection_in_context(
Some(())
}
fn focus_editing_host_selection_in_context(
scope: &mut v8::PinScope<'_, '_>,
runtime_ptr: *mut JsContextHost,
document: DomHandle,
editing_host: DomHandle,
) -> Option<()> {
let window = scope.get_current_context().global(scope);
let selection = selection_value_for_window(scope, window)?;
let anchor = if selection_direction(scope, selection).as_deref() == Some("backward") {
selection_composed_end_node(scope, selection)
} else {
selection_composed_start_node(scope, selection)
}
.and_then(|anchor| callback_value_dom_handle(scope, anchor.into()));
let runtime = unsafe { &*runtime_ptr };
if runtime.document_selected_text_control(document).is_none()
&& anchor.is_some_and(|anchor| {
contenteditable_editing_host(runtime, anchor) == Some(editing_host)
})
{
// A selection anchored in this editor survives refocusing, including
// backward selections and selections extending outside the editor.
return Some(());
}
let (container, offset) = initial_editing_caret(runtime, editing_host)?;
let (container, offset) = project_caret_out_of_shadow_trees(runtime, container, offset)?;
let document_object = wrap_node(scope, runtime_ptr, document)?;
let host_object = wrap_node(scope, runtime_ptr, editing_host)?;
let container = wrap_node(scope, runtime_ptr, container)?;
let range = new_range_for_document(scope, document_object)?;
selection_store_with_composed_boundaries(
scope,
selection,
range,
container,
offset,
container,
offset,
"none",
container,
offset,
container,
offset,
host_object,
0,
host_object,
0,
);
let _ = unsafe { &mut *runtime_ptr }.queue_user_interaction_event_task(
scope,
RendererPageUserInteractionEventKind::DocumentSelectionChange,
document,
);
Some(())
}
fn project_caret_out_of_shadow_trees(
runtime: &JsContextHost,
mut container: DomHandle,
mut offset: u32,
) -> Option<(DomHandle, u32)> {
let dom = runtime.dom_host();
let mut root = dom.root_node_handle(container)?;
while dom.is_shadow_root(root) {
let host = dom.shadow_root_host(root)?;
container = dom.parent_node(host)?;
offset = u32::try_from(dom.child_index(container, host)?).ok()?;
root = dom.root_node_handle(container)?;
}
Some((container, offset))
}
fn wrap_node<'s>(
scope: &mut v8::PinScope<'s, '_>,
runtime_ptr: *mut JsContextHost,
@@ -49,23 +49,25 @@ pub(crate) fn contenteditable_editing_host(
) -> Option<DomHandle> {
let dom = runtime.dom_host().dom();
let mut current = Some(handle);
let mut editing_host = None;
while let Some(candidate) = current {
if let Some(element) = dom.node(candidate).and_then(Node::as_element)
&& element.namespace() == document::XHTML_NS
&& let Some(value) = element.attribute("contenteditable")
{
match contenteditable_state_from_attr(value) {
Some(true) => return Some(candidate),
Some(false) => return None,
Some(true) => editing_host = Some(candidate),
Some(false) => break,
None => {}
}
}
current = dom.parent_node(candidate);
}
None
editing_host
}
fn contenteditable_state_from_attr(value: &str) -> Option<bool> {
let normalized = value.trim().to_ascii_lowercase();
let normalized = value.to_ascii_lowercase();
if normalized.is_empty() || normalized == "true" || normalized == "plaintext-only" {
Some(true)
} else if normalized == "false" {
@@ -899,7 +901,7 @@ fn update_focus_from_previous_with_previous_focus_within(
}
runtime.note_focus_style_activity(None, next);
if let Some(handle) = next {
let _ = crate::context_bootstrap::focus_text_control_selection(scope, runtime_ptr, handle);
let _ = crate::context_bootstrap::focus_element_selection(scope, runtime_ptr, handle);
let runtime = unsafe { &mut *runtime_ptr };
if is_text_control(runtime, handle) {
runtime.note_text_control_selection(handle);
@@ -1,5 +1,120 @@
use super::*;
#[test]
fn editing_host_focus_initializes_the_first_visible_dom_caret() {
let mut vm = new_storage_test_vm("https://editing-focus-selection.test/");
assert_eq!(
vm.eval(include_str!(
"../../../../tests/fixtures/editing-host-focus-selection.js"
))
.expect("editing focus should initialize a native caret"),
""
);
}
#[test]
fn editing_host_focus_preserves_selection_identity_and_native_host_semantics() {
let mut vm = new_storage_test_vm("https://editing-focus-retention.test/");
assert_eq!(
vm.eval(include_str!(
"../../../../tests/fixtures/editing-host-focus-retention.js"
))
.expect("editing focus should preserve existing host selections"),
""
);
}
#[test]
fn editing_host_focus_selection_uses_owner_realm_and_shadow_boundaries() {
let mut vm = new_storage_test_vm("https://editing-focus-realms.test/");
assert_eq!(
vm.eval(include_str!(
"../../../../tests/fixtures/editing-host-focus-realms.js"
))
.expect("editing focus should respect realms and shadow trees"),
""
);
}
#[test]
fn editing_host_initial_caret_is_used_by_native_text_input() {
let mut vm = new_streamed_parser_test_vm(
"https://editing-focus-input.test/",
r#"<!doctype html><body><div id="editor" contenteditable><p> abc</p></div>"#,
);
vm.eval("document.getElementById('editor').focus()")
.expect("editor should focus");
assert!(
vm.insert_text_into_active_control("X")
.expect("insert text")
);
assert_eq!(
vm.eval(
"JSON.stringify([document.getElementById('editor').innerHTML, getSelection().anchorOffset])"
)
.expect("text should be inserted at initial caret"),
r#"["<p> Xabc</p>",2]"#
);
}
#[tokio::test]
async fn editing_host_focus_selectionchange_is_queued_and_coalesced() {
let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).expect("loader");
let mut vm = new_storage_page_task_executor_test_vm_with_loader(
"https://editing-focus-events.test/",
&loader,
);
assert_eq!(
vm.eval(r#"
(() => {
const root = document.documentElement || document.appendChild(document.createElement('html'));
const body = document.body || root.appendChild(document.createElement('body'));
body.innerHTML = '<button id="reset"></button><div id="editor" contenteditable>abc</div><div id="other" contenteditable>def</div>';
globalThis.editingFocusEvents = [];
document.getElementById('editor').focus();
document.getElementById('other').focus();
document.getElementById('reset').focus();
document.getElementById('other').focus();
document.addEventListener('selectionchange', event => {
editingFocusEvents.push([event.target === document, event.bubbles, event.composed].join(':'));
});
return editingFocusEvents.length;
})()
"#).expect("selectionchange should not dispatch synchronously"),
"0"
);
for _ in 0..16 {
if !vm
.run_one_oldest_ready_page_task_executor_turn(&loader)
.await
.expect("selection tasks should run")
{
break;
}
}
assert_eq!(
vm.eval("editingFocusEvents.join('|')").expect("event log"),
"true:false:false"
);
vm.eval(
"editingFocusEvents.length = 0; document.getElementById('reset').focus(); document.getElementById('other').focus();",
)
.expect("refocus should retain the range");
for _ in 0..16 {
if !vm
.run_one_oldest_ready_page_task_executor_turn(&loader)
.await
.expect("refocus tasks should run")
{
break;
}
}
assert_eq!(
vm.eval("editingFocusEvents.length").expect("event log"),
"0"
);
}
#[test]
fn text_control_focus_projects_selection_without_replacing_retained_ranges() {
let mut vm = new_storage_test_vm("https://focus-selection.test/");
@@ -0,0 +1,64 @@
(() => {
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 reset = fixture.appendChild(document.createElement('button'));
const selection = getSelection();
const failures = [];
const check = (condition, label) => { if (!condition) failures.push(label); };
function at(range, node, start, end = start) {
return range && range.startContainer === node && range.startOffset === start &&
range.endContainer === node && range.endOffset === end;
}
for (const mode of ['open', 'closed']) {
const host = fixture.appendChild(document.createElement('div'));
const outer = host.attachShadow({mode});
const nested = outer.appendChild(document.createElement('div'));
const inner = nested.attachShadow({mode});
const editor = inner.appendChild(document.createElement('div'));
editor.contentEditable = 'true';
editor.innerHTML = '<p> abc</p>';
selection.removeAllRanges();
editor.focus();
check(selection.rangeCount === 1, mode + ': selection exists');
if (selection.rangeCount) {
const range = selection.getRangeAt(0);
const index = Array.prototype.indexOf.call(fixture.childNodes, host);
check(at(range, fixture, index), mode + ': range before outer host');
check(at(selection.getComposedRanges()[0], fixture, index, index + 1), mode + ': composed outer host');
check(at(selection.getComposedRanges({shadowRoots: [outer]})[0], outer, 0, 1), mode + ': composed inner host');
check(at(selection.getComposedRanges({shadowRoots: [inner]})[0], editor, 0), mode + ': raw editor boundary');
reset.focus();
editor.focus();
check(selection.getRangeAt(0) === range, mode + ': refocus retains shadow range');
}
host.remove();
}
const editor = fixture.appendChild(document.createElement('div'));
editor.contentEditable = 'true';
editor.textContent = 'parent editor';
editor.focus();
const topRange = selection.getRangeAt(0);
const frame = fixture.appendChild(document.createElement('iframe'));
const other = frame.contentWindow;
const doc = other.document;
const childBody = doc.body || doc.documentElement.appendChild(doc.createElement('body'));
const childEditor = childBody.appendChild(doc.createElement('div'));
childEditor.contentEditable = 'plaintext-only';
childEditor.textContent = 'child editor';
const childSelection = other.getSelection();
const OtherRange = other.Range;
other.Range = function () { throw new Error('replaced child Range'); };
HTMLElement.prototype.focus.call(childEditor);
check(childSelection.rangeCount === 1, 'borrowed focus updates owner selection');
if (childSelection.rangeCount) {
const range = childSelection.getRangeAt(0);
check(range instanceof OtherRange && !(range instanceof Range) && at(range, childEditor.firstChild, 0),
'initial range belongs to owner realm');
other.HTMLElement.prototype.focus.call(editor);
check(childSelection.getRangeAt(0) === range, 'parent focus retains child range');
}
check(selection.getRangeAt(0) === topRange, 'child focus preserves parent selection');
fixture.remove();
return failures.join('\n');
})()
@@ -0,0 +1,142 @@
(() => {
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'));
fixture.innerHTML = '<button id="reset">reset</button><p id="outside">outside</p>' +
'<div id="editor" contenteditable><span id="text">abcdef</span><input></div>' +
'<div id="other" contenteditable>other</div>';
const reset = fixture.querySelector('#reset');
const outside = fixture.querySelector('#outside').firstChild;
const editor = fixture.querySelector('#editor');
const text = fixture.querySelector('#text').firstChild;
const control = editor.querySelector('input');
const other = fixture.querySelector('#other');
const selection = getSelection();
const failures = [];
const check = (condition, label) => { if (!condition) failures.push(label); };
function caret(node, offset) {
return selection.rangeCount === 1 && selection.anchorNode === node &&
selection.anchorOffset === offset && selection.focusNode === node && selection.focusOffset === offset;
}
for (const [anchor, a, focus, f] of [[text, 4, text, 2], [text, 2, outside, 1], [editor, 0, editor, 0]]) {
selection.setBaseAndExtent(anchor, a, focus, f);
const range = selection.getRangeAt(0);
const direction = selection.direction;
reset.focus();
editor.focus();
check(selection.getRangeAt(0) === range && selection.anchorNode === anchor && selection.anchorOffset === a &&
selection.focusNode === focus && selection.focusOffset === f && selection.direction === direction,
'refocus preserves selection anchored in host');
}
selection.setBaseAndExtent(outside, 1, text, 2);
reset.focus();
editor.focus();
check(caret(text, 0), 'outside anchor resets selection');
control.focus();
editor.focus();
check(caret(text, 0), 'nested text control does not retain control projection');
selection.removeAllRanges();
editor.focus();
check(selection.rangeCount === 0, 'already focused editor does not recreate selection');
reset.focus();
editor.focus();
check(caret(text, 0), 'blur and refocus recreates cleared selection');
// A true or invalid state inside an editable parent does not create a host.
for (const value of ['true', 'plaintext-only', '', ' true ', 'false ', 'invalid']) {
text.parentNode.setAttribute('contenteditable', value);
reset.focus();
selection.collapse(outside, 1);
const range = selection.getRangeAt(0);
text.parentNode.focus();
check(document.activeElement === reset && selection.getRangeAt(0) === range,
value + ': nested editable element is not independently focusable');
text.parentNode.tabIndex = 0;
text.parentNode.focus();
check(document.activeElement === text.parentNode && selection.getRangeAt(0) === range,
value + ': focusable descendant does not initialize host selection');
text.parentNode.removeAttribute('tabindex');
}
text.parentNode.contentEditable = 'false';
selection.collapse(text, 2);
reset.focus();
editor.focus();
check(caret(editor, 0), 'selection in noneditable island does not belong to host');
text.parentNode.removeAttribute('contenteditable');
const island = editor.appendChild(document.createElement('div'));
island.contentEditable = 'false';
const nested = island.appendChild(document.createElement('div'));
nested.contentEditable = 'TrUe';
nested.textContent = 'nested editor';
reset.focus();
nested.focus();
check(document.activeElement === nested && caret(nested.firstChild, 0), 'true state below false creates host');
const invalid = fixture.appendChild(document.createElement('div'));
invalid.setAttribute('contenteditable', ' true ');
reset.focus();
invalid.focus();
check(document.activeElement === reset, 'enumerated contenteditable does not trim whitespace');
editor.focus();
editor.addEventListener('blur', () => nested.focus(), {once: true});
other.focus();
check(document.activeElement === nested && caret(nested.firstChild, 0), 'blur redirection retains redirected selection');
editor.addEventListener('focus', () => selection.collapse(text, 3), {once: true});
editor.focus();
check(caret(text, 3), 'focus listener selection is not overwritten');
other.addEventListener('focus', () => nested.focus(), {once: true});
other.focus();
check(document.activeElement === nested && caret(nested.firstChild, 0), 'focus redirection retains redirected selection');
const OriginalRange = Range;
const getSelectionOriginal = window.getSelection;
const computedStyleOriginal = window.getComputedStyle;
const createRangeOriginal = document.createRange;
const collapseOriginal = Selection.prototype.collapse;
let calls = 0;
const forbidden = () => { calls++; throw new Error('author hook entered'); };
try {
Object.defineProperty(window, 'Range', {configurable: true, get: forbidden});
window.getSelection = window.getComputedStyle = document.createRange = Selection.prototype.collapse = forbidden;
for (const name of ['parentNode', 'ownerDocument', 'contentEditable', 'firstChild', 'style']) {
Object.defineProperty(other, name, {configurable: true, get: forbidden});
}
other.focus();
check(selection.getRangeAt(0) instanceof OriginalRange &&
caret(other.childNodes[0], 0) && calls === 0, 'initial selection uses native DOM and intrinsic Range');
} finally {
Object.defineProperty(window, 'Range', {configurable: true, writable: true, value: OriginalRange});
window.getSelection = getSelectionOriginal;
window.getComputedStyle = computedStyleOriginal;
document.createRange = createRangeOriginal;
Selection.prototype.collapse = collapseOriginal;
for (const name of ['parentNode', 'ownerDocument', 'contentEditable', 'firstChild', 'style']) delete other[name];
}
// The visible caret follows its associated live Range while its initial
// composed boundary remains at the start of the editing host.
for (const action of ['remove-text', 'delete-prefix', 'split-prefix']) {
const box = fixture.appendChild(document.createElement('div'));
box.contentEditable = 'true';
box.innerHTML = '<span> abc</span><b>def</b>';
reset.focus();
selection.removeAllRanges();
box.focus();
const range = selection.getRangeAt(0);
const text = box.firstChild.firstChild;
if (action === 'remove-text') box.firstChild.remove();
if (action === 'delete-prefix') text.deleteData(0, 1);
if (action === 'split-prefix') text.splitText(0);
check(caret(range.startContainer, range.startOffset) && selection.getRangeAt(0) === range,
action + ': live caret endpoints');
const composed = selection.getComposedRanges()[0];
check(composed.startContainer === box && composed.startOffset === 0 &&
composed.endContainer === box && composed.endOffset === 0, action + ': composed host boundary');
reset.focus();
box.focus();
check(selection.getRangeAt(0) === range, action + ': mutated range retained on refocus');
box.remove();
}
fixture.remove();
return failures.join('\n');
})()
@@ -0,0 +1,121 @@
(() => {
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 reset = fixture.appendChild(document.createElement('button'));
const seed = fixture.appendChild(document.createTextNode('retained selection'));
const selection = getSelection();
const failures = [];
const check = (condition, label) => { if (!condition) failures.push(label); };
function at(range, node, offset) {
return range && range.startContainer === node && range.startOffset === offset &&
range.endContainer === node && range.endOffset === offset;
}
// Paths and offsets are native DOM boundaries, including UTF-16 text offsets.
const cases = [
['empty', '', [], 0],
['text', 'abc', [0], 0],
['nested text', '<span>abc</span>', [0, 0], 0],
['collapsed prefix', '<p> \t\nabc</p>', [0, 0], 3],
['pre', '<p style="white-space:pre"> \nabc</p>', [0, 0], 0],
['pre-wrap', '<p style="white-space:pre-wrap"> \nabc</p>', [0, 0], 0],
['pre-line', '<p style="white-space:pre-line"> \nabc</p>', [0, 0], 1],
['break-spaces', '<p style="white-space:break-spaces"> abc</p>', [0, 0], 0],
['nonbreaking space', '\u00a0abc', [0], 0],
['inline leading space', ' abc', [0], 1, 0],
['surrogate pair', ' \ud83d\ude00abc', [0], 1, 0],
['lone surrogate', ' \ud800abc', [0], 1, 0],
['only collapsed space', ' \n', [], 0],
['empty inline', '<span></span>', [], 0],
['empty inline before text', '<span></span>abc', [1], 0],
['empty blocks', '<p><!--comment--></p><div><p> </p></div><p>abc</p>', [2, 0], 0],
['sized empty block', '<div style="height:30px"></div><p>abc</p>', [0], 0],
['padded empty block', '<div style="padding:10px"></div><p>abc</p>', [0], 0],
['bordered empty block', '<div style="border:2px solid"></div><p>abc</p>', [0], 0],
['empty inline block', '<span style="display:inline-block"></span>abc', [1], 0],
['line break', '<span><br></span>', [0], 0],
['atomic boundary', '<span></span><input>abc', [], 1],
['nested atomic boundary', '<span><b></b><input></span>abc', [0], 1],
['image boundary', '<span></span><img alt="image">abc', [], 1],
['noneditable island', '<span></span><span contenteditable="false">abc</span>def', [], 0],
['inert island', '<span></span><span inert>abc</span>def', [], 0],
['noneditable control', '<span></span><input contenteditable="false">abc', [], 0],
['nested noneditable island', '<div><span></span><span contenteditable="false">abc</span>def</div>', [0], 0],
['hidden subtree', '<span style="display:none">hidden</span><p>shown</p>', [1, 0], 0],
['hidden text', '<span style="visibility:hidden">hidden</span><span>shown</span>', [1, 0], 0],
['visibility override', '<p style="visibility:hidden"><span style="visibility:visible">shown</span></p>', [0, 0, 0], 0],
['list', '<ul><li>abc</li></ul>', [0, 0, 0], 0],
['table boundary', '<table><tr><td>abc</td></tr></table>', [], 0],
['SVG text', '<svg><text> abc</text></svg>def', [0, 0, 0], 1],
['SVG foreignObject', '<svg><foreignObject width="100" height="100"><span> abc</span></foreignObject></svg>def', [0, 0, 0, 0], 1],
['SVG graphics before text', '<svg><rect width="10" height="10"/></svg>def', [1], 0],
['MathML text', '<math><mi> abc</mi></math>def', [0, 0, 0], 1],
['display contents', '<p style="display:contents"><span>abc</span></p>', [0, 0, 0], 0],
['offscreen text', '<p style="position:absolute;top:-100px">abc</p><p>def</p>', [0, 0], 0],
];
for (const tag of ['div', 'span']) {
for (const [name, html, path, blockOffset, inlineOffset = blockOffset] of cases) {
const offset = tag === 'span' ? inlineOffset : blockOffset;
const editor = fixture.appendChild(document.createElement(tag));
editor.contentEditable = 'true';
editor.innerHTML = html;
const node = path.reduce((node, index) => node.childNodes[index], editor);
reset.focus();
selection.setBaseAndExtent(seed, 1, seed, 4);
const previous = selection.getRangeAt(0);
let observed = false;
editor.addEventListener('focus', () => {
observed = selection.rangeCount === 1 && at(selection.getRangeAt(0), node, offset);
}, {once: true});
editor.focus();
const label = tag + ': ' + name;
check(document.activeElement === editor && observed, label + ': updated before focus');
check(selection.rangeCount === 1, label + ': range exists');
if (selection.rangeCount) {
const range = selection.getRangeAt(0);
check(at(range, node, offset) && selection.isCollapsed && selection.direction === 'none',
label + ': initial caret');
check(selection.anchorNode === node && selection.anchorOffset === offset &&
selection.focusNode === node && selection.focusOffset === offset, label + ': endpoints');
check(at(selection.getComposedRanges()[0], editor, 0), label + ': composed initial boundary');
check(range !== previous && previous.startContainer === seed && previous.startOffset === 1 &&
previous.endContainer === seed && previous.endOffset === 4, label + ': old range unchanged');
reset.focus();
editor.focus();
check(selection.getRangeAt(0) === range, label + ': refocus retains range');
}
editor.remove();
}
}
for (const [before, html, after, path, offset] of [
['abc', ' abc', '', [0], 0],
['abc ', ' abc', '', [0], 3],
['<span>abc</span><!--x--><span></span>', '<span> abc</span>', '', [0, 0], 0],
['<p>abc</p>', ' abc', '', [0], 1],
['<br>', ' abc', '', [0], 1],
['<input>', ' abc', '', [0], 0],
['<span style="display:none">abc</span>', ' abc', '', [0], 1],
['<span style="visibility:hidden">abc</span>', ' abc', '', [0], 0],
['<span style="display:inline-block">abc </span>', ' abc', '', [0], 0],
['abc', '<span> </span><span>abc</span>', '', [0, 0], 0],
['abc ', '<span> </span><span>abc</span>', '', [1, 0], 0],
['abc', ' ', 'def', [0], 0],
['abc', ' ', '', [], 0],
['abc', '<span style="white-space:pre-line"> \nabc</span>', '', [0, 0], 1],
['abc', '<span style="white-space:pre-line"> </span><span style="white-space:pre-line">\nabc</span>', '', [1, 0], 0],
['<span style="white-space:pre">abc </span>', ' abc', '', [0], 0],
['<svg width="10" height="10"><rect width="10" height="10"/></svg>', ' abc', '', [0], 0],
]) {
const block = fixture.appendChild(document.createElement('div'));
block.innerHTML = before + '<span data-editor contenteditable>' + html + '</span>' + after;
const editor = block.querySelector('[data-editor]');
const node = path.reduce((node, index) => node.childNodes[index], editor);
selection.removeAllRanges();
editor.focus();
check(selection.rangeCount === 1 && at(selection.getRangeAt(0), node, offset),
'inline whitespace: ' + before + ' / ' + html + ' / ' + after);
block.remove();
}
fixture.remove();
return failures.join('\n');
})()