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 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  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. }
  152. >();
  153. const [injectJS, setInjectJS] = useState('');
  154. const getCurrentGroup = (): PlanexGroupType | undefined => {
  155. let currentGroupString = AsyncStorageManager.getString(
  156. AsyncStorageManager.PREFERENCES.planexCurrentGroup.key
  157. );
  158. let group: PlanexGroupType;
  159. if (currentGroupString !== '') {
  160. group = JSON.parse(currentGroupString);
  161. navigation.setOptions({
  162. title: getPrettierPlanexGroupName(group.name),
  163. });
  164. return group;
  165. }
  166. return undefined;
  167. };
  168. const [currentGroup, setCurrentGroup] = useState<PlanexGroupType | undefined>(
  169. getCurrentGroup()
  170. );
  171. useFocusEffect(
  172. useCallback(() => {
  173. if (props.route.params?.group) {
  174. // reset params to prevent infinite loop
  175. selectNewGroup(props.route.params.group);
  176. navigation.dispatch(CommonActions.setParams({ group: undefined }));
  177. }
  178. // eslint-disable-next-line react-hooks/exhaustive-deps
  179. }, [props.route.params])
  180. );
  181. /**
  182. * Gets the Webview, with an error view on top if no group is selected.
  183. *
  184. * @returns {*}
  185. */
  186. const getWebView = () => {
  187. return (
  188. <View style={GENERAL_STYLES.flex}>
  189. {!currentGroup ? (
  190. <ErrorView
  191. icon={'account-clock'}
  192. message={i18n.t('screens.planex.noGroupSelected')}
  193. />
  194. ) : null}
  195. <WebViewScreen
  196. url={Urls.planex.planning}
  197. initialJS={generateInjectedJS(currentGroup)}
  198. injectJS={injectJS}
  199. onMessage={onMessage}
  200. onScroll={onScroll}
  201. showAdvancedControls={false}
  202. />
  203. </View>
  204. );
  205. };
  206. /**
  207. * Callback used when the user clicks on the navigate to settings button.
  208. * This will hide the banner and open the SettingsScreen
  209. */
  210. const onGoToSettings = () => navigation.navigate('settings');
  211. /**
  212. * Sends a FullCalendar action to the web page inside the webview.
  213. *
  214. * @param action The action to perform, as described in the FullCalendar doc https://fullcalendar.io/docs/v3.
  215. * Or "setGroup" with the group id as data to set the selected group
  216. * @param data Data to pass to the action
  217. */
  218. const sendMessage = (action: string, data?: string) => {
  219. let command;
  220. if (action === 'setGroup') {
  221. command = `displayAde(${data})`;
  222. } else {
  223. command = `$('#calendar').fullCalendar('${action}', '${data}')`;
  224. }
  225. // String must resolve to true to prevent crash on iOS
  226. command += ';true;';
  227. // Change the injected
  228. if (command === injectJS) {
  229. command += ';true;';
  230. }
  231. setInjectJS(command);
  232. };
  233. /**
  234. * Shows a dialog when the user clicks on an event.
  235. *
  236. * @param event
  237. */
  238. const onMessage = (event: { nativeEvent: { data: string } }) => {
  239. const data: {
  240. start: string;
  241. end: string;
  242. title: string;
  243. color: string;
  244. } = JSON.parse(event.nativeEvent.data);
  245. const startDate = dateToString(new Date(data.start), true);
  246. const endDate = dateToString(new Date(data.end), true);
  247. const startString = getTimeOnlyString(startDate);
  248. const endString = getTimeOnlyString(endDate);
  249. let msg = `${DateManager.getInstance().getTranslatedDate(startDate)}\n`;
  250. if (startString != null && endString != null) {
  251. msg += `${startString} - ${endString}`;
  252. }
  253. showDialog(data.title, msg);
  254. };
  255. /**
  256. * Shows a simple dialog to the user.
  257. *
  258. * @param title The dialog's title
  259. * @param message The message to show
  260. */
  261. const showDialog = (title: string, message: string) => {
  262. setDialogContent({
  263. title: (
  264. <Autolink
  265. text={title}
  266. hashtag={'facebook'}
  267. component={Title}
  268. truncate={32}
  269. email={true}
  270. url={true}
  271. phone={true}
  272. />
  273. ),
  274. message: message,
  275. });
  276. };
  277. const hideDialog = () => setDialogContent(undefined);
  278. /**
  279. * Binds the onScroll event to the control bar for automatic hiding based on scroll direction and speed
  280. *
  281. * @param event
  282. */
  283. const onScroll = (event: NativeSyntheticEvent<NativeScrollEvent>) => {
  284. if (barRef.current) {
  285. barRef.current.onScroll(event);
  286. }
  287. };
  288. /**
  289. * Sends the webpage a message with the new group to select and save it to preferences
  290. *
  291. * @param group The group object selected
  292. */
  293. const selectNewGroup = (group: PlanexGroupType) => {
  294. sendMessage('setGroup', group.id.toString());
  295. setCurrentGroup(group);
  296. AsyncStorageManager.set(
  297. AsyncStorageManager.PREFERENCES.planexCurrentGroup.key,
  298. group
  299. );
  300. navigation.setOptions({ title: getPrettierPlanexGroupName(group.name) });
  301. };
  302. /**
  303. * Generates custom JavaScript to be injected into the webpage
  304. *
  305. * @param groupID The current group selected
  306. */
  307. const generateInjectedJS = (group: PlanexGroupType | undefined) => {
  308. console.log(group);
  309. let customInjectedJS = `$(document).ready(function() {
  310. ${OBSERVE_MUTATIONS_INJECTED}
  311. ${INJECT_STYLE}
  312. ${FULL_CALENDAR_SETTINGS}`;
  313. if (group) {
  314. customInjectedJS += `displayAde(${group.id});`;
  315. }
  316. if (DateManager.isWeekend(new Date())) {
  317. customInjectedJS += `calendar.next();`;
  318. }
  319. if (ThemeManager.getNightMode()) {
  320. customInjectedJS += INJECT_STYLE_DARK;
  321. }
  322. customInjectedJS += 'removeAlpha();});true;'; // Prevents crash on ios
  323. return customInjectedJS;
  324. };
  325. return (
  326. <View style={GENERAL_STYLES.flex}>
  327. {/* Allow to draw webview bellow banner */}
  328. <View style={styles.container}>
  329. {theme.dark ? ( // Force component theme update by recreating it on theme change
  330. getWebView()
  331. ) : (
  332. <View style={GENERAL_STYLES.flex}>{getWebView()}</View>
  333. )}
  334. </View>
  335. {AsyncStorageManager.getString(
  336. AsyncStorageManager.PREFERENCES.defaultStartScreen.key
  337. ).toLowerCase() !== 'planex' ? (
  338. <MascotPopup
  339. prefKey={AsyncStorageManager.PREFERENCES.planexShowMascot.key}
  340. title={i18n.t('screens.planex.mascotDialog.title')}
  341. message={i18n.t('screens.planex.mascotDialog.message')}
  342. icon="emoticon-kiss"
  343. buttons={{
  344. action: {
  345. message: i18n.t('screens.planex.mascotDialog.ok'),
  346. icon: 'cog',
  347. onPress: onGoToSettings,
  348. },
  349. cancel: {
  350. message: i18n.t('screens.planex.mascotDialog.cancel'),
  351. icon: 'close',
  352. color: theme.colors.warning,
  353. },
  354. }}
  355. emotion={MASCOT_STYLE.INTELLO}
  356. />
  357. ) : null}
  358. <AlertDialog
  359. visible={dialogContent !== undefined}
  360. onDismiss={hideDialog}
  361. title={dialogContent ? dialogContent.title : ''}
  362. message={dialogContent ? dialogContent.message : ''}
  363. />
  364. <AnimatedBottomBar
  365. navigation={navigation}
  366. ref={barRef}
  367. onPress={sendMessage}
  368. seekAttention={currentGroup === undefined}
  369. />
  370. </View>
  371. );
  372. }
  373. export default PlanexScreen;