您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

MessageContainer.tsx 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. import throttle from 'lodash/throttle';
  2. import React, { RefObject } from 'react';
  3. import { scrollIntoView } from 'seamless-scroll-polyfill';
  4. import { MESSAGE_TYPE_LOCAL, 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 or the local user send a new message,
  118. * 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 newMessages = this.props.messages.filter(message => !prevProps.messages.includes(message));
  126. const hasLocalMessage = newMessages.map(message => message.messageType).includes(MESSAGE_TYPE_LOCAL);
  127. if (newMessages.length > 0) {
  128. if (this.state.isScrolledToBottom || hasLocalMessage) {
  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 - The 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. }