Application Android et IOS pour l'amicale des élèves
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.js 15KB

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