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.

GroupSelectionScreen.js 8.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. // @flow
  2. import * as React from 'react';
  3. import {Platform} from 'react-native';
  4. import i18n from 'i18n-js';
  5. import {Searchbar} from 'react-native-paper';
  6. import {StackNavigationProp} from '@react-navigation/stack';
  7. import {stringMatchQuery} from '../../utils/Search';
  8. import WebSectionList from '../../components/Screens/WebSectionList';
  9. import GroupListAccordion from '../../components/Lists/PlanexGroups/GroupListAccordion';
  10. import AsyncStorageManager from '../../managers/AsyncStorageManager';
  11. const LIST_ITEM_HEIGHT = 70;
  12. export type PlanexGroupType = {
  13. name: string,
  14. id: number,
  15. isFav: boolean,
  16. };
  17. export type PlanexGroupCategoryType = {
  18. name: string,
  19. id: number,
  20. content: Array<PlanexGroupType>,
  21. };
  22. type PropsType = {
  23. navigation: StackNavigationProp,
  24. };
  25. type StateType = {
  26. currentSearchString: string,
  27. favoriteGroups: Array<PlanexGroupType>,
  28. };
  29. function sortName(
  30. a: PlanexGroupType | PlanexGroupCategoryType,
  31. b: PlanexGroupType | PlanexGroupCategoryType,
  32. ): number {
  33. if (a.name.toLowerCase() < b.name.toLowerCase()) return -1;
  34. if (a.name.toLowerCase() > b.name.toLowerCase()) return 1;
  35. return 0;
  36. }
  37. const GROUPS_URL = 'http://planex.insa-toulouse.fr/wsAdeGrp.php?projectId=1';
  38. const REPLACE_REGEX = /_/g;
  39. /**
  40. * Class defining planex group selection screen.
  41. */
  42. class GroupSelectionScreen extends React.Component<PropsType, StateType> {
  43. /**
  44. * Removes the given group from the given array
  45. *
  46. * @param favorites The array containing favorites groups
  47. * @param group The group to remove from the array
  48. */
  49. static removeGroupFromFavorites(
  50. favorites: Array<PlanexGroupType>,
  51. group: PlanexGroupType,
  52. ) {
  53. for (let i = 0; i < favorites.length; i += 1) {
  54. if (group.id === favorites[i].id) {
  55. favorites.splice(i, 1);
  56. break;
  57. }
  58. }
  59. }
  60. /**
  61. * Adds the given group to the given array
  62. *
  63. * @param favorites The array containing favorites groups
  64. * @param group The group to add to the array
  65. */
  66. static addGroupToFavorites(
  67. favorites: Array<PlanexGroupType>,
  68. group: PlanexGroupType,
  69. ) {
  70. const favGroup = {...group};
  71. favGroup.isFav = true;
  72. favorites.push(favGroup);
  73. favorites.sort(sortName);
  74. }
  75. constructor(props: PropsType) {
  76. super(props);
  77. this.state = {
  78. currentSearchString: '',
  79. favoriteGroups: AsyncStorageManager.getObject(
  80. AsyncStorageManager.PREFERENCES.planexFavoriteGroups.key,
  81. ),
  82. };
  83. }
  84. /**
  85. * Creates the header content
  86. */
  87. componentDidMount() {
  88. const [navigation] = this.props;
  89. navigation.setOptions({
  90. headerTitle: this.getSearchBar,
  91. headerBackTitleVisible: false,
  92. headerTitleContainerStyle:
  93. Platform.OS === 'ios'
  94. ? {marginHorizontal: 0, width: '70%'}
  95. : {marginHorizontal: 0, right: 50, left: 50},
  96. });
  97. }
  98. /**
  99. * Gets the header search bar
  100. *
  101. * @return {*}
  102. */
  103. getSearchBar = (): React.Node => {
  104. return (
  105. <Searchbar
  106. placeholder={i18n.t('screens.proximo.search')}
  107. onChangeText={this.onSearchStringChange}
  108. />
  109. );
  110. };
  111. /**
  112. * Gets a render item for the given article
  113. *
  114. * @param item The article to render
  115. * @return {*}
  116. */
  117. getRenderItem = ({item}: {item: PlanexGroupCategoryType}): React.Node => {
  118. const {currentSearchString, favoriteGroups} = this.state;
  119. if (this.shouldDisplayAccordion(item)) {
  120. return (
  121. <GroupListAccordion
  122. item={item}
  123. onGroupPress={this.onListItemPress}
  124. onFavoritePress={this.onListFavoritePress}
  125. currentSearchString={currentSearchString}
  126. favoriteNumber={favoriteGroups.length}
  127. height={LIST_ITEM_HEIGHT}
  128. />
  129. );
  130. }
  131. return null;
  132. };
  133. /**
  134. * Replaces underscore by spaces and sets the favorite state of every group in the given category
  135. *
  136. * @param groups The groups to format
  137. * @return {Array<PlanexGroupType>}
  138. */
  139. getFormattedGroups(groups: Array<PlanexGroupType>): Array<PlanexGroupType> {
  140. return groups.map((group: PlanexGroupType): PlanexGroupType => {
  141. const newGroup = {...group};
  142. newGroup.name = group.name.replace(REPLACE_REGEX, ' ');
  143. newGroup.isFav = this.isGroupInFavorites(group);
  144. return newGroup;
  145. });
  146. }
  147. /**
  148. * Creates the dataset to be used in the FlatList
  149. *
  150. * @param fetchedData
  151. * @return {*}
  152. * */
  153. createDataset = (fetchedData: {
  154. [key: string]: PlanexGroupCategoryType,
  155. }): Array<{title: string, data: Array<PlanexGroupCategoryType>}> => {
  156. return [
  157. {
  158. title: '',
  159. data: this.generateData(fetchedData),
  160. },
  161. ];
  162. };
  163. /**
  164. * Callback used when the search changes
  165. *
  166. * @param str The new search string
  167. */
  168. onSearchStringChange = (str: string) => {
  169. this.setState({currentSearchString: str});
  170. };
  171. /**
  172. * Callback used when clicking an article in the list.
  173. * It opens the modal to show detailed information about the article
  174. *
  175. * @param item The article pressed
  176. */
  177. onListItemPress = (item: PlanexGroupType) => {
  178. const {navigation} = this.props;
  179. navigation.navigate('planex', {
  180. screen: 'index',
  181. params: {group: item},
  182. });
  183. };
  184. /**
  185. * Callback used when the user clicks on the favorite button
  186. *
  187. * @param item The item to add/remove from favorites
  188. */
  189. onListFavoritePress = (item: PlanexGroupType) => {
  190. this.updateGroupFavorites(item);
  191. };
  192. /**
  193. * Checks if the given group is in the favorites list
  194. *
  195. * @param group The group to check
  196. * @returns {boolean}
  197. */
  198. isGroupInFavorites(group: PlanexGroupType): boolean {
  199. let isFav = false;
  200. const {favoriteGroups} = this.state;
  201. favoriteGroups.forEach((favGroup: PlanexGroupType) => {
  202. if (group.id === favGroup.id) isFav = true;
  203. });
  204. return isFav;
  205. }
  206. /**
  207. * Adds or removes the given group to the favorites list, depending on whether it is already in it or not.
  208. * Favorites are then saved in user preferences
  209. *
  210. * @param group The group to add/remove to favorites
  211. */
  212. updateGroupFavorites(group: PlanexGroupType) {
  213. const {favoriteGroups} = this.state;
  214. const newFavorites = [...favoriteGroups];
  215. if (this.isGroupInFavorites(group))
  216. GroupSelectionScreen.removeGroupFromFavorites(newFavorites, group);
  217. else GroupSelectionScreen.addGroupToFavorites(newFavorites, group);
  218. this.setState({favoriteGroups: newFavorites});
  219. AsyncStorageManager.set(
  220. AsyncStorageManager.PREFERENCES.planexFavoriteGroups.key,
  221. newFavorites,
  222. );
  223. }
  224. /**
  225. * Checks whether to display the given group category, depending on user search query
  226. *
  227. * @param item The group category
  228. * @returns {boolean}
  229. */
  230. shouldDisplayAccordion(item: PlanexGroupCategoryType): boolean {
  231. const {currentSearchString} = this.state;
  232. let shouldDisplay = false;
  233. for (let i = 0; i < item.content.length; i += 1) {
  234. if (stringMatchQuery(item.content[i].name, currentSearchString)) {
  235. shouldDisplay = true;
  236. break;
  237. }
  238. }
  239. return shouldDisplay;
  240. }
  241. /**
  242. * Generates the dataset to be used in the FlatList.
  243. * This improves formatting of group names, sorts alphabetically the categories, and adds favorites at the top.
  244. *
  245. * @param fetchedData The raw data fetched from the server
  246. * @returns {[]}
  247. */
  248. generateData(fetchedData: {
  249. [key: string]: PlanexGroupCategoryType,
  250. }): Array<PlanexGroupCategoryType> {
  251. const {favoriteGroups} = this.state;
  252. const data = [];
  253. // eslint-disable-next-line flowtype/no-weak-types
  254. (Object.values(fetchedData): Array<any>).forEach(
  255. (category: PlanexGroupCategoryType) => {
  256. const newCat = {...category};
  257. newCat.content = this.getFormattedGroups(category.content);
  258. data.push(newCat);
  259. },
  260. );
  261. data.sort(sortName);
  262. data.unshift({
  263. name: i18n.t('screens.planex.favorites'),
  264. id: 0,
  265. content: favoriteGroups,
  266. });
  267. return data;
  268. }
  269. render(): React.Node {
  270. const {props, state} = this;
  271. return (
  272. <WebSectionList
  273. navigation={props.navigation}
  274. createDataset={this.createDataset}
  275. autoRefreshTime={0}
  276. refreshOnFocus={false}
  277. fetchUrl={GROUPS_URL}
  278. renderItem={this.getRenderItem}
  279. updateData={state.currentSearchString + state.favoriteGroups.length}
  280. itemHeight={LIST_ITEM_HEIGHT}
  281. />
  282. );
  283. }
  284. }
  285. export default GroupSelectionScreen;