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

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