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.

HomeScreen.tsx 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  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 {
  21. FlatList,
  22. NativeScrollEvent,
  23. NativeSyntheticEvent,
  24. StyleSheet,
  25. } from 'react-native';
  26. import i18n from 'i18n-js';
  27. import { ActivityIndicator, Headline, withTheme } from 'react-native-paper';
  28. import { CommonActions } from '@react-navigation/native';
  29. import { StackNavigationProp } from '@react-navigation/stack';
  30. import * as Animatable from 'react-native-animatable';
  31. import { View } from 'react-native-animatable';
  32. import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons';
  33. import DashboardItem from '../../components/Home/EventDashboardItem';
  34. import WebSectionList from '../../components/Screens/WebSectionList';
  35. import FeedItem from '../../components/Home/FeedItem';
  36. import SmallDashboardItem from '../../components/Home/SmallDashboardItem';
  37. import PreviewEventDashboardItem from '../../components/Home/PreviewEventDashboardItem';
  38. import ActionsDashBoardItem from '../../components/Home/ActionsDashboardItem';
  39. import MaterialHeaderButtons, {
  40. Item,
  41. } from '../../components/Overrides/CustomHeaderButton';
  42. import AnimatedFAB from '../../components/Animations/AnimatedFAB';
  43. import ConnectionManager from '../../managers/ConnectionManager';
  44. import LogoutDialog from '../../components/Amicale/LogoutDialog';
  45. import AsyncStorageManager from '../../managers/AsyncStorageManager';
  46. import { MASCOT_STYLE } from '../../components/Mascot/Mascot';
  47. import MascotPopup from '../../components/Mascot/MascotPopup';
  48. import DashboardManager from '../../managers/DashboardManager';
  49. import type { ServiceItemType } from '../../managers/ServicesManager';
  50. import { getDisplayEvent, getFutureEvents } from '../../utils/Home';
  51. import type { PlanningEventType } from '../../utils/Planning';
  52. import GENERAL_STYLES from '../../constants/Styles';
  53. import Urls from '../../constants/Urls';
  54. const FEED_ITEM_HEIGHT = 500;
  55. const SECTIONS_ID = ['dashboard', 'news_feed'];
  56. const REFRESH_TIME = 1000 * 20; // Refresh every 20 seconds
  57. export type FeedItemType = {
  58. id: string;
  59. message: string;
  60. url: string;
  61. image: string | null;
  62. video: string | null;
  63. link: string | null;
  64. time: number;
  65. page_id: string;
  66. };
  67. export type FullDashboardType = {
  68. today_menu: Array<{ [key: string]: object }>;
  69. proximo_articles: number;
  70. available_dryers: number;
  71. available_washers: number;
  72. today_events: Array<PlanningEventType>;
  73. available_tutorials: number;
  74. };
  75. type RawNewsFeedType = { [key: string]: Array<FeedItemType> };
  76. type RawDashboardType = {
  77. news_feed: RawNewsFeedType;
  78. dashboard: FullDashboardType;
  79. };
  80. type PropsType = {
  81. navigation: StackNavigationProp<any>;
  82. route: { params: { nextScreen: string; data: object } };
  83. theme: ReactNativePaper.Theme;
  84. };
  85. type StateType = {
  86. dialogVisible: boolean;
  87. };
  88. const styles = StyleSheet.create({
  89. dashboardRow: {
  90. marginLeft: 'auto',
  91. marginRight: 'auto',
  92. marginTop: 10,
  93. marginBottom: 10,
  94. },
  95. sectionHeader: {
  96. textAlign: 'center',
  97. marginTop: 50,
  98. marginBottom: 10,
  99. },
  100. sectionHeaderEmpty: {
  101. textAlign: 'center',
  102. marginTop: 50,
  103. marginBottom: 10,
  104. marginLeft: 20,
  105. marginRight: 20,
  106. },
  107. activityIndicator: {
  108. marginTop: 10,
  109. },
  110. content: {
  111. position: 'absolute',
  112. width: '100%',
  113. height: '100%',
  114. },
  115. });
  116. /**
  117. * Class defining the app's home screen
  118. */
  119. class HomeScreen extends React.Component<PropsType, StateType> {
  120. static sortFeedTime = (a: FeedItemType, b: FeedItemType): number =>
  121. b.time - a.time;
  122. static generateNewsFeed(rawFeed: RawNewsFeedType): Array<FeedItemType> {
  123. const finalFeed: Array<FeedItemType> = [];
  124. Object.keys(rawFeed).forEach((key: string) => {
  125. const category: Array<FeedItemType> | null = rawFeed[key];
  126. if (category != null && category.length > 0) {
  127. finalFeed.push(...category);
  128. }
  129. });
  130. finalFeed.sort(HomeScreen.sortFeedTime);
  131. return finalFeed;
  132. }
  133. isLoggedIn: boolean | null;
  134. fabRef: { current: null | AnimatedFAB };
  135. currentNewFeed: Array<FeedItemType>;
  136. currentDashboard: FullDashboardType | null;
  137. dashboardManager: DashboardManager;
  138. constructor(props: PropsType) {
  139. super(props);
  140. this.fabRef = React.createRef();
  141. this.dashboardManager = new DashboardManager(props.navigation);
  142. this.currentNewFeed = [];
  143. this.currentDashboard = null;
  144. this.isLoggedIn = ConnectionManager.getInstance().isLoggedIn();
  145. props.navigation.setOptions({
  146. headerRight: this.getHeaderButton,
  147. });
  148. this.state = {
  149. dialogVisible: false,
  150. };
  151. }
  152. componentDidMount() {
  153. const { props } = this;
  154. props.navigation.addListener('focus', this.onScreenFocus);
  155. // Handle link open when home is focused
  156. props.navigation.addListener('state', this.handleNavigationParams);
  157. }
  158. /**
  159. * Updates login state and navigation parameters on screen focus
  160. */
  161. onScreenFocus = () => {
  162. const { props } = this;
  163. if (ConnectionManager.getInstance().isLoggedIn() !== this.isLoggedIn) {
  164. this.isLoggedIn = ConnectionManager.getInstance().isLoggedIn();
  165. props.navigation.setOptions({
  166. headerRight: this.getHeaderButton,
  167. });
  168. }
  169. // handle link open when home is not focused or created
  170. this.handleNavigationParams();
  171. };
  172. /**
  173. * Gets header buttons based on login state
  174. *
  175. * @returns {*}
  176. */
  177. getHeaderButton = () => {
  178. const { props } = this;
  179. let onPressLog = (): void =>
  180. props.navigation.navigate('login', { nextScreen: 'profile' });
  181. let logIcon = 'login';
  182. let logColor = props.theme.colors.primary;
  183. if (this.isLoggedIn) {
  184. onPressLog = (): void => this.showDisconnectDialog();
  185. logIcon = 'logout';
  186. logColor = props.theme.colors.text;
  187. }
  188. const onPressSettings = (): void => props.navigation.navigate('settings');
  189. return (
  190. <MaterialHeaderButtons>
  191. <Item
  192. title="log"
  193. iconName={logIcon}
  194. color={logColor}
  195. onPress={onPressLog}
  196. />
  197. <Item
  198. title={i18n.t('screens.settings.title')}
  199. iconName="cog"
  200. onPress={onPressSettings}
  201. />
  202. </MaterialHeaderButtons>
  203. );
  204. };
  205. /**
  206. * Gets the event dashboard render item.
  207. * If a preview is available, it will be rendered inside
  208. *
  209. * @param content
  210. * @return {*}
  211. */
  212. getDashboardEvent(content: Array<PlanningEventType>) {
  213. const futureEvents = getFutureEvents(content);
  214. const displayEvent = getDisplayEvent(futureEvents);
  215. // const clickPreviewAction = () =>
  216. // this.props.navigation.navigate('students', {
  217. // screen: 'planning-information',
  218. // params: {data: displayEvent}
  219. // });
  220. return (
  221. <DashboardItem
  222. eventNumber={futureEvents.length}
  223. clickAction={this.onEventContainerClick}
  224. >
  225. <PreviewEventDashboardItem
  226. event={displayEvent}
  227. clickAction={this.onEventContainerClick}
  228. />
  229. </DashboardItem>
  230. );
  231. }
  232. /**
  233. * Gets a dashboard item with a row of shortcut buttons.
  234. *
  235. * @param content
  236. * @return {*}
  237. */
  238. getDashboardRow(content: Array<ServiceItemType | null>) {
  239. return (
  240. <FlatList
  241. data={content}
  242. renderItem={this.getDashboardRowRenderItem}
  243. horizontal
  244. contentContainerStyle={styles.dashboardRow}
  245. />
  246. );
  247. }
  248. /**
  249. * Gets a dashboard shortcut item
  250. *
  251. * @param item
  252. * @returns {*}
  253. */
  254. getDashboardRowRenderItem = ({ item }: { item: ServiceItemType | null }) => {
  255. if (item != null) {
  256. return (
  257. <SmallDashboardItem
  258. image={item.image}
  259. onPress={item.onPress}
  260. badgeCount={
  261. this.currentDashboard != null && item.badgeFunction != null
  262. ? item.badgeFunction(this.currentDashboard)
  263. : undefined
  264. }
  265. />
  266. );
  267. }
  268. return <SmallDashboardItem />;
  269. };
  270. /**
  271. * Gets a render item for the given feed object
  272. *
  273. * @param item The feed item to display
  274. * @return {*}
  275. */
  276. getFeedItem(item: FeedItemType) {
  277. return <FeedItem item={item} height={FEED_ITEM_HEIGHT} />;
  278. }
  279. /**
  280. * Gets a FlatList render item
  281. *
  282. * @param item The item to display
  283. * @param section The current section
  284. * @return {*}
  285. */
  286. getRenderItem = ({ item }: { item: FeedItemType }) => this.getFeedItem(item);
  287. getRenderSectionHeader = (
  288. data: {
  289. section: {
  290. data: Array<object>;
  291. title: string;
  292. };
  293. },
  294. isLoading: boolean
  295. ) => {
  296. const { props } = this;
  297. if (data.section.data.length > 0) {
  298. return (
  299. <Headline style={styles.sectionHeader}>{data.section.title}</Headline>
  300. );
  301. }
  302. return (
  303. <View>
  304. <Headline
  305. style={{
  306. ...styles.sectionHeaderEmpty,
  307. color: props.theme.colors.textDisabled,
  308. }}
  309. >
  310. {data.section.title}
  311. </Headline>
  312. {isLoading ? (
  313. <ActivityIndicator style={styles.activityIndicator} />
  314. ) : (
  315. <MaterialCommunityIcons
  316. name="access-point-network-off"
  317. size={100}
  318. color={props.theme.colors.textDisabled}
  319. style={GENERAL_STYLES.center}
  320. />
  321. )}
  322. </View>
  323. );
  324. };
  325. getListHeader = (fetchedData: RawDashboardType) => {
  326. let dashboard = null;
  327. if (fetchedData != null) {
  328. dashboard = fetchedData.dashboard;
  329. }
  330. return (
  331. <Animatable.View animation="fadeInDown" duration={500} useNativeDriver>
  332. <ActionsDashBoardItem />
  333. {this.getDashboardRow(this.dashboardManager.getCurrentDashboard())}
  334. {this.getDashboardEvent(
  335. dashboard == null ? [] : dashboard.today_events
  336. )}
  337. </Animatable.View>
  338. );
  339. };
  340. /**
  341. * Navigates to the a new screen if navigation parameters specify one
  342. */
  343. handleNavigationParams = () => {
  344. const { props } = this;
  345. if (props.route.params != null) {
  346. if (props.route.params.nextScreen != null) {
  347. props.navigation.navigate(
  348. props.route.params.nextScreen,
  349. props.route.params.data
  350. );
  351. // reset params to prevent infinite loop
  352. props.navigation.dispatch(
  353. CommonActions.setParams({ nextScreen: null })
  354. );
  355. }
  356. }
  357. };
  358. showDisconnectDialog = (): void => this.setState({ dialogVisible: true });
  359. hideDisconnectDialog = (): void => this.setState({ dialogVisible: false });
  360. openScanner = () => {
  361. const { props } = this;
  362. props.navigation.navigate('scanner');
  363. };
  364. /**
  365. * Creates the dataset to be used in the FlatList
  366. *
  367. * @param fetchedData
  368. * @param isLoading
  369. * @return {*}
  370. */
  371. createDataset = (
  372. fetchedData: RawDashboardType | null,
  373. isLoading: boolean
  374. ): Array<{
  375. title: string;
  376. data: [] | Array<FeedItemType>;
  377. id: string;
  378. }> => {
  379. // fetchedData = DATA;
  380. if (fetchedData != null) {
  381. if (fetchedData.news_feed != null) {
  382. this.currentNewFeed = HomeScreen.generateNewsFeed(
  383. fetchedData.news_feed
  384. );
  385. }
  386. if (fetchedData.dashboard != null) {
  387. this.currentDashboard = fetchedData.dashboard;
  388. }
  389. }
  390. if (this.currentNewFeed.length > 0) {
  391. return [
  392. {
  393. title: i18n.t('screens.home.feedTitle'),
  394. data: this.currentNewFeed,
  395. id: SECTIONS_ID[1],
  396. },
  397. ];
  398. }
  399. return [
  400. {
  401. title: isLoading
  402. ? i18n.t('screens.home.feedLoading')
  403. : i18n.t('screens.home.feedError'),
  404. data: [],
  405. id: SECTIONS_ID[1],
  406. },
  407. ];
  408. };
  409. onEventContainerClick = () => {
  410. const { props } = this;
  411. props.navigation.navigate('planning');
  412. };
  413. onScroll = (event: NativeSyntheticEvent<NativeScrollEvent>) => {
  414. if (this.fabRef.current) {
  415. this.fabRef.current.onScroll(event);
  416. }
  417. };
  418. /**
  419. * Callback when pressing the login button on the banner.
  420. * This hides the banner and takes the user to the login page.
  421. */
  422. onLogin = () => {
  423. const { props } = this;
  424. props.navigation.navigate('login', {
  425. nextScreen: 'profile',
  426. });
  427. };
  428. render() {
  429. const { props, state } = this;
  430. return (
  431. <View style={GENERAL_STYLES.flex}>
  432. <View style={styles.content}>
  433. <WebSectionList
  434. navigation={props.navigation}
  435. createDataset={this.createDataset}
  436. autoRefreshTime={REFRESH_TIME}
  437. refreshOnFocus
  438. fetchUrl={Urls.app.dashboard}
  439. renderItem={this.getRenderItem}
  440. itemHeight={FEED_ITEM_HEIGHT}
  441. onScroll={this.onScroll}
  442. showError={false}
  443. renderSectionHeader={this.getRenderSectionHeader}
  444. renderListHeaderComponent={this.getListHeader}
  445. />
  446. </View>
  447. {!this.isLoggedIn ? (
  448. <MascotPopup
  449. prefKey={AsyncStorageManager.PREFERENCES.homeShowMascot.key}
  450. title={i18n.t('screens.home.mascotDialog.title')}
  451. message={i18n.t('screens.home.mascotDialog.message')}
  452. icon="human-greeting"
  453. buttons={{
  454. action: {
  455. message: i18n.t('screens.home.mascotDialog.login'),
  456. icon: 'login',
  457. onPress: this.onLogin,
  458. },
  459. cancel: {
  460. message: i18n.t('screens.home.mascotDialog.later'),
  461. icon: 'close',
  462. color: props.theme.colors.warning,
  463. },
  464. }}
  465. emotion={MASCOT_STYLE.CUTE}
  466. />
  467. ) : null}
  468. <AnimatedFAB
  469. ref={this.fabRef}
  470. icon="qrcode-scan"
  471. onPress={this.openScanner}
  472. />
  473. <LogoutDialog
  474. visible={state.dialogVisible}
  475. onDismiss={this.hideDisconnectDialog}
  476. />
  477. </View>
  478. );
  479. }
  480. }
  481. export default withTheme(HomeScreen);