@@ -42,6 +42,8 @@ export default function useRangeOpen(
42
42
firstTimeOpen : boolean ,
43
43
triggerOpen : ( open : boolean , activeIndex : 0 | 1 | false , source : SourceType ) => void ,
44
44
] {
45
+ const rafRef = React . useRef < number > ( null ) ;
46
+
45
47
const [ firstTimeOpen , setFirstTimeOpen ] = React . useState ( false ) ;
46
48
47
49
const [ afferentOpen , setAfferentOpen ] = useMergedState ( defaultOpen || false , {
@@ -61,13 +63,26 @@ export default function useRangeOpen(
61
63
62
64
const [ nextActiveIndex , setNextActiveIndex ] = React . useState < 0 | 1 > ( null ) ;
63
65
66
+ const queryNextIndex = ( index : number ) => ( index === 0 ? 1 : 0 ) ;
67
+
64
68
React . useEffect ( ( ) => {
65
69
if ( mergedOpen ) {
66
70
setFirstTimeOpen ( true ) ;
67
71
}
68
72
} , [ mergedOpen ] ) ;
69
73
70
- const queryNextIndex = ( index : number ) => ( index === 0 ? 1 : 0 ) ;
74
+ React . useEffect ( ( ) => {
75
+ if ( ! afferentOpen && rafRef . current !== null ) {
76
+ // Unfocus
77
+ raf . cancel ( rafRef . current ) ;
78
+ rafRef . current = null ;
79
+
80
+ // Since the index will eventually point to the next one, it needs to be reset.
81
+ if ( mergedActivePickerIndex !== null ) {
82
+ setMergedActivePickerIndex ( queryNextIndex ( mergedActivePickerIndex ) ) ;
83
+ }
84
+ }
85
+ } , [ afferentOpen ] ) ;
71
86
72
87
const triggerOpen = useEvent ( ( nextOpen : boolean , index : 0 | 1 | false , source : SourceType ) => {
73
88
if ( index === false ) {
@@ -102,12 +117,17 @@ export default function useRangeOpen(
102
117
setFirstTimeOpen ( false ) ;
103
118
setMergedActivePickerIndex ( customNextActiveIndex ) ;
104
119
}
105
-
120
+
106
121
setNextActiveIndex ( null ) ;
107
122
108
123
// Focus back
109
124
if ( customNextActiveIndex !== null && ! disabled [ customNextActiveIndex ] ) {
110
- raf ( ( ) => {
125
+ // Trigger closure to ensure consistency between controlled and uncontrolled logic.
126
+ if ( afferentOpen && ! firstTimeOpen && nextActiveIndex === null ) {
127
+ setMergedOpen ( false ) ;
128
+ }
129
+
130
+ rafRef . current = raf ( ( ) => {
111
131
const ref = [ startInputRef , endInputRef ] [ customNextActiveIndex ] ;
112
132
ref . current ?. focus ( ) ;
113
133
} ) ;
0 commit comments