w3c / selection-api

Selection API
http://w3c.github.io/selection-api/
Other
46 stars 28 forks source link

Define `Selection.rangeCount` when an input field is focused #166

Open whsieh opened 1 year ago

whsieh commented 1 year ago

Hello!

In the process of investigating a web compat issue in WebKit that affects Quip's editor, I stumbled into the fact that Selection.rangeCount behaves differently across FF, Chrome and Safari when the selection is moved into a text field.

Consider the following reduced test case:

<input />
<script>
document.querySelector("input").focus();
document.write(`rangeCount := ${getSelection().rangeCount}`);
</script>

Safari 16 and Chrome will show a rangeCount of 1. However, Safari 17 (with Live Range Selection enabled, at time of writing) and Firefox both show a rangeCount of 0. However, if I adjust the test case to additionally set the DOM selection prior to focusing the input:

<input />
<script>
getSelection().setPosition(document.body, 0);
document.querySelector("input").focus();
document.write(`rangeCount := ${getSelection().rangeCount}`);
</script>

...then Firefox outputs 1 instead of 0. The behavior in Firefox seems to be that moving focus into an input field doesn't affect selection ranges, whereas behavior in Safari 16 and Chrome is that the selection will move to the start of the containing shadow host (in this case, the input element). In Safari 17, with Live Range Selection enabled, we'll now expose a rangeCount of 0 after moving focus into a text field.

Edit: this is essentially a small piece of https://github.com/w3c/selection-api/issues/83, that's just about the rangeCount.

annevk commented 1 year ago

cc @smaug---- @mfreed7

smaug---- commented 1 year ago

FWIW, input type=text element in Firefox doesn't have shadow DOM inside it.

masayuki-nakano commented 5 months ago

Firefox may have multiple Selection objects per document. One is for the Document which is exposed with getSelection(). The others are independent objects for each <input> and <textarea> to make the selection range(s) restored easy at re-focus. And Firefox does not move the document selection at moving focus to a form control with a mouse click, but otherwise, e.g., tab navigation or Element.focus(), collapse Selection before the form control.