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.

286 lines
8.6 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 'flavours/glitch/containers/intersection_observer_article_container';
  5. import LoadMore from './load_more';
  6. import IntersectionObserverWrapper from 'flavours/glitch/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 'flavours/glitch/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 =
  82. 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) {
  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, prevState) {
  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) this.updateScrollBottom(snapshot);
  134. }
  135. componentWillUnmount () {
  136. this.clearMouseIdleTimer();
  137. this.detachScrollListener();
  138. this.detachIntersectionObserver();
  139. detachFullscreenListener(this.onFullScreenChange);
  140. }
  141. onFullScreenChange = () => {
  142. this.setState({ fullscreen: isFullscreen() });
  143. }
  144. attachIntersectionObserver () {
  145. this.intersectionObserverWrapper.connect({
  146. root: this.node,
  147. rootMargin: '300% 0px',
  148. });
  149. }
  150. detachIntersectionObserver () {
  151. this.intersectionObserverWrapper.disconnect();
  152. }
  153. attachScrollListener () {
  154. this.node.addEventListener('scroll', this.handleScroll);
  155. this.node.addEventListener('wheel', this.handleWheel);
  156. }
  157. detachScrollListener () {
  158. this.node.removeEventListener('scroll', this.handleScroll);
  159. this.node.removeEventListener('wheel', this.handleWheel);
  160. }
  161. getFirstChildKey (props) {
  162. const { children } = props;
  163. let firstChild = children;
  164. if (children instanceof ImmutableList) {
  165. firstChild = children.get(0);
  166. } else if (Array.isArray(children)) {
  167. firstChild = children[0];
  168. }
  169. return firstChild && firstChild.key;
  170. }
  171. setRef = (c) => {
  172. this.node = c;
  173. }
  174. handleLoadMore = e => {
  175. e.preventDefault();
  176. this.props.onLoadMore();
  177. }
  178. defaultShouldUpdateScroll = (prevRouterProps, { location }) => {
  179. if ((((prevRouterProps || {}).location || {}).state || {}).mastodonModalOpen) return false;
  180. return !(location.state && location.state.mastodonModalOpen);
  181. }
  182. render () {
  183. const { children, scrollKey, trackScroll, shouldUpdateScroll, showLoading, isLoading, hasMore, prepend, alwaysPrepend, emptyMessage, onLoadMore } = this.props;
  184. const { fullscreen } = this.state;
  185. const childrenCount = React.Children.count(children);
  186. const loadMore = (hasMore && onLoadMore) ? <LoadMore visible={!isLoading} onClick={this.handleLoadMore} /> : null;
  187. let scrollableArea = null;
  188. if (showLoading) {
  189. scrollableArea = (
  190. <div className='scrollable scrollable--flex' ref={this.setRef}>
  191. <div role='feed' className='item-list'>
  192. {prepend}
  193. </div>
  194. <div className='scrollable__append'>
  195. <LoadingIndicator />
  196. </div>
  197. </div>
  198. );
  199. } else if (isLoading || childrenCount > 0 || hasMore || !emptyMessage) {
  200. scrollableArea = (
  201. <div className={classNames('scrollable', { fullscreen })} ref={this.setRef} onMouseMove={this.handleMouseMove}>
  202. <div role='feed' className='item-list'>
  203. {prepend}
  204. {React.Children.map(this.props.children, (child, index) => (
  205. <IntersectionObserverArticleContainer
  206. key={child.key}
  207. id={child.key}
  208. index={index}
  209. listLength={childrenCount}
  210. intersectionObserverWrapper={this.intersectionObserverWrapper}
  211. saveHeightKey={trackScroll ? `${this.context.router.route.location.key}:${scrollKey}` : null}
  212. >
  213. {React.cloneElement(child, {getScrollPosition: this.getScrollPosition, updateScrollBottom: this.updateScrollBottom})}
  214. </IntersectionObserverArticleContainer>
  215. ))}
  216. {loadMore}
  217. </div>
  218. </div>
  219. );
  220. } else {
  221. scrollableArea = (
  222. <div className={classNames('scrollable scrollable--flex', { fullscreen })} ref={this.setRef}>
  223. {alwaysPrepend && prepend}
  224. <div className='empty-column-indicator'>
  225. {emptyMessage}
  226. </div>
  227. </div>
  228. );
  229. }
  230. if (trackScroll) {
  231. return (
  232. <ScrollContainer scrollKey={scrollKey} shouldUpdateScroll={shouldUpdateScroll || this.defaultShouldUpdateScroll}>
  233. {scrollableArea}
  234. </ScrollContainer>
  235. );
  236. } else {
  237. return scrollableArea;
  238. }
  239. }
  240. }