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

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