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.

WebViewScreen.tsx 7.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  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 WebView from 'react-native-webview';
  21. import {
  22. Divider,
  23. HiddenItem,
  24. OverflowMenu,
  25. } from 'react-navigation-header-buttons';
  26. import i18n from 'i18n-js';
  27. import {
  28. Animated,
  29. BackHandler,
  30. Linking,
  31. NativeScrollEvent,
  32. NativeSyntheticEvent,
  33. } from 'react-native';
  34. import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons';
  35. import {withTheme} from 'react-native-paper';
  36. import {StackNavigationProp} from '@react-navigation/stack';
  37. import {Collapsible} from 'react-navigation-collapsible';
  38. import withCollapsible from '../../utils/withCollapsible';
  39. import MaterialHeaderButtons, {Item} from '../Overrides/CustomHeaderButton';
  40. import {ERROR_TYPE} from '../../utils/WebData';
  41. import ErrorView from './ErrorView';
  42. import BasicLoadingScreen from './BasicLoadingScreen';
  43. type PropsType = {
  44. navigation: StackNavigationProp<any>;
  45. theme: ReactNativePaper.Theme;
  46. url: string;
  47. collapsibleStack: Collapsible;
  48. onMessage: (event: {nativeEvent: {data: string}}) => void;
  49. onScroll: (event: NativeSyntheticEvent<NativeScrollEvent>) => void;
  50. customJS?: string;
  51. customPaddingFunction?: null | ((padding: number) => string);
  52. showAdvancedControls?: boolean;
  53. };
  54. const AnimatedWebView = Animated.createAnimatedComponent(WebView);
  55. /**
  56. * Class defining a webview screen.
  57. */
  58. class WebViewScreen extends React.PureComponent<PropsType> {
  59. static defaultProps = {
  60. customJS: '',
  61. showAdvancedControls: true,
  62. customPaddingFunction: null,
  63. };
  64. currentUrl: string;
  65. webviewRef: {current: null | WebView};
  66. canGoBack: boolean;
  67. constructor(props: PropsType) {
  68. super(props);
  69. this.webviewRef = React.createRef();
  70. this.canGoBack = false;
  71. this.currentUrl = props.url;
  72. }
  73. /**
  74. * Creates header buttons and listens to events after mounting
  75. */
  76. componentDidMount() {
  77. const {props} = this;
  78. props.navigation.setOptions({
  79. headerRight: props.showAdvancedControls
  80. ? this.getAdvancedButtons
  81. : this.getBasicButton,
  82. });
  83. props.navigation.addListener('focus', () => {
  84. BackHandler.addEventListener(
  85. 'hardwareBackPress',
  86. this.onBackButtonPressAndroid,
  87. );
  88. });
  89. props.navigation.addListener('blur', () => {
  90. BackHandler.removeEventListener(
  91. 'hardwareBackPress',
  92. this.onBackButtonPressAndroid,
  93. );
  94. });
  95. }
  96. /**
  97. * Goes back on the webview or on the navigation stack if we cannot go back anymore
  98. *
  99. * @returns {boolean}
  100. */
  101. onBackButtonPressAndroid = (): boolean => {
  102. if (this.canGoBack) {
  103. this.onGoBackClicked();
  104. return true;
  105. }
  106. return false;
  107. };
  108. /**
  109. * Gets header refresh and open in browser buttons
  110. *
  111. * @return {*}
  112. */
  113. getBasicButton = () => {
  114. return (
  115. <MaterialHeaderButtons>
  116. <Item
  117. title="refresh"
  118. iconName="refresh"
  119. onPress={this.onRefreshClicked}
  120. />
  121. <Item
  122. title={i18n.t('general.openInBrowser')}
  123. iconName="open-in-new"
  124. onPress={this.onOpenClicked}
  125. />
  126. </MaterialHeaderButtons>
  127. );
  128. };
  129. /**
  130. * Creates advanced header control buttons.
  131. * These buttons allows the user to refresh, go back, go forward and open in the browser.
  132. *
  133. * @returns {*}
  134. */
  135. getAdvancedButtons = () => {
  136. const {props} = this;
  137. return (
  138. <MaterialHeaderButtons>
  139. <Item
  140. title="refresh"
  141. iconName="refresh"
  142. onPress={this.onRefreshClicked}
  143. />
  144. <OverflowMenu
  145. style={{marginHorizontal: 10}}
  146. OverflowIcon={
  147. <MaterialCommunityIcons
  148. name="dots-vertical"
  149. size={26}
  150. color={props.theme.colors.text}
  151. />
  152. }>
  153. <HiddenItem
  154. title={i18n.t('general.goBack')}
  155. onPress={this.onGoBackClicked}
  156. />
  157. <HiddenItem
  158. title={i18n.t('general.goForward')}
  159. onPress={this.onGoForwardClicked}
  160. />
  161. <Divider />
  162. <HiddenItem
  163. title={i18n.t('general.openInBrowser')}
  164. onPress={this.onOpenClicked}
  165. />
  166. </OverflowMenu>
  167. </MaterialHeaderButtons>
  168. );
  169. };
  170. /**
  171. * Gets the loading indicator
  172. *
  173. * @return {*}
  174. */
  175. getRenderLoading = () => <BasicLoadingScreen isAbsolute />;
  176. /**
  177. * Gets the javascript needed to generate a padding on top of the page
  178. * This adds padding to the body and runs the custom padding function given in props
  179. *
  180. * @param padding The padding to add in pixels
  181. * @returns {string}
  182. */
  183. getJavascriptPadding(padding: number): string {
  184. const {props} = this;
  185. const customPadding =
  186. props.customPaddingFunction != null
  187. ? props.customPaddingFunction(padding)
  188. : '';
  189. return `document.getElementsByTagName('body')[0].style.paddingTop = '${padding}px';${customPadding}true;`;
  190. }
  191. /**
  192. * Callback to use when refresh button is clicked. Reloads the webview.
  193. */
  194. onRefreshClicked = () => {
  195. if (this.webviewRef.current != null) {
  196. this.webviewRef.current.reload();
  197. }
  198. };
  199. onGoBackClicked = () => {
  200. if (this.webviewRef.current != null) {
  201. this.webviewRef.current.goBack();
  202. }
  203. };
  204. onGoForwardClicked = () => {
  205. if (this.webviewRef.current != null) {
  206. this.webviewRef.current.goForward();
  207. }
  208. };
  209. onOpenClicked = () => {
  210. Linking.openURL(this.currentUrl);
  211. };
  212. onScroll = (event: NativeSyntheticEvent<NativeScrollEvent>) => {
  213. const {onScroll} = this.props;
  214. if (onScroll) {
  215. onScroll(event);
  216. }
  217. };
  218. /**
  219. * Injects the given javascript string into the web page
  220. *
  221. * @param script The script to inject
  222. */
  223. injectJavaScript = (script: string) => {
  224. if (this.webviewRef.current != null) {
  225. this.webviewRef.current.injectJavaScript(script);
  226. }
  227. };
  228. render() {
  229. const {props} = this;
  230. const {containerPaddingTop, onScrollWithListener} = props.collapsibleStack;
  231. return (
  232. <AnimatedWebView
  233. ref={this.webviewRef}
  234. source={{uri: props.url}}
  235. startInLoadingState
  236. injectedJavaScript={props.customJS}
  237. javaScriptEnabled
  238. renderLoading={this.getRenderLoading}
  239. renderError={() => (
  240. <ErrorView
  241. errorCode={ERROR_TYPE.CONNECTION_ERROR}
  242. onRefresh={this.onRefreshClicked}
  243. />
  244. )}
  245. onNavigationStateChange={(navState) => {
  246. this.currentUrl = navState.url;
  247. this.canGoBack = navState.canGoBack;
  248. }}
  249. onMessage={props.onMessage}
  250. onLoad={() => {
  251. this.injectJavaScript(this.getJavascriptPadding(containerPaddingTop));
  252. }}
  253. // Animations
  254. onScroll={(event) => onScrollWithListener(this.onScroll)(event)}
  255. />
  256. );
  257. }
  258. }
  259. export default withCollapsible(withTheme(WebViewScreen));