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

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