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.

PlanexScreen.tsx 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  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, { useCallback, useRef, useState } from 'react';
  20. import { Title, useTheme } from 'react-native-paper';
  21. import i18n from 'i18n-js';
  22. import {
  23. NativeScrollEvent,
  24. NativeSyntheticEvent,
  25. StyleSheet,
  26. View,
  27. } from 'react-native';
  28. import {
  29. CommonActions,
  30. useFocusEffect,
  31. useNavigation,
  32. } from '@react-navigation/native';
  33. import Autolink from 'react-native-autolink';
  34. import ThemeManager from '../../managers/ThemeManager';
  35. import WebViewScreen from '../../components/Screens/WebViewScreen';
  36. import AsyncStorageManager from '../../managers/AsyncStorageManager';
  37. import AlertDialog from '../../components/Dialogs/AlertDialog';
  38. import { dateToString, getTimeOnlyString } from '../../utils/Planning';
  39. import DateManager from '../../managers/DateManager';
  40. import AnimatedBottomBar from '../../components/Animations/AnimatedBottomBar';
  41. import ErrorView from '../../components/Screens/ErrorView';
  42. import type { PlanexGroupType } from './GroupSelectionScreen';
  43. import { MASCOT_STYLE } from '../../components/Mascot/Mascot';
  44. import MascotPopup from '../../components/Mascot/MascotPopup';
  45. import { getPrettierPlanexGroupName } from '../../utils/Utils';
  46. import GENERAL_STYLES from '../../constants/Styles';
  47. import Urls from '../../constants/Urls';
  48. // // JS + JQuery functions used to remove alpha from events. Copy paste in browser console for quick testing
  49. // // Remove alpha from given Jquery node
  50. // function removeAlpha(node) {
  51. // let bg = node.css("background-color");
  52. // if (bg.match("^rgba")) {
  53. // let a = bg.slice(5).split(',');
  54. // // Fix for tooltips with broken background
  55. // if (parseInt(a[0]) === parseInt(a[1]) && parseInt(a[1]) === parseInt(a[2]) && parseInt(a[2]) === 0) {
  56. // a[0] = a[1] = a[2] = '255';
  57. // }
  58. // let newBg ='rgb(' + a[0] + ',' + a[1] + ',' + a[2] + ')';
  59. // node.css("background-color", newBg);
  60. // }
  61. // }
  62. // // Observe for planning DOM changes
  63. // let observer = new MutationObserver(function(mutations) {
  64. // for (let i = 0; i < mutations.length; i++) {
  65. // if (mutations[i]['addedNodes'].length > 0 &&
  66. // ($(mutations[i]['addedNodes'][0]).hasClass("fc-event") || $(mutations[i]['addedNodes'][0]).hasClass("tooltiptopicevent")))
  67. // removeAlpha($(mutations[i]['addedNodes'][0]))
  68. // }
  69. // });
  70. // // observer.observe(document.querySelector(".fc-body"), {attributes: false, childList: true, characterData: false, subtree:true});
  71. // observer.observe(document.querySelector("body"), {attributes: false, childList: true, characterData: false, subtree:true});
  72. // // Run remove alpha a first time on whole planning. Useful when code injected after planning fully loaded.
  73. // $(".fc-event-container .fc-event").each(function(index) {
  74. // removeAlpha($(this));
  75. // });
  76. // Watch for changes in the calendar and call the remove alpha function to prevent invisible events
  77. const OBSERVE_MUTATIONS_INJECTED =
  78. 'function removeAlpha(node) {\n' +
  79. ' let bg = node.css("background-color");\n' +
  80. ' if (bg.match("^rgba")) {\n' +
  81. " let a = bg.slice(5).split(',');\n" +
  82. ' // Fix for tooltips with broken background\n' +
  83. ' if (parseInt(a[0]) === parseInt(a[1]) && parseInt(a[1]) === parseInt(a[2]) && parseInt(a[2]) === 0) {\n' +
  84. " a[0] = a[1] = a[2] = '255';\n" +
  85. ' }\n' +
  86. " let newBg ='rgb(' + a[0] + ',' + a[1] + ',' + a[2] + ')';\n" +
  87. ' node.css("background-color", newBg);\n' +
  88. ' }\n' +
  89. '}\n' +
  90. '// Observe for planning DOM changes\n' +
  91. 'let observer = new MutationObserver(function(mutations) {\n' +
  92. ' for (let i = 0; i < mutations.length; i++) {\n' +
  93. " if (mutations[i]['addedNodes'].length > 0 &&\n" +
  94. ' ($(mutations[i][\'addedNodes\'][0]).hasClass("fc-event") || $(mutations[i][\'addedNodes\'][0]).hasClass("tooltiptopicevent")))\n' +
  95. " removeAlpha($(mutations[i]['addedNodes'][0]))\n" +
  96. ' }\n' +
  97. '});\n' +
  98. '// observer.observe(document.querySelector(".fc-body"), {attributes: false, childList: true, characterData: false, subtree:true});\n' +
  99. 'observer.observe(document.querySelector("body"), {attributes: false, childList: true, characterData: false, subtree:true});\n' +
  100. '// Run remove alpha a first time on whole planning. Useful when code injected after planning fully loaded.\n' +
  101. '$(".fc-event-container .fc-event").each(function(index) {\n' +
  102. ' removeAlpha($(this));\n' +
  103. '});';
  104. // Overrides default settings to send a message to the webview when clicking on an event
  105. const FULL_CALENDAR_SETTINGS = `
  106. let calendar = $('#calendar').fullCalendar('getCalendar');
  107. calendar.option({
  108. eventClick: function (data, event, view) {
  109. let message = {
  110. title: data.title,
  111. color: data.color,
  112. start: data.start._d,
  113. end: data.end._d,
  114. };
  115. window.ReactNativeWebView.postMessage(JSON.stringify(message));
  116. }
  117. });`;
  118. // Mobile friendly CSS
  119. const CUSTOM_CSS =
  120. 'body>.container{padding-top:20px; padding-bottom: 50px}header,#entite,#groupe_visibility,#calendar .fc-left,#calendar .fc-right{display:none}#calendar .fc-agendaWeek-view .fc-content-skeleton .fc-title{font-size:.6rem}#calendar .fc-agendaWeek-view .fc-content-skeleton .fc-time{font-size:.5rem}#calendar .fc-month-view .fc-content-skeleton .fc-title{font-size:.6rem}#calendar .fc-month-view .fc-content-skeleton .fc-time{font-size:.7rem}.fc-axis{font-size:.8rem;width:15px!important}.fc-day-header{font-size:.8rem}.fc-unthemed td.fc-today{background:#be1522; opacity:0.4}';
  121. // Dark mode CSS, to be used with the mobile friendly css
  122. const CUSTOM_CSS_DARK =
  123. 'body{background-color:#121212}.fc-unthemed .fc-content,.fc-unthemed .fc-divider,.fc-unthemed .fc-list-heading td,.fc-unthemed .fc-list-view,.fc-unthemed .fc-popover,.fc-unthemed .fc-row,.fc-unthemed tbody,.fc-unthemed td,.fc-unthemed th,.fc-unthemed thead{border-color:#222}.fc-toolbar .fc-center>*,h2,table{color:#fff}.fc-event-container{color:#121212}.fc-event-container .fc-bg{opacity:0.2;background-color:#000}.fc-unthemed td.fc-today{background:#be1522; opacity:0.4}';
  124. // Inject the custom css into the webpage
  125. const INJECT_STYLE = `$('head').append('<style>${CUSTOM_CSS}</style>');`;
  126. // Inject the dark mode into the webpage, to call after the custom css inject above
  127. const INJECT_STYLE_DARK = `$('head').append('<style>${CUSTOM_CSS_DARK}</style>');`;
  128. const styles = StyleSheet.create({
  129. container: {
  130. position: 'absolute',
  131. height: '100%',
  132. width: '100%',
  133. },
  134. });
  135. type Props = {
  136. route: {
  137. params: {
  138. group?: PlanexGroupType;
  139. };
  140. };
  141. };
  142. function PlanexScreen(props: Props) {
  143. const navigation = useNavigation();
  144. const theme = useTheme();
  145. const barRef = useRef<typeof AnimatedBottomBar>();
  146. const [dialogContent, setDialogContent] = useState<
  147. | undefined
  148. | {
  149. title: string | React.ReactElement;
  150. message: string | React.ReactElement;
  151. color: string;
  152. }
  153. >();
  154. const [injectJS, setInjectJS] = useState('');
  155. const getCurrentGroup = (): PlanexGroupType | undefined => {
  156. let currentGroupString = AsyncStorageManager.getString(
  157. AsyncStorageManager.PREFERENCES.planexCurrentGroup.key
  158. );
  159. let group: PlanexGroupType;
  160. if (currentGroupString !== '') {
  161. group = JSON.parse(currentGroupString);
  162. navigation.setOptions({
  163. title: getPrettierPlanexGroupName(group.name),
  164. });
  165. return group;
  166. }
  167. return undefined;
  168. };
  169. const [currentGroup, setCurrentGroup] = useState<PlanexGroupType | undefined>(
  170. getCurrentGroup()
  171. );
  172. useFocusEffect(
  173. useCallback(() => {
  174. if (props.route.params?.group) {
  175. // reset params to prevent infinite loop
  176. selectNewGroup(props.route.params.group);
  177. navigation.dispatch(CommonActions.setParams({ group: undefined }));
  178. }
  179. // eslint-disable-next-line react-hooks/exhaustive-deps
  180. }, [props.route.params])
  181. );
  182. /**
  183. * Gets the Webview, with an error view on top if no group is selected.
  184. *
  185. * @returns {*}
  186. */
  187. const getWebView = () => {
  188. return (
  189. <View style={GENERAL_STYLES.flex}>
  190. {!currentGroup ? (
  191. <ErrorView
  192. icon={'account-clock'}
  193. message={i18n.t('screens.planex.noGroupSelected')}
  194. />
  195. ) : null}
  196. <WebViewScreen
  197. url={Urls.planex.planning}
  198. initialJS={generateInjectedJS(currentGroup)}
  199. injectJS={injectJS}
  200. onMessage={onMessage}
  201. onScroll={onScroll}
  202. showAdvancedControls={false}
  203. />
  204. </View>
  205. );
  206. };
  207. /**
  208. * Callback used when the user clicks on the navigate to settings button.
  209. * This will hide the banner and open the SettingsScreen
  210. */
  211. const onGoToSettings = () => navigation.navigate('settings');
  212. /**
  213. * Sends a FullCalendar action to the web page inside the webview.
  214. *
  215. * @param action The action to perform, as described in the FullCalendar doc https://fullcalendar.io/docs/v3.
  216. * Or "setGroup" with the group id as data to set the selected group
  217. * @param data Data to pass to the action
  218. */
  219. const sendMessage = (action: string, data?: string) => {
  220. let command;
  221. if (action === 'setGroup') {
  222. command = `displayAde(${data})`;
  223. } else {
  224. command = `$('#calendar').fullCalendar('${action}', '${data}')`;
  225. }
  226. // String must resolve to true to prevent crash on iOS
  227. command += ';true;';
  228. // Change the injected
  229. if (command === injectJS) {
  230. command += ';true;';
  231. }
  232. setInjectJS(command);
  233. };
  234. /**
  235. * Shows a dialog when the user clicks on an event.
  236. *
  237. * @param event
  238. */
  239. const onMessage = (event: { nativeEvent: { data: string } }) => {
  240. const data: {
  241. start: string;
  242. end: string;
  243. title: string;
  244. color: string;
  245. } = JSON.parse(event.nativeEvent.data);
  246. const startDate = dateToString(new Date(data.start), true);
  247. const endDate = dateToString(new Date(data.end), true);
  248. const startString = getTimeOnlyString(startDate);
  249. const endString = getTimeOnlyString(endDate);
  250. let msg = `${DateManager.getInstance().getTranslatedDate(startDate)}\n`;
  251. if (startString != null && endString != null) {
  252. msg += `${startString} - ${endString}`;
  253. }
  254. showDialog(data.title, msg, data.color);
  255. };
  256. /**
  257. * Shows a simple dialog to the user.
  258. *
  259. * @param title The dialog's title
  260. * @param message The message to show
  261. */
  262. const showDialog = (title: string, message: string, color?: string) => {
  263. const finalColor = color ? color : theme.colors.surface;
  264. setDialogContent({
  265. title: (
  266. <Autolink
  267. text={title}
  268. hashtag={'facebook'}
  269. component={Title}
  270. truncate={32}
  271. email={true}
  272. url={true}
  273. phone={true}
  274. />
  275. ),
  276. message: message,
  277. color: finalColor,
  278. });
  279. };
  280. const hideDialog = () => setDialogContent(undefined);
  281. /**
  282. * Binds the onScroll event to the control bar for automatic hiding based on scroll direction and speed
  283. *
  284. * @param event
  285. */
  286. const onScroll = (event: NativeSyntheticEvent<NativeScrollEvent>) => {
  287. if (barRef.current) {
  288. barRef.current.onScroll(event);
  289. }
  290. };
  291. /**
  292. * Sends the webpage a message with the new group to select and save it to preferences
  293. *
  294. * @param group The group object selected
  295. */
  296. const selectNewGroup = (group: PlanexGroupType) => {
  297. sendMessage('setGroup', group.id.toString());
  298. setCurrentGroup(group);
  299. AsyncStorageManager.set(
  300. AsyncStorageManager.PREFERENCES.planexCurrentGroup.key,
  301. group
  302. );
  303. navigation.setOptions({ title: getPrettierPlanexGroupName(group.name) });
  304. };
  305. /**
  306. * Generates custom JavaScript to be injected into the webpage
  307. *
  308. * @param groupID The current group selected
  309. */
  310. const generateInjectedJS = (group: PlanexGroupType | undefined) => {
  311. let customInjectedJS = `$(document).ready(function() {
  312. ${OBSERVE_MUTATIONS_INJECTED}
  313. ${INJECT_STYLE}
  314. ${FULL_CALENDAR_SETTINGS}`;
  315. if (group) {
  316. customInjectedJS += `displayAde(${group.id});`;
  317. }
  318. if (DateManager.isWeekend(new Date())) {
  319. customInjectedJS += `calendar.next();`;
  320. }
  321. if (ThemeManager.getNightMode()) {
  322. customInjectedJS += INJECT_STYLE_DARK;
  323. }
  324. customInjectedJS += 'removeAlpha();});true;'; // Prevents crash on ios
  325. return customInjectedJS;
  326. };
  327. return (
  328. <View style={GENERAL_STYLES.flex}>
  329. {/* Allow to draw webview bellow banner */}
  330. <View style={styles.container}>
  331. {theme.dark ? ( // Force component theme update by recreating it on theme change
  332. getWebView()
  333. ) : (
  334. <View style={GENERAL_STYLES.flex}>{getWebView()}</View>
  335. )}
  336. </View>
  337. {AsyncStorageManager.getString(
  338. AsyncStorageManager.PREFERENCES.defaultStartScreen.key
  339. ).toLowerCase() !== 'planex' ? (
  340. <MascotPopup
  341. prefKey={AsyncStorageManager.PREFERENCES.planexShowMascot.key}
  342. title={i18n.t('screens.planex.mascotDialog.title')}
  343. message={i18n.t('screens.planex.mascotDialog.message')}
  344. icon="emoticon-kiss"
  345. buttons={{
  346. action: {
  347. message: i18n.t('screens.planex.mascotDialog.ok'),
  348. icon: 'cog',
  349. onPress: onGoToSettings,
  350. },
  351. cancel: {
  352. message: i18n.t('screens.planex.mascotDialog.cancel'),
  353. icon: 'close',
  354. color: theme.colors.warning,
  355. },
  356. }}
  357. emotion={MASCOT_STYLE.INTELLO}
  358. />
  359. ) : null}
  360. <AlertDialog
  361. visible={dialogContent !== undefined}
  362. onDismiss={hideDialog}
  363. title={dialogContent ? dialogContent.title : ''}
  364. message={dialogContent ? dialogContent.message : ''}
  365. style={
  366. dialogContent
  367. ? { borderColor: dialogContent.color, borderWidth: 2 }
  368. : undefined
  369. }
  370. />
  371. <AnimatedBottomBar
  372. navigation={navigation}
  373. ref={barRef}
  374. onPress={sendMessage}
  375. seekAttention={currentGroup === undefined}
  376. />
  377. </View>
  378. );
  379. }
  380. export default PlanexScreen;