Compare commits

..

2 commits

Author SHA1 Message Date
Arnaud Vergnet
b78357968a Update planning screens to use TypeScript 2020-09-22 22:18:05 +02:00
Arnaud Vergnet
742cb1802d Update Planex screens to use TypeScript 2020-09-22 22:04:39 +02:00
4 changed files with 126 additions and 100 deletions

View file

@ -17,8 +17,6 @@
* along with Campus INSAT. If not, see <https://www.gnu.org/licenses/>.
*/
// @flow
import * as React from 'react';
import {Platform} from 'react-native';
import i18n from 'i18n-js';
@ -32,31 +30,35 @@ import AsyncStorageManager from '../../managers/AsyncStorageManager';
const LIST_ITEM_HEIGHT = 70;
export type PlanexGroupType = {
name: string,
id: number,
name: string;
id: number;
};
export type PlanexGroupCategoryType = {
name: string,
id: number,
content: Array<PlanexGroupType>,
name: string;
id: number;
content: Array<PlanexGroupType>;
};
type PropsType = {
navigation: StackNavigationProp,
navigation: StackNavigationProp<any>;
};
type StateType = {
currentSearchString: string,
favoriteGroups: Array<PlanexGroupType>,
currentSearchString: string;
favoriteGroups: Array<PlanexGroupType>;
};
function sortName(
a: PlanexGroupType | PlanexGroupCategoryType,
b: PlanexGroupType | PlanexGroupCategoryType,
): number {
if (a.name.toLowerCase() < b.name.toLowerCase()) return -1;
if (a.name.toLowerCase() > b.name.toLowerCase()) return 1;
if (a.name.toLowerCase() < b.name.toLowerCase()) {
return -1;
}
if (a.name.toLowerCase() > b.name.toLowerCase()) {
return 1;
}
return 0;
}
@ -96,8 +98,9 @@ class GroupSelectionScreen extends React.Component<PropsType, StateType> {
*
* @return {*}
*/
getSearchBar = (): React.Node => {
getSearchBar = () => {
return (
// @ts-ignore
<Searchbar
placeholder={i18n.t('screens.proximo.search')}
onChangeText={this.onSearchStringChange}
@ -111,7 +114,7 @@ class GroupSelectionScreen extends React.Component<PropsType, StateType> {
* @param item The article to render
* @return {*}
*/
getRenderItem = ({item}: {item: PlanexGroupCategoryType}): React.Node => {
getRenderItem = ({item}: {item: PlanexGroupCategoryType}) => {
const {currentSearchString, favoriteGroups} = this.state;
if (
this.shouldDisplayAccordion(item) ||
@ -138,8 +141,8 @@ class GroupSelectionScreen extends React.Component<PropsType, StateType> {
* @return {*}
* */
createDataset = (fetchedData: {
[key: string]: PlanexGroupCategoryType,
}): Array<{title: string, data: Array<PlanexGroupCategoryType>}> => {
[key: string]: PlanexGroupCategoryType;
}): Array<{title: string; data: Array<PlanexGroupCategoryType>}> => {
return [
{
title: '',
@ -190,7 +193,9 @@ class GroupSelectionScreen extends React.Component<PropsType, StateType> {
let isFav = false;
const {favoriteGroups} = this.state;
favoriteGroups.forEach((favGroup: PlanexGroupType) => {
if (group.id === favGroup.id) isFav = true;
if (group.id === favGroup.id) {
isFav = true;
}
});
return isFav;
}
@ -202,8 +207,11 @@ class GroupSelectionScreen extends React.Component<PropsType, StateType> {
* @param group The group to add/remove to favorites
*/
updateGroupFavorites(group: PlanexGroupType) {
if (this.isGroupInFavorites(group)) this.removeGroupFromFavorites(group);
else this.addGroupToFavorites(group);
if (this.isGroupInFavorites(group)) {
this.removeGroupFromFavorites(group);
} else {
this.addGroupToFavorites(group);
}
}
/**
@ -232,16 +240,13 @@ class GroupSelectionScreen extends React.Component<PropsType, StateType> {
* @returns {[]}
*/
generateData(fetchedData: {
[key: string]: PlanexGroupCategoryType,
[key: string]: PlanexGroupCategoryType;
}): Array<PlanexGroupCategoryType> {
const {favoriteGroups} = this.state;
const data = [];
// eslint-disable-next-line flowtype/no-weak-types
(Object.values(fetchedData): Array<any>).forEach(
(category: PlanexGroupCategoryType) => {
data.push(category);
},
);
const data: Array<PlanexGroupCategoryType> = [];
Object.values(fetchedData).forEach((category: PlanexGroupCategoryType) => {
data.push(category);
});
data.sort(sortName);
data.unshift({
name: i18n.t('screens.planex.favorites'),
@ -258,7 +263,7 @@ class GroupSelectionScreen extends React.Component<PropsType, StateType> {
*/
removeGroupFromFavorites(group: PlanexGroupType) {
this.setState((prevState: StateType): {
favoriteGroups: Array<PlanexGroupType>,
favoriteGroups: Array<PlanexGroupType>;
} => {
const {favoriteGroups} = prevState;
for (let i = 0; i < favoriteGroups.length; i += 1) {
@ -282,7 +287,7 @@ class GroupSelectionScreen extends React.Component<PropsType, StateType> {
*/
addGroupToFavorites(group: PlanexGroupType) {
this.setState((prevState: StateType): {
favoriteGroups: Array<PlanexGroupType>,
favoriteGroups: Array<PlanexGroupType>;
} => {
const {favoriteGroups} = prevState;
favoriteGroups.push(group);
@ -295,7 +300,7 @@ class GroupSelectionScreen extends React.Component<PropsType, StateType> {
});
}
render(): React.Node {
render() {
const {props, state} = this;
return (
<WebSectionList

View file

@ -22,11 +22,10 @@
import * as React from 'react';
import {Title, withTheme} from 'react-native-paper';
import i18n from 'i18n-js';
import {View} from 'react-native';
import {NativeScrollEvent, NativeSyntheticEvent, View} from 'react-native';
import {CommonActions} from '@react-navigation/native';
import {StackNavigationProp} from '@react-navigation/stack';
import Autolink from 'react-native-autolink';
import type {CustomThemeType} from '../../managers/ThemeManager';
import ThemeManager from '../../managers/ThemeManager';
import WebViewScreen from '../../components/Screens/WebViewScreen';
import AsyncStorageManager from '../../managers/AsyncStorageManager';
@ -40,16 +39,16 @@ import {MASCOT_STYLE} from '../../components/Mascot/Mascot';
import MascotPopup from '../../components/Mascot/MascotPopup';
type PropsType = {
navigation: StackNavigationProp,
route: {params: {group: PlanexGroupType}},
theme: CustomThemeType,
navigation: StackNavigationProp<any>;
route: {params: {group: PlanexGroupType}};
theme: ReactNativePaper.Theme;
};
type StateType = {
dialogVisible: boolean,
dialogTitle: string | React.Node,
dialogMessage: string,
currentGroup: PlanexGroupType,
dialogVisible: boolean;
dialogTitle: string | React.ReactNode;
dialogMessage: string;
currentGroup: PlanexGroupType;
};
const PLANEX_URL = 'http://planex.insa-toulouse.fr/';
@ -154,14 +153,15 @@ class PlanexScreen extends React.Component<PropsType, StateType> {
super(props);
this.webScreenRef = React.createRef();
this.barRef = React.createRef();
let currentGroup = AsyncStorageManager.getString(
this.customInjectedJS = '';
let currentGroupString = AsyncStorageManager.getString(
AsyncStorageManager.PREFERENCES.planexCurrentGroup.key,
);
if (currentGroup === '')
currentGroup = {name: 'SELECT GROUP', id: -1, isFav: false};
else {
currentGroup = JSON.parse(currentGroup);
let currentGroup: PlanexGroupType;
if (currentGroupString === '') {
currentGroup = {name: 'SELECT GROUP', id: -1};
} else {
currentGroup = JSON.parse(currentGroupString);
props.navigation.setOptions({title: currentGroup.name});
}
this.state = {
@ -189,8 +189,9 @@ class PlanexScreen extends React.Component<PropsType, StateType> {
*/
shouldComponentUpdate(nextProps: PropsType): boolean {
const {props, state} = this;
if (nextProps.theme.dark !== props.theme.dark)
if (nextProps.theme.dark !== props.theme.dark) {
this.generateInjectedJS(state.currentGroup.id);
}
return true;
}
@ -199,7 +200,7 @@ class PlanexScreen extends React.Component<PropsType, StateType> {
*
* @returns {*}
*/
getWebView(): React.Node {
getWebView() {
const {props, state} = this;
const showWebview = state.currentGroup.id !== -1;
@ -246,12 +247,16 @@ class PlanexScreen extends React.Component<PropsType, StateType> {
* Or "setGroup" with the group id as data to set the selected group
* @param data Data to pass to the action
*/
sendMessage = (action: string, data: string) => {
sendMessage = (action: string, data?: string) => {
let command;
if (action === 'setGroup') command = `displayAde(${data})`;
else command = `$('#calendar').fullCalendar('${action}', '${data}')`;
if (this.webScreenRef.current != null)
this.webScreenRef.current.injectJavaScript(`${command};true;`); // Injected javascript must end with true
if (action === 'setGroup') {
command = `displayAde(${data})`;
} else {
command = `$('#calendar').fullCalendar('${action}', '${data}')`;
}
if (this.webScreenRef.current != null) {
this.webScreenRef.current.injectJavaScript(`${command};true;`);
} // Injected javascript must end with true
};
/**
@ -261,10 +266,10 @@ class PlanexScreen extends React.Component<PropsType, StateType> {
*/
onMessage = (event: {nativeEvent: {data: string}}) => {
const data: {
start: string,
end: string,
title: string,
color: string,
start: string;
end: string;
title: string;
color: string;
} = JSON.parse(event.nativeEvent.data);
const startDate = dateToString(new Date(data.start), true);
const endDate = dateToString(new Date(data.end), true);
@ -272,8 +277,9 @@ class PlanexScreen extends React.Component<PropsType, StateType> {
const endString = getTimeOnlyString(endDate);
let msg = `${DateManager.getInstance().getTranslatedDate(startDate)}\n`;
if (startString != null && endString != null)
if (startString != null && endString != null) {
msg += `${startString} - ${endString}`;
}
this.showDialog(data.title, msg);
};
@ -286,7 +292,8 @@ class PlanexScreen extends React.Component<PropsType, StateType> {
showDialog = (title: string, message: string) => {
this.setState({
dialogVisible: true,
dialogTitle: <Autolink text={title} component={Title}/>,
// @ts-ignore
dialogTitle: <Autolink text={title} component={Title} />,
dialogMessage: message,
});
};
@ -305,8 +312,10 @@ class PlanexScreen extends React.Component<PropsType, StateType> {
*
* @param event
*/
onScroll = (event: SyntheticEvent<EventTarget>) => {
if (this.barRef.current != null) this.barRef.current.onScroll(event);
onScroll = (event: NativeSyntheticEvent<NativeScrollEvent>) => {
if (this.barRef.current != null) {
this.barRef.current.onScroll(event);
}
};
/**
@ -354,13 +363,14 @@ class PlanexScreen extends React.Component<PropsType, StateType> {
DateManager.isWeekend(new Date()) ? 'calendar.next()' : ''
}${INJECT_STYLE}`;
if (ThemeManager.getNightMode())
if (ThemeManager.getNightMode()) {
this.customInjectedJS += `$('head').append('<style>${CUSTOM_CSS_DARK}</style>');`;
}
this.customInjectedJS += 'removeAlpha();});true;'; // Prevents crash on ios
}
render(): React.Node {
render() {
const {props, state} = this;
return (
<View style={{flex: 1}}>

View file

@ -36,12 +36,12 @@ import type {PlanningEventType} from '../../utils/Planning';
import ImageGalleryButton from '../../components/Media/ImageGalleryButton';
type PropsType = {
navigation: StackNavigationProp,
route: {params: {data: PlanningEventType, id: number, eventId: number}},
navigation: StackNavigationProp<any>;
route: {params: {data: PlanningEventType; id: number; eventId: number}};
};
type StateType = {
loading: boolean,
loading: boolean;
};
const EVENT_INFO_URL = 'event/info';
@ -111,22 +111,23 @@ class PlanningDisplayScreen extends React.Component<PropsType, StateType> {
*
* @returns {*}
*/
getContent(): React.Node {
const {navigation} = this.props;
getContent() {
const {displayData} = this;
if (displayData == null) return null;
if (displayData == null) {
return null;
}
let subtitle = getTimeOnlyString(displayData.date_begin);
const dateString = getDateOnlyString(displayData.date_begin);
if (dateString !== null && subtitle != null)
if (dateString !== null && subtitle != null) {
subtitle += ` | ${DateManager.getInstance().getTranslatedDate(
dateString,
)}`;
}
return (
<CollapsibleScrollView style={{paddingLeft: 5, paddingRight: 5}} hasTab>
<Card.Title title={displayData.title} subtitle={subtitle} />
{displayData.logo !== null ? (
<ImageGalleryButton
navigation={navigation}
images={[{url: displayData.logo}]}
style={{
width: 300,
@ -154,9 +155,9 @@ class PlanningDisplayScreen extends React.Component<PropsType, StateType> {
*
* @returns {*}
*/
getErrorView(): React.Node {
getErrorView() {
const {navigation} = this.props;
if (this.errorCode === ERROR_TYPE.BAD_INPUT)
if (this.errorCode === ERROR_TYPE.BAD_INPUT) {
return (
<ErrorView
navigation={navigation}
@ -165,6 +166,7 @@ class PlanningDisplayScreen extends React.Component<PropsType, StateType> {
icon="calendar-remove"
/>
);
}
return (
<ErrorView
navigation={navigation}
@ -179,15 +181,19 @@ class PlanningDisplayScreen extends React.Component<PropsType, StateType> {
*/
fetchData = () => {
this.setState({loading: true});
apiRequest(EVENT_INFO_URL, 'POST', {id: this.eventId})
apiRequest<PlanningEventType>(EVENT_INFO_URL, 'POST', {id: this.eventId})
.then(this.onFetchSuccess)
.catch(this.onFetchError);
};
render(): React.Node {
render() {
const {loading} = this.state;
if (loading) return <BasicLoadingScreen />;
if (this.errorCode === 0) return this.getContent();
if (loading) {
return <BasicLoadingScreen />;
}
if (this.errorCode === 0) {
return this.getContent();
}
return this.getErrorView();
}
}

View file

@ -17,8 +17,6 @@
* along with Campus INSAT. If not, see <https://www.gnu.org/licenses/>.
*/
// @flow
import * as React from 'react';
import {BackHandler, View} from 'react-native';
import i18n from 'i18n-js';
@ -26,12 +24,12 @@ import {Agenda, LocaleConfig} from 'react-native-calendars';
import {Avatar, Divider, List} from 'react-native-paper';
import {StackNavigationProp} from '@react-navigation/stack';
import {readData} from '../../utils/WebData';
import type {PlanningEventType} from '../../utils/Planning';
import {
generateEventAgenda,
getCurrentDateString,
getDateOnlyString,
getTimeOnlyString,
PlanningEventType,
} from '../../utils/Planning';
import CustomAgenda from '../../components/Overrides/CustomAgenda';
import {MASCOT_STYLE} from '../../components/Mascot/Mascot';
@ -77,17 +75,16 @@ LocaleConfig.locales.fr = {
'Samedi',
],
dayNamesShort: ['Dim', 'Lun', 'Mar', 'Mer', 'Jeu', 'Ven', 'Sam'],
today: "Aujourd'hui",
};
type PropsType = {
navigation: StackNavigationProp,
navigation: StackNavigationProp<any>;
};
type StateType = {
refreshing: boolean,
agendaItems: {[key: string]: Array<PlanningEventType>},
calendarShowing: boolean,
refreshing: boolean;
agendaItems: {[key: string]: Array<PlanningEventType>};
calendarShowing: boolean;
};
const FETCH_URL = 'https://www.amicale-insat.fr/api/event/list';
@ -97,19 +94,22 @@ const AGENDA_MONTH_SPAN = 3;
* Class defining the app's planning screen
*/
class PlanningScreen extends React.Component<PropsType, StateType> {
agendaRef: null | Agenda;
agendaRef: null | Agenda<any>;
lastRefresh: Date;
lastRefresh: Date | null;
minTimeBetweenRefresh = 60;
currentDate = getDateOnlyString(getCurrentDateString());
currentDate: string | null;
constructor(props: PropsType) {
super(props);
if (i18n.currentLocale().startsWith('fr')) {
LocaleConfig.defaultLocale = 'fr';
}
this.agendaRef = null;
this.currentDate = getDateOnlyString(getCurrentDateString());
this.lastRefresh = null;
this.state = {
refreshing: false,
agendaItems: {},
@ -145,6 +145,7 @@ class PlanningScreen extends React.Component<PropsType, StateType> {
onBackButtonPressAndroid = (): boolean => {
const {calendarShowing} = this.state;
if (calendarShowing && this.agendaRef != null) {
// @ts-ignore
this.agendaRef.chooseDay(this.agendaRef.state.selectedDay);
return true;
}
@ -156,11 +157,13 @@ class PlanningScreen extends React.Component<PropsType, StateType> {
*/
onRefresh = () => {
let canRefresh;
if (this.lastRefresh !== undefined)
if (this.lastRefresh) {
canRefresh =
(new Date().getTime() - this.lastRefresh.getTime()) / 1000 >
this.minTimeBetweenRefresh;
else canRefresh = true;
} else {
canRefresh = true;
}
if (canRefresh) {
this.setState({refreshing: true});
@ -185,7 +188,7 @@ class PlanningScreen extends React.Component<PropsType, StateType> {
*
* @param ref
*/
onAgendaRef = (ref: Agenda) => {
onAgendaRef = (ref: Agenda<any>) => {
this.agendaRef = ref;
};
@ -204,23 +207,24 @@ class PlanningScreen extends React.Component<PropsType, StateType> {
* @param item The current event to render
* @return {*}
*/
getRenderItem = (item: PlanningEventType): React.Node => {
getRenderItem = (item: PlanningEventType) => {
const {navigation} = this.props;
const onPress = () => {
navigation.navigate('planning-information', {
data: item,
});
};
if (item.logo !== null) {
const logo = item.logo;
if (logo) {
return (
<View>
<Divider />
<List.Item
title={item.title}
description={getTimeOnlyString(item.date_begin)}
left={(): React.Node => (
left={() => (
<Avatar.Image
source={{uri: item.logo}}
source={{uri: logo}}
style={{backgroundColor: 'transparent'}}
/>
)}
@ -246,23 +250,22 @@ class PlanningScreen extends React.Component<PropsType, StateType> {
*
* @return {*}
*/
getRenderEmptyDate = (): React.Node => <Divider />;
getRenderEmptyDate = () => <Divider />;
render(): React.Node {
render() {
const {state, props} = this;
return (
<View style={{flex: 1}}>
<CustomAgenda
// eslint-disable-next-line react/jsx-props-no-spreading
{...props}
// the list of items that have to be displayed in agenda. If you want to render item as empty date
// the value of date key kas to be an empty array []. If there exists no value for date key it is
// considered that the date in question is not yet loaded
items={state.agendaItems}
// initially selected day
selected={this.currentDate}
selected={this.currentDate ? this.currentDate : undefined}
// Minimum date that can be selected, dates before minDate will be grayed out. Default = undefined
minDate={this.currentDate}
minDate={this.currentDate ? this.currentDate : undefined}
// Max amount of months allowed to scroll to the past. Default = 50
pastScrollRange={1}
// Max amount of months allowed to scroll to the future. Default = 50
@ -279,6 +282,9 @@ class PlanningScreen extends React.Component<PropsType, StateType> {
firstDay={1}
// ref to this agenda in order to handle back button event
onRef={this.onAgendaRef}
rowHasChanged={(r1: PlanningEventType, r2: PlanningEventType) =>
r1.id !== r2.id
}
/>
<MascotPopup
prefKey={AsyncStorageManager.PREFERENCES.eventsShowMascot.key}
@ -286,7 +292,6 @@ class PlanningScreen extends React.Component<PropsType, StateType> {
message={i18n.t('screens.planning.mascotDialog.message')}
icon="party-popper"
buttons={{
action: null,
cancel: {
message: i18n.t('screens.planning.mascotDialog.button'),
icon: 'check',