@@ -14,13 +14,26 @@ See the License for the specific language governing permissions and
14
14
limitations under the License.
15
15
*/
16
16
17
- import { useCallback , useEffect , useRef } from "react" ;
17
+ import { MutableRefObject , useCallback , useEffect , useRef } from "react" ;
18
18
19
19
import useFocus from "../../../../../hooks/useFocus" ;
20
20
import { setSelection } from "../utils/selection" ;
21
21
22
22
type SubSelection = Pick < Selection , 'anchorNode' | 'anchorOffset' | 'focusNode' | 'focusOffset' > ;
23
23
24
+ function setSelectionRef ( selectionRef : MutableRefObject < SubSelection > ) {
25
+ const selection = document . getSelection ( ) ;
26
+
27
+ if ( selection ) {
28
+ selectionRef . current = {
29
+ anchorNode : selection . anchorNode ,
30
+ anchorOffset : selection . anchorOffset ,
31
+ focusNode : selection . focusNode ,
32
+ focusOffset : selection . focusOffset ,
33
+ } ;
34
+ }
35
+ }
36
+
24
37
export function useSelection ( ) {
25
38
const selectionRef = useRef < SubSelection > ( {
26
39
anchorNode : null ,
@@ -32,16 +45,7 @@ export function useSelection() {
32
45
33
46
useEffect ( ( ) => {
34
47
function onSelectionChange ( ) {
35
- const selection = document . getSelection ( ) ;
36
-
37
- if ( selection ) {
38
- selectionRef . current = {
39
- anchorNode : selection . anchorNode ,
40
- anchorOffset : selection . anchorOffset ,
41
- focusNode : selection . focusNode ,
42
- focusOffset : selection . focusOffset ,
43
- } ;
44
- }
48
+ setSelectionRef ( selectionRef ) ;
45
49
}
46
50
47
51
if ( isFocused ) {
@@ -51,9 +55,13 @@ export function useSelection() {
51
55
return ( ) => document . removeEventListener ( 'selectionchange' , onSelectionChange ) ;
52
56
} , [ isFocused ] ) ;
53
57
58
+ const onInput = useCallback ( ( ) => {
59
+ setSelectionRef ( selectionRef ) ;
60
+ } , [ ] ) ;
61
+
54
62
const selectPreviousSelection = useCallback ( ( ) => {
55
63
setSelection ( selectionRef . current ) ;
56
- } , [ selectionRef ] ) ;
64
+ } , [ ] ) ;
57
65
58
- return { ...focusProps , selectPreviousSelection } ;
66
+ return { ...focusProps , selectPreviousSelection, onInput } ;
59
67
}
0 commit comments