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

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