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.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  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. }, [navigation]);
  72. const getSearchBar = () => {
  73. return (
  74. // @ts-ignore
  75. <Searchbar
  76. placeholder={i18n.t('screens.proximo.search')}
  77. onChangeText={setCurrentSearchString}
  78. />
  79. );
  80. };
  81. /**
  82. * Gets a render item for the given article
  83. *
  84. * @param item The article to render
  85. * @return {*}
  86. */
  87. const getRenderItem = ({ item }: { item: PlanexGroupCategoryType }) => (
  88. <GroupListAccordion
  89. item={item}
  90. favorites={[...favoriteGroups]}
  91. onGroupPress={onListItemPress}
  92. onFavoritePress={onListFavoritePress}
  93. currentSearchString={currentSearchString}
  94. />
  95. );
  96. /**
  97. * Creates the dataset to be used in the FlatList
  98. *
  99. * @param fetchedData
  100. * @return {*}
  101. * */
  102. const createDataset = (
  103. fetchedData:
  104. | {
  105. [key: string]: PlanexGroupCategoryType;
  106. }
  107. | undefined
  108. ): Array<{ title: string; data: Array<PlanexGroupCategoryType> }> => {
  109. return [
  110. {
  111. title: '',
  112. data: generateData(fetchedData),
  113. },
  114. ];
  115. };
  116. /**
  117. * Callback used when clicking an article in the list.
  118. * It opens the modal to show detailed information about the article
  119. *
  120. * @param item The article pressed
  121. */
  122. const onListItemPress = (item: PlanexGroupType) => {
  123. navigation.navigate('planex', {
  124. screen: 'index',
  125. params: { group: item },
  126. });
  127. };
  128. /**
  129. * Callback used when the user clicks on the favorite button
  130. *
  131. * @param item The item to add/remove from favorites
  132. */
  133. const onListFavoritePress = (item: PlanexGroupType) => {
  134. updateGroupFavorites(item);
  135. };
  136. /**
  137. * Checks if the given group is in the favorites list
  138. *
  139. * @param group The group to check
  140. * @returns {boolean}
  141. */
  142. const isGroupInFavorites = (group: PlanexGroupType): boolean => {
  143. let isFav = false;
  144. favoriteGroups.forEach((favGroup: PlanexGroupType) => {
  145. if (group.id === favGroup.id) {
  146. isFav = true;
  147. }
  148. });
  149. return isFav;
  150. };
  151. /**
  152. * Adds or removes the given group to the favorites list, depending on whether it is already in it or not.
  153. * Favorites are then saved in user preferences
  154. *
  155. * @param group The group to add/remove to favorites
  156. */
  157. const updateGroupFavorites = (group: PlanexGroupType) => {
  158. if (isGroupInFavorites(group)) {
  159. removeGroupFromFavorites(group);
  160. } else {
  161. addGroupToFavorites(group);
  162. }
  163. };
  164. /**
  165. * Generates the dataset to be used in the FlatList.
  166. * This improves formatting of group names, sorts alphabetically the categories, and adds favorites at the top.
  167. *
  168. * @param fetchedData The raw data fetched from the server
  169. * @returns {[]}
  170. */
  171. const generateData = (
  172. fetchedData: PlanexGroupsType | undefined
  173. ): Array<PlanexGroupCategoryType> => {
  174. const data: Array<PlanexGroupCategoryType> = [];
  175. if (fetchedData) {
  176. // Convert the object into an array
  177. Object.values(fetchedData).forEach(
  178. (category: PlanexGroupCategoryType) => {
  179. const content: Array<PlanexGroupType> = [];
  180. // Filter groups matching the search query
  181. category.content.forEach((g: PlanexGroupType) => {
  182. if (stringMatchQuery(g.name, currentSearchString)) {
  183. content.push(g);
  184. }
  185. });
  186. // Only add categories with groups matching the query
  187. if (content.length > 0) {
  188. data.push({
  189. id: category.id,
  190. name: category.name,
  191. content: content,
  192. });
  193. }
  194. }
  195. );
  196. data.sort(sortName);
  197. // Add the favorites at the top
  198. data.unshift({
  199. name: i18n.t('screens.planex.favorites.title'),
  200. id: 0,
  201. content: favoriteGroups,
  202. });
  203. }
  204. return data;
  205. };
  206. /**
  207. * Removes the given group from the favorites
  208. *
  209. * @param group The group to remove from the array
  210. */
  211. const removeGroupFromFavorites = (group: PlanexGroupType) => {
  212. setFavoriteGroups(favoriteGroups.filter((g) => g.id !== group.id));
  213. };
  214. useEffect(() => {
  215. AsyncStorageManager.set(
  216. AsyncStorageManager.PREFERENCES.planexFavoriteGroups.key,
  217. favoriteGroups
  218. );
  219. }, [favoriteGroups]);
  220. /**
  221. * Adds the given group to favorites
  222. *
  223. * @param group The group to add to the array
  224. */
  225. const addGroupToFavorites = (group: PlanexGroupType) => {
  226. setFavoriteGroups([...favoriteGroups, group].sort(sortName));
  227. };
  228. return (
  229. <WebSectionList
  230. request={() => readData<PlanexGroupsType>(Urls.planex.groups)}
  231. createDataset={createDataset}
  232. refreshOnFocus={true}
  233. renderItem={getRenderItem}
  234. extraData={currentSearchString + favoriteGroups.length}
  235. cache={groups}
  236. onCacheUpdate={setGroups}
  237. />
  238. );
  239. }
  240. export default GroupSelectionScreen;