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.tsx 8.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  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. import * as React from 'react';
  20. import i18n from 'i18n-js';
  21. import {Snackbar} from 'react-native-paper';
  22. import {
  23. NativeSyntheticEvent,
  24. RefreshControl,
  25. SectionListData,
  26. View,
  27. } from 'react-native';
  28. import * as Animatable from 'react-native-animatable';
  29. import {Collapsible} from 'react-navigation-collapsible';
  30. import {StackNavigationProp} from '@react-navigation/stack';
  31. import ErrorView from './ErrorView';
  32. import BasicLoadingScreen from './BasicLoadingScreen';
  33. import withCollapsible from '../../utils/withCollapsible';
  34. import CustomTabBar from '../Tabbar/CustomTabBar';
  35. import {ERROR_TYPE, readData} from '../../utils/WebData';
  36. import CollapsibleSectionList from '../Collapsible/CollapsibleSectionList';
  37. export type SectionListDataType<ItemT> = Array<{
  38. title: string;
  39. data: Array<ItemT>;
  40. keyExtractor?: (data: ItemT) => string;
  41. }>;
  42. type PropsType<ItemT, RawData> = {
  43. navigation: StackNavigationProp<any>;
  44. fetchUrl: string;
  45. autoRefreshTime: number;
  46. refreshOnFocus: boolean;
  47. renderItem: (data: {item: ItemT}) => React.ReactNode;
  48. createDataset: (
  49. data: RawData | null,
  50. isLoading?: boolean,
  51. ) => SectionListDataType<ItemT>;
  52. onScroll: (event: NativeSyntheticEvent<EventTarget>) => void;
  53. collapsibleStack: Collapsible;
  54. showError?: boolean;
  55. itemHeight?: number | null;
  56. updateData?: number;
  57. renderListHeaderComponent?: (
  58. data: RawData | null,
  59. ) => React.ComponentType<any> | React.ReactElement | null;
  60. renderSectionHeader?: (
  61. data: {section: SectionListData<ItemT>},
  62. isLoading?: boolean,
  63. ) => React.ReactElement | null;
  64. stickyHeader?: boolean;
  65. };
  66. type StateType<RawData> = {
  67. refreshing: boolean;
  68. fetchedData: RawData | null;
  69. snackbarVisible: boolean;
  70. };
  71. const MIN_REFRESH_TIME = 5 * 1000;
  72. /**
  73. * Component used to render a SectionList with data fetched from the web
  74. *
  75. * This is a pure component, meaning it will only update if a shallow comparison of state and props is different.
  76. * To force the component to update, change the value of updateData.
  77. */
  78. class WebSectionList<ItemT, RawData> extends React.PureComponent<
  79. PropsType<ItemT, RawData>,
  80. StateType<RawData>
  81. > {
  82. static defaultProps = {
  83. showError: true,
  84. itemHeight: null,
  85. updateData: 0,
  86. renderListHeaderComponent: () => null,
  87. renderSectionHeader: () => null,
  88. stickyHeader: false,
  89. };
  90. refreshInterval: NodeJS.Timeout | undefined;
  91. lastRefresh: Date | undefined;
  92. constructor(props: PropsType<ItemT, RawData>) {
  93. super(props);
  94. this.state = {
  95. refreshing: false,
  96. fetchedData: null,
  97. snackbarVisible: false,
  98. };
  99. }
  100. /**
  101. * Registers react navigation events on first screen load.
  102. * Allows to detect when the screen is focused
  103. */
  104. componentDidMount() {
  105. const {navigation} = this.props;
  106. navigation.addListener('focus', this.onScreenFocus);
  107. navigation.addListener('blur', this.onScreenBlur);
  108. this.lastRefresh = undefined;
  109. this.onRefresh();
  110. }
  111. /**
  112. * Refreshes data when focusing the screen and setup a refresh interval if asked to
  113. */
  114. onScreenFocus = () => {
  115. const {props} = this;
  116. if (props.refreshOnFocus && this.lastRefresh) {
  117. setTimeout(this.onRefresh, 200);
  118. }
  119. if (props.autoRefreshTime > 0) {
  120. this.refreshInterval = setInterval(this.onRefresh, props.autoRefreshTime);
  121. }
  122. };
  123. /**
  124. * Removes any interval on un-focus
  125. */
  126. onScreenBlur = () => {
  127. if (this.refreshInterval) {
  128. clearInterval(this.refreshInterval);
  129. }
  130. };
  131. /**
  132. * Callback used when fetch is successful.
  133. * It will update the displayed data and stop the refresh animation
  134. *
  135. * @param fetchedData The newly fetched data
  136. */
  137. onFetchSuccess = (fetchedData: RawData) => {
  138. this.setState({
  139. fetchedData,
  140. refreshing: false,
  141. });
  142. this.lastRefresh = new Date();
  143. };
  144. /**
  145. * Callback used when fetch encountered an error.
  146. * It will reset the displayed data and show an error.
  147. */
  148. onFetchError = () => {
  149. this.setState({
  150. fetchedData: null,
  151. refreshing: false,
  152. });
  153. this.showSnackBar();
  154. };
  155. /**
  156. * Refreshes data and shows an animations while doing it
  157. */
  158. onRefresh = () => {
  159. const {fetchUrl} = this.props;
  160. let canRefresh;
  161. if (this.lastRefresh != null) {
  162. const last = this.lastRefresh;
  163. canRefresh = new Date().getTime() - last.getTime() > MIN_REFRESH_TIME;
  164. } else {
  165. canRefresh = true;
  166. }
  167. if (canRefresh) {
  168. this.setState({refreshing: true});
  169. readData(fetchUrl).then(this.onFetchSuccess).catch(this.onFetchError);
  170. }
  171. };
  172. /**
  173. * Shows the error popup
  174. */
  175. showSnackBar = () => {
  176. this.setState({snackbarVisible: true});
  177. };
  178. /**
  179. * Hides the error popup
  180. */
  181. hideSnackBar = () => {
  182. this.setState({snackbarVisible: false});
  183. };
  184. getItemLayout = (
  185. height: number,
  186. data: Array<SectionListData<ItemT>> | null,
  187. index: number,
  188. ): {length: number; offset: number; index: number} => {
  189. return {
  190. length: height,
  191. offset: height * index,
  192. index,
  193. };
  194. };
  195. getRenderSectionHeader = (data: {section: SectionListData<ItemT>}) => {
  196. const {renderSectionHeader} = this.props;
  197. const {refreshing} = this.state;
  198. if (renderSectionHeader != null) {
  199. return (
  200. <Animatable.View animation="fadeInUp" duration={500} useNativeDriver>
  201. {renderSectionHeader(data, refreshing)}
  202. </Animatable.View>
  203. );
  204. }
  205. return null;
  206. };
  207. getRenderItem = (data: {item: ItemT}) => {
  208. const {renderItem} = this.props;
  209. return (
  210. <Animatable.View animation="fadeInUp" duration={500} useNativeDriver>
  211. {renderItem(data)}
  212. </Animatable.View>
  213. );
  214. };
  215. onScroll = (event: NativeSyntheticEvent<EventTarget>) => {
  216. const {onScroll} = this.props;
  217. if (onScroll != null) {
  218. onScroll(event);
  219. }
  220. };
  221. render() {
  222. const {props, state} = this;
  223. const {itemHeight} = props;
  224. let dataset: SectionListDataType<ItemT> = [];
  225. if (
  226. state.fetchedData != null ||
  227. (state.fetchedData == null && !props.showError)
  228. ) {
  229. dataset = props.createDataset(state.fetchedData, state.refreshing);
  230. }
  231. const {containerPaddingTop} = props.collapsibleStack;
  232. return (
  233. <View>
  234. <CollapsibleSectionList
  235. sections={dataset}
  236. extraData={props.updateData}
  237. refreshControl={
  238. <RefreshControl
  239. progressViewOffset={containerPaddingTop}
  240. refreshing={state.refreshing}
  241. onRefresh={this.onRefresh}
  242. />
  243. }
  244. renderSectionHeader={this.getRenderSectionHeader}
  245. renderItem={this.getRenderItem}
  246. stickySectionHeadersEnabled={props.stickyHeader}
  247. style={{minHeight: '100%'}}
  248. ListHeaderComponent={
  249. props.renderListHeaderComponent != null
  250. ? props.renderListHeaderComponent(state.fetchedData)
  251. : null
  252. }
  253. ListEmptyComponent={
  254. state.refreshing ? (
  255. <BasicLoadingScreen />
  256. ) : (
  257. <ErrorView
  258. navigation={props.navigation}
  259. errorCode={ERROR_TYPE.CONNECTION_ERROR}
  260. onRefresh={this.onRefresh}
  261. />
  262. )
  263. }
  264. getItemLayout={
  265. itemHeight
  266. ? (data, index) => this.getItemLayout(itemHeight, data, index)
  267. : undefined
  268. }
  269. onScroll={this.onScroll}
  270. hasTab
  271. />
  272. <Snackbar
  273. visible={state.snackbarVisible}
  274. onDismiss={this.hideSnackBar}
  275. action={{
  276. label: 'OK',
  277. onPress: () => {},
  278. }}
  279. duration={4000}
  280. style={{
  281. bottom: CustomTabBar.TAB_BAR_HEIGHT,
  282. }}>
  283. {i18n.t('general.listUpdateFail')}
  284. </Snackbar>
  285. </View>
  286. );
  287. }
  288. }
  289. export default withCollapsible(WebSectionList);