@@ -35,6 +35,10 @@ function stripPatternCharacters(value) {
35
35
return value . replace ( / [ ^ \d A - z ] / g, '' ) ;
36
36
}
37
37
38
+ function isUserCharacter ( character ) {
39
+ return / [ \d A - z ] / . test ( character ) ;
40
+ }
41
+
38
42
function Input ( {
39
43
onChange = noop ,
40
44
onValueChange = noop ,
@@ -56,9 +60,11 @@ function Input({
56
60
let rawValue = stripPatternCharacters ( inputValue ) ;
57
61
58
62
if ( didDelete ) {
59
- const nonNumericWasDeleted = / [ ^ \d A - z ] / . test ( [ ...value ] [ cursorPosition ] ) ;
63
+ const patternCharacterDeleted = ! isUserCharacter (
64
+ [ ...value ] [ cursorPosition ]
65
+ ) ;
60
66
61
- if ( nonNumericWasDeleted ) {
67
+ if ( patternCharacterDeleted ) {
62
68
const firstBit = inputValue . substr ( 0 , cursorPosition ) ;
63
69
const rawFirstBit = stripPatternCharacters ( firstBit ) ;
64
70
@@ -75,19 +81,39 @@ function Input({
75
81
76
82
const formattedValue = format ( rawValue , pattern ) ;
77
83
78
- infoRef . current . formattingWasAdded =
79
- formattedValue . length - value . length > 1 ;
84
+ infoRef . current . endOfSection = false ;
85
+
86
+ if ( ! didDelete ) {
87
+ const formattedCharacters = [ ...formattedValue ] ;
88
+ const nextCharacter = formattedCharacters [ cursorPosition ] ;
89
+ const nextCharacterIsPattern = ! isUserCharacter ( nextCharacter ) ;
90
+ const nextUserCharacterIndex = formattedValue
91
+ . substr ( cursorPosition )
92
+ . search ( / [ \d A - z ] / ) ;
93
+ const numbersAhead = nextUserCharacterIndex !== - 1 ;
94
+
95
+ infoRef . current . endOfSection = nextCharacterIsPattern && ! numbersAhead ;
96
+
97
+ if (
98
+ nextCharacterIsPattern &&
99
+ ! isUserCharacter ( formattedCharacters [ cursorPosition - 1 ] ) &&
100
+ numbersAhead
101
+ )
102
+ infoRef . current . cursorPosition =
103
+ cursorPosition + nextUserCharacterIndex + 1 ;
104
+ }
80
105
81
106
onValueChange ( rawValue ) ;
82
107
onChange ( event ) ;
83
108
setValue ( formattedValue ) ;
84
109
}
85
110
86
111
useEffect ( ( ) => {
87
- const { cursorPosition, formattingWasAdded } = infoRef . current ;
112
+ const { cursorPosition, endOfSection } = infoRef . current ;
113
+
114
+ if ( endOfSection ) return ;
88
115
89
- if ( ! formattingWasAdded )
90
- inputRef . current . setSelectionRange ( cursorPosition , cursorPosition ) ;
116
+ inputRef . current . setSelectionRange ( cursorPosition , cursorPosition ) ;
91
117
} , [ value ] ) ;
92
118
93
119
return (
0 commit comments