You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

MessageContainer.tsx 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. import throttle from 'lodash/throttle';
  2. import React, { RefObject } from 'react';
  3. import { scrollIntoView } from 'seamless-scroll-polyfill';
  4. import { MESSAGE_TYPE_REMOTE } from '../../constants';
  5. import AbstractMessageContainer, { IProps } from '../AbstractMessageContainer';
  6. // @ts-ignore
  7. import ChatMessageGroup from './ChatMessageGroup';
  8. import NewMessagesButton from './NewMessagesButton';
  9. interface IState {
  10. /**
  11. * Whether or not message container has received new messages.
  12. */
  13. hasNewMessages: boolean;
  14. /**
  15. * Whether or not scroll position is at the bottom of container.
  16. */
  17. isScrolledToBottom: boolean;
  18. /**
  19. * The id of the last read message.
  20. */
  21. lastReadMessageId: string;
  22. }
  23. /**
  24. * Displays all received chat messages, grouped by sender.
  25. *
  26. * @augments AbstractMessageContainer
  27. */
  28. export default class MessageContainer extends AbstractMessageContainer<IProps, IState> {
  29. /**
  30. * Component state used to decide when the hasNewMessages button to appear
  31. * and where to scroll when click on hasNewMessages button.
  32. */
  33. state: IState = {
  34. hasNewMessages: false,
  35. isScrolledToBottom: true,
  36. lastReadMessageId: ''
  37. };
  38. /**
  39. * Reference to the HTML element at the end of the list of displayed chat
  40. * messages. Used for scrolling to the end of the chat messages.
  41. */
  42. _messagesListEndRef: RefObject<HTMLDivElement>;
  43. /**
  44. * A React ref to the HTML element containing all {@code ChatMessageGroup}
  45. * instances.
  46. */
  47. _messageListRef: RefObject<HTMLDivElement>;
  48. /**
  49. * Intersection observer used to detect intersections of messages with the bottom of the message container.
  50. */
  51. _bottomListObserver: IntersectionObserver;
  52. /**
  53. * Initializes a new {@code MessageContainer} instance.
  54. *
  55. * @param {IProps} props - The React {@code Component} props to initialize
  56. * the new {@code MessageContainer} instance with.
  57. */
  58. constructor(props: IProps) {
  59. super(props);
  60. this._messageListRef = React.createRef<HTMLDivElement>();
  61. this._messagesListEndRef = React.createRef<HTMLDivElement>();
  62. // Bind event handlers so they are only bound once for every instance.
  63. this._handleIntersectBottomList = this._handleIntersectBottomList.bind(this);
  64. this._findFirstUnreadMessage = this._findFirstUnreadMessage.bind(this);
  65. this._isMessageVisible = this._isMessageVisible.bind(this);
  66. this._onChatScroll = throttle(this._onChatScroll.bind(this), 300, { leading: true });
  67. this._onGoToFirstUnreadMessage = this._onGoToFirstUnreadMessage.bind(this);
  68. }
  69. /**
  70. * Implements {@code Component#render}.
  71. *
  72. * @inheritdoc
  73. */
  74. render() {
  75. const groupedMessages = this._getMessagesGroupedBySender();
  76. const messages = groupedMessages.map((group, index) => {
  77. const messageType = group[0]?.messageType;
  78. return (
  79. <ChatMessageGroup
  80. className = { messageType || MESSAGE_TYPE_REMOTE }
  81. key = { index }
  82. messages = { group } />
  83. );
  84. });
  85. return (
  86. <div id = 'chat-conversation-container'>
  87. <div
  88. aria-labelledby = 'chat-header'
  89. id = 'chatconversation'
  90. onScroll = { this._onChatScroll }
  91. ref = { this._messageListRef }
  92. role = 'log'
  93. tabIndex = { 0 }>
  94. { messages }
  95. { !this.state.isScrolledToBottom && this.state.hasNewMessages
  96. && <NewMessagesButton
  97. onGoToFirstUnreadMessage = { this._onGoToFirstUnreadMessage } /> }
  98. <div
  99. id = 'messagesListEnd'
  100. ref = { this._messagesListEndRef } />
  101. </div>
  102. </div>
  103. );
  104. }
  105. /**
  106. * Implements {@code Component#componentDidMount}.
  107. * When Component mount scroll message container to bottom.
  108. * Create observer to react when scroll position is at bottom or leave the bottom.
  109. *
  110. * @inheritdoc
  111. */
  112. componentDidMount() {
  113. this.scrollToElement(false, null);
  114. this._createBottomListObserver();
  115. }
  116. /**
  117. * Implements {@code Component#componentDidUpdate}.
  118. * If the user receive a new message scroll automatically to the bottom if scroll position was at the bottom.
  119. * Otherwise update hasNewMessages from component state.
  120. *
  121. * @inheritdoc
  122. * @returns {void}
  123. */
  124. componentDidUpdate(prevProps: IProps) {
  125. const hasNewMessages = this.props.messages.length !== prevProps.messages.length;
  126. if (hasNewMessages) {
  127. if (this.state.isScrolledToBottom) {
  128. this.scrollToElement(false, null);
  129. } else {
  130. // eslint-disable-next-line react/no-did-update-set-state
  131. this.setState({ hasNewMessages: true });
  132. }
  133. }
  134. }
  135. /**
  136. * Implements React's {@link Component#componentWillUnmount()}. Invoked
  137. * immediately before this component is unmounted and destroyed.
  138. *
  139. * @inheritdoc
  140. */
  141. componentWillUnmount() {
  142. const target = document.querySelector('#messagesListEnd');
  143. this._bottomListObserver.unobserve(target as Element);
  144. }
  145. /**
  146. * Automatically scrolls the displayed chat messages to bottom or to a specific element if it is provided.
  147. *
  148. * @param {boolean} withAnimation - Whether or not to show a scrolling.
  149. * @param {TMLElement} element - Where to scroll.
  150. * Animation.
  151. * @returns {void}
  152. */
  153. scrollToElement(withAnimation: boolean, element: Element | null) {
  154. const scrollTo = element ? element : this._messagesListEndRef.current;
  155. const block = element ? 'center' : 'nearest';
  156. scrollIntoView(scrollTo as Element, {
  157. behavior: withAnimation ? 'smooth' : 'auto',
  158. block
  159. });
  160. }
  161. /**
  162. * Callback invoked to listen to current scroll position and update next unread message.
  163. * The callback is invoked inside a throttle with 300 ms to decrease the number of function calls.
  164. *
  165. * @private
  166. * @returns {void}
  167. */
  168. _onChatScroll() {
  169. const firstUnreadMessage = this._findFirstUnreadMessage();
  170. if (firstUnreadMessage && firstUnreadMessage.id !== this.state.lastReadMessageId) {
  171. this.setState({ lastReadMessageId: firstUnreadMessage?.id });
  172. }
  173. }
  174. /**
  175. * Find the first unread message.
  176. * Update component state and scroll to element.
  177. *
  178. * @private
  179. * @returns {void}
  180. */
  181. _onGoToFirstUnreadMessage() {
  182. const firstUnreadMessage = this._findFirstUnreadMessage();
  183. this.setState({ lastReadMessageId: firstUnreadMessage?.id || null });
  184. this.scrollToElement(true, firstUnreadMessage as Element);
  185. }
  186. /**
  187. * Create observer to react when scroll position is at bottom or leave the bottom.
  188. *
  189. * @private
  190. * @returns {void}
  191. */
  192. _createBottomListObserver() {
  193. const options = {
  194. root: document.querySelector('#chatconversation'),
  195. rootMargin: '35px',
  196. threshold: 0.5
  197. };
  198. const target = document.querySelector('#messagesListEnd');
  199. if (target) {
  200. this._bottomListObserver = new IntersectionObserver(this._handleIntersectBottomList, options);
  201. this._bottomListObserver.observe(target);
  202. }
  203. }
  204. /** .
  205. * _HandleIntersectBottomList.
  206. * When entry is intersecting with bottom of container set last message as last read message.
  207. * When entry is not intersecting update only isScrolledToBottom with false value.
  208. *
  209. * @param {Array} entries - List of entries.
  210. * @private
  211. * @returns {void}
  212. */
  213. _handleIntersectBottomList(entries: IntersectionObserverEntry[]) {
  214. entries.forEach((entry: IntersectionObserverEntry) => {
  215. if (entry.isIntersecting && this.props.messages.length) {
  216. const lastMessageIndex = this.props.messages.length - 1;
  217. const lastMessage = this.props.messages[lastMessageIndex];
  218. const lastReadMessageId = lastMessage.messageId;
  219. this.setState(
  220. {
  221. isScrolledToBottom: true,
  222. hasNewMessages: false,
  223. lastReadMessageId
  224. });
  225. }
  226. if (!entry.isIntersecting) {
  227. this.setState(
  228. {
  229. isScrolledToBottom: false
  230. });
  231. }
  232. });
  233. }
  234. /**
  235. * Find first unread message.
  236. * MessageIsAfterLastSeenMessage filter elements which are not visible but are before the last read message.
  237. *
  238. * @private
  239. * @returns {Element}
  240. */
  241. _findFirstUnreadMessage() {
  242. const messagesNodeList = document.querySelectorAll('.chatmessage-wrapper');
  243. // @ts-ignore
  244. const messagesToArray = [ ...messagesNodeList ];
  245. const previousIndex = messagesToArray.findIndex((message: Element) =>
  246. message.id === this.state.lastReadMessageId);
  247. if (previousIndex !== -1) {
  248. for (let i = previousIndex; i < messagesToArray.length; i++) {
  249. if (!this._isMessageVisible(messagesToArray[i])) {
  250. return messagesToArray[i];
  251. }
  252. }
  253. }
  254. }
  255. /**
  256. * Check if a message is visible in view.
  257. *
  258. * @param {Element} message -
  259. *
  260. * @returns {boolean}
  261. */
  262. _isMessageVisible(message: Element): boolean {
  263. const { bottom, height, top } = message.getBoundingClientRect();
  264. if (this._messageListRef.current) {
  265. const containerRect = this._messageListRef.current.getBoundingClientRect();
  266. return top <= containerRect.top
  267. ? containerRect.top - top <= height : bottom - containerRect.bottom <= height;
  268. }
  269. return false;
  270. }
  271. }