Improve planex components to match linter

This commit is contained in:
Arnaud Vergnet 2020-08-04 14:06:09 +02:00
parent 11b5f2ac71
commit ab86c1c85c
4 changed files with 753 additions and 679 deletions

View file

@ -2,96 +2,115 @@
import * as React from 'react'; import * as React from 'react';
import {List, withTheme} from 'react-native-paper'; import {List, withTheme} from 'react-native-paper';
import {FlatList, View} from "react-native"; import {FlatList, View} from 'react-native';
import {stringMatchQuery} from "../../../utils/Search"; import {stringMatchQuery} from '../../../utils/Search';
import GroupListItem from "./GroupListItem"; import GroupListItem from './GroupListItem';
import AnimatedAccordion from "../../Animations/AnimatedAccordion"; import AnimatedAccordion from '../../Animations/AnimatedAccordion';
import type {group, groupCategory} from "../../../screens/Planex/GroupSelectionScreen"; import type {
import type {CustomTheme} from "../../../managers/ThemeManager"; PlanexGroupType,
PlanexGroupCategoryType,
} from '../../../screens/Planex/GroupSelectionScreen';
import type {CustomTheme} from '../../../managers/ThemeManager';
type Props = { type PropsType = {
item: groupCategory, item: PlanexGroupCategoryType,
onGroupPress: (group) => void, onGroupPress: (PlanexGroupType) => void,
onFavoritePress: (group) => void, onFavoritePress: (PlanexGroupType) => void,
currentSearchString: string, currentSearchString: string,
favoriteNumber: number, favoriteNumber: number,
height: number, height: number,
theme: CustomTheme, theme: CustomTheme,
} };
const LIST_ITEM_HEIGHT = 64; const LIST_ITEM_HEIGHT = 64;
class GroupListAccordion extends React.Component<Props> { class GroupListAccordion extends React.Component<PropsType> {
shouldComponentUpdate(nextProps: PropsType): boolean {
const {props} = this;
return (
nextProps.currentSearchString !== props.currentSearchString ||
nextProps.favoriteNumber !== props.favoriteNumber ||
nextProps.item.content.length !== props.item.content.length
);
}
shouldComponentUpdate(nextProps: Props) { getRenderItem = ({item}: {item: PlanexGroupType}): React.Node => {
return (nextProps.currentSearchString !== this.props.currentSearchString) const {props} = this;
|| (nextProps.favoriteNumber !== this.props.favoriteNumber) const onPress = () => {
|| (nextProps.item.content.length !== this.props.item.content.length); props.onGroupPress(item);
} };
const onStarPress = () => {
props.onFavoritePress(item);
};
return (
<GroupListItem
height={LIST_ITEM_HEIGHT}
item={item}
onPress={onPress}
onStarPress={onStarPress}
/>
);
};
keyExtractor = (item: group) => item.id.toString(); getData(): Array<PlanexGroupType> {
const {props} = this;
const originalData = props.item.content;
const displayData = [];
originalData.forEach((data: PlanexGroupType) => {
if (stringMatchQuery(data.name, props.currentSearchString))
displayData.push(data);
});
return displayData;
}
renderItem = ({item}: { item: group }) => { itemLayout = (
const onPress = () => this.props.onGroupPress(item); data: ?Array<PlanexGroupType>,
const onStarPress = () => this.props.onFavoritePress(item); index: number,
return ( ): {length: number, offset: number, index: number} => ({
<GroupListItem length: LIST_ITEM_HEIGHT,
height={LIST_ITEM_HEIGHT} offset: LIST_ITEM_HEIGHT * index,
item={item} index,
onPress={onPress} });
onStarPress={onStarPress}/>
);
}
getData() { keyExtractor = (item: PlanexGroupType): string => item.id.toString();
const originalData = this.props.item.content;
let displayData = [];
for (let i = 0; i < originalData.length; i++) {
if (stringMatchQuery(originalData[i].name, this.props.currentSearchString))
displayData.push(originalData[i]);
}
return displayData;
}
itemLayout = (data, index) => ({length: LIST_ITEM_HEIGHT, offset: LIST_ITEM_HEIGHT * index, index}); render(): React.Node {
const {props} = this;
const {item} = this.props;
render() { return (
const item = this.props.item; <View>
return ( <AnimatedAccordion
<View> title={item.name}
<AnimatedAccordion style={{
title={item.name} height: props.height,
style={{ justifyContent: 'center',
height: this.props.height, }}
justifyContent: 'center', left={({size}: {size: number}): React.Node =>
}} item.id === 0 ? (
left={props => <List.Icon
item.id === 0 size={size}
? <List.Icon icon="star"
{...props} color={props.theme.colors.tetrisScore}
icon={"star"} />
color={this.props.theme.colors.tetrisScore} ) : null
/> }
: null} unmountWhenCollapsed // Only render list if expanded for increased performance
unmountWhenCollapsed={true}// Only render list if expanded for increased performance opened={props.item.id === 0 || props.currentSearchString.length > 0}>
opened={this.props.item.id === 0 || this.props.currentSearchString.length > 0} {/* $FlowFixMe */}
> <FlatList
{/*$FlowFixMe*/} data={this.getData()}
<FlatList extraData={props.currentSearchString}
data={this.getData()} renderItem={this.getRenderItem}
extraData={this.props.currentSearchString} keyExtractor={this.keyExtractor}
renderItem={this.renderItem} listKey={item.id.toString()}
keyExtractor={this.keyExtractor} // Performance props, see https://reactnative.dev/docs/optimizing-flatlist-configuration
listKey={item.id.toString()} getItemLayout={this.itemLayout}
// Performance props, see https://reactnative.dev/docs/optimizing-flatlist-configuration removeClippedSubviews
getItemLayout={this.itemLayout} />
removeClippedSubviews={true} </AnimatedAccordion>
/> </View>
</AnimatedAccordion> );
</View> }
);
}
} }
export default withTheme(GroupListAccordion) export default withTheme(GroupListAccordion);

View file

@ -2,65 +2,67 @@
import * as React from 'react'; import * as React from 'react';
import {IconButton, List, withTheme} from 'react-native-paper'; import {IconButton, List, withTheme} from 'react-native-paper';
import type {CustomTheme} from "../../../managers/ThemeManager"; import type {CustomTheme} from '../../../managers/ThemeManager';
import type {group} from "../../../screens/Planex/GroupSelectionScreen"; import type {PlanexGroupType} from '../../../screens/Planex/GroupSelectionScreen';
type Props = { type PropsType = {
theme: CustomTheme, theme: CustomTheme,
onPress: () => void, onPress: () => void,
onStarPress: () => void, onStarPress: () => void,
item: group, item: PlanexGroupType,
height: number, height: number,
} };
type State = { type StateType = {
isFav: boolean, isFav: boolean,
} };
class GroupListItem extends React.Component<Props, State> { class GroupListItem extends React.Component<PropsType, StateType> {
constructor(props: PropsType) {
super(props);
this.state = {
isFav: props.item.isFav !== undefined && props.item.isFav,
};
}
constructor(props) { shouldComponentUpdate(prevProps: PropsType, prevState: StateType): boolean {
super(props); const {isFav} = this.state;
this.state = { return prevState.isFav !== isFav;
isFav: (props.item.isFav !== undefined && props.item.isFav), }
}
}
shouldComponentUpdate(prevProps: Props, prevState: State) { onStarPress = () => {
return (prevState.isFav !== this.state.isFav); const {props} = this;
} this.setState((prevState: StateType): StateType => ({
isFav: !prevState.isFav,
}));
props.onStarPress();
};
onStarPress = () => { render(): React.Node {
this.setState({isFav: !this.state.isFav}); const {props, state} = this;
this.props.onStarPress(); const {colors} = props.theme;
} return (
<List.Item
render() { title={props.item.name}
const colors = this.props.theme.colors; onPress={props.onPress}
return ( left={({size}: {size: number}): React.Node => (
<List.Item <List.Icon size={size} icon="chevron-right" />
title={this.props.item.name} )}
onPress={this.props.onPress} right={({size, color}: {size: number, color: string}): React.Node => (
left={props => <IconButton
<List.Icon size={size}
{...props} icon="star"
icon={"chevron-right"}/>} onPress={this.onStarPress}
right={props => color={state.isFav ? colors.tetrisScore : color}
<IconButton />
{...props} )}
icon={"star"} style={{
onPress={this.onStarPress} height: props.height,
color={this.state.isFav justifyContent: 'center',
? colors.tetrisScore }}
: props.color} />
/>} );
style={{ }
height: this.props.height,
justifyContent: 'center',
}}
/>
);
}
} }
export default withTheme(GroupListItem); export default withTheme(GroupListItem);

View file

@ -1,44 +1,45 @@
// @flow // @flow
import * as React from 'react'; import * as React from 'react';
import {Platform} from "react-native"; import {Platform} from 'react-native';
import i18n from "i18n-js"; import i18n from 'i18n-js';
import {Searchbar} from "react-native-paper"; import {Searchbar} from 'react-native-paper';
import {stringMatchQuery} from "../../utils/Search"; import {StackNavigationProp} from '@react-navigation/stack';
import WebSectionList from "../../components/Screens/WebSectionList"; import {stringMatchQuery} from '../../utils/Search';
import GroupListAccordion from "../../components/Lists/PlanexGroups/GroupListAccordion"; import WebSectionList from '../../components/Screens/WebSectionList';
import AsyncStorageManager from "../../managers/AsyncStorageManager"; import GroupListAccordion from '../../components/Lists/PlanexGroups/GroupListAccordion';
import {StackNavigationProp} from "@react-navigation/stack"; import AsyncStorageManager from '../../managers/AsyncStorageManager';
const LIST_ITEM_HEIGHT = 70; const LIST_ITEM_HEIGHT = 70;
export type group = { export type PlanexGroupType = {
name: string, name: string,
id: number, id: number,
isFav: boolean, isFav: boolean,
}; };
export type groupCategory = { export type PlanexGroupCategoryType = {
name: string, name: string,
id: number, id: number,
content: Array<group>, content: Array<PlanexGroupType>,
}; };
type Props = { type PropsType = {
navigation: StackNavigationProp, navigation: StackNavigationProp,
}
type State = {
currentSearchString: string,
favoriteGroups: Array<group>,
}; };
function sortName(a: group | groupCategory, b: group | groupCategory) { type StateType = {
if (a.name.toLowerCase() < b.name.toLowerCase()) currentSearchString: string,
return -1; favoriteGroups: Array<PlanexGroupType>,
if (a.name.toLowerCase() > b.name.toLowerCase()) };
return 1;
return 0; 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;
return 0;
} }
const GROUPS_URL = 'http://planex.insa-toulouse.fr/wsAdeGrp.php?projectId=1'; const GROUPS_URL = 'http://planex.insa-toulouse.fr/wsAdeGrp.php?projectId=1';
@ -47,232 +48,263 @@ const REPLACE_REGEX = /_/g;
/** /**
* Class defining planex group selection screen. * Class defining planex group selection screen.
*/ */
class GroupSelectionScreen extends React.Component<Props, State> { class GroupSelectionScreen extends React.Component<PropsType, StateType> {
/**
constructor(props: Props) { * Removes the given group from the given array
super(props); *
this.state = { * @param favorites The array containing favorites groups
currentSearchString: '', * @param group The group to remove from the array
favoriteGroups: AsyncStorageManager.getObject(AsyncStorageManager.PREFERENCES.planexFavoriteGroups.key), */
}; static removeGroupFromFavorites(
favorites: Array<PlanexGroupType>,
group: PlanexGroupType,
) {
for (let i = 0; i < favorites.length; i += 1) {
if (group.id === favorites[i].id) {
favorites.splice(i, 1);
break;
}
} }
}
/** /**
* Creates the header content * Adds the given group to the given array
*/ *
componentDidMount() { * @param favorites The array containing favorites groups
this.props.navigation.setOptions({ * @param group The group to add to the array
headerTitle: this.getSearchBar, */
headerBackTitleVisible: false, static addGroupToFavorites(
headerTitleContainerStyle: Platform.OS === 'ios' ? favorites: Array<PlanexGroupType>,
{marginHorizontal: 0, width: '70%'} : group: PlanexGroupType,
{marginHorizontal: 0, right: 50, left: 50}, ) {
}); const favGroup = {...group};
} favGroup.isFav = true;
favorites.push(favGroup);
favorites.sort(sortName);
}
/** constructor(props: PropsType) {
* Gets the header search bar super(props);
* this.state = {
* @return {*} currentSearchString: '',
*/ favoriteGroups: AsyncStorageManager.getObject(
getSearchBar = () => { AsyncStorageManager.PREFERENCES.planexFavoriteGroups.key,
return ( ),
<Searchbar
placeholder={i18n.t('screens.proximo.search')}
onChangeText={this.onSearchStringChange}
/>
);
}; };
}
/** /**
* Callback used when the search changes * Creates the header content
* */
* @param str The new search string componentDidMount() {
*/ const [navigation] = this.props;
onSearchStringChange = (str: string) => { navigation.setOptions({
this.setState({currentSearchString: str}) headerTitle: this.getSearchBar,
}; headerBackTitleVisible: false,
headerTitleContainerStyle:
Platform.OS === 'ios'
? {marginHorizontal: 0, width: '70%'}
: {marginHorizontal: 0, right: 50, left: 50},
});
}
/** /**
* Callback used when clicking an article in the list. * Gets the header search bar
* It opens the modal to show detailed information about the article *
* * @return {*}
* @param item The article pressed */
*/ getSearchBar = (): React.Node => {
onListItemPress = (item: group) => { return (
this.props.navigation.navigate("planex", { <Searchbar
screen: "index", placeholder={i18n.t('screens.proximo.search')}
params: {group: item} onChangeText={this.onSearchStringChange}
}); />
}; );
};
/** /**
* Callback used when the user clicks on the favorite button * Gets a render item for the given article
* *
* @param item The item to add/remove from favorites * @param item The article to render
*/ * @return {*}
onListFavoritePress = (item: group) => { */
this.updateGroupFavorites(item); getRenderItem = ({item}: {item: PlanexGroupCategoryType}): React.Node => {
}; const {currentSearchString, favoriteGroups} = this.state;
if (this.shouldDisplayAccordion(item)) {
/** return (
* Checks if the given group is in the favorites list <GroupListAccordion
* item={item}
* @param group The group to check onGroupPress={this.onListItemPress}
* @returns {boolean} onFavoritePress={this.onListFavoritePress}
*/ currentSearchString={currentSearchString}
isGroupInFavorites(group: group) { favoriteNumber={favoriteGroups.length}
let isFav = false; height={LIST_ITEM_HEIGHT}
for (let i = 0; i < this.state.favoriteGroups.length; i++) { />
if (group.id === this.state.favoriteGroups[i].id) { );
isFav = true;
break;
}
}
return isFav;
} }
return null;
};
/** /**
* Removes the given group from the given array * Replaces underscore by spaces and sets the favorite state of every group in the given category
* *
* @param favorites The array containing favorites groups * @param groups The groups to format
* @param group The group to remove from the array * @return {Array<PlanexGroupType>}
*/ */
removeGroupFromFavorites(favorites: Array<group>, group: group) { getFormattedGroups(groups: Array<PlanexGroupType>): Array<PlanexGroupType> {
for (let i = 0; i < favorites.length; i++) { return groups.map((group: PlanexGroupType): PlanexGroupType => {
if (group.id === favorites[i].id) { const newGroup = {...group};
favorites.splice(i, 1); newGroup.name = group.name.replace(REPLACE_REGEX, ' ');
break; newGroup.isFav = this.isGroupInFavorites(group);
} return newGroup;
} });
}
/**
* Creates the dataset to be used in the FlatList
*
* @param fetchedData
* @return {*}
* */
createDataset = (fetchedData: {
[key: string]: PlanexGroupCategoryType,
}): Array<{title: string, data: Array<PlanexGroupCategoryType>}> => {
return [
{
title: '',
data: this.generateData(fetchedData),
},
];
};
/**
* Callback used when the search changes
*
* @param str The new search string
*/
onSearchStringChange = (str: string) => {
this.setState({currentSearchString: str});
};
/**
* Callback used when clicking an article in the list.
* It opens the modal to show detailed information about the article
*
* @param item The article pressed
*/
onListItemPress = (item: PlanexGroupType) => {
const {navigation} = this.props;
navigation.navigate('planex', {
screen: 'index',
params: {group: item},
});
};
/**
* Callback used when the user clicks on the favorite button
*
* @param item The item to add/remove from favorites
*/
onListFavoritePress = (item: PlanexGroupType) => {
this.updateGroupFavorites(item);
};
/**
* Checks if the given group is in the favorites list
*
* @param group The group to check
* @returns {boolean}
*/
isGroupInFavorites(group: PlanexGroupType): boolean {
let isFav = false;
const {favoriteGroups} = this.state;
favoriteGroups.forEach((favGroup: PlanexGroupType) => {
if (group.id === favGroup.id) isFav = true;
});
return isFav;
}
/**
* Adds or removes the given group to the favorites list, depending on whether it is already in it or not.
* Favorites are then saved in user preferences
*
* @param group The group to add/remove to favorites
*/
updateGroupFavorites(group: PlanexGroupType) {
const {favoriteGroups} = this.state;
const newFavorites = [...favoriteGroups];
if (this.isGroupInFavorites(group))
GroupSelectionScreen.removeGroupFromFavorites(newFavorites, group);
else GroupSelectionScreen.addGroupToFavorites(newFavorites, group);
this.setState({favoriteGroups: newFavorites});
AsyncStorageManager.set(
AsyncStorageManager.PREFERENCES.planexFavoriteGroups.key,
newFavorites,
);
}
/**
* Checks whether to display the given group category, depending on user search query
*
* @param item The group category
* @returns {boolean}
*/
shouldDisplayAccordion(item: PlanexGroupCategoryType): boolean {
const {currentSearchString} = this.state;
let shouldDisplay = false;
for (let i = 0; i < item.content.length; i += 1) {
if (stringMatchQuery(item.content[i].name, currentSearchString)) {
shouldDisplay = true;
break;
}
} }
return shouldDisplay;
}
/** /**
* Adds the given group to the given array * Generates the dataset to be used in the FlatList.
* * This improves formatting of group names, sorts alphabetically the categories, and adds favorites at the top.
* @param favorites The array containing favorites groups *
* @param group The group to add to the array * @param fetchedData The raw data fetched from the server
*/ * @returns {[]}
addGroupToFavorites(favorites: Array<group>, group: group) { */
group.isFav = true; generateData(fetchedData: {
favorites.push(group); [key: string]: PlanexGroupCategoryType,
favorites.sort(sortName); }): Array<PlanexGroupCategoryType> {
} const {favoriteGroups} = this.state;
const data = [];
// eslint-disable-next-line flowtype/no-weak-types
(Object.values(fetchedData): Array<any>).forEach(
(category: PlanexGroupCategoryType) => {
const newCat = {...category};
newCat.content = this.getFormattedGroups(category.content);
data.push(newCat);
},
);
data.sort(sortName);
data.unshift({
name: i18n.t('screens.planex.favorites'),
id: 0,
content: favoriteGroups,
});
return data;
}
/** render(): React.Node {
* Adds or removes the given group to the favorites list, depending on whether it is already in it or not. const {props, state} = this;
* Favorites are then saved in user preferences return (
* <WebSectionList
* @param group The group to add/remove to favorites navigation={props.navigation}
*/ createDataset={this.createDataset}
updateGroupFavorites(group: group) { autoRefreshTime={0}
let newFavorites = [...this.state.favoriteGroups] refreshOnFocus={false}
if (this.isGroupInFavorites(group)) fetchUrl={GROUPS_URL}
this.removeGroupFromFavorites(newFavorites, group); renderItem={this.getRenderItem}
else updateData={state.currentSearchString + state.favoriteGroups.length}
this.addGroupToFavorites(newFavorites, group); itemHeight={LIST_ITEM_HEIGHT}
this.setState({favoriteGroups: newFavorites}) />
AsyncStorageManager.set(AsyncStorageManager.PREFERENCES.planexFavoriteGroups.key, newFavorites); );
} }
/**
* Checks whether to display the given group category, depending on user search query
*
* @param item The group category
* @returns {boolean}
*/
shouldDisplayAccordion(item: groupCategory) {
let shouldDisplay = false;
for (let i = 0; i < item.content.length; i++) {
if (stringMatchQuery(item.content[i].name, this.state.currentSearchString)) {
shouldDisplay = true;
break;
}
}
return shouldDisplay;
}
/**
* Gets a render item for the given article
*
* @param item The article to render
* @return {*}
*/
renderItem = ({item}: { item: groupCategory }) => {
if (this.shouldDisplayAccordion(item)) {
return (
<GroupListAccordion
item={item}
onGroupPress={this.onListItemPress}
onFavoritePress={this.onListFavoritePress}
currentSearchString={this.state.currentSearchString}
favoriteNumber={this.state.favoriteGroups.length}
height={LIST_ITEM_HEIGHT}
/>
);
} else
return null;
};
/**
* Generates the dataset to be used in the FlatList.
* This improves formatting of group names, sorts alphabetically the categories, and adds favorites at the top.
*
* @param fetchedData The raw data fetched from the server
* @returns {[]}
*/
generateData(fetchedData: { [key: string]: groupCategory }) {
let data = [];
for (let key in fetchedData) {
this.formatGroups(fetchedData[key]);
data.push(fetchedData[key]);
}
data.sort(sortName);
data.unshift({name: i18n.t("screens.planex.favorites"), id: 0, content: this.state.favoriteGroups});
return data;
}
/**
* Replaces underscore by spaces and sets the favorite state of every group in the given category
*
* @param item The category containing groups to format
*/
formatGroups(item: groupCategory) {
for (let i = 0; i < item.content.length; i++) {
item.content[i].name = item.content[i].name.replace(REPLACE_REGEX, " ")
item.content[i].isFav = this.isGroupInFavorites(item.content[i]);
}
}
/**
* Creates the dataset to be used in the FlatList
*
* @param fetchedData
* @return {*}
* */
createDataset = (fetchedData: { [key: string]: groupCategory }) => {
return [
{
title: '',
data: this.generateData(fetchedData)
}
];
}
render() {
return (
<WebSectionList
{...this.props}
createDataset={this.createDataset}
autoRefreshTime={0}
refreshOnFocus={false}
fetchUrl={GROUPS_URL}
renderItem={this.renderItem}
updateData={this.state.currentSearchString + this.state.favoriteGroups.length}
itemHeight={LIST_ITEM_HEIGHT}
/>
);
}
} }
export default GroupSelectionScreen; export default GroupSelectionScreen;

View file

@ -1,37 +1,36 @@
// @flow // @flow
import * as React from 'react'; import * as React from 'react';
import type {CustomTheme} from "../../managers/ThemeManager"; import {withTheme} from 'react-native-paper';
import ThemeManager from "../../managers/ThemeManager"; import i18n from 'i18n-js';
import WebViewScreen from "../../components/Screens/WebViewScreen"; import {View} from 'react-native';
import {withTheme} from "react-native-paper"; import {CommonActions} from '@react-navigation/native';
import i18n from "i18n-js"; import {StackNavigationProp} from '@react-navigation/stack';
import {View} from "react-native"; import type {CustomTheme} from '../../managers/ThemeManager';
import AsyncStorageManager from "../../managers/AsyncStorageManager"; import ThemeManager from '../../managers/ThemeManager';
import AlertDialog from "../../components/Dialogs/AlertDialog"; import WebViewScreen from '../../components/Screens/WebViewScreen';
import {dateToString, getTimeOnlyString} from "../../utils/Planning"; import AsyncStorageManager from '../../managers/AsyncStorageManager';
import DateManager from "../../managers/DateManager"; import AlertDialog from '../../components/Dialogs/AlertDialog';
import AnimatedBottomBar from "../../components/Animations/AnimatedBottomBar"; import {dateToString, getTimeOnlyString} from '../../utils/Planning';
import {CommonActions} from "@react-navigation/native"; import DateManager from '../../managers/DateManager';
import ErrorView from "../../components/Screens/ErrorView"; import AnimatedBottomBar from '../../components/Animations/AnimatedBottomBar';
import {StackNavigationProp} from "@react-navigation/stack"; import ErrorView from '../../components/Screens/ErrorView';
import type {group} from "./GroupSelectionScreen"; import type {PlanexGroupType} from './GroupSelectionScreen';
import {MASCOT_STYLE} from "../../components/Mascot/Mascot"; import {MASCOT_STYLE} from '../../components/Mascot/Mascot';
import MascotPopup from "../../components/Mascot/MascotPopup"; import MascotPopup from '../../components/Mascot/MascotPopup';
type Props = { type PropsType = {
navigation: StackNavigationProp, navigation: StackNavigationProp,
route: { params: { group: group } }, route: {params: {group: PlanexGroupType}},
theme: CustomTheme, theme: CustomTheme,
} };
type State = {
dialogVisible: boolean,
dialogTitle: string,
dialogMessage: string,
currentGroup: group,
}
type StateType = {
dialogVisible: boolean,
dialogTitle: string,
dialogMessage: string,
currentGroup: PlanexGroupType,
};
const PLANEX_URL = 'http://planex.insa-toulouse.fr/'; const PLANEX_URL = 'http://planex.insa-toulouse.fr/';
@ -66,32 +65,32 @@ const PLANEX_URL = 'http://planex.insa-toulouse.fr/';
// Watch for changes in the calendar and call the remove alpha function to prevent invisible events // Watch for changes in the calendar and call the remove alpha function to prevent invisible events
const OBSERVE_MUTATIONS_INJECTED = const OBSERVE_MUTATIONS_INJECTED =
'function removeAlpha(node) {\n' + 'function removeAlpha(node) {\n' +
' let bg = node.css("background-color");\n' + ' let bg = node.css("background-color");\n' +
' if (bg.match("^rgba")) {\n' + ' if (bg.match("^rgba")) {\n' +
' let a = bg.slice(5).split(\',\');\n' + " let a = bg.slice(5).split(',');\n" +
' // Fix for tooltips with broken background\n' + ' // Fix for tooltips with broken background\n' +
' if (parseInt(a[0]) === parseInt(a[1]) && parseInt(a[1]) === parseInt(a[2]) && parseInt(a[2]) === 0) {\n' + ' if (parseInt(a[0]) === parseInt(a[1]) && parseInt(a[1]) === parseInt(a[2]) && parseInt(a[2]) === 0) {\n' +
' a[0] = a[1] = a[2] = \'255\';\n' + " a[0] = a[1] = a[2] = '255';\n" +
' }\n' + ' }\n' +
' let newBg =\'rgb(\' + a[0] + \',\' + a[1] + \',\' + a[2] + \')\';\n' + " let newBg ='rgb(' + a[0] + ',' + a[1] + ',' + a[2] + ')';\n" +
' node.css("background-color", newBg);\n' + ' node.css("background-color", newBg);\n' +
' }\n' + ' }\n' +
'}\n' + '}\n' +
'// Observe for planning DOM changes\n' + '// Observe for planning DOM changes\n' +
'let observer = new MutationObserver(function(mutations) {\n' + 'let observer = new MutationObserver(function(mutations) {\n' +
' for (let i = 0; i < mutations.length; i++) {\n' + ' for (let i = 0; i < mutations.length; i++) {\n' +
' if (mutations[i][\'addedNodes\'].length > 0 &&\n' + " if (mutations[i]['addedNodes'].length > 0 &&\n" +
' ($(mutations[i][\'addedNodes\'][0]).hasClass("fc-event") || $(mutations[i][\'addedNodes\'][0]).hasClass("tooltiptopicevent")))\n' + ' ($(mutations[i][\'addedNodes\'][0]).hasClass("fc-event") || $(mutations[i][\'addedNodes\'][0]).hasClass("tooltiptopicevent")))\n' +
' removeAlpha($(mutations[i][\'addedNodes\'][0]))\n' + " removeAlpha($(mutations[i]['addedNodes'][0]))\n" +
' }\n' + ' }\n' +
'});\n' + '});\n' +
'// observer.observe(document.querySelector(".fc-body"), {attributes: false, childList: true, characterData: false, subtree:true});\n' + '// observer.observe(document.querySelector(".fc-body"), {attributes: false, childList: true, characterData: false, subtree:true});\n' +
'observer.observe(document.querySelector("body"), {attributes: false, childList: true, characterData: false, subtree:true});\n' + 'observer.observe(document.querySelector("body"), {attributes: false, childList: true, characterData: false, subtree:true});\n' +
'// Run remove alpha a first time on whole planning. Useful when code injected after planning fully loaded.\n' + '// Run remove alpha a first time on whole planning. Useful when code injected after planning fully loaded.\n' +
'$(".fc-event-container .fc-event").each(function(index) {\n' + '$(".fc-event-container .fc-event").each(function(index) {\n' +
' removeAlpha($(this));\n' + ' removeAlpha($(this));\n' +
'});'; '});';
// Overrides default settings to send a message to the webview when clicking on an event // Overrides default settings to send a message to the webview when clicking on an event
const FULL_CALENDAR_SETTINGS = ` const FULL_CALENDAR_SETTINGS = `
@ -108,272 +107,294 @@ calendar.option({
} }
});`; });`;
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}"; const CUSTOM_CSS =
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}"; '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}';
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}';
const INJECT_STYLE = ` const INJECT_STYLE = `
$('head').append('<style>` + CUSTOM_CSS + `</style>'); $('head').append('<style>${CUSTOM_CSS}</style>');
`; `;
/** /**
* Class defining the app's Planex screen. * Class defining the app's Planex screen.
* This screen uses a webview to render the page * This screen uses a webview to render the page
*/ */
class PlanexScreen extends React.Component<Props, State> { class PlanexScreen extends React.Component<PropsType, StateType> {
webScreenRef: {current: null | WebViewScreen};
webScreenRef: { current: null | WebViewScreen }; barRef: {current: null | AnimatedBottomBar};
barRef: { current: null | AnimatedBottomBar };
customInjectedJS: string; customInjectedJS: string;
/** /**
* Defines custom injected JavaScript to improve the page display on mobile * Defines custom injected JavaScript to improve the page display on mobile
*/ */
constructor(props) { constructor(props: PropsType) {
super(props); super(props);
this.webScreenRef = React.createRef(); this.webScreenRef = React.createRef();
this.barRef = React.createRef(); this.barRef = React.createRef();
let currentGroup = AsyncStorageManager.getString(AsyncStorageManager.PREFERENCES.planexCurrentGroup.key); let currentGroup = AsyncStorageManager.getString(
if (currentGroup === '') AsyncStorageManager.PREFERENCES.planexCurrentGroup.key,
currentGroup = {name: "SELECT GROUP", id: -1, isFav: false}; );
else { if (currentGroup === '')
currentGroup = JSON.parse(currentGroup); currentGroup = {name: 'SELECT GROUP', id: -1, isFav: false};
props.navigation.setOptions({title: currentGroup.name}) else {
} currentGroup = JSON.parse(currentGroup);
this.state = { props.navigation.setOptions({title: currentGroup.name});
dialogVisible: false,
dialogTitle: "",
dialogMessage: "",
currentGroup: currentGroup,
};
this.generateInjectedJS(currentGroup.id);
} }
this.state = {
dialogVisible: false,
dialogTitle: '',
dialogMessage: '',
currentGroup,
};
this.generateInjectedJS(currentGroup.id);
}
/** /**
* Register for events and show the banner after 2 seconds * Register for events and show the banner after 2 seconds
*/ */
componentDidMount() { componentDidMount() {
this.props.navigation.addListener('focus', this.onScreenFocus); const {navigation} = this.props;
navigation.addListener('focus', this.onScreenFocus);
}
/**
* Only update the screen if the dark theme changed
*
* @param nextProps
* @returns {boolean}
*/
shouldComponentUpdate(nextProps: PropsType): boolean {
const {props, state} = this;
if (nextProps.theme.dark !== props.theme.dark)
this.generateInjectedJS(state.currentGroup.id);
return true;
}
/**
* Gets the Webview, with an error view on top if no group is selected.
*
* @returns {*}
*/
getWebView(): React.Node {
const {props, state} = this;
const showWebview = state.currentGroup.id !== -1;
return (
<View style={{height: '100%'}}>
{!showWebview ? (
<ErrorView
navigation={props.navigation}
icon="account-clock"
message={i18n.t('screens.planex.noGroupSelected')}
showRetryButton={false}
/>
) : null}
<WebViewScreen
ref={this.webScreenRef}
navigation={props.navigation}
url={PLANEX_URL}
customJS={this.customInjectedJS}
onMessage={this.onMessage}
onScroll={this.onScroll}
showAdvancedControls={false}
/>
</View>
);
}
/**
* Callback used when the user clicks on the navigate to settings button.
* This will hide the banner and open the SettingsScreen
*/
onGoToSettings = () => {
const {navigation} = this.props;
navigation.navigate('settings');
};
onScreenFocus = () => {
this.handleNavigationParams();
};
/**
* Sends a FullCalendar action to the web page inside the webview.
*
* @param action The action to perform, as described in the FullCalendar doc https://fullcalendar.io/docs/v3.
* 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) => {
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
};
/**
* Shows a dialog when the user clicks on an event.
*
* @param event
*/
onMessage = (event: {nativeEvent: {data: string}}) => {
const data: {
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);
const startString = getTimeOnlyString(startDate);
const endString = getTimeOnlyString(endDate);
let msg = `${DateManager.getInstance().getTranslatedDate(startDate)}\n`;
if (startString != null && endString != null)
msg += `${startString} - ${endString}`;
this.showDialog(data.title, msg);
};
/**
* Shows a simple dialog to the user.
*
* @param title The dialog's title
* @param message The message to show
*/
showDialog = (title: string, message: string) => {
this.setState({
dialogVisible: true,
dialogTitle: title,
dialogMessage: message,
});
};
/**
* Hides the dialog
*/
hideDialog = () => {
this.setState({
dialogVisible: false,
});
};
/**
* Binds the onScroll event to the control bar for automatic hiding based on scroll direction and speed
*
* @param event
*/
onScroll = (event: SyntheticEvent<EventTarget>) => {
if (this.barRef.current != null) this.barRef.current.onScroll(event);
};
/**
* If navigations parameters contain a group, set it as selected
*/
handleNavigationParams = () => {
const {props} = this;
if (props.route.params != null) {
if (
props.route.params.group !== undefined &&
props.route.params.group !== null
) {
// reset params to prevent infinite loop
this.selectNewGroup(props.route.params.group);
props.navigation.dispatch(CommonActions.setParams({group: null}));
}
} }
};
/** /**
* Callback used when the user clicks on the navigate to settings button. * Sends the webpage a message with the new group to select and save it to preferences
* This will hide the banner and open the SettingsScreen *
*/ * @param group The group object selected
onGoToSettings = () => this.props.navigation.navigate('settings'); */
selectNewGroup(group: PlanexGroupType) {
const {navigation} = this.props;
this.sendMessage('setGroup', group.id.toString());
this.setState({currentGroup: group});
AsyncStorageManager.set(
AsyncStorageManager.PREFERENCES.planexCurrentGroup.key,
group,
);
navigation.setOptions({title: group.name});
this.generateInjectedJS(group.id);
}
onScreenFocus = () => { /**
this.handleNavigationParams(); * Generates custom JavaScript to be injected into the webpage
}; *
* @param groupID The current group selected
*/
generateInjectedJS(groupID: number) {
this.customInjectedJS = `$(document).ready(function() {${OBSERVE_MUTATIONS_INJECTED}${FULL_CALENDAR_SETTINGS}displayAde(${groupID});${
// Reset Ade
DateManager.isWeekend(new Date()) ? 'calendar.next()' : ''
}${INJECT_STYLE}`;
/** if (ThemeManager.getNightMode())
* If navigations parameters contain a group, set it as selected this.customInjectedJS += `$('head').append('<style>${CUSTOM_CSS_DARK}</style>');`;
*/
handleNavigationParams = () => {
if (this.props.route.params != null) {
if (this.props.route.params.group !== undefined && this.props.route.params.group !== null) {
// reset params to prevent infinite loop
this.selectNewGroup(this.props.route.params.group);
this.props.navigation.dispatch(CommonActions.setParams({group: null}));
}
}
};
/** this.customInjectedJS += 'removeAlpha();});true;'; // Prevents crash on ios
* Sends the webpage a message with the new group to select and save it to preferences }
*
* @param group The group object selected
*/
selectNewGroup(group: group) {
this.sendMessage('setGroup', group.id);
this.setState({currentGroup: group});
AsyncStorageManager.set(AsyncStorageManager.PREFERENCES.planexCurrentGroup.key, group);
this.props.navigation.setOptions({title: group.name});
this.generateInjectedJS(group.id);
}
/** render(): React.Node {
* Generates custom JavaScript to be injected into the webpage const {props, state} = this;
* return (
* @param groupID The current group selected <View style={{flex: 1}}>
*/ {/* Allow to draw webview bellow banner */}
generateInjectedJS(groupID: number) { <View
this.customInjectedJS = "$(document).ready(function() {" style={{
+ OBSERVE_MUTATIONS_INJECTED position: 'absolute',
+ FULL_CALENDAR_SETTINGS height: '100%',
+ "displayAde(" + groupID + ");" // Reset Ade width: '100%',
+ (DateManager.isWeekend(new Date()) ? "calendar.next()" : "") }}>
+ INJECT_STYLE; {props.theme.dark ? ( // Force component theme update by recreating it on theme change
this.getWebView()
if (ThemeManager.getNightMode()) ) : (
this.customInjectedJS += "$('head').append('<style>" + CUSTOM_CSS_DARK + "</style>');"; <View style={{height: '100%'}}>{this.getWebView()}</View>
)}
this.customInjectedJS += 'removeAlpha();});true;'; // Prevents crash on ios </View>
} {AsyncStorageManager.getString(
AsyncStorageManager.PREFERENCES.defaultStartScreen.key,
/** ).toLowerCase() !== 'planex' ? (
* Only update the screen if the dark theme changed <MascotPopup
* prefKey={AsyncStorageManager.PREFERENCES.planexShowBanner.key}
* @param nextProps title={i18n.t('screens.planex.mascotDialog.title')}
* @returns {boolean} message={i18n.t('screens.planex.mascotDialog.message')}
*/ icon="emoticon-kiss"
shouldComponentUpdate(nextProps: Props): boolean { buttons={{
if (nextProps.theme.dark !== this.props.theme.dark) action: {
this.generateInjectedJS(this.state.currentGroup.id); message: i18n.t('screens.planex.mascotDialog.ok'),
return true; icon: 'cog',
} onPress: this.onGoToSettings,
},
cancel: {
/** message: i18n.t('screens.planex.mascotDialog.cancel'),
* Sends a FullCalendar action to the web page inside the webview. icon: 'close',
* color: props.theme.colors.warning,
* @param action The action to perform, as described in the FullCalendar doc https://fullcalendar.io/docs/v3. },
* Or "setGroup" with the group id as data to set the selected group }}
* @param data Data to pass to the action emotion={MASCOT_STYLE.INTELLO}
*/ />
sendMessage = (action: string, data: any) => { ) : null}
let command; <AlertDialog
if (action === "setGroup") visible={state.dialogVisible}
command = "displayAde(" + data + ")"; onDismiss={this.hideDialog}
else title={state.dialogTitle}
command = "$('#calendar').fullCalendar('" + action + "', '" + data + "')"; message={state.dialogMessage}
if (this.webScreenRef.current != null) />
this.webScreenRef.current.injectJavaScript(command + ';true;'); // Injected javascript must end with true <AnimatedBottomBar
}; navigation={props.navigation}
ref={this.barRef}
/** onPress={this.sendMessage}
* Shows a dialog when the user clicks on an event. seekAttention={state.currentGroup.id === -1}
* />
* @param event </View>
*/ );
onMessage = (event: { nativeEvent: { data: string } }) => { }
const data: { 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);
const startString = getTimeOnlyString(startDate);
const endString = getTimeOnlyString(endDate);
let msg = DateManager.getInstance().getTranslatedDate(startDate) + "\n";
if (startString != null && endString != null)
msg += startString + ' - ' + endString;
this.showDialog(data.title, msg)
};
/**
* Shows a simple dialog to the user.
*
* @param title The dialog's title
* @param message The message to show
*/
showDialog = (title: string, message: string) => {
this.setState({
dialogVisible: true,
dialogTitle: title,
dialogMessage: message,
});
};
/**
* Hides the dialog
*/
hideDialog = () => {
this.setState({
dialogVisible: false,
});
};
/**
* Binds the onScroll event to the control bar for automatic hiding based on scroll direction and speed
*
* @param event
*/
onScroll = (event: SyntheticEvent<EventTarget>) => {
if (this.barRef.current != null)
this.barRef.current.onScroll(event);
};
/**
* Gets the Webview, with an error view on top if no group is selected.
*
* @returns {*}
*/
getWebView() {
const showWebview = this.state.currentGroup.id !== -1;
return (
<View style={{height: '100%'}}>
{!showWebview
? <ErrorView
{...this.props}
icon={'account-clock'}
message={i18n.t("screens.planex.noGroupSelected")}
showRetryButton={false}
/>
: null}
<WebViewScreen
ref={this.webScreenRef}
navigation={this.props.navigation}
url={PLANEX_URL}
customJS={this.customInjectedJS}
onMessage={this.onMessage}
onScroll={this.onScroll}
showAdvancedControls={false}
/>
</View>
);
}
render() {
return (
<View
style={{flex: 1}}
>
{/*Allow to draw webview bellow banner*/}
<View style={{
position: 'absolute',
height: '100%',
width: '100%',
}}>
{this.props.theme.dark // Force component theme update by recreating it on theme change
? this.getWebView()
: <View style={{height: '100%'}}>{this.getWebView()}</View>}
</View>
{AsyncStorageManager.getString(AsyncStorageManager.PREFERENCES.defaultStartScreen.key)
.toLowerCase() !== 'planex'
? <MascotPopup
prefKey={AsyncStorageManager.PREFERENCES.planexShowBanner.key}
title={i18n.t("screens.planex.mascotDialog.title")}
message={i18n.t("screens.planex.mascotDialog.message")}
icon={"emoticon-kiss"}
buttons={{
action: {
message: i18n.t("screens.planex.mascotDialog.ok"),
icon: "cog",
onPress: this.onGoToSettings,
},
cancel: {
message: i18n.t("screens.planex.mascotDialog.cancel"),
icon: "close",
color: this.props.theme.colors.warning,
}
}}
emotion={MASCOT_STYLE.INTELLO}
/> : null }
<AlertDialog
visible={this.state.dialogVisible}
onDismiss={this.hideDialog}
title={this.state.dialogTitle}
message={this.state.dialogMessage}/>
<AnimatedBottomBar
{...this.props}
ref={this.barRef}
onPress={this.sendMessage}
seekAttention={this.state.currentGroup.id === -1}
/>
</View>
);
}
} }
export default withTheme(PlanexScreen); export default withTheme(PlanexScreen);