@@ -172,6 +172,64 @@ test("focus a given element when dialog opens and initialFocusRef is passed in",
172172 expect ( button2 ) . toHaveFocus ( ) ;
173173} ) ;
174174
175+ test ( "focus a given element when dialog opens and initial focus has been manually set using React.useEffect" , ( ) => {
176+ const Test = ( ) => {
177+ const dialog = useDialogState ( ) ;
178+ const ref = React . useRef < HTMLButtonElement > ( null ) ;
179+
180+ React . useEffect ( ( ) => {
181+ if ( dialog . visible && ref . current ) {
182+ ref . current . focus ( ) ;
183+ }
184+ } , [ dialog . visible ] ) ;
185+
186+ return (
187+ < >
188+ < DialogDisclosure { ...dialog } > disclosure</ DialogDisclosure >
189+ < Dialog { ...dialog } aria-label = "dialog" >
190+ < button > button1</ button >
191+ < button ref = { ref } > button2</ button >
192+ </ Dialog >
193+ </ >
194+ ) ;
195+ } ;
196+ const { getByText } = render ( < Test /> ) ;
197+ const disclosure = getByText ( "disclosure" ) ;
198+ const button2 = getByText ( "button2" ) ;
199+ expect ( document . body ) . toHaveFocus ( ) ;
200+ fireEvent . click ( disclosure ) ;
201+ expect ( button2 ) . toHaveFocus ( ) ;
202+ } ) ;
203+
204+ test ( "focus a given element when dialog opens and initial focus has been manually set using autoFocus" , ( ) => {
205+ const Test = ( ) => {
206+ const dialog = useDialogState ( ) ;
207+ return (
208+ < >
209+ < DialogDisclosure { ...dialog } > disclosure</ DialogDisclosure >
210+ < Dialog { ...dialog } aria-label = "dialog" >
211+ { props =>
212+ dialog . visible && (
213+ < div { ...props } >
214+ < button > button1</ button >
215+ { /* eslint-disable-next-line jsx-a11y/no-autofocus */ }
216+ < button autoFocus > button2</ button >
217+ </ div >
218+ )
219+ }
220+ </ Dialog >
221+ </ >
222+ ) ;
223+ } ;
224+ const { getByText } = render ( < Test /> ) ;
225+ const disclosure = getByText ( "disclosure" ) ;
226+ expect ( document . body ) . toHaveFocus ( ) ;
227+ expect ( ( ) => getByText ( "button2" ) ) . toThrow ( ) ;
228+ fireEvent . click ( disclosure ) ;
229+ const button2 = getByText ( "button2" ) ;
230+ expect ( button2 ) . toHaveFocus ( ) ;
231+ } ) ;
232+
175233test ( "focus dialog itself if there is no tabbable descendant element" , ( ) => {
176234 const Test = ( ) => {
177235 const dialog = useDialogState ( ) ;
0 commit comments