chatscope / chat-ui-kit-react

Build your own chat UI with React components in few minutes. Chat UI Kit from chatscope is an open source UI toolkit for developing web chat applications.
https://chatscope.io
MIT License
1.34k stars 116 forks source link

scrollbar stays at the top when infinite scrolling #26

Open louisholley opened 3 years ago

louisholley commented 3 years ago

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!

supersnager commented 3 years ago

@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?

louisholley commented 3 years ago

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 commented 3 years ago

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 :)

yevhen-logosha commented 3 years ago

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 commented 3 years ago

@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 commented 3 years ago

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

supersnager commented 3 years ago

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

yevhen-logosha commented 3 years ago

@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:

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

supersnager commented 3 years ago

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

supersnager commented 3 years ago

@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.

yevhen-logosha commented 3 years ago

@supersnager thanks for your time and work mate.

GhazanfarKhan commented 3 years ago

@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?

supersnager commented 3 years ago

@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.

yevhen-logosha commented 3 years ago

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

GhazanfarKhan commented 3 years ago

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.

supersnager commented 3 years ago

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

GhazanfarKhan commented 3 years ago

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

supersnager commented 3 years ago

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

supersnager commented 3 years ago

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

rawatmanoj commented 2 years ago

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

laakal commented 2 years ago

We fixed it using lodash debounce.

supersnager commented 2 years ago

@laakal Could you please explain more?

ryanalencar commented 2 years ago

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

supersnager commented 2 years ago

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

j-krl commented 1 year ago

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.