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.

HomeScreen.tsx 14KB

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