Application Android et IOS pour l'amicale des élèves
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.

WebSectionList.js 8.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. // @flow
  2. import * as React from 'react';
  3. import {ERROR_TYPE, readData} from "../../utils/WebData";
  4. import i18n from "i18n-js";
  5. import {Snackbar} from 'react-native-paper';
  6. import {Animated, RefreshControl, View} from "react-native";
  7. import ErrorView from "./ErrorView";
  8. import BasicLoadingScreen from "./BasicLoadingScreen";
  9. import {withCollapsible} from "../../utils/withCollapsible";
  10. import * as Animatable from 'react-native-animatable';
  11. import CustomTabBar from "../Tabbar/CustomTabBar";
  12. import {Collapsible} from "react-navigation-collapsible";
  13. type Props = {
  14. navigation: { [key: string]: any },
  15. fetchUrl: string,
  16. autoRefreshTime: number,
  17. refreshOnFocus: boolean,
  18. renderItem: (data: { [key: string]: any }) => React.Node,
  19. createDataset: (data: { [key: string]: any }) => Array<Object>,
  20. onScroll: (event: SyntheticEvent<EventTarget>) => void,
  21. collapsibleStack: Collapsible,
  22. showError: boolean,
  23. itemHeight?: number,
  24. updateData?: number,
  25. renderSectionHeader?: (data: { [key: string]: any }) => React.Node,
  26. stickyHeader?: boolean,
  27. }
  28. type State = {
  29. refreshing: boolean,
  30. firstLoading: boolean,
  31. fetchedData: { [key: string]: any } | null,
  32. snackbarVisible: boolean
  33. };
  34. const MIN_REFRESH_TIME = 5 * 1000;
  35. /**
  36. * Component used to render a SectionList with data fetched from the web
  37. *
  38. * This is a pure component, meaning it will only update if a shallow comparison of state and props is different.
  39. * To force the component to update, change the value of updateData.
  40. */
  41. class WebSectionList extends React.PureComponent<Props, State> {
  42. static defaultProps = {
  43. stickyHeader: false,
  44. updateData: 0,
  45. showError: true,
  46. };
  47. scrollRef: { current: null | Animated.SectionList };
  48. refreshInterval: IntervalID;
  49. lastRefresh: Date | null;
  50. state = {
  51. refreshing: false,
  52. firstLoading: true,
  53. fetchedData: null,
  54. snackbarVisible: false
  55. };
  56. /**
  57. * Registers react navigation events on first screen load.
  58. * Allows to detect when the screen is focused
  59. */
  60. componentDidMount() {
  61. const onScreenFocus = this.onScreenFocus.bind(this);
  62. const onScreenBlur = this.onScreenBlur.bind(this);
  63. this.props.navigation.addListener('focus', onScreenFocus);
  64. this.props.navigation.addListener('blur', onScreenBlur);
  65. this.scrollRef = React.createRef();
  66. this.onRefresh();
  67. this.lastRefresh = null;
  68. }
  69. /**
  70. * Refreshes data when focusing the screen and setup a refresh interval if asked to
  71. */
  72. onScreenFocus() {
  73. if (this.props.refreshOnFocus && this.lastRefresh)
  74. this.onRefresh();
  75. if (this.props.autoRefreshTime > 0)
  76. this.refreshInterval = setInterval(this.onRefresh, this.props.autoRefreshTime)
  77. // if (this.scrollRef.current) // Reset scroll to top
  78. // this.scrollRef.current.getNode().scrollToLocation({animated:false, itemIndex:0, sectionIndex:0});
  79. }
  80. /**
  81. * Removes any interval on un-focus
  82. */
  83. onScreenBlur() {
  84. clearInterval(this.refreshInterval);
  85. }
  86. /**
  87. * Callback used when fetch is successful.
  88. * It will update the displayed data and stop the refresh animation
  89. *
  90. * @param fetchedData The newly fetched data
  91. */
  92. onFetchSuccess = (fetchedData: { [key: string]: any }) => {
  93. this.setState({
  94. fetchedData: fetchedData,
  95. refreshing: false,
  96. firstLoading: false
  97. });
  98. this.lastRefresh = new Date();
  99. };
  100. /**
  101. * Callback used when fetch encountered an error.
  102. * It will reset the displayed data and show an error.
  103. */
  104. onFetchError = () => {
  105. this.setState({
  106. fetchedData: null,
  107. refreshing: false,
  108. firstLoading: false
  109. });
  110. this.showSnackBar();
  111. };
  112. /**
  113. * Refreshes data and shows an animations while doing it
  114. */
  115. onRefresh = () => {
  116. let canRefresh;
  117. if (this.lastRefresh != null) {
  118. const last = this.lastRefresh;
  119. canRefresh = (new Date().getTime() - last.getTime()) > MIN_REFRESH_TIME;
  120. } else
  121. canRefresh = true;
  122. if (canRefresh) {
  123. this.setState({refreshing: true});
  124. readData(this.props.fetchUrl)
  125. .then(this.onFetchSuccess)
  126. .catch(this.onFetchError);
  127. }
  128. };
  129. /**
  130. * Shows the error popup
  131. */
  132. showSnackBar = () => this.setState({snackbarVisible: true});
  133. /**
  134. * Hides the error popup
  135. */
  136. hideSnackBar = () => this.setState({snackbarVisible: false});
  137. itemLayout = (data: { [key: string]: any }, index: number) => {
  138. const height = this.props.itemHeight;
  139. if (height == null)
  140. return undefined;
  141. return {
  142. length: height,
  143. offset: height * index,
  144. index
  145. }
  146. };
  147. renderSectionHeader = (data: { section: { [key: string]: any } }) => {
  148. if (this.props.renderSectionHeader != null) {
  149. return (
  150. <Animatable.View
  151. animation={"fadeInUp"}
  152. duration={500}
  153. useNativeDriver
  154. >
  155. {this.props.renderSectionHeader(data)}
  156. </Animatable.View>
  157. );
  158. } else
  159. return null;
  160. }
  161. renderItem = (data: {
  162. item: { [key: string]: any },
  163. index: number,
  164. section: { [key: string]: any },
  165. separators: { [key: string]: any },
  166. }) => {
  167. return (
  168. <Animatable.View
  169. animation={"fadeInUp"}
  170. duration={500}
  171. useNativeDriver
  172. >
  173. {this.props.renderItem(data)}
  174. </Animatable.View>
  175. );
  176. }
  177. onScroll = (event: SyntheticEvent<EventTarget>) => {
  178. if (this.props.onScroll)
  179. this.props.onScroll(event);
  180. }
  181. render() {
  182. let dataset = [];
  183. if (this.state.fetchedData != null || (this.state.fetchedData == null && !this.props.showError)) {
  184. if (this.state.fetchedData == null)
  185. dataset = this.props.createDataset({});
  186. else
  187. dataset = this.props.createDataset(this.state.fetchedData);
  188. }
  189. const {containerPaddingTop, scrollIndicatorInsetTop, onScrollWithListener} = this.props.collapsibleStack;
  190. return (
  191. <View>
  192. <Animated.SectionList
  193. ref={this.scrollRef}
  194. sections={dataset}
  195. extraData={this.props.updateData}
  196. refreshControl={
  197. <RefreshControl
  198. progressViewOffset={containerPaddingTop}
  199. refreshing={this.state.refreshing}
  200. onRefresh={this.onRefresh}
  201. />
  202. }
  203. renderSectionHeader={this.renderSectionHeader}
  204. renderItem={this.renderItem}
  205. stickySectionHeadersEnabled={this.props.stickyHeader}
  206. style={{minHeight: '100%'}}
  207. ListEmptyComponent={this.state.refreshing
  208. ? <BasicLoadingScreen/>
  209. : <ErrorView
  210. {...this.props}
  211. errorCode={ERROR_TYPE.CONNECTION_ERROR}
  212. onRefresh={this.onRefresh}/>
  213. }
  214. getItemLayout={this.props.itemHeight != null ? this.itemLayout : undefined}
  215. // Animations
  216. onScroll={onScrollWithListener(this.onScroll)}
  217. contentContainerStyle={{
  218. paddingTop: containerPaddingTop,
  219. paddingBottom: CustomTabBar.TAB_BAR_HEIGHT,
  220. minHeight: '100%'
  221. }}
  222. scrollIndicatorInsets={{top: scrollIndicatorInsetTop}}
  223. />
  224. <Snackbar
  225. visible={this.state.snackbarVisible}
  226. onDismiss={this.hideSnackBar}
  227. action={{
  228. label: 'OK',
  229. onPress: () => {
  230. },
  231. }}
  232. duration={4000}
  233. style={{
  234. bottom: CustomTabBar.TAB_BAR_HEIGHT
  235. }}
  236. >
  237. {i18n.t("screens.home.listUpdateFail")}
  238. </Snackbar>
  239. </View>
  240. );
  241. }
  242. }
  243. export default withCollapsible(WebSectionList);