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.

273 lines
7.9 KiB

  1. import React, { PureComponent } from 'react';
  2. import { ScrollContainer } from 'react-router-scroll-4';
  3. import PropTypes from 'prop-types';
  4. import IntersectionObserverArticleContainer from '../containers/intersection_observer_article_container';
  5. import LoadMore from './load_more';
  6. import IntersectionObserverWrapper from '../features/ui/util/intersection_observer_wrapper';
  7. import { throttle } from 'lodash';
  8. import { List as ImmutableList } from 'immutable';
  9. import classNames from 'classnames';
  10. import { attachFullscreenListener, detachFullscreenListener, isFullscreen } from '../features/ui/util/fullscreen';
  11. import LoadingIndicator from './loading_indicator';
  12. const MOUSE_IDLE_DELAY = 300;
  13. export default class ScrollableList extends PureComponent {
  14. static contextTypes = {
  15. router: PropTypes.object,
  16. };
  17. static propTypes = {
  18. scrollKey: PropTypes.string.isRequired,
  19. onLoadMore: PropTypes.func,
  20. onScrollToTop: PropTypes.func,
  21. onScroll: PropTypes.func,
  22. trackScroll: PropTypes.bool,
  23. shouldUpdateScroll: PropTypes.func,
  24. isLoading: PropTypes.bool,
  25. showLoading: PropTypes.bool,
  26. hasMore: PropTypes.bool,
  27. prepend: PropTypes.node,
  28. alwaysPrepend: PropTypes.bool,
  29. emptyMessage: PropTypes.node,
  30. children: PropTypes.node,
  31. };
  32. static defaultProps = {
  33. trackScroll: true,
  34. };
  35. state = {
  36. fullscreen: null,
  37. };
  38. intersectionObserverWrapper = new IntersectionObserverWrapper();
  39. handleScroll = throttle(() => {
  40. if (this.node) {
  41. const { scrollTop, scrollHeight, clientHeight } = this.node;
  42. const offset = scrollHeight - scrollTop - clientHeight;
  43. if (400 > offset && this.props.onLoadMore && this.props.hasMore && !this.props.isLoading) {
  44. this.props.onLoadMore();
  45. }
  46. if (scrollTop < 100 && this.props.onScrollToTop) {
  47. this.props.onScrollToTop();
  48. } else if (this.props.onScroll) {
  49. this.props.onScroll();
  50. }
  51. if (!this.lastScrollWasSynthetic) {
  52. // If the last scroll wasn't caused by setScrollTop(), assume it was
  53. // intentional and cancel any pending scroll reset on mouse idle
  54. this.scrollToTopOnMouseIdle = false;
  55. }
  56. this.lastScrollWasSynthetic = false;
  57. }
  58. }, 150, {
  59. trailing: true,
  60. });
  61. mouseIdleTimer = null;
  62. mouseMovedRecently = false;
  63. lastScrollWasSynthetic = false;
  64. scrollToTopOnMouseIdle = false;
  65. setScrollTop = newScrollTop => {
  66. if (this.node.scrollTop !== newScrollTop) {
  67. this.lastScrollWasSynthetic = true;
  68. this.node.scrollTop = newScrollTop;
  69. }
  70. };
  71. clearMouseIdleTimer = () => {
  72. if (this.mouseIdleTimer === null) {
  73. return;
  74. }
  75. clearTimeout(this.mouseIdleTimer);
  76. this.mouseIdleTimer = null;
  77. };
  78. handleMouseMove = throttle(() => {
  79. // As long as the mouse keeps moving, clear and restart the idle timer.
  80. this.clearMouseIdleTimer();
  81. this.mouseIdleTimer = setTimeout(this.handleMouseIdle, MOUSE_IDLE_DELAY);
  82. if (!this.mouseMovedRecently && this.node.scrollTop === 0) {
  83. // Only set if we just started moving and are scrolled to the top.
  84. this.scrollToTopOnMouseIdle = true;
  85. }
  86. // Save setting this flag for last, so we can do the comparison above.
  87. this.mouseMovedRecently = true;
  88. }, MOUSE_IDLE_DELAY / 2);
  89. handleWheel = throttle(() => {
  90. this.scrollToTopOnMouseIdle = false;
  91. }, 150, {
  92. trailing: true,
  93. });
  94. handleMouseIdle = () => {
  95. if (this.scrollToTopOnMouseIdle) {
  96. this.setScrollTop(0);
  97. }
  98. this.mouseMovedRecently = false;
  99. this.scrollToTopOnMouseIdle = false;
  100. }
  101. componentDidMount () {
  102. this.attachScrollListener();
  103. this.attachIntersectionObserver();
  104. attachFullscreenListener(this.onFullScreenChange);
  105. // Handle initial scroll posiiton
  106. this.handleScroll();
  107. }
  108. getSnapshotBeforeUpdate (prevProps) {
  109. const someItemInserted = React.Children.count(prevProps.children) > 0 &&
  110. React.Children.count(prevProps.children) < React.Children.count(this.props.children) &&
  111. this.getFirstChildKey(prevProps) !== this.getFirstChildKey(this.props);
  112. if (someItemInserted && (this.node.scrollTop > 0 || this.mouseMovedRecently)) {
  113. return this.node.scrollHeight - this.node.scrollTop;
  114. } else {
  115. return null;
  116. }
  117. }
  118. componentDidUpdate (prevProps, prevState, snapshot) {
  119. // Reset the scroll position when a new child comes in in order not to
  120. // jerk the scrollbar around if you're already scrolled down the page.
  121. if (snapshot !== null) {
  122. this.setScrollTop(this.node.scrollHeight - snapshot);
  123. }
  124. }
  125. componentWillUnmount () {
  126. this.clearMouseIdleTimer();
  127. this.detachScrollListener();
  128. this.detachIntersectionObserver();
  129. detachFullscreenListener(this.onFullScreenChange);
  130. }
  131. onFullScreenChange = () => {
  132. this.setState({ fullscreen: isFullscreen() });
  133. }
  134. attachIntersectionObserver () {
  135. this.intersectionObserverWrapper.connect({
  136. root: this.node,
  137. rootMargin: '300% 0px',
  138. });
  139. }
  140. detachIntersectionObserver () {
  141. this.intersectionObserverWrapper.disconnect();
  142. }
  143. attachScrollListener () {
  144. this.node.addEventListener('scroll', this.handleScroll);
  145. this.node.addEventListener('wheel', this.handleWheel);
  146. }
  147. detachScrollListener () {
  148. this.node.removeEventListener('scroll', this.handleScroll);
  149. this.node.removeEventListener('wheel', this.handleWheel);
  150. }
  151. getFirstChildKey (props) {
  152. const { children } = props;
  153. let firstChild = children;
  154. if (children instanceof ImmutableList) {
  155. firstChild = children.get(0);
  156. } else if (Array.isArray(children)) {
  157. firstChild = children[0];
  158. }
  159. return firstChild && firstChild.key;
  160. }
  161. setRef = (c) => {
  162. this.node = c;
  163. }
  164. handleLoadMore = e => {
  165. e.preventDefault();
  166. this.props.onLoadMore();
  167. }
  168. render () {
  169. const { children, scrollKey, trackScroll, shouldUpdateScroll, showLoading, isLoading, hasMore, prepend, alwaysPrepend, emptyMessage, onLoadMore } = this.props;
  170. const { fullscreen } = this.state;
  171. const childrenCount = React.Children.count(children);
  172. const loadMore = (hasMore && onLoadMore) ? <LoadMore visible={!isLoading} onClick={this.handleLoadMore} /> : null;
  173. let scrollableArea = null;
  174. if (showLoading) {
  175. scrollableArea = (
  176. <div className='scrollable scrollable--flex' ref={this.setRef}>
  177. <div role='feed' className='item-list'>
  178. {prepend}
  179. </div>
  180. <div className='scrollable__append'>
  181. <LoadingIndicator />
  182. </div>
  183. </div>
  184. );
  185. } else if (isLoading || childrenCount > 0 || hasMore || !emptyMessage) {
  186. scrollableArea = (
  187. <div className={classNames('scrollable', { fullscreen })} ref={this.setRef} onMouseMove={this.handleMouseMove}>
  188. <div role='feed' className='item-list'>
  189. {prepend}
  190. {React.Children.map(this.props.children, (child, index) => (
  191. <IntersectionObserverArticleContainer
  192. key={child.key}
  193. id={child.key}
  194. index={index}
  195. listLength={childrenCount}
  196. intersectionObserverWrapper={this.intersectionObserverWrapper}
  197. saveHeightKey={trackScroll ? `${this.context.router.route.location.key}:${scrollKey}` : null}
  198. >
  199. {child}
  200. </IntersectionObserverArticleContainer>
  201. ))}
  202. {loadMore}
  203. </div>
  204. </div>
  205. );
  206. } else {
  207. scrollableArea = (
  208. <div className={classNames('scrollable scrollable--flex', { fullscreen })} ref={this.setRef}>
  209. {alwaysPrepend && prepend}
  210. <div className='empty-column-indicator'>
  211. {emptyMessage}
  212. </div>
  213. </div>
  214. );
  215. }
  216. if (trackScroll) {
  217. return (
  218. <ScrollContainer scrollKey={scrollKey} shouldUpdateScroll={shouldUpdateScroll}>
  219. {scrollableArea}
  220. </ScrollContainer>
  221. );
  222. } else {
  223. return scrollableArea;
  224. }
  225. }
  226. }