File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -391,11 +391,41 @@ it("autofocuses each selected conversation once without stealing focus on update
391391 expect ( other ) . toHaveFocus ( ) ;
392392 h . retarget ( { channelId : "another-channel" } ) ;
393393 expect ( h . input ( ) ) . toHaveFocus ( ) ;
394+ h . retarget ( { channelId : "keyboard-navigation" } ) ;
395+ expect ( h . input ( ) ) . toHaveFocus ( ) ;
394396 } finally {
395397 other . remove ( ) ;
396398 }
397399} ) ;
398400
401+ it ( "lets an explicit focus restoration in the mount commit win" , ( ) => {
402+ const h = mount ( ) ;
403+ h . unmount ( ) ;
404+ const target = document . createElement ( "button" ) ;
405+ document . body . append ( target ) ;
406+ function RestoreFocus ( ) {
407+ useLayoutEffect ( ( ) => target . focus ( ) , [ ] ) ;
408+ return null ;
409+ }
410+ try {
411+ render (
412+ < >
413+ < MessageComposer
414+ session = { h . session }
415+ scope = "scope"
416+ channelId = "channel"
417+ channelName = "General"
418+ autoFocus
419+ />
420+ < RestoreFocus />
421+ </ > ,
422+ ) ;
423+ expect ( target ) . toHaveFocus ( ) ;
424+ } finally {
425+ target . remove ( ) ;
426+ }
427+ } ) ;
428+
399429it ( "leaves focus alone unless an enabled composer opts into mount focus" , ( ) => {
400430 const h = mount ( ) ;
401431 expect ( h . input ( ) ) . not . toHaveFocus ( ) ;
Original file line number Diff line number Diff line change @@ -205,9 +205,21 @@ function Composer({
205205 const valueRef = useRef ( value ) ;
206206 const caret = useRef < number | undefined > ( undefined ) ;
207207 const input = useRef < ComposerInputElement > ( null ) ;
208- const focusOnMount = useRef ( autoFocus && ! disabled ) ;
208+ const focusOnMount = useRef (
209+ autoFocus && ! disabled && typeof document !== "undefined"
210+ ? document . activeElement
211+ : undefined ,
212+ ) ;
209213 useEffect ( ( ) => {
210- if ( focusOnMount . current ) input . current ?. focus ( ) ;
214+ // A navigation/dialog owner may restore focus during this commit. Let that
215+ // explicit handoff win over the conversation's default initial focus.
216+ const previous = focusOnMount . current ;
217+ if (
218+ previous &&
219+ ( previous === document . activeElement ||
220+ ( ! previous . isConnected && document . activeElement === document . body ) )
221+ )
222+ input . current ?. focus ( ) ;
211223 } , [ ] ) ;
212224 const nonmembers = useNonmemberMentions ( session , channelId , ( ) =>
213225 input . current ?. focus ( ) ,
You can’t perform that action at this time.
0 commit comments