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.

299 lines
8.8 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. cachedMediaWidth: 250, // Default media/card width using default Mastodon theme
  38. };
  39. intersectionObserverWrapper = new IntersectionObserverWrapper();
  40. handleScroll = throttle(() => {
  41. if (this.node) {
  42. const { scrollTop, scrollHeight, clientHeight } = this.node;
  43. const offset = scrollHeight - scrollTop - clientHeight;
  44. if (400 > offset && this.props.onLoadMore && this.props.hasMore && !this.props.isLoading) {
  45. this.props.onLoadMore();
  46. }
  47. if (scrollTop < 100 && this.props.onScrollToTop) {
  48. this.props.onScrollToTop();
  49. } else if (this.props.onScroll) {
  50. this.props.onScroll();
  51. }
  52. if (!this.lastScrollWasSynthetic) {
  53. // If the last scroll wasn't caused by setScrollTop(), assume it was
  54. // intentional and cancel any pending scroll reset on mouse idle
  55. this.scrollToTopOnMouseIdle = false;
  56. }
  57. this.lastScrollWasSynthetic = false;
  58. }
  59. }, 150, {
  60. trailing: true,
  61. });
  62. mouseIdleTimer = null;
  63. mouseMovedRecently = false;
  64. lastScrollWasSynthetic = false;
  65. scrollToTopOnMouseIdle = false;
  66. setScrollTop = newScrollTop => {
  67. if (this.node.scrollTop !== newScrollTop) {
  68. this.lastScrollWasSynthetic = true;
  69. this.node.scrollTop = newScrollTop;
  70. }
  71. };
  72. clearMouseIdleTimer = () => {
  73. if (this.mouseIdleTimer === null) {
  74. return;
  75. }
  76. clearTimeout(this.mouseIdleTimer);
  77. this.mouseIdleTimer = null;
  78. };
  79. handleMouseMove = throttle(() => {
  80. // As long as the mouse keeps moving, clear and restart the idle timer.
  81. this.clearMouseIdleTimer();
  82. this.mouseIdleTimer = setTimeout(this.handleMouseIdle, MOUSE_IDLE_DELAY);
  83. if (!this.mouseMovedRecently && this.node.scrollTop === 0) {
  84. // Only set if we just started moving and are scrolled to the top.
  85. this.scrollToTopOnMouseIdle = true;
  86. }
  87. // Save setting this flag for last, so we can do the comparison above.
  88. this.mouseMovedRecently = true;
  89. }, MOUSE_IDLE_DELAY / 2);
  90. handleWheel = throttle(() => {
  91. this.scrollToTopOnMouseIdle = false;
  92. }, 150, {
  93. trailing: true,
  94. });
  95. handleMouseIdle = () => {
  96. if (this.scrollToTopOnMouseIdle) {
  97. this.setScrollTop(0);
  98. }
  99. this.mouseMovedRecently = false;
  100. this.scrollToTopOnMouseIdle = false;
  101. }
  102. componentDidMount () {
  103. this.attachScrollListener();
  104. this.attachIntersectionObserver();
  105. attachFullscreenListener(this.onFullScreenChange);
  106. // Handle initial scroll posiiton
  107. this.handleScroll();
  108. }
  109. getScrollPosition = () => {
  110. if (this.node && (this.node.scrollTop > 0 || this.mouseMovedRecently)) {
  111. return { height: this.node.scrollHeight, top: this.node.scrollTop };
  112. } else {
  113. return null;
  114. }
  115. }
  116. updateScrollBottom = (snapshot) => {
  117. const newScrollTop = this.node.scrollHeight - snapshot;
  118. this.setScrollTop(newScrollTop);
  119. }
  120. getSnapshotBeforeUpdate (prevProps) {
  121. const someItemInserted = React.Children.count(prevProps.children) > 0 &&
  122. React.Children.count(prevProps.children) < React.Children.count(this.props.children) &&
  123. this.getFirstChildKey(prevProps) !== this.getFirstChildKey(this.props);
  124. if (someItemInserted && (this.node.scrollTop > 0 || this.mouseMovedRecently)) {
  125. return this.node.scrollHeight - this.node.scrollTop;
  126. } else {
  127. return null;
  128. }
  129. }
  130. componentDidUpdate (prevProps, prevState, snapshot) {
  131. // Reset the scroll position when a new child comes in in order not to
  132. // jerk the scrollbar around if you're already scrolled down the page.
  133. if (snapshot !== null) {
  134. this.setScrollTop(this.node.scrollHeight - snapshot);
  135. }
  136. }
  137. cacheMediaWidth = (width) => {
  138. if (width && this.state.cachedMediaWidth !== width) {
  139. this.setState({ cachedMediaWidth: width });
  140. }
  141. }
  142. componentWillUnmount () {
  143. this.clearMouseIdleTimer();
  144. this.detachScrollListener();
  145. this.detachIntersectionObserver();
  146. detachFullscreenListener(this.onFullScreenChange);
  147. }
  148. onFullScreenChange = () => {
  149. this.setState({ fullscreen: isFullscreen() });
  150. }
  151. attachIntersectionObserver () {
  152. this.intersectionObserverWrapper.connect({
  153. root: this.node,
  154. rootMargin: '300% 0px',
  155. });
  156. }
  157. detachIntersectionObserver () {
  158. this.intersectionObserverWrapper.disconnect();
  159. }
  160. attachScrollListener () {
  161. this.node.addEventListener('scroll', this.handleScroll);
  162. this.node.addEventListener('wheel', this.handleWheel);
  163. }
  164. detachScrollListener () {
  165. this.node.removeEventListener('scroll', this.handleScroll);
  166. this.node.removeEventListener('wheel', this.handleWheel);
  167. }
  168. getFirstChildKey (props) {
  169. const { children } = props;
  170. let firstChild = children;
  171. if (children instanceof ImmutableList) {
  172. firstChild = children.get(0);
  173. } else if (Array.isArray(children)) {
  174. firstChild = children[0];
  175. }
  176. return firstChild && firstChild.key;
  177. }
  178. setRef = (c) => {
  179. this.node = c;
  180. }
  181. handleLoadMore = e => {
  182. e.preventDefault();
  183. this.props.onLoadMore();
  184. }
  185. render () {
  186. const { children, scrollKey, trackScroll, shouldUpdateScroll, showLoading, isLoading, hasMore, prepend, alwaysPrepend, emptyMessage, onLoadMore } = this.props;
  187. const { fullscreen } = this.state;
  188. const childrenCount = React.Children.count(children);
  189. const loadMore = (hasMore && onLoadMore) ? <LoadMore visible={!isLoading} onClick={this.handleLoadMore} /> : null;
  190. let scrollableArea = null;
  191. if (showLoading) {
  192. scrollableArea = (
  193. <div className='scrollable scrollable--flex' ref={this.setRef}>
  194. <div role='feed' className='item-list'>
  195. {prepend}
  196. </div>
  197. <div className='scrollable__append'>
  198. <LoadingIndicator />
  199. </div>
  200. </div>
  201. );
  202. } else if (isLoading || childrenCount > 0 || hasMore || !emptyMessage) {
  203. scrollableArea = (
  204. <div className={classNames('scrollable', { fullscreen })} ref={this.setRef} onMouseMove={this.handleMouseMove}>
  205. <div role='feed' className='item-list'>
  206. {prepend}
  207. {React.Children.map(this.props.children, (child, index) => (
  208. <IntersectionObserverArticleContainer
  209. key={child.key}
  210. id={child.key}
  211. index={index}
  212. listLength={childrenCount}
  213. intersectionObserverWrapper={this.intersectionObserverWrapper}
  214. saveHeightKey={trackScroll ? `${this.context.router.route.location.key}:${scrollKey}` : null}
  215. >
  216. {React.cloneElement(child, {
  217. getScrollPosition: this.getScrollPosition,
  218. updateScrollBottom: this.updateScrollBottom,
  219. cachedMediaWidth: this.state.cachedMediaWidth,
  220. cacheMediaWidth: this.cacheMediaWidth,
  221. })}
  222. </IntersectionObserverArticleContainer>
  223. ))}
  224. {loadMore}
  225. </div>
  226. </div>
  227. );
  228. } else {
  229. scrollableArea = (
  230. <div className={classNames('scrollable scrollable--flex', { fullscreen })} ref={this.setRef}>
  231. {alwaysPrepend && prepend}
  232. <div className='empty-column-indicator'>
  233. {emptyMessage}
  234. </div>
  235. </div>
  236. );
  237. }
  238. if (trackScroll) {
  239. return (
  240. <ScrollContainer scrollKey={scrollKey} shouldUpdateScroll={shouldUpdateScroll}>
  241. {scrollableArea}
  242. </ScrollContainer>
  243. );
  244. } else {
  245. return scrollableArea;
  246. }
  247. }
  248. }