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.

GroupSelectionScreen.tsx 7.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  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 React, { useEffect, useLayoutEffect, useState } from 'react';
  20. import { Platform } from 'react-native';
  21. import i18n from 'i18n-js';
  22. import { Searchbar } from 'react-native-paper';
  23. import { stringMatchQuery } from '../../utils/Search';
  24. import WebSectionList from '../../components/Screens/WebSectionList';
  25. import GroupListAccordion from '../../components/Lists/PlanexGroups/GroupListAccordion';
  26. import AsyncStorageManager from '../../managers/AsyncStorageManager';
  27. import Urls from '../../constants/Urls';
  28. import { readData } from '../../utils/WebData';
  29. import { useNavigation } from '@react-navigation/core';
  30. import { useCachedPlanexGroups } from '../../utils/cacheContext';
  31. export type PlanexGroupType = {
  32. name: string;
  33. id: number;
  34. };
  35. export type PlanexGroupCategoryType = {
  36. name: string;
  37. id: number;
  38. content: Array<PlanexGroupType>;
  39. };
  40. export type PlanexGroupsType = { [key: string]: PlanexGroupCategoryType };
  41. function sortName(
  42. a: PlanexGroupType | PlanexGroupCategoryType,
  43. b: PlanexGroupType | PlanexGroupCategoryType
  44. ): number {
  45. if (a.name.toLowerCase() < b.name.toLowerCase()) {
  46. return -1;
  47. }
  48. if (a.name.toLowerCase() > b.name.toLowerCase()) {
  49. return 1;
  50. }
  51. return 0;
  52. }
  53. function GroupSelectionScreen() {
  54. const navigation = useNavigation();
  55. const { groups, setGroups } = useCachedPlanexGroups();
  56. const [currentSearchString, setCurrentSearchString] = useState('');
  57. const [favoriteGroups, setFavoriteGroups] = useState<Array<PlanexGroupType>>(
  58. AsyncStorageManager.getObject(
  59. AsyncStorageManager.PREFERENCES.planexFavoriteGroups.key
  60. )
  61. );
  62. useLayoutEffect(() => {
  63. navigation.setOptions({
  64. headerTitle: getSearchBar,
  65. headerBackTitleVisible: false,
  66. headerTitleContainerStyle:
  67. Platform.OS === 'ios'
  68. ? { marginHorizontal: 0, width: '70%' }
  69. : { marginHorizontal: 0, right: 50, left: 50 },
  70. });
  71. // eslint-disable-next-line react-hooks/exhaustive-deps
  72. }, [navigation]);
  73. const getSearchBar = () => {
  74. return (
  75. // @ts-ignore
  76. <Searchbar
  77. placeholder={i18n.t('screens.proximo.search')}
  78. onChangeText={setCurrentSearchString}
  79. />
  80. );
  81. };
  82. /**
  83. * Gets a render item for the given article
  84. *
  85. * @param item The article to render
  86. * @return {*}
  87. */
  88. const getRenderItem = ({ item }: { item: PlanexGroupCategoryType }) => {
  89. if (
  90. shouldDisplayAccordion(item) ||
  91. (item.id === 0 && item.content.length === 0)
  92. ) {
  93. return (
  94. <GroupListAccordion
  95. item={item}
  96. favorites={[...favoriteGroups]}
  97. onGroupPress={onListItemPress}
  98. onFavoritePress={onListFavoritePress}
  99. currentSearchString={currentSearchString}
  100. />
  101. );
  102. }
  103. return null;
  104. };
  105. /**
  106. * Creates the dataset to be used in the FlatList
  107. *
  108. * @param fetchedData
  109. * @return {*}
  110. * */
  111. const createDataset = (
  112. fetchedData:
  113. | {
  114. [key: string]: PlanexGroupCategoryType;
  115. }
  116. | undefined
  117. ): Array<{ title: string; data: Array<PlanexGroupCategoryType> }> => {
  118. return [
  119. {
  120. title: '',
  121. data: generateData(fetchedData),
  122. },
  123. ];
  124. };
  125. /**
  126. * Callback used when clicking an article in the list.
  127. * It opens the modal to show detailed information about the article
  128. *
  129. * @param item The article pressed
  130. */
  131. const onListItemPress = (item: PlanexGroupType) => {
  132. navigation.navigate('planex', {
  133. screen: 'index',
  134. params: { group: item },
  135. });
  136. };
  137. /**
  138. * Callback used when the user clicks on the favorite button
  139. *
  140. * @param item The item to add/remove from favorites
  141. */
  142. const onListFavoritePress = (item: PlanexGroupType) => {
  143. updateGroupFavorites(item);
  144. };
  145. /**
  146. * Checks if the given group is in the favorites list
  147. *
  148. * @param group The group to check
  149. * @returns {boolean}
  150. */
  151. const isGroupInFavorites = (group: PlanexGroupType): boolean => {
  152. let isFav = false;
  153. favoriteGroups.forEach((favGroup: PlanexGroupType) => {
  154. if (group.id === favGroup.id) {
  155. isFav = true;
  156. }
  157. });
  158. return isFav;
  159. };
  160. /**
  161. * Adds or removes the given group to the favorites list, depending on whether it is already in it or not.
  162. * Favorites are then saved in user preferences
  163. *
  164. * @param group The group to add/remove to favorites
  165. */
  166. const updateGroupFavorites = (group: PlanexGroupType) => {
  167. if (isGroupInFavorites(group)) {
  168. removeGroupFromFavorites(group);
  169. } else {
  170. addGroupToFavorites(group);
  171. }
  172. };
  173. /**
  174. * Checks whether to display the given group category, depending on user search query
  175. *
  176. * @param item The group category
  177. * @returns {boolean}
  178. */
  179. const shouldDisplayAccordion = (item: PlanexGroupCategoryType): boolean => {
  180. let shouldDisplay = false;
  181. for (let i = 0; i < item.content.length; i += 1) {
  182. if (stringMatchQuery(item.content[i].name, currentSearchString)) {
  183. shouldDisplay = true;
  184. break;
  185. }
  186. }
  187. return shouldDisplay;
  188. };
  189. /**
  190. * Generates the dataset to be used in the FlatList.
  191. * This improves formatting of group names, sorts alphabetically the categories, and adds favorites at the top.
  192. *
  193. * @param fetchedData The raw data fetched from the server
  194. * @returns {[]}
  195. */
  196. const generateData = (
  197. fetchedData: PlanexGroupsType | undefined
  198. ): Array<PlanexGroupCategoryType> => {
  199. const data: Array<PlanexGroupCategoryType> = [];
  200. if (fetchedData) {
  201. Object.values(fetchedData).forEach(
  202. (category: PlanexGroupCategoryType) => {
  203. data.push(category);
  204. }
  205. );
  206. data.sort(sortName);
  207. data.unshift({
  208. name: i18n.t('screens.planex.favorites'),
  209. id: 0,
  210. content: favoriteGroups,
  211. });
  212. }
  213. return data;
  214. };
  215. /**
  216. * Removes the given group from the favorites
  217. *
  218. * @param group The group to remove from the array
  219. */
  220. const removeGroupFromFavorites = (group: PlanexGroupType) => {
  221. setFavoriteGroups(favoriteGroups.filter((g) => g.id !== group.id));
  222. };
  223. useEffect(() => {
  224. AsyncStorageManager.set(
  225. AsyncStorageManager.PREFERENCES.planexFavoriteGroups.key,
  226. favoriteGroups
  227. );
  228. }, [favoriteGroups]);
  229. /**
  230. * Adds the given group to favorites
  231. *
  232. * @param group The group to add to the array
  233. */
  234. const addGroupToFavorites = (group: PlanexGroupType) => {
  235. setFavoriteGroups([...favoriteGroups, group].sort(sortName));
  236. };
  237. return (
  238. <WebSectionList
  239. request={() => readData<PlanexGroupsType>(Urls.planex.groups)}
  240. createDataset={createDataset}
  241. refreshOnFocus={true}
  242. renderItem={getRenderItem}
  243. updateData={currentSearchString + favoriteGroups.length}
  244. cache={groups}
  245. onCacheUpdate={setGroups}
  246. />
  247. );
  248. }
  249. export default GroupSelectionScreen;