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

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