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

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