@@ -400,6 +400,18 @@ const MessageFlashListWithContext = (props: MessageFlashListPropsWithContext) =>
400400 }
401401 } , [ disabled ] ) ;
402402
403+ const indexToScrollToRef = useRef < number | undefined > ( undefined ) ;
404+
405+ const initialIndexToScrollTo = useMemo ( ( ) => {
406+ return targetedMessage
407+ ? processedMessageList . findIndex ( ( message ) => message ?. id === targetedMessage )
408+ : - 1 ;
409+ } , [ processedMessageList , targetedMessage ] ) ;
410+
411+ useEffect ( ( ) => {
412+ indexToScrollToRef . current = initialIndexToScrollTo ;
413+ } , [ initialIndexToScrollTo ] ) ;
414+
403415 /**
404416 * Check if a messageId needs to be scrolled to after list loads, and scroll to it
405417 * Note: This effect fires on every list change with a small debounce so that scrolling isnt abrupted by an immediate rerender
@@ -431,8 +443,28 @@ const MessageFlashListWithContext = (props: MessageFlashListPropsWithContext) =>
431443 }
432444 } , [ loadChannelAroundMessage , processedMessageList , setTargetedMessage , targetedMessage ] ) ;
433445
434- const goToMessage = useStableCallback ( ( messageId : string ) => {
435- setTargetedMessage ( messageId ) ;
446+ const goToMessage = useStableCallback ( async ( messageId : string ) => {
447+ const indexOfParentInMessageList = processedMessageList . findIndex (
448+ ( message ) => message ?. id === messageId ,
449+ ) ;
450+
451+ indexToScrollToRef . current = indexOfParentInMessageList ;
452+
453+ try {
454+ if ( indexOfParentInMessageList === - 1 ) {
455+ clearTimeout ( scrollToDebounceTimeoutRef . current ) ;
456+ await loadChannelAroundMessage ( { messageId, setTargetedMessage } ) ;
457+ } else {
458+ flashListRef . current ?. scrollToIndex ( {
459+ animated : true ,
460+ index : indexOfParentInMessageList ,
461+ viewPosition : 0.5 ,
462+ } ) ;
463+ setTargetedMessage ( messageId ) ;
464+ }
465+ } catch ( e ) {
466+ console . warn ( 'Error while scrolling to message' , e ) ;
467+ }
436468 } ) ;
437469
438470 useEffect ( ( ) => {
@@ -494,6 +526,7 @@ const MessageFlashListWithContext = (props: MessageFlashListPropsWithContext) =>
494526 setScrollToBottomButtonVisible ( true ) ;
495527 return ;
496528 } else {
529+ indexToScrollToRef . current = undefined ;
497530 setAutoscrollToRecent ( true ) ;
498531 }
499532 const latestNonCurrentMessageBeforeUpdate = latestNonCurrentMessageBeforeUpdateRef . current ;
@@ -1107,6 +1140,9 @@ const MessageFlashListWithContext = (props: MessageFlashListPropsWithContext) =>
11071140 data = { processedMessageList }
11081141 drawDistance = { 800 }
11091142 getItemType = { getItemType }
1143+ initialScrollIndex = {
1144+ indexToScrollToRef . current === - 1 ? undefined : indexToScrollToRef . current
1145+ }
11101146 keyboardShouldPersistTaps = 'handled'
11111147 keyExtractor = { keyExtractor }
11121148 ListFooterComponent = { FooterComponent }
0 commit comments