chat-ui-kit-react icon indicating copy to clipboard operation
chat-ui-kit-react copied to clipboard

scrollbar stays at the top when infinite scrolling

Open louisholley opened this issue 3 years ago • 25 comments

hey, thanks for the great package!

i'm using infinite scrolling on the MessageList component like this:

 <MessageList
  onYReachStart={loadMore}
  loadingMore={networkStatus === NetworkStatus.fetchMore}
 >

but when more messages are loaded, the scrollbar is still at the top of the container so it just keeps calling loadMore over and over. ideally the behaviour would be something like this:

before onYReachStart is called:

message4 <-----scroll to here
message5
message6

after onYReachStart is called:

message1
message2
message3
message4 <-----scroll bar is here
message5
message6

so that only the next page of messages is fetched, rather than continually fetching more pages until you manually scroll down. hope that makes sense!

louisholley avatar Apr 08 '21 14:04 louisholley

@louisholley It's strange because it should work out of the box exactly as you said.

Please compare your code with this example in the storybook: https://chatscope.io/storybook/react/?path=/docs/components-messagelist--loading-more-state

What are the differences? How can I reproduce it?

supersnager avatar Apr 08 '21 17:04 supersnager

yeah pretty sure my code is as the example:

<ChatContainer className="chat-body">
  <MessageList
    onYReachStart={loadMore}
    loadingMore={loadingMore}
  >
    {networkStatus === NetworkStatus.loading ? (
      <LoadingMessages />
    ) : (
      groupedMessages.map((messages, i) => (
        <MessageGroup
          direction={sentByMe ? "outgoing" : "incoming"}
          sender={messages[0].user.forenames}
          sentTime={messages[0].createdAt}
        >
          {!sentByMe && (
            <Avatar
              src={messages[0].user.photoUrl}
              name={messages[0].user.forenames}
            />
          )}
          <MessageGroup.Messages>
            {messages.map((message, i) => (
              <Message
                key={i}
                model={{
                  message: message.content,
                }}
              />
            ))}
          </MessageGroup.Messages>
        </MessageGroup>
      ))
    )}
  </MessageList>
</ChatContainer>;

then

 const loadMore = async () => {
    if (loadingMore) return;
    setLoadingMore(true);

    await fetchMore({
      variables: { id, after: data.conversation.messages.after },
    });

    setLoadingMore(false);
  };

it loads 2 or 3 batches before exhibiting the behaviour I described...not sure what to suggest in terms of reproducibility. I'll see if I get the time today to setup a codesandbox or something

louisholley avatar Apr 09 '21 08:04 louisholley

so i just replaced MessageGroup with a custom component and it is working perfectly...maybe it's from me trying to combine this UI kit with lots of custom code that is the issue. happy for you to close this! thanks :)

louisholley avatar Apr 09 '21 08:04 louisholley

Facing similar business with onYReachStart too. My chat is in modal. First thing is that it calls onYReachStart method on initial render(first modal open) even though scroll bar is at the bottom initially. Second and consequent openings of modal dont fire onYReachStart. Second thing is When I scroll to top, getting infinite calls of onYReachStart..

const Chat = () => {
...

  const onYReachEnd = () => {
    if (moreMessageLoading) {
      return;
    }

    try {
      loadMoreMessages({
        variables: {
          topicKey,
          afterMessageId: lastLoadedMessageId,
          direction: 'ASC',
          pageSize: 20,
        },
      });
    } catch (error) {
      console.error('Failed to load more: ', { error });
    } 
  };


  const getMessageHistory = () => {
    return messages.map((message) => {
      const isLastUnread = chatMessagesByTopic.getChatMessageByTopic.lastViewedMessageId === message.id;
      const messageDirection = message.ownMessage ? 'outgoing' : 'incoming';
      const messageFooterMessage = moment(message.createdAt).format('MMM DD, YYYY [at] h:mma z');
      return (
        <div as="Message" key={message.id}>
          <StyledMessage
            $isOwnMessage={message.ownMessage}
            model={{
              message: message.messageBody,
              direction: messageDirection,
            }}
          >
            <StyledMessage.Footer sender={messageFooterMessage} />
          </StyledMessage>

          {localUnreadCount && isLastUnread && (
            <ServiceMessage id="unreadCountMsg" $isUnreadCount>
              {localUnreadCount} Unread Messages
            </ServiceMessage>
          )}
        </div>
      );
    });
  };

return (
    <div style={{ position: 'relative', height: '500px' }}>
      <StyledMainContainer>
        <StyledChatContainer>
          <MessageList
            ref={msgListRef}
            autoScrollToBottomOnMount={false}
            autoScrollToBottom={false}
            scrollBehavior="smooth"
            loadingMore={moreMessageLoading}
            onYReachEnd={onYReachEnd}
          >
            {!chatMessagesByTopic ? <ServiceMessage>No Messages Yet</ServiceMessage> : getMessageHistory()}
          </MessageList>
          {chatMessagesByTopic && (
            <StyledMessageInputGroupContainer as={MessageInput}>
              <MessageInput
                ref={inputRef}
                onChange={(msg) => setMsgInputValue(msg)}
                value={msgInputValue}
                sendButton={false}
                attachButton={false}
                onSend={handleSend}
                autoFocus
                style={{
                  flexGrow: 1,
                  borderTop: 0,
                }}
              />
              <StyledButton isTall onClick={() => handleSend(msgInputValue)} disabled={msgInputValue.length === 0}>
                Send
              </StyledButton>
            </StyledMessageInputGroupContainer>
          )}
        </StyledChatContainer>
      </StyledMainContainer>
    </div>
  );
};

FYI not even using freshly fetched messages yet (I mean not rendering them) just want to get them logged. Closing modal first time also triggers onYReachStart (if scrollbar is at the top at the time of closing) Similar behaviour is for onYReachEnd.. Must be doing something wrong 🤔

@supersnager any chance you could think of whats wrong with the code above ?

for onYReachEnd added autoScrollToBottomOnMount={false} and autoScrollToBottom={false} still on chat open in modal, it makes api calls until all messages are fetched because scroll bar is at the bottom of the screen

yevhen-logosha avatar Apr 10 '21 15:04 yevhen-logosha

@louisholley hey mate, what have you used as a custom component instead of MessageGroup ? Getting kinda similar infinite calls to api in onYReactStart/End

yevhen-logosha avatar Apr 12 '21 10:04 yevhen-logosha

basically soon as chat loads, both onYReachStart and onYReachEnd gets called. Even with autoScrollToBottomOnMount={false} and autoScrollToBottom={false} 😖

yevhen-logosha avatar Apr 12 '21 17:04 yevhen-logosha

@yevhen-logosha Can you provide a minimal repro repository, please?

supersnager avatar Apr 12 '21 18:04 supersnager

@supersnager thanks for reply. Here is super simple repo using modal I use elsewhere, https://codesandbox.io/s/unruffled-booth-de3wb its done in 10 mins so no judging 🙈

Open console please, click open modal and see onYReachEnd called few times, there are like 10msg so no scroll bar even.. close modal, observe onYReachEnd called few times again.. autoScrollToBottomOnMount={false} and autoScrollToBottom={false} applied..

Perhaps its ok behaviour, but how could we make it so we dont call either onYReachEnd or onYReachStart upon first render 🤔 Im also getting double calls of either of those at work, but that beast is tough to make a repo out of lol.

Here is the gist:

  • using apollo graphql, calling query, in useeffect setting result to state,
  • render messages from that state.
  • upon scroll - fetching more data with uselazyquery,
  • adding result to same state
  • all renders well..

just infinite scroll bugs me.. each scroll calls api twice now, then bounces back(good), scroll again - 2 calls and so on, plus upon initial render onYReach both get called..

sorry long, boring and confusing

yevhen-logosha avatar Apr 12 '21 19:04 yevhen-logosha

@yevhen-logosha Thanks for repro. I will analyze it and come back to you with my thoughts.

supersnager avatar Apr 14 '21 12:04 supersnager

@yevhen-logosha I have probably found what causes this behavior.

From what I have found the main problem is that onYReachEnd is fired on the first <MessageList /> render even when the content is smaller than component height and there is no scrollbar at all. This is caused by calling updateScroll method of ReactPerfectScrollbar in the ResizeObserver callback. This callback is fired the first time when a watched element is inserted into the DOM (The documentation says: "Observation will fire when watched Element is inserted/removed from DOM.").

Now I need to find a way to prevent the updateScroll method from firing when the element is inserted. I need so time to make a fix. Probably tomorrow will try to deal with this, so please be patient it will definitely be fixed.

One more thing: onYReachEnd is fired three times in your repro because the Modal renders its own content three times.

supersnager avatar Apr 15 '21 13:04 supersnager

@supersnager thanks for your time and work mate.

yevhen-logosha avatar Apr 15 '21 18:04 yevhen-logosha

@supersnager onYReachStart={loadChannelMessages}> mine method is also firing multiple times on just rendering. I just move it to bottom inside useEffect

setTimeout(() => { if (msgListRef.current) msgListRef.current.scrollToBottom('smooth'); }, 1000);

How to stop it on first render until the user scroll to top manually. Is this related to the above issue?

GhazanfarKhan avatar Apr 15 '21 19:04 GhazanfarKhan

@yevhen-logosha Please try v1.6.1 I have added disableOnYReachWhenNoScroll property to <MessageList />. Set this property to true and let me know if this helped.

@GhazanfarKhan It looks like your problem is related to this issue. onYReachStart also is fired sometimes by default where there is no scrollbar. Please check the mentioned version and come back with your result.

supersnager avatar Apr 19 '21 16:04 supersnager

@supersnager looks good mate. thanks for your work! 🍻

yevhen-logosha avatar Apr 21 '21 16:04 yevhen-logosha

In my case its not working. I manually setup a field and when the message binds and scroll moves to bottom on first load then I made that field false.

GhazanfarKhan avatar Apr 26 '21 10:04 GhazanfarKhan

@GhazanfarKhan I'm not sure what do you mean. Could you please describe it more precisely or prepare some simple repro?

supersnager avatar Apr 27 '21 08:04 supersnager

Hi check this sandbox. https://codesandbox.io/s/angry-star-wq9m5 on onYReachStart is called and End called 2 times

GhazanfarKhan avatar Apr 27 '21 10:04 GhazanfarKhan

@GhazanfarKhan Thanks for repro. I will analyze it and come back to you with my thoughts.

supersnager avatar May 16 '21 19:05 supersnager

Note to myself: resizeObserver is the key for a case when the scrollbar exists.

supersnager avatar May 17 '21 12:05 supersnager

Hi, I am getting the same issue. did anyone find any fix??

rawatmanoj avatar Jan 11 '22 21:01 rawatmanoj

We fixed it using lodash debounce.

laakal avatar Mar 07 '22 13:03 laakal

@laakal Could you please explain more?

supersnager avatar Mar 08 '22 07:03 supersnager

How did you fix this problem? I'm having the same, API is called two times when the MesageList first renders.

ryanalencar avatar Sep 15 '22 01:09 ryanalencar

@ryanalencar When do you call the API, is it in the onYReachEnd?

supersnager avatar Nov 16 '22 08:11 supersnager

When I set scrollBehaviour="smooth", the scrollbar always starts at the top on first render. This doesn't happen with the default scrollBehaviour="auto". Can open a separate issue for this.

j-krl avatar Feb 24 '23 22:02 j-krl