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

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