Application Android et IOS pour l'amicale des élèves https://play.google.com/store/apps/details?id=fr.amicaleinsat.application
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.7KB

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