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,91 +2,110 @@
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 {
shouldComponentUpdate(nextProps: Props) { const {props} = this;
return (nextProps.currentSearchString !== this.props.currentSearchString) return (
|| (nextProps.favoriteNumber !== this.props.favoriteNumber) nextProps.currentSearchString !== props.currentSearchString ||
|| (nextProps.item.content.length !== this.props.item.content.length); nextProps.favoriteNumber !== props.favoriteNumber ||
nextProps.item.content.length !== props.item.content.length
);
} }
keyExtractor = (item: group) => item.id.toString(); getRenderItem = ({item}: {item: PlanexGroupType}): React.Node => {
const {props} = this;
renderItem = ({item}: { item: group }) => { const onPress = () => {
const onPress = () => this.props.onGroupPress(item); props.onGroupPress(item);
const onStarPress = () => this.props.onFavoritePress(item); };
const onStarPress = () => {
props.onFavoritePress(item);
};
return ( return (
<GroupListItem <GroupListItem
height={LIST_ITEM_HEIGHT} height={LIST_ITEM_HEIGHT}
item={item} item={item}
onPress={onPress} onPress={onPress}
onStarPress={onStarPress}/> onStarPress={onStarPress}
/>
); );
} };
getData() { getData(): Array<PlanexGroupType> {
const originalData = this.props.item.content; const {props} = this;
let displayData = []; const originalData = props.item.content;
for (let i = 0; i < originalData.length; i++) { const displayData = [];
if (stringMatchQuery(originalData[i].name, this.props.currentSearchString)) originalData.forEach((data: PlanexGroupType) => {
displayData.push(originalData[i]); if (stringMatchQuery(data.name, props.currentSearchString))
} displayData.push(data);
});
return displayData; return displayData;
} }
itemLayout = (data, index) => ({length: LIST_ITEM_HEIGHT, offset: LIST_ITEM_HEIGHT * index, index}); itemLayout = (
data: ?Array<PlanexGroupType>,
index: number,
): {length: number, offset: number, index: number} => ({
length: LIST_ITEM_HEIGHT,
offset: LIST_ITEM_HEIGHT * index,
index,
});
keyExtractor = (item: PlanexGroupType): string => item.id.toString();
render() { render(): React.Node {
const item = this.props.item; const {props} = this;
const {item} = this.props;
return ( return (
<View> <View>
<AnimatedAccordion <AnimatedAccordion
title={item.name} title={item.name}
style={{ style={{
height: this.props.height, height: props.height,
justifyContent: 'center', justifyContent: 'center',
}} }}
left={props => left={({size}: {size: number}): React.Node =>
item.id === 0 item.id === 0 ? (
? <List.Icon <List.Icon
{...props} size={size}
icon={"star"} icon="star"
color={this.props.theme.colors.tetrisScore} color={props.theme.colors.tetrisScore}
/> />
: null} ) : null
unmountWhenCollapsed={true}// Only render list if expanded for increased performance }
opened={this.props.item.id === 0 || this.props.currentSearchString.length > 0} unmountWhenCollapsed // Only render list if expanded for increased performance
> opened={props.item.id === 0 || props.currentSearchString.length > 0}>
{/* $FlowFixMe */} {/* $FlowFixMe */}
<FlatList <FlatList
data={this.getData()} data={this.getData()}
extraData={this.props.currentSearchString} extraData={props.currentSearchString}
renderItem={this.renderItem} renderItem={this.getRenderItem}
keyExtractor={this.keyExtractor} keyExtractor={this.keyExtractor}
listKey={item.id.toString()} listKey={item.id.toString()}
// Performance props, see https://reactnative.dev/docs/optimizing-flatlist-configuration // Performance props, see https://reactnative.dev/docs/optimizing-flatlist-configuration
getItemLayout={this.itemLayout} getItemLayout={this.itemLayout}
removeClippedSubviews={true} removeClippedSubviews
/> />
</AnimatedAccordion> </AnimatedAccordion>
</View> </View>
@ -94,4 +113,4 @@ class GroupListAccordion extends React.Component<Props> {
} }
} }
export default withTheme(GroupListAccordion) export default withTheme(GroupListAccordion);

View file

@ -2,60 +2,62 @@
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) {
constructor(props) {
super(props); super(props);
this.state = { this.state = {
isFav: (props.item.isFav !== undefined && props.item.isFav), isFav: props.item.isFav !== undefined && props.item.isFav,
} };
} }
shouldComponentUpdate(prevProps: Props, prevState: State) { shouldComponentUpdate(prevProps: PropsType, prevState: StateType): boolean {
return (prevState.isFav !== this.state.isFav); const {isFav} = this.state;
return prevState.isFav !== isFav;
} }
onStarPress = () => { onStarPress = () => {
this.setState({isFav: !this.state.isFav}); const {props} = this;
this.props.onStarPress(); this.setState((prevState: StateType): StateType => ({
} isFav: !prevState.isFav,
}));
props.onStarPress();
};
render() { render(): React.Node {
const colors = this.props.theme.colors; const {props, state} = this;
const {colors} = props.theme;
return ( return (
<List.Item <List.Item
title={this.props.item.name} title={props.item.name}
onPress={this.props.onPress} onPress={props.onPress}
left={props => left={({size}: {size: number}): React.Node => (
<List.Icon <List.Icon size={size} icon="chevron-right" />
{...props} )}
icon={"chevron-right"}/>} right={({size, color}: {size: number, color: string}): React.Node => (
right={props =>
<IconButton <IconButton
{...props} size={size}
icon={"star"} icon="star"
onPress={this.onStarPress} onPress={this.onStarPress}
color={this.state.isFav color={state.isFav ? colors.tetrisScore : color}
? colors.tetrisScore />
: props.color} )}
/>}
style={{ style={{
height: this.props.height, height: props.height,
justifyContent: 'center', justifyContent: 'center',
}} }}
/> />

View file

@ -1,43 +1,44 @@
// @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;
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; return 0;
} }
@ -47,99 +48,18 @@ 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) {
super(props);
this.state = {
currentSearchString: '',
favoriteGroups: AsyncStorageManager.getObject(AsyncStorageManager.PREFERENCES.planexFavoriteGroups.key),
};
}
/**
* Creates the header content
*/
componentDidMount() {
this.props.navigation.setOptions({
headerTitle: this.getSearchBar,
headerBackTitleVisible: false,
headerTitleContainerStyle: Platform.OS === 'ios' ?
{marginHorizontal: 0, width: '70%'} :
{marginHorizontal: 0, right: 50, left: 50},
});
}
/**
* Gets the header search bar
*
* @return {*}
*/
getSearchBar = () => {
return (
<Searchbar
placeholder={i18n.t('screens.proximo.search')}
onChangeText={this.onSearchStringChange}
/>
);
};
/**
* 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: group) => {
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: group) => {
this.updateGroupFavorites(item);
};
/**
* Checks if the given group is in the favorites list
*
* @param group The group to check
* @returns {boolean}
*/
isGroupInFavorites(group: group) {
let isFav = false;
for (let i = 0; i < this.state.favoriteGroups.length; i++) {
if (group.id === this.state.favoriteGroups[i].id) {
isFav = true;
break;
}
}
return isFav;
}
/** /**
* Removes the given group from the given array * Removes the given group from the given array
* *
* @param favorites The array containing favorites groups * @param favorites The array containing favorites groups
* @param group The group to remove from the array * @param group The group to remove from the array
*/ */
removeGroupFromFavorites(favorites: Array<group>, group: group) { static removeGroupFromFavorites(
for (let i = 0; i < favorites.length; i++) { favorites: Array<PlanexGroupType>,
group: PlanexGroupType,
) {
for (let i = 0; i < favorites.length; i += 1) {
if (group.id === favorites[i].id) { if (group.id === favorites[i].id) {
favorites.splice(i, 1); favorites.splice(i, 1);
break; break;
@ -153,95 +73,91 @@ class GroupSelectionScreen extends React.Component<Props, State> {
* @param favorites The array containing favorites groups * @param favorites The array containing favorites groups
* @param group The group to add to the array * @param group The group to add to the array
*/ */
addGroupToFavorites(favorites: Array<group>, group: group) { static addGroupToFavorites(
group.isFav = true; favorites: Array<PlanexGroupType>,
favorites.push(group); group: PlanexGroupType,
) {
const favGroup = {...group};
favGroup.isFav = true;
favorites.push(favGroup);
favorites.sort(sortName); favorites.sort(sortName);
} }
/** constructor(props: PropsType) {
* Adds or removes the given group to the favorites list, depending on whether it is already in it or not. super(props);
* Favorites are then saved in user preferences this.state = {
* currentSearchString: '',
* @param group The group to add/remove to favorites favoriteGroups: AsyncStorageManager.getObject(
*/ AsyncStorageManager.PREFERENCES.planexFavoriteGroups.key,
updateGroupFavorites(group: group) { ),
let newFavorites = [...this.state.favoriteGroups] };
if (this.isGroupInFavorites(group))
this.removeGroupFromFavorites(newFavorites, group);
else
this.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 * Creates the header content
*
* @param item The group category
* @returns {boolean}
*/ */
shouldDisplayAccordion(item: groupCategory) { componentDidMount() {
let shouldDisplay = false; const [navigation] = this.props;
for (let i = 0; i < item.content.length; i++) { navigation.setOptions({
if (stringMatchQuery(item.content[i].name, this.state.currentSearchString)) { headerTitle: this.getSearchBar,
shouldDisplay = true; headerBackTitleVisible: false,
break; headerTitleContainerStyle:
} Platform.OS === 'ios'
} ? {marginHorizontal: 0, width: '70%'}
return shouldDisplay; : {marginHorizontal: 0, right: 50, left: 50},
});
} }
/**
* Gets the header search bar
*
* @return {*}
*/
getSearchBar = (): React.Node => {
return (
<Searchbar
placeholder={i18n.t('screens.proximo.search')}
onChangeText={this.onSearchStringChange}
/>
);
};
/** /**
* Gets a render item for the given article * Gets a render item for the given article
* *
* @param item The article to render * @param item The article to render
* @return {*} * @return {*}
*/ */
renderItem = ({item}: { item: groupCategory }) => { getRenderItem = ({item}: {item: PlanexGroupCategoryType}): React.Node => {
const {currentSearchString, favoriteGroups} = this.state;
if (this.shouldDisplayAccordion(item)) { if (this.shouldDisplayAccordion(item)) {
return ( return (
<GroupListAccordion <GroupListAccordion
item={item} item={item}
onGroupPress={this.onListItemPress} onGroupPress={this.onListItemPress}
onFavoritePress={this.onListFavoritePress} onFavoritePress={this.onListFavoritePress}
currentSearchString={this.state.currentSearchString} currentSearchString={currentSearchString}
favoriteNumber={this.state.favoriteGroups.length} favoriteNumber={favoriteGroups.length}
height={LIST_ITEM_HEIGHT} height={LIST_ITEM_HEIGHT}
/> />
); );
} else }
return null; 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 * Replaces underscore by spaces and sets the favorite state of every group in the given category
* *
* @param item The category containing groups to format * @param groups The groups to format
* @return {Array<PlanexGroupType>}
*/ */
formatGroups(item: groupCategory) { getFormattedGroups(groups: Array<PlanexGroupType>): Array<PlanexGroupType> {
for (let i = 0; i < item.content.length; i++) { return groups.map((group: PlanexGroupType): PlanexGroupType => {
item.content[i].name = item.content[i].name.replace(REPLACE_REGEX, " ") const newGroup = {...group};
item.content[i].isFav = this.isGroupInFavorites(item.content[i]); newGroup.name = group.name.replace(REPLACE_REGEX, ' ');
} newGroup.isFav = this.isGroupInFavorites(group);
return newGroup;
});
} }
/** /**
@ -250,25 +166,141 @@ class GroupSelectionScreen extends React.Component<Props, State> {
* @param fetchedData * @param fetchedData
* @return {*} * @return {*}
* */ * */
createDataset = (fetchedData: { [key: string]: groupCategory }) => { createDataset = (fetchedData: {
[key: string]: PlanexGroupCategoryType,
}): Array<{title: string, data: Array<PlanexGroupCategoryType>}> => {
return [ return [
{ {
title: '', title: '',
data: this.generateData(fetchedData) 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;
} }
render() { /**
* 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;
}
/**
* 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]: 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) => {
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 {
const {props, state} = this;
return ( return (
<WebSectionList <WebSectionList
{...this.props} navigation={props.navigation}
createDataset={this.createDataset} createDataset={this.createDataset}
autoRefreshTime={0} autoRefreshTime={0}
refreshOnFocus={false} refreshOnFocus={false}
fetchUrl={GROUPS_URL} fetchUrl={GROUPS_URL}
renderItem={this.renderItem} renderItem={this.getRenderItem}
updateData={this.state.currentSearchString + this.state.favoriteGroups.length} updateData={state.currentSearchString + state.favoriteGroups.length}
itemHeight={LIST_ITEM_HEIGHT} itemHeight={LIST_ITEM_HEIGHT}
/> />
); );

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 = { type StateType = {
dialogVisible: boolean, dialogVisible: boolean,
dialogTitle: string, dialogTitle: string,
dialogMessage: string, dialogMessage: string,
currentGroup: group, currentGroup: PlanexGroupType,
} };
const PLANEX_URL = 'http://planex.insa-toulouse.fr/'; const PLANEX_URL = 'http://planex.insa-toulouse.fr/';
@ -69,21 +68,21 @@ 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' +
@ -108,20 +107,22 @@ 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;
@ -129,23 +130,25 @@ class PlanexScreen extends React.Component<Props, State> {
/** /**
* 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(
AsyncStorageManager.PREFERENCES.planexCurrentGroup.key,
);
if (currentGroup === '') if (currentGroup === '')
currentGroup = {name: "SELECT GROUP", id: -1, isFav: false}; currentGroup = {name: 'SELECT GROUP', id: -1, isFav: false};
else { else {
currentGroup = JSON.parse(currentGroup); currentGroup = JSON.parse(currentGroup);
props.navigation.setOptions({title: currentGroup.name}) props.navigation.setOptions({title: currentGroup.name});
} }
this.state = { this.state = {
dialogVisible: false, dialogVisible: false,
dialogTitle: "", dialogTitle: '',
dialogMessage: "", dialogMessage: '',
currentGroup: currentGroup, currentGroup,
}; };
this.generateInjectedJS(currentGroup.id); this.generateInjectedJS(currentGroup.id);
} }
@ -154,62 +157,8 @@ class PlanexScreen extends React.Component<Props, State> {
* 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);
/**
* Callback used when the user clicks on the navigate to settings button.
* This will hide the banner and open the SettingsScreen
*/
onGoToSettings = () => this.props.navigation.navigate('settings');
onScreenFocus = () => {
this.handleNavigationParams();
};
/**
* If navigations parameters contain a group, set it as selected
*/
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}));
}
}
};
/**
* 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);
}
/**
* 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())
this.customInjectedJS += "$('head').append('<style>" + CUSTOM_CSS_DARK + "</style>');";
this.customInjectedJS += 'removeAlpha();});true;'; // Prevents crash on ios
} }
/** /**
@ -218,12 +167,57 @@ class PlanexScreen extends React.Component<Props, State> {
* @param nextProps * @param nextProps
* @returns {boolean} * @returns {boolean}
*/ */
shouldComponentUpdate(nextProps: Props): boolean { shouldComponentUpdate(nextProps: PropsType): boolean {
if (nextProps.theme.dark !== this.props.theme.dark) const {props, state} = this;
this.generateInjectedJS(this.state.currentGroup.id); if (nextProps.theme.dark !== props.theme.dark)
this.generateInjectedJS(state.currentGroup.id);
return true; 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. * Sends a FullCalendar action to the web page inside the webview.
@ -232,14 +226,12 @@ class PlanexScreen extends React.Component<Props, State> {
* Or "setGroup" with the group id as data to set the selected group * Or "setGroup" with the group id as data to set the selected group
* @param data Data to pass to the action * @param data Data to pass to the action
*/ */
sendMessage = (action: string, data: any) => { sendMessage = (action: string, data: string) => {
let command; let command;
if (action === "setGroup") if (action === 'setGroup') command = `displayAde(${data})`;
command = "displayAde(" + data + ")"; else command = `$('#calendar').fullCalendar('${action}', '${data}')`;
else
command = "$('#calendar').fullCalendar('" + action + "', '" + data + "')";
if (this.webScreenRef.current != null) if (this.webScreenRef.current != null)
this.webScreenRef.current.injectJavaScript(command + ';true;'); // Injected javascript must end with true this.webScreenRef.current.injectJavaScript(`${command};true;`); // Injected javascript must end with true
}; };
/** /**
@ -248,16 +240,21 @@ class PlanexScreen extends React.Component<Props, State> {
* @param event * @param event
*/ */
onMessage = (event: {nativeEvent: {data: string}}) => { onMessage = (event: {nativeEvent: {data: string}}) => {
const data: { start: string, end: string, title: string, color: string } = JSON.parse(event.nativeEvent.data); const data: {
start: string,
end: string,
title: string,
color: string,
} = JSON.parse(event.nativeEvent.data);
const startDate = dateToString(new Date(data.start), true); const startDate = dateToString(new Date(data.start), true);
const endDate = dateToString(new Date(data.end), true); const endDate = dateToString(new Date(data.end), true);
const startString = getTimeOnlyString(startDate); const startString = getTimeOnlyString(startDate);
const endString = getTimeOnlyString(endDate); const endString = getTimeOnlyString(endDate);
let msg = DateManager.getInstance().getTranslatedDate(startDate) + "\n"; let msg = `${DateManager.getInstance().getTranslatedDate(startDate)}\n`;
if (startString != null && endString != null) if (startString != null && endString != null)
msg += startString + ' - ' + endString; msg += `${startString} - ${endString}`;
this.showDialog(data.title, msg) this.showDialog(data.title, msg);
}; };
/** /**
@ -289,87 +286,111 @@ class PlanexScreen extends React.Component<Props, State> {
* @param event * @param event
*/ */
onScroll = (event: SyntheticEvent<EventTarget>) => { onScroll = (event: SyntheticEvent<EventTarget>) => {
if (this.barRef.current != null) if (this.barRef.current != null) this.barRef.current.onScroll(event);
this.barRef.current.onScroll(event);
}; };
/** /**
* Gets the Webview, with an error view on top if no group is selected. * If navigations parameters contain a group, set it as selected
*
* @returns {*}
*/ */
getWebView() { handleNavigationParams = () => {
const showWebview = this.state.currentGroup.id !== -1; 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}));
}
}
};
return ( /**
<View style={{height: '100%'}}> * Sends the webpage a message with the new group to select and save it to preferences
{!showWebview *
? <ErrorView * @param group The group object selected
{...this.props} */
icon={'account-clock'} selectNewGroup(group: PlanexGroupType) {
message={i18n.t("screens.planex.noGroupSelected")} const {navigation} = this.props;
showRetryButton={false} this.sendMessage('setGroup', group.id.toString());
/> this.setState({currentGroup: group});
: null} AsyncStorageManager.set(
<WebViewScreen AsyncStorageManager.PREFERENCES.planexCurrentGroup.key,
ref={this.webScreenRef} group,
navigation={this.props.navigation}
url={PLANEX_URL}
customJS={this.customInjectedJS}
onMessage={this.onMessage}
onScroll={this.onScroll}
showAdvancedControls={false}
/>
</View>
); );
navigation.setOptions({title: group.name});
this.generateInjectedJS(group.id);
} }
render() { /**
* 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())
this.customInjectedJS += `$('head').append('<style>${CUSTOM_CSS_DARK}</style>');`;
this.customInjectedJS += 'removeAlpha();});true;'; // Prevents crash on ios
}
render(): React.Node {
const {props, state} = this;
return ( return (
<View <View style={{flex: 1}}>
style={{flex: 1}}
>
{/* Allow to draw webview bellow banner */} {/* Allow to draw webview bellow banner */}
<View style={{ <View
style={{
position: 'absolute', position: 'absolute',
height: '100%', height: '100%',
width: '100%', width: '100%',
}}> }}>
{this.props.theme.dark // Force component theme update by recreating it on theme change {props.theme.dark ? ( // Force component theme update by recreating it on theme change
? this.getWebView() this.getWebView()
: <View style={{height: '100%'}}>{this.getWebView()}</View>} ) : (
<View style={{height: '100%'}}>{this.getWebView()}</View>
)}
</View> </View>
{AsyncStorageManager.getString(AsyncStorageManager.PREFERENCES.defaultStartScreen.key) {AsyncStorageManager.getString(
.toLowerCase() !== 'planex' AsyncStorageManager.PREFERENCES.defaultStartScreen.key,
? <MascotPopup ).toLowerCase() !== 'planex' ? (
<MascotPopup
prefKey={AsyncStorageManager.PREFERENCES.planexShowBanner.key} prefKey={AsyncStorageManager.PREFERENCES.planexShowBanner.key}
title={i18n.t("screens.planex.mascotDialog.title")} title={i18n.t('screens.planex.mascotDialog.title')}
message={i18n.t("screens.planex.mascotDialog.message")} message={i18n.t('screens.planex.mascotDialog.message')}
icon={"emoticon-kiss"} icon="emoticon-kiss"
buttons={{ buttons={{
action: { action: {
message: i18n.t("screens.planex.mascotDialog.ok"), message: i18n.t('screens.planex.mascotDialog.ok'),
icon: "cog", icon: 'cog',
onPress: this.onGoToSettings, onPress: this.onGoToSettings,
}, },
cancel: { cancel: {
message: i18n.t("screens.planex.mascotDialog.cancel"), message: i18n.t('screens.planex.mascotDialog.cancel'),
icon: "close", icon: 'close',
color: this.props.theme.colors.warning, color: props.theme.colors.warning,
} },
}} }}
emotion={MASCOT_STYLE.INTELLO} emotion={MASCOT_STYLE.INTELLO}
/> : null } />
) : null}
<AlertDialog <AlertDialog
visible={this.state.dialogVisible} visible={state.dialogVisible}
onDismiss={this.hideDialog} onDismiss={this.hideDialog}
title={this.state.dialogTitle} title={state.dialogTitle}
message={this.state.dialogMessage}/> message={state.dialogMessage}
/>
<AnimatedBottomBar <AnimatedBottomBar
{...this.props} navigation={props.navigation}
ref={this.barRef} ref={this.barRef}
onPress={this.sendMessage} onPress={this.sendMessage}
seekAttention={this.state.currentGroup.id === -1} seekAttention={state.currentGroup.id === -1}
/> />
</View> </View>
); );