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.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. /*
  2. * Copyright (c) 2019 - 2020 Arnaud Vergnet.
  3. *
  4. * This file is part of Campus INSAT.
  5. *
  6. * Campus INSAT is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * Campus INSAT is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with Campus INSAT. If not, see <https://www.gnu.org/licenses/>.
  18. */
  19. // @flow
  20. import * as React from 'react';
  21. import i18n from 'i18n-js';
  22. import {Snackbar} from 'react-native-paper';
  23. import {RefreshControl, View} from 'react-native';
  24. import * as Animatable from 'react-native-animatable';
  25. import {Collapsible} from 'react-navigation-collapsible';
  26. import {StackNavigationProp} from '@react-navigation/stack';
  27. import ErrorView from './ErrorView';
  28. import BasicLoadingScreen from './BasicLoadingScreen';
  29. import withCollapsible from '../../utils/withCollapsible';
  30. import CustomTabBar from '../Tabbar/CustomTabBar';
  31. import {ERROR_TYPE, readData} from '../../utils/WebData';
  32. import CollapsibleSectionList from '../Collapsible/CollapsibleSectionList';
  33. import type {ApiGenericDataType} from '../../utils/WebData';
  34. export type SectionListDataType<T> = Array<{
  35. title: string,
  36. data: Array<T>,
  37. keyExtractor?: (T) => string,
  38. }>;
  39. type PropsType<T> = {
  40. navigation: StackNavigationProp,
  41. fetchUrl: string,
  42. autoRefreshTime: number,
  43. refreshOnFocus: boolean,
  44. renderItem: (data: {item: T}) => React.Node,
  45. createDataset: (
  46. data: ApiGenericDataType | null,
  47. isLoading?: boolean,
  48. ) => SectionListDataType<T>,
  49. onScroll: (event: SyntheticEvent<EventTarget>) => void,
  50. collapsibleStack: Collapsible,
  51. showError?: boolean,
  52. itemHeight?: number | null,
  53. updateData?: number,
  54. renderListHeaderComponent?: (data: ApiGenericDataType | null) => React.Node,
  55. renderSectionHeader?: (
  56. data: {section: {title: string}},
  57. isLoading?: boolean,
  58. ) => React.Node,
  59. stickyHeader?: boolean,
  60. };
  61. type StateType = {
  62. refreshing: boolean,
  63. fetchedData: ApiGenericDataType | null,
  64. snackbarVisible: boolean,
  65. };
  66. const MIN_REFRESH_TIME = 5 * 1000;
  67. /**
  68. * Component used to render a SectionList with data fetched from the web
  69. *
  70. * This is a pure component, meaning it will only update if a shallow comparison of state and props is different.
  71. * To force the component to update, change the value of updateData.
  72. */
  73. class WebSectionList<T> extends React.PureComponent<PropsType<T>, StateType> {
  74. static defaultProps = {
  75. showError: true,
  76. itemHeight: null,
  77. updateData: 0,
  78. renderListHeaderComponent: (): React.Node => null,
  79. renderSectionHeader: (): React.Node => null,
  80. stickyHeader: false,
  81. };
  82. refreshInterval: IntervalID;
  83. lastRefresh: Date | null;
  84. constructor() {
  85. super();
  86. this.state = {
  87. refreshing: false,
  88. fetchedData: null,
  89. snackbarVisible: false,
  90. };
  91. }
  92. /**
  93. * Registers react navigation events on first screen load.
  94. * Allows to detect when the screen is focused
  95. */
  96. componentDidMount() {
  97. const {navigation} = this.props;
  98. navigation.addListener('focus', this.onScreenFocus);
  99. navigation.addListener('blur', this.onScreenBlur);
  100. this.lastRefresh = null;
  101. this.onRefresh();
  102. }
  103. /**
  104. * Refreshes data when focusing the screen and setup a refresh interval if asked to
  105. */
  106. onScreenFocus = () => {
  107. const {props} = this;
  108. if (props.refreshOnFocus && this.lastRefresh) {
  109. setTimeout(this.onRefresh, 200);
  110. }
  111. if (props.autoRefreshTime > 0)
  112. this.refreshInterval = setInterval(this.onRefresh, props.autoRefreshTime);
  113. };
  114. /**
  115. * Removes any interval on un-focus
  116. */
  117. onScreenBlur = () => {
  118. clearInterval(this.refreshInterval);
  119. };
  120. /**
  121. * Callback used when fetch is successful.
  122. * It will update the displayed data and stop the refresh animation
  123. *
  124. * @param fetchedData The newly fetched data
  125. */
  126. onFetchSuccess = (fetchedData: ApiGenericDataType) => {
  127. this.setState({
  128. fetchedData,
  129. refreshing: false,
  130. });
  131. this.lastRefresh = new Date();
  132. };
  133. /**
  134. * Callback used when fetch encountered an error.
  135. * It will reset the displayed data and show an error.
  136. */
  137. onFetchError = () => {
  138. this.setState({
  139. fetchedData: null,
  140. refreshing: false,
  141. });
  142. this.showSnackBar();
  143. };
  144. /**
  145. * Refreshes data and shows an animations while doing it
  146. */
  147. onRefresh = () => {
  148. const {fetchUrl} = this.props;
  149. let canRefresh;
  150. if (this.lastRefresh != null) {
  151. const last = this.lastRefresh;
  152. canRefresh = new Date().getTime() - last.getTime() > MIN_REFRESH_TIME;
  153. } else canRefresh = true;
  154. if (canRefresh) {
  155. this.setState({refreshing: true});
  156. readData(fetchUrl).then(this.onFetchSuccess).catch(this.onFetchError);
  157. }
  158. };
  159. /**
  160. * Shows the error popup
  161. */
  162. showSnackBar = () => {
  163. this.setState({snackbarVisible: true});
  164. };
  165. /**
  166. * Hides the error popup
  167. */
  168. hideSnackBar = () => {
  169. this.setState({snackbarVisible: false});
  170. };
  171. getItemLayout = (
  172. data: T,
  173. index: number,
  174. ): {length: number, offset: number, index: number} | null => {
  175. const {itemHeight} = this.props;
  176. if (itemHeight == null) return null;
  177. return {
  178. length: itemHeight,
  179. offset: itemHeight * index,
  180. index,
  181. };
  182. };
  183. getRenderSectionHeader = (data: {section: {title: string}}): React.Node => {
  184. const {renderSectionHeader} = this.props;
  185. const {refreshing} = this.state;
  186. if (renderSectionHeader != null) {
  187. return (
  188. <Animatable.View animation="fadeInUp" duration={500} useNativeDriver>
  189. {renderSectionHeader(data, refreshing)}
  190. </Animatable.View>
  191. );
  192. }
  193. return null;
  194. };
  195. getRenderItem = (data: {item: T}): React.Node => {
  196. const {renderItem} = this.props;
  197. return (
  198. <Animatable.View animation="fadeInUp" duration={500} useNativeDriver>
  199. {renderItem(data)}
  200. </Animatable.View>
  201. );
  202. };
  203. onScroll = (event: SyntheticEvent<EventTarget>) => {
  204. const {onScroll} = this.props;
  205. if (onScroll != null) onScroll(event);
  206. };
  207. render(): React.Node {
  208. const {props, state} = this;
  209. let dataset = [];
  210. if (
  211. state.fetchedData != null ||
  212. (state.fetchedData == null && !props.showError)
  213. )
  214. dataset = props.createDataset(state.fetchedData, state.refreshing);
  215. const {containerPaddingTop} = props.collapsibleStack;
  216. return (
  217. <View>
  218. <CollapsibleSectionList
  219. sections={dataset}
  220. extraData={props.updateData}
  221. refreshControl={
  222. <RefreshControl
  223. progressViewOffset={containerPaddingTop}
  224. refreshing={state.refreshing}
  225. onRefresh={this.onRefresh}
  226. />
  227. }
  228. renderSectionHeader={this.getRenderSectionHeader}
  229. renderItem={this.getRenderItem}
  230. stickySectionHeadersEnabled={props.stickyHeader}
  231. style={{minHeight: '100%'}}
  232. ListHeaderComponent={
  233. props.renderListHeaderComponent != null
  234. ? props.renderListHeaderComponent(state.fetchedData)
  235. : null
  236. }
  237. ListEmptyComponent={
  238. state.refreshing ? (
  239. <BasicLoadingScreen />
  240. ) : (
  241. <ErrorView
  242. navigation={props.navigation}
  243. errorCode={ERROR_TYPE.CONNECTION_ERROR}
  244. onRefresh={this.onRefresh}
  245. />
  246. )
  247. }
  248. getItemLayout={props.itemHeight != null ? this.getItemLayout : null}
  249. onScroll={this.onScroll}
  250. hasTab
  251. />
  252. <Snackbar
  253. visible={state.snackbarVisible}
  254. onDismiss={this.hideSnackBar}
  255. action={{
  256. label: 'OK',
  257. onPress: () => {},
  258. }}
  259. duration={4000}
  260. style={{
  261. bottom: CustomTabBar.TAB_BAR_HEIGHT,
  262. }}>
  263. {i18n.t('general.listUpdateFail')}
  264. </Snackbar>
  265. </View>
  266. );
  267. }
  268. }
  269. export default withCollapsible(WebSectionList);