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.js 14KB

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