Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

MessageContainer.tsx 10.0KB

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