Compare commits

..

4 commits

18 changed files with 2885 additions and 2616 deletions

View file

@ -2,71 +2,88 @@
import * as React from 'react'; import * as React from 'react';
import {withTheme} from 'react-native-paper'; import {withTheme} from 'react-native-paper';
import {FlatList, Image, View} from "react-native"; import {FlatList, Image, View} from 'react-native';
import DashboardEditItem from "./DashboardEditItem"; import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons';
import AnimatedAccordion from "../../Animations/AnimatedAccordion"; import DashboardEditItem from './DashboardEditItem';
import type {ServiceCategory, ServiceItem} from "../../../managers/ServicesManager"; import AnimatedAccordion from '../../Animations/AnimatedAccordion';
import MaterialCommunityIcons from "react-native-vector-icons/MaterialCommunityIcons"; import type {
import type {CustomTheme} from "../../../managers/ThemeManager"; ServiceCategoryType,
ServiceItemType,
} from '../../../managers/ServicesManager';
import type {CustomTheme} from '../../../managers/ThemeManager';
type Props = { type PropsType = {
item: ServiceCategory, item: ServiceCategoryType,
activeDashboard: Array<string>, activeDashboard: Array<string>,
onPress: (service: ServiceItem) => void, onPress: (service: ServiceItemType) => void,
theme: CustomTheme, theme: CustomTheme,
} };
const LIST_ITEM_HEIGHT = 64; const LIST_ITEM_HEIGHT = 64;
class DashboardEditAccordion extends React.Component<Props> { class DashboardEditAccordion extends React.Component<PropsType> {
getRenderItem = ({item}: {item: ServiceItemType}): React.Node => {
const {props} = this;
return (
<DashboardEditItem
height={LIST_ITEM_HEIGHT}
item={item}
isActive={props.activeDashboard.includes(item.key)}
onPress={() => {
props.onPress(item);
}}
/>
);
};
renderItem = ({item}: { item: ServiceItem }) => { getItemLayout = (
return ( data: ?Array<ServiceItemType>,
<DashboardEditItem index: number,
height={LIST_ITEM_HEIGHT} ): {length: number, offset: number, index: number} => ({
item={item} length: LIST_ITEM_HEIGHT,
isActive={this.props.activeDashboard.includes(item.key)} offset: LIST_ITEM_HEIGHT * index,
onPress={() => this.props.onPress(item)}/> index,
); });
}
itemLayout = (data, index) => ({length: LIST_ITEM_HEIGHT, offset: LIST_ITEM_HEIGHT * index, index}); render(): React.Node {
const {props} = this;
render() { const {item} = props;
const item = this.props.item; return (
return ( <View>
<View> <AnimatedAccordion
<AnimatedAccordion title={item.title}
title={item.title} left={(): React.Node =>
left={props => typeof item.image === "number" typeof item.image === 'number' ? (
? <Image <Image
{...props} source={item.image}
source={item.image} style={{
style={{ width: 40,
width: 40, height: 40,
height: 40 }}
}} />
/> ) : (
: <MaterialCommunityIcons <MaterialCommunityIcons
//$FlowFixMe // $FlowFixMe
name={item.image} name={item.image}
color={this.props.theme.colors.primary} color={props.theme.colors.primary}
size={40}/>} size={40}
> />
{/*$FlowFixMe*/} )
<FlatList }>
data={item.content} {/* $FlowFixMe */}
extraData={this.props.activeDashboard.toString()} <FlatList
renderItem={this.renderItem} data={item.content}
listKey={item.key} extraData={props.activeDashboard.toString()}
// Performance props, see https://reactnative.dev/docs/optimizing-flatlist-configuration renderItem={this.getRenderItem}
getItemLayout={this.itemLayout} listKey={item.key}
removeClippedSubviews={true} // Performance props, see https://reactnative.dev/docs/optimizing-flatlist-configuration
/> getItemLayout={this.getItemLayout}
</AnimatedAccordion> removeClippedSubviews
</View> />
); </AnimatedAccordion>
} </View>
);
}
} }
export default withTheme(DashboardEditAccordion) export default withTheme(DashboardEditAccordion);

View file

@ -1,55 +1,61 @@
// @flow // @flow
import * as React from 'react'; import * as React from 'react';
import {Image} from "react-native"; import {Image} from 'react-native';
import {List, withTheme} from 'react-native-paper'; import {List, withTheme} from 'react-native-paper';
import type {CustomTheme} from "../../../managers/ThemeManager"; import type {CustomTheme} from '../../../managers/ThemeManager';
import type {ServiceItem} from "../../../managers/ServicesManager"; import type {ServiceItemType} from '../../../managers/ServicesManager';
type Props = { type PropsType = {
item: ServiceItem, item: ServiceItemType,
isActive: boolean, isActive: boolean,
height: number, height: number,
onPress: () => void, onPress: () => void,
theme: CustomTheme, theme: CustomTheme,
} };
class DashboardEditItem extends React.Component<Props> { class DashboardEditItem extends React.Component<PropsType> {
shouldComponentUpdate(nextProps: PropsType): boolean {
const {isActive} = this.props;
return nextProps.isActive !== isActive;
}
shouldComponentUpdate(nextProps: Props) { render(): React.Node {
return (nextProps.isActive !== this.props.isActive); const {props} = this;
} return (
<List.Item
render() { title={props.item.title}
return ( description={props.item.subtitle}
<List.Item onPress={props.isActive ? null : props.onPress}
title={this.props.item.title} left={(): React.Node => (
description={this.props.item.subtitle} <Image
onPress={this.props.isActive ? null : this.props.onPress} source={{uri: props.item.image}}
left={props => style={{
<Image width: 40,
{...props} height: 40,
source={{uri: this.props.item.image}} }}
style={{ />
width: 40, )}
height: 40 right={({size}: {size: number}): React.Node =>
}} props.isActive ? (
/>} <List.Icon
right={props => this.props.isActive size={size}
? <List.Icon icon="check"
{...props} color={props.theme.colors.success}
icon={"check"}
color={this.props.theme.colors.success}
/> : null}
style={{
height: this.props.height,
justifyContent: 'center',
paddingLeft: 30,
backgroundColor: this.props.isActive ? this.props.theme.colors.proxiwashFinishedColor : "transparent"
}}
/> />
); ) : null
} }
style={{
height: props.height,
justifyContent: 'center',
paddingLeft: 30,
backgroundColor: props.isActive
? props.theme.colors.proxiwashFinishedColor
: 'transparent',
}}
/>
);
}
} }
export default withTheme(DashboardEditItem); export default withTheme(DashboardEditItem);

View file

@ -2,57 +2,57 @@
import * as React from 'react'; import * as React from 'react';
import {TouchableRipple, withTheme} from 'react-native-paper'; import {TouchableRipple, withTheme} from 'react-native-paper';
import {Dimensions, Image, View} from "react-native"; import {Dimensions, Image, View} from 'react-native';
import type {CustomTheme} from "../../../managers/ThemeManager"; import type {CustomTheme} from '../../../managers/ThemeManager';
type Props = { type PropsType = {
image: string, image: string,
isActive: boolean, isActive: boolean,
onPress: () => void, onPress: () => void,
theme: CustomTheme, theme: CustomTheme,
}; };
/** /**
* Component used to render a small dashboard item * Component used to render a small dashboard item
*/ */
class DashboardEditPreviewItem extends React.Component<Props> { class DashboardEditPreviewItem extends React.Component<PropsType> {
itemSize: number;
itemSize: number; constructor(props: PropsType) {
super(props);
constructor(props: Props) { this.itemSize = Dimensions.get('window').width / 8;
super(props); }
this.itemSize = Dimensions.get('window').width / 8;
}
render() {
const props = this.props;
return (
<TouchableRipple
onPress={this.props.onPress}
borderless={true}
style={{
marginLeft: 5,
marginRight: 5,
backgroundColor: this.props.isActive ? this.props.theme.colors.textDisabled : "transparent",
borderRadius: 5
}}
>
<View style={{
width: this.itemSize,
height: this.itemSize,
}}>
<Image
source={{uri: props.image}}
style={{
width: "100%",
height: "100%",
}}
/>
</View>
</TouchableRipple>
);
}
render(): React.Node {
const {props} = this;
return (
<TouchableRipple
onPress={props.onPress}
borderless
style={{
marginLeft: 5,
marginRight: 5,
backgroundColor: props.isActive
? props.theme.colors.textDisabled
: 'transparent',
borderRadius: 5,
}}>
<View
style={{
width: this.itemSize,
height: this.itemSize,
}}>
<Image
source={{uri: props.image}}
style={{
width: '100%',
height: '100%',
}}
/>
</View>
</TouchableRipple>
);
}
} }
export default withTheme(DashboardEditPreviewItem) export default withTheme(DashboardEditPreviewItem);

View file

@ -2,111 +2,112 @@
import * as React from 'react'; import * as React from 'react';
import {Avatar, List, withTheme} from 'react-native-paper'; import {Avatar, List, withTheme} from 'react-native-paper';
import type {CustomTheme} from "../../../managers/ThemeManager"; import i18n from 'i18n-js';
import type {Device} from "../../../screens/Amicale/Equipment/EquipmentListScreen"; import {StackNavigationProp} from '@react-navigation/stack';
import i18n from "i18n-js"; import type {CustomTheme} from '../../../managers/ThemeManager';
import type {DeviceType} from '../../../screens/Amicale/Equipment/EquipmentListScreen';
import { import {
getFirstEquipmentAvailability, getFirstEquipmentAvailability,
getRelativeDateString, getRelativeDateString,
isEquipmentAvailable isEquipmentAvailable,
} from "../../../utils/EquipmentBooking"; } from '../../../utils/EquipmentBooking';
import {StackNavigationProp} from "@react-navigation/stack";
type Props = { type PropsType = {
navigation: StackNavigationProp, navigation: StackNavigationProp,
userDeviceRentDates: [string, string], userDeviceRentDates: [string, string],
item: Device, item: DeviceType,
height: number, height: number,
theme: CustomTheme, theme: CustomTheme,
} };
class EquipmentListItem extends React.Component<Props> { class EquipmentListItem extends React.Component<PropsType> {
shouldComponentUpdate(nextProps: PropsType): boolean {
const {userDeviceRentDates} = this.props;
return nextProps.userDeviceRentDates !== userDeviceRentDates;
}
shouldComponentUpdate(nextProps: Props): boolean { render(): React.Node {
return nextProps.userDeviceRentDates !== this.props.userDeviceRentDates; const {item, userDeviceRentDates, navigation, height, theme} = this.props;
} const isRented = userDeviceRentDates != null;
const isAvailable = isEquipmentAvailable(item);
const firstAvailability = getFirstEquipmentAvailability(item);
render() { let onPress;
const colors = this.props.theme.colors; if (isRented)
const item = this.props.item; onPress = () => {
const userDeviceRentDates = this.props.userDeviceRentDates; navigation.navigate('equipment-confirm', {
const isRented = userDeviceRentDates != null; item,
const isAvailable = isEquipmentAvailable(item); dates: userDeviceRentDates,
const firstAvailability = getFirstEquipmentAvailability(item); });
};
else
onPress = () => {
navigation.navigate('equipment-rent', {item});
};
let onPress; let description;
if (isRented) if (isRented) {
onPress = () => this.props.navigation.navigate("equipment-confirm", { const start = new Date(userDeviceRentDates[0]);
item: item, const end = new Date(userDeviceRentDates[1]);
dates: userDeviceRentDates if (start.getTime() !== end.getTime())
}); description = i18n.t('screens.equipment.bookingPeriod', {
else begin: getRelativeDateString(start),
onPress = () => this.props.navigation.navigate("equipment-rent", {item: item}); end: getRelativeDateString(end),
});
else
description = i18n.t('screens.equipment.bookingDay', {
date: getRelativeDateString(start),
});
} else if (isAvailable)
description = i18n.t('screens.equipment.bail', {cost: item.caution});
else
description = i18n.t('screens.equipment.available', {
date: getRelativeDateString(firstAvailability),
});
let description; let icon;
if (isRented) { if (isRented) icon = 'bookmark-check';
const start = new Date(userDeviceRentDates[0]); else if (isAvailable) icon = 'check-circle-outline';
const end = new Date(userDeviceRentDates[1]); else icon = 'update';
if (start.getTime() !== end.getTime())
description = i18n.t('screens.equipment.bookingPeriod', {
begin: getRelativeDateString(start),
end: getRelativeDateString(end)
});
else
description = i18n.t('screens.equipment.bookingDay', {
date: getRelativeDateString(start)
});
} else if (isAvailable)
description = i18n.t('screens.equipment.bail', {cost: item.caution});
else
description = i18n.t('screens.equipment.available', {date: getRelativeDateString(firstAvailability)});
let icon; let color;
if (isRented) if (isRented) color = theme.colors.warning;
icon = "bookmark-check"; else if (isAvailable) color = theme.colors.success;
else if (isAvailable) else color = theme.colors.primary;
icon = "check-circle-outline";
else
icon = "update";
let color; return (
if (isRented) <List.Item
color = colors.warning; title={item.name}
else if (isAvailable) description={description}
color = colors.success; onPress={onPress}
else left={({size}: {size: number}): React.Node => (
color = colors.primary; <Avatar.Icon
size={size}
return ( style={{
<List.Item backgroundColor: 'transparent',
title={item.name} }}
description={description} icon={icon}
onPress={onPress} color={color}
left={(props) => <Avatar.Icon />
{...props} )}
style={{ right={(): React.Node => (
backgroundColor: 'transparent', <Avatar.Icon
}} style={{
icon={icon} marginTop: 'auto',
color={color} marginBottom: 'auto',
/>} backgroundColor: 'transparent',
right={(props) => <Avatar.Icon }}
{...props} size={48}
style={{ icon="chevron-right"
marginTop: 'auto', />
marginBottom: 'auto', )}
backgroundColor: 'transparent', style={{
}} height,
size={48} justifyContent: 'center',
icon={"chevron-right"} }}
/>} />
style={{ );
height: this.props.height, }
justifyContent: 'center',
}}
/>
);
}
} }
export default withTheme(EquipmentListItem); export default withTheme(EquipmentListItem);

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

@ -2,48 +2,48 @@
import * as React from 'react'; import * as React from 'react';
import {Avatar, List, Text, withTheme} from 'react-native-paper'; import {Avatar, List, Text, withTheme} from 'react-native-paper';
import i18n from "i18n-js"; import i18n from 'i18n-js';
import type {ProximoArticleType} from '../../../screens/Services/Proximo/ProximoMainScreen';
type Props = { type PropsType = {
onPress: Function, onPress: () => void,
color: string, color: string,
item: Object, item: ProximoArticleType,
height: number, height: number,
} };
class ProximoListItem extends React.Component<Props> { class ProximoListItem extends React.Component<PropsType> {
shouldComponentUpdate(): boolean {
return false;
}
colors: Object; render(): React.Node {
const {props} = this;
constructor(props) { return (
super(props); <List.Item
this.colors = props.theme.colors; title={props.item.name}
} description={`${props.item.quantity} ${i18n.t(
'screens.proximo.inStock',
shouldComponentUpdate() { )}`}
return false; descriptionStyle={{color: props.color}}
} onPress={props.onPress}
left={(): React.Node => (
render() { <Avatar.Image
return ( style={{backgroundColor: 'transparent'}}
<List.Item size={64}
title={this.props.item.name} source={{uri: props.item.image}}
description={this.props.item.quantity + ' ' + i18n.t('screens.proximo.inStock')} />
descriptionStyle={{color: this.props.color}} )}
onPress={this.props.onPress} right={(): React.Node => (
left={() => <Avatar.Image style={{backgroundColor: 'transparent'}} size={64} <Text style={{fontWeight: 'bold'}}>{props.item.price}</Text>
source={{uri: this.props.item.image}}/>} )}
right={() => style={{
<Text style={{fontWeight: "bold"}}> height: props.height,
{this.props.item.price} justifyContent: 'center',
</Text>} }}
style={{ />
height: this.props.height, );
justifyContent: 'center', }
}}
/>
);
}
} }
export default withTheme(ProximoListItem); export default withTheme(ProximoListItem);

View file

@ -1,44 +1,55 @@
// @flow // @flow
import * as React from 'react'; import * as React from 'react';
import {ERROR_TYPE, readData} from "../../utils/WebData"; import i18n from 'i18n-js';
import i18n from "i18n-js";
import {Snackbar} from 'react-native-paper'; import {Snackbar} from 'react-native-paper';
import {RefreshControl, View} from "react-native"; import {RefreshControl, View} from 'react-native';
import ErrorView from "./ErrorView";
import BasicLoadingScreen from "./BasicLoadingScreen";
import {withCollapsible} from "../../utils/withCollapsible";
import * as Animatable from 'react-native-animatable'; import * as Animatable from 'react-native-animatable';
import CustomTabBar from "../Tabbar/CustomTabBar"; import {Collapsible} from 'react-navigation-collapsible';
import {Collapsible} from "react-navigation-collapsible"; import {StackNavigationProp} from '@react-navigation/stack';
import {StackNavigationProp} from "@react-navigation/stack"; import ErrorView from './ErrorView';
import CollapsibleSectionList from "../Collapsible/CollapsibleSectionList"; import BasicLoadingScreen from './BasicLoadingScreen';
import {withCollapsible} from '../../utils/withCollapsible';
import CustomTabBar from '../Tabbar/CustomTabBar';
import {ERROR_TYPE, readData} from '../../utils/WebData';
import CollapsibleSectionList from '../Collapsible/CollapsibleSectionList';
import type {ApiGenericDataType} from '../../utils/WebData';
type Props = { export type SectionListDataType<T> = Array<{
navigation: StackNavigationProp, title: string,
fetchUrl: string, data: Array<T>,
autoRefreshTime: number, keyExtractor?: (T) => string,
refreshOnFocus: boolean, }>;
renderItem: (data: { [key: string]: any }) => React.Node,
createDataset: (data: { [key: string]: any } | null, isLoading?: boolean) => Array<Object>,
onScroll: (event: SyntheticEvent<EventTarget>) => void,
collapsibleStack: Collapsible,
showError: boolean, type PropsType<T> = {
itemHeight?: number, navigation: StackNavigationProp,
updateData?: number, fetchUrl: string,
renderListHeaderComponent?: (data: { [key: string]: any } | null) => React.Node, autoRefreshTime: number,
renderSectionHeader?: (data: { section: { [key: string]: any } }, isLoading?: boolean) => React.Node, refreshOnFocus: boolean,
stickyHeader?: boolean, renderItem: (data: {item: T}) => React.Node,
} createDataset: (
data: ApiGenericDataType | null,
isLoading?: boolean,
) => SectionListDataType<T>,
onScroll: (event: SyntheticEvent<EventTarget>) => void,
collapsibleStack: Collapsible,
type State = { showError?: boolean,
refreshing: boolean, itemHeight?: number | null,
firstLoading: boolean, updateData?: number,
fetchedData: { [key: string]: any } | null, renderListHeaderComponent?: (data: ApiGenericDataType | null) => React.Node,
snackbarVisible: boolean renderSectionHeader?: (
data: {section: {title: string}},
isLoading?: boolean,
) => React.Node,
stickyHeader?: boolean,
}; };
type StateType = {
refreshing: boolean,
fetchedData: ApiGenericDataType | null,
snackbarVisible: boolean,
};
const MIN_REFRESH_TIME = 5 * 1000; const MIN_REFRESH_TIME = 5 * 1000;
@ -48,211 +59,216 @@ const MIN_REFRESH_TIME = 5 * 1000;
* This is a pure component, meaning it will only update if a shallow comparison of state and props is different. * This is a pure component, meaning it will only update if a shallow comparison of state and props is different.
* To force the component to update, change the value of updateData. * To force the component to update, change the value of updateData.
*/ */
class WebSectionList extends React.PureComponent<Props, State> { class WebSectionList<T> extends React.PureComponent<PropsType<T>, StateType> {
static defaultProps = {
showError: true,
itemHeight: null,
updateData: 0,
renderListHeaderComponent: (): React.Node => null,
renderSectionHeader: (): React.Node => null,
stickyHeader: false,
};
static defaultProps = { refreshInterval: IntervalID;
stickyHeader: false,
updateData: 0, lastRefresh: Date | null;
showError: true,
constructor() {
super();
this.state = {
refreshing: false,
fetchedData: null,
snackbarVisible: false,
}; };
}
refreshInterval: IntervalID; /**
lastRefresh: Date | null; * Registers react navigation events on first screen load.
* Allows to detect when the screen is focused
*/
componentDidMount() {
const {navigation} = this.props;
navigation.addListener('focus', this.onScreenFocus);
navigation.addListener('blur', this.onScreenBlur);
this.lastRefresh = null;
this.onRefresh();
}
state = { /**
refreshing: false, * Refreshes data when focusing the screen and setup a refresh interval if asked to
firstLoading: true, */
fetchedData: null, onScreenFocus = () => {
snackbarVisible: false const {props} = this;
if (props.refreshOnFocus && this.lastRefresh) this.onRefresh();
if (props.autoRefreshTime > 0)
this.refreshInterval = setInterval(this.onRefresh, props.autoRefreshTime);
};
/**
* Removes any interval on un-focus
*/
onScreenBlur = () => {
clearInterval(this.refreshInterval);
};
/**
* Callback used when fetch is successful.
* It will update the displayed data and stop the refresh animation
*
* @param fetchedData The newly fetched data
*/
onFetchSuccess = (fetchedData: ApiGenericDataType) => {
this.setState({
fetchedData,
refreshing: false,
});
this.lastRefresh = new Date();
};
/**
* Callback used when fetch encountered an error.
* It will reset the displayed data and show an error.
*/
onFetchError = () => {
this.setState({
fetchedData: null,
refreshing: false,
});
this.showSnackBar();
};
/**
* Refreshes data and shows an animations while doing it
*/
onRefresh = () => {
const {fetchUrl} = this.props;
let canRefresh;
if (this.lastRefresh != null) {
const last = this.lastRefresh;
canRefresh = new Date().getTime() - last.getTime() > MIN_REFRESH_TIME;
} else canRefresh = true;
if (canRefresh) {
this.setState({refreshing: true});
readData(fetchUrl).then(this.onFetchSuccess).catch(this.onFetchError);
}
};
/**
* Shows the error popup
*/
showSnackBar = () => {
this.setState({snackbarVisible: true});
};
/**
* Hides the error popup
*/
hideSnackBar = () => {
this.setState({snackbarVisible: false});
};
getItemLayout = (
data: T,
index: number,
): {length: number, offset: number, index: number} | null => {
const {itemHeight} = this.props;
if (itemHeight == null) return null;
return {
length: itemHeight,
offset: itemHeight * index,
index,
}; };
};
/** getRenderSectionHeader = (data: {section: {title: string}}): React.Node => {
* Registers react navigation events on first screen load. const {renderSectionHeader} = this.props;
* Allows to detect when the screen is focused const {refreshing} = this.state;
*/ if (renderSectionHeader != null) {
componentDidMount() { return (
this.props.navigation.addListener('focus', this.onScreenFocus); <Animatable.View animation="fadeInUp" duration={500} useNativeDriver>
this.props.navigation.addListener('blur', this.onScreenBlur); {renderSectionHeader(data, refreshing)}
this.lastRefresh = null; </Animatable.View>
this.onRefresh(); );
} }
return null;
};
/** getRenderItem = (data: {item: T}): React.Node => {
* Refreshes data when focusing the screen and setup a refresh interval if asked to const {renderItem} = this.props;
*/ return (
onScreenFocus = () => { <Animatable.View animation="fadeInUp" duration={500} useNativeDriver>
if (this.props.refreshOnFocus && this.lastRefresh) {renderItem(data)}
this.onRefresh(); </Animatable.View>
if (this.props.autoRefreshTime > 0) );
this.refreshInterval = setInterval(this.onRefresh, this.props.autoRefreshTime) };
}
/** onScroll = (event: SyntheticEvent<EventTarget>) => {
* Removes any interval on un-focus const {onScroll} = this.props;
*/ if (onScroll != null) onScroll(event);
onScreenBlur = () => { };
clearInterval(this.refreshInterval);
}
render(): React.Node {
const {props, state} = this;
let dataset = [];
if (
state.fetchedData != null ||
(state.fetchedData == null && !props.showError)
)
dataset = props.createDataset(state.fetchedData, state.refreshing);
/** const {containerPaddingTop} = props.collapsibleStack;
* Callback used when fetch is successful. return (
* It will update the displayed data and stop the refresh animation <View>
* <CollapsibleSectionList
* @param fetchedData The newly fetched data sections={dataset}
*/ extraData={props.updateData}
onFetchSuccess = (fetchedData: { [key: string]: any }) => { refreshControl={
this.setState({ <RefreshControl
fetchedData: fetchedData, progressViewOffset={containerPaddingTop}
refreshing: false, refreshing={state.refreshing}
firstLoading: false onRefresh={this.onRefresh}
}); />
this.lastRefresh = new Date(); }
}; renderSectionHeader={this.getRenderSectionHeader}
renderItem={this.getRenderItem}
/** stickySectionHeadersEnabled={props.stickyHeader}
* Callback used when fetch encountered an error. style={{minHeight: '100%'}}
* It will reset the displayed data and show an error. ListHeaderComponent={
*/ props.renderListHeaderComponent != null
onFetchError = () => { ? props.renderListHeaderComponent(state.fetchedData)
this.setState({ : null
fetchedData: null, }
refreshing: false, ListEmptyComponent={
firstLoading: false state.refreshing ? (
}); <BasicLoadingScreen />
this.showSnackBar(); ) : (
}; <ErrorView
navigation={props.navigation}
/** errorCode={ERROR_TYPE.CONNECTION_ERROR}
* Refreshes data and shows an animations while doing it onRefresh={this.onRefresh}
*/ />
onRefresh = () => { )
let canRefresh; }
if (this.lastRefresh != null) { getItemLayout={props.itemHeight != null ? this.getItemLayout : null}
const last = this.lastRefresh; onScroll={this.onScroll}
canRefresh = (new Date().getTime() - last.getTime()) > MIN_REFRESH_TIME; hasTab
} else />
canRefresh = true; <Snackbar
if (canRefresh) { visible={state.snackbarVisible}
this.setState({refreshing: true}); onDismiss={this.hideSnackBar}
readData(this.props.fetchUrl) action={{
.then(this.onFetchSuccess) label: 'OK',
.catch(this.onFetchError); onPress: () => {},
} }}
}; duration={4000}
style={{
/** bottom: CustomTabBar.TAB_BAR_HEIGHT,
* Shows the error popup }}>
*/ {i18n.t('general.listUpdateFail')}
showSnackBar = () => this.setState({snackbarVisible: true}); </Snackbar>
</View>
/** );
* Hides the error popup }
*/
hideSnackBar = () => this.setState({snackbarVisible: false});
itemLayout = (data: { [key: string]: any }, index: number) => {
const height = this.props.itemHeight;
if (height == null)
return undefined;
return {
length: height,
offset: height * index,
index
}
};
renderSectionHeader = (data: { section: { [key: string]: any } }) => {
if (this.props.renderSectionHeader != null) {
return (
<Animatable.View
animation={"fadeInUp"}
duration={500}
useNativeDriver
>
{this.props.renderSectionHeader(data, this.state.refreshing)}
</Animatable.View>
);
} else
return null;
}
renderItem = (data: {
item: { [key: string]: any },
index: number,
section: { [key: string]: any },
separators: { [key: string]: any },
}) => {
return (
<Animatable.View
animation={"fadeInUp"}
duration={500}
useNativeDriver
>
{this.props.renderItem(data)}
</Animatable.View>
);
}
onScroll = (event: SyntheticEvent<EventTarget>) => {
if (this.props.onScroll)
this.props.onScroll(event);
}
render() {
let dataset = [];
if (this.state.fetchedData != null || (this.state.fetchedData == null && !this.props.showError)) {
dataset = this.props.createDataset(this.state.fetchedData, this.state.refreshing);
}
const {containerPaddingTop} = this.props.collapsibleStack;
return (
<View>
<CollapsibleSectionList
sections={dataset}
extraData={this.props.updateData}
refreshControl={
<RefreshControl
progressViewOffset={containerPaddingTop}
refreshing={this.state.refreshing}
onRefresh={this.onRefresh}
/>
}
renderSectionHeader={this.renderSectionHeader}
renderItem={this.renderItem}
stickySectionHeadersEnabled={this.props.stickyHeader}
style={{minHeight: '100%'}}
ListHeaderComponent={this.props.renderListHeaderComponent != null
? this.props.renderListHeaderComponent(this.state.fetchedData)
: null}
ListEmptyComponent={this.state.refreshing
? <BasicLoadingScreen/>
: <ErrorView
{...this.props}
errorCode={ERROR_TYPE.CONNECTION_ERROR}
onRefresh={this.onRefresh}/>
}
getItemLayout={this.props.itemHeight != null ? this.itemLayout : undefined}
onScroll={this.onScroll}
hasTab={true}
/>
<Snackbar
visible={this.state.snackbarVisible}
onDismiss={this.hideSnackBar}
action={{
label: 'OK',
onPress: () => {
},
}}
duration={4000}
style={{
bottom: CustomTabBar.TAB_BAR_HEIGHT
}}
>
{i18n.t("general.listUpdateFail")}
</Snackbar>
</View>
);
}
} }
export default withCollapsible(WebSectionList); export default withCollapsible(WebSectionList);

View file

@ -1,105 +1,102 @@
// @flow // @flow
import * as React from 'react'; import * as React from 'react';
import {Button, Caption, Card, Headline, Paragraph, withTheme} from 'react-native-paper'; import {
import {StackNavigationProp} from "@react-navigation/stack"; Button,
import type {CustomTheme} from "../../../managers/ThemeManager"; Caption,
import type {Device} from "./EquipmentListScreen"; Card,
import {View} from "react-native"; Headline,
import i18n from "i18n-js"; Paragraph,
import {getRelativeDateString} from "../../../utils/EquipmentBooking"; withTheme,
import CollapsibleScrollView from "../../../components/Collapsible/CollapsibleScrollView"; } from 'react-native-paper';
import {View} from 'react-native';
import i18n from 'i18n-js';
import type {CustomTheme} from '../../../managers/ThemeManager';
import type {DeviceType} from './EquipmentListScreen';
import {getRelativeDateString} from '../../../utils/EquipmentBooking';
import CollapsibleScrollView from '../../../components/Collapsible/CollapsibleScrollView';
type Props = { type PropsType = {
navigation: StackNavigationProp, route: {
route: { params?: {
params?: { item?: DeviceType,
item?: Device, dates: [string, string],
dates: [string, string]
},
}, },
theme: CustomTheme, },
} theme: CustomTheme,
};
class EquipmentConfirmScreen extends React.Component<PropsType> {
item: DeviceType | null;
class EquipmentConfirmScreen extends React.Component<Props> { dates: [string, string] | null;
item: Device | null; constructor(props: PropsType) {
dates: [string, string] | null; super(props);
if (props.route.params != null) {
constructor(props: Props) { if (props.route.params.item != null) this.item = props.route.params.item;
super(props); else this.item = null;
if (this.props.route.params != null) { if (props.route.params.dates != null)
if (this.props.route.params.item != null) this.dates = props.route.params.dates;
this.item = this.props.route.params.item; else this.dates = null;
else
this.item = null;
if (this.props.route.params.dates != null)
this.dates = this.props.route.params.dates;
else
this.dates = null;
}
} }
}
render() { render(): React.Node {
const item = this.item; const {item, dates, props} = this;
const dates = this.dates; if (item != null && dates != null) {
if (item != null && dates != null) { const start = new Date(dates[0]);
const start = new Date(dates[0]); const end = new Date(dates[1]);
const end = new Date(dates[1]); let buttonText;
return ( if (start == null) buttonText = i18n.t('screens.equipment.booking');
<CollapsibleScrollView> else if (end != null && start.getTime() !== end.getTime())
<Card style={{margin: 5}}> buttonText = i18n.t('screens.equipment.bookingPeriod', {
<Card.Content> begin: getRelativeDateString(start),
<View style={{flex: 1}}> end: getRelativeDateString(end),
<View style={{ });
marginLeft: "auto", else
marginRight: "auto", buttonText = i18n.t('screens.equipment.bookingDay', {
flexDirection: "row", date: getRelativeDateString(start),
flexWrap: "wrap", });
}}> return (
<Headline style={{textAlign: "center"}}> <CollapsibleScrollView>
{item.name} <Card style={{margin: 5}}>
</Headline> <Card.Content>
<Caption style={{ <View style={{flex: 1}}>
textAlign: "center", <View
lineHeight: 35, style={{
marginLeft: 10, marginLeft: 'auto',
}}> marginRight: 'auto',
({i18n.t('screens.equipment.bail', {cost: item.caution})}) flexDirection: 'row',
</Caption> flexWrap: 'wrap',
</View> }}>
</View> <Headline style={{textAlign: 'center'}}>{item.name}</Headline>
<Button <Caption
icon={"check-circle-outline"} style={{
color={this.props.theme.colors.success} textAlign: 'center',
mode="text" lineHeight: 35,
> marginLeft: 10,
{ }}>
start == null ({i18n.t('screens.equipment.bail', {cost: item.caution})})
? i18n.t('screens.equipment.booking') </Caption>
: end != null && start.getTime() !== end.getTime() </View>
? i18n.t('screens.equipment.bookingPeriod', { </View>
begin: getRelativeDateString(start), <Button
end: getRelativeDateString(end) icon="check-circle-outline"
}) color={props.theme.colors.success}
: i18n.t('screens.equipment.bookingDay', { mode="text">
date: getRelativeDateString(start) {buttonText}
}) </Button>
} <Paragraph style={{textAlign: 'center'}}>
</Button> {i18n.t('screens.equipment.bookingConfirmedMessage')}
<Paragraph style={{textAlign: "center"}}> </Paragraph>
{i18n.t("screens.equipment.bookingConfirmedMessage")} </Card.Content>
</Paragraph> </Card>
</Card.Content> </CollapsibleScrollView>
</Card> );
</CollapsibleScrollView>
);
} else
return null;
} }
return null;
}
} }
export default withTheme(EquipmentConfirmScreen); export default withTheme(EquipmentConfirmScreen);

View file

@ -1,193 +1,197 @@
// @flow // @flow
import * as React from 'react'; import * as React from 'react';
import {View} from "react-native"; import {View} from 'react-native';
import {Button, withTheme} from 'react-native-paper'; import {Button, withTheme} from 'react-native-paper';
import AuthenticatedScreen from "../../../components/Amicale/AuthenticatedScreen"; import {StackNavigationProp} from '@react-navigation/stack';
import {StackNavigationProp} from "@react-navigation/stack"; import i18n from 'i18n-js';
import type {CustomTheme} from "../../../managers/ThemeManager"; import AuthenticatedScreen from '../../../components/Amicale/AuthenticatedScreen';
import i18n from "i18n-js"; import type {ClubType} from '../Clubs/ClubListScreen';
import type {club} from "../Clubs/ClubListScreen"; import EquipmentListItem from '../../../components/Lists/Equipment/EquipmentListItem';
import EquipmentListItem from "../../../components/Lists/Equipment/EquipmentListItem"; import MascotPopup from '../../../components/Mascot/MascotPopup';
import MascotPopup from "../../../components/Mascot/MascotPopup"; import {MASCOT_STYLE} from '../../../components/Mascot/Mascot';
import {MASCOT_STYLE} from "../../../components/Mascot/Mascot"; import AsyncStorageManager from '../../../managers/AsyncStorageManager';
import AsyncStorageManager from "../../../managers/AsyncStorageManager"; import CollapsibleFlatList from '../../../components/Collapsible/CollapsibleFlatList';
import CollapsibleFlatList from "../../../components/Collapsible/CollapsibleFlatList"; import type {ApiGenericDataType} from '../../../utils/WebData';
type Props = { type PropsType = {
navigation: StackNavigationProp, navigation: StackNavigationProp,
theme: CustomTheme,
}
type State = {
mascotDialogVisible: boolean,
}
export type Device = {
id: number,
name: string,
caution: number,
booked_at: Array<{ begin: string, end: string }>,
}; };
export type RentedDevice = { type StateType = {
device_id: number, mascotDialogVisible: boolean,
device_name: string, };
begin: string,
end: string, export type DeviceType = {
} id: number,
name: string,
caution: number,
booked_at: Array<{begin: string, end: string}>,
};
export type RentedDeviceType = {
device_id: number,
device_name: string,
begin: string,
end: string,
};
const LIST_ITEM_HEIGHT = 64; const LIST_ITEM_HEIGHT = 64;
class EquipmentListScreen extends React.Component<Props, State> { class EquipmentListScreen extends React.Component<PropsType, StateType> {
data: Array<DeviceType>;
state = { userRents: Array<RentedDeviceType>;
mascotDialogVisible: AsyncStorageManager.getBool(AsyncStorageManager.PREFERENCES.equipmentShowBanner.key),
}
data: Array<Device>; authRef: {current: null | AuthenticatedScreen};
userRents: Array<RentedDevice>;
authRef: { current: null | AuthenticatedScreen }; canRefresh: boolean;
canRefresh: boolean;
constructor(props: Props) { constructor(props: PropsType) {
super(props); super(props);
this.canRefresh = false; this.state = {
this.authRef = React.createRef(); mascotDialogVisible: AsyncStorageManager.getBool(
this.props.navigation.addListener('focus', this.onScreenFocus); AsyncStorageManager.PREFERENCES.equipmentShowBanner.key,
} ),
onScreenFocus = () => {
if (this.canRefresh && this.authRef.current != null)
this.authRef.current.reload();
this.canRefresh = true;
}; };
this.canRefresh = false;
this.authRef = React.createRef();
props.navigation.addListener('focus', this.onScreenFocus);
}
getRenderItem = ({item}: { item: Device }) => { onScreenFocus = () => {
return ( if (this.canRefresh && this.authRef.current != null)
<EquipmentListItem this.authRef.current.reload();
navigation={this.props.navigation} this.canRefresh = true;
item={item} };
userDeviceRentDates={this.getUserDeviceRentDates(item)}
height={LIST_ITEM_HEIGHT}/>
);
};
getUserDeviceRentDates(item: Device) { getRenderItem = ({item}: {item: DeviceType}): React.Node => {
let dates = null; const {navigation} = this.props;
for (let i = 0; i < this.userRents.length; i++) { return (
let device = this.userRents[i]; <EquipmentListItem
if (item.id === device.device_id) { navigation={navigation}
dates = [device.begin, device.end]; item={item}
break; userDeviceRentDates={this.getUserDeviceRentDates(item)}
} height={LIST_ITEM_HEIGHT}
} />
return dates; );
};
getUserDeviceRentDates(item: DeviceType): [number, number] | null {
let dates = null;
this.userRents.forEach((device: RentedDeviceType) => {
if (item.id === device.device_id) {
dates = [device.begin, device.end];
}
});
return dates;
}
/**
* Gets the list header, with explains this screen's purpose
*
* @returns {*}
*/
getListHeader(): React.Node {
return (
<View
style={{
width: '100%',
marginTop: 10,
marginBottom: 10,
}}>
<Button
mode="contained"
icon="help-circle"
onPress={this.showMascotDialog}
style={{
marginRight: 'auto',
marginLeft: 'auto',
}}>
{i18n.t('screens.equipment.mascotDialog.title')}
</Button>
</View>
);
}
keyExtractor = (item: ClubType): string => item.id.toString();
/**
* Gets the main screen component with the fetched data
*
* @param data The data fetched from the server
* @returns {*}
*/
getScreen = (data: Array<ApiGenericDataType | null>): React.Node => {
if (data[0] != null) {
const fetchedData = data[0];
if (fetchedData != null) this.data = fetchedData.devices;
} }
if (data[1] != null) {
/** const fetchedData = data[1];
* Gets the list header, with explains this screen's purpose if (fetchedData != null) this.userRents = fetchedData.locations;
*
* @returns {*}
*/
getListHeader() {
return (
<View style={{
width: "100%",
marginTop: 10,
marginBottom: 10,
}}>
<Button
mode={"contained"}
icon={"help-circle"}
onPress={this.showMascotDialog}
style={{
marginRight: "auto",
marginLeft: "auto",
}}>
{i18n.t("screens.equipment.mascotDialog.title")}
</Button>
</View>
);
} }
return (
<CollapsibleFlatList
keyExtractor={this.keyExtractor}
renderItem={this.getRenderItem}
ListHeaderComponent={this.getListHeader()}
data={this.data}
/>
);
};
keyExtractor = (item: club) => item.id.toString(); showMascotDialog = () => {
this.setState({mascotDialogVisible: true});
};
/** hideMascotDialog = () => {
* Gets the main screen component with the fetched data AsyncStorageManager.set(
* AsyncStorageManager.PREFERENCES.equipmentShowBanner.key,
* @param data The data fetched from the server false,
* @returns {*} );
*/ this.setState({mascotDialogVisible: false});
getScreen = (data: Array<{ [key: string]: any } | null>) => { };
if (data[0] != null) {
const fetchedData = data[0];
if (fetchedData != null)
this.data = fetchedData["devices"];
}
if (data[1] != null) {
const fetchedData = data[1];
if (fetchedData != null)
this.userRents = fetchedData["locations"];
}
return (
<CollapsibleFlatList
keyExtractor={this.keyExtractor}
renderItem={this.getRenderItem}
ListHeaderComponent={this.getListHeader()}
data={this.data}
/>
)
};
showMascotDialog = () => { render(): React.Node {
this.setState({mascotDialogVisible: true}) const {props, state} = this;
}; return (
<View style={{flex: 1}}>
hideMascotDialog = () => { <AuthenticatedScreen
AsyncStorageManager.set(AsyncStorageManager.PREFERENCES.equipmentShowBanner.key, false); navigation={props.navigation}
this.setState({mascotDialogVisible: false}) ref={this.authRef}
}; requests={[
{
render() { link: 'location/all',
return ( params: {},
<View style={{flex: 1}}> mandatory: true,
<AuthenticatedScreen },
{...this.props} {
ref={this.authRef} link: 'location/my',
requests={[ params: {},
{ mandatory: false,
link: 'location/all', },
params: {}, ]}
mandatory: true, renderFunction={this.getScreen}
}, />
{ <MascotPopup
link: 'location/my', visible={state.mascotDialogVisible}
params: {}, title={i18n.t('screens.equipment.mascotDialog.title')}
mandatory: false, message={i18n.t('screens.equipment.mascotDialog.message')}
} icon="vote"
]} buttons={{
renderFunction={this.getScreen} action: null,
/> cancel: {
<MascotPopup message: i18n.t('screens.equipment.mascotDialog.button'),
visible={this.state.mascotDialogVisible} icon: 'check',
title={i18n.t("screens.equipment.mascotDialog.title")} onPress: this.hideMascotDialog,
message={i18n.t("screens.equipment.mascotDialog.message")} },
icon={"vote"} }}
buttons={{ emotion={MASCOT_STYLE.WINK}
action: null, />
cancel: { </View>
message: i18n.t("screens.equipment.mascotDialog.button"), );
icon: "check", }
onPress: this.hideMascotDialog,
}
}}
emotion={MASCOT_STYLE.WINK}
/>
</View>
);
}
} }
export default withTheme(EquipmentListScreen); export default withTheme(EquipmentListScreen);

View file

@ -1,441 +1,441 @@
// @flow // @flow
import * as React from 'react'; import * as React from 'react';
import {Button, Caption, Card, Headline, Subheading, withTheme} from 'react-native-paper';
import {StackNavigationProp} from "@react-navigation/stack";
import type {CustomTheme} from "../../../managers/ThemeManager";
import type {Device} from "./EquipmentListScreen";
import {BackHandler, View} from "react-native";
import * as Animatable from "react-native-animatable";
import i18n from "i18n-js";
import {CalendarList} from "react-native-calendars";
import LoadingConfirmDialog from "../../../components/Dialogs/LoadingConfirmDialog";
import ErrorDialog from "../../../components/Dialogs/ErrorDialog";
import { import {
generateMarkedDates, Button,
getFirstEquipmentAvailability, Caption,
getISODate, Card,
getRelativeDateString, Headline,
getValidRange, Subheading,
isEquipmentAvailable withTheme,
} from "../../../utils/EquipmentBooking"; } from 'react-native-paper';
import ConnectionManager from "../../../managers/ConnectionManager"; import {StackNavigationProp} from '@react-navigation/stack';
import CollapsibleScrollView from "../../../components/Collapsible/CollapsibleScrollView"; import {BackHandler, View} from 'react-native';
import * as Animatable from 'react-native-animatable';
import i18n from 'i18n-js';
import {CalendarList} from 'react-native-calendars';
import type {DeviceType} from './EquipmentListScreen';
import type {CustomTheme} from '../../../managers/ThemeManager';
import LoadingConfirmDialog from '../../../components/Dialogs/LoadingConfirmDialog';
import ErrorDialog from '../../../components/Dialogs/ErrorDialog';
import {
generateMarkedDates,
getFirstEquipmentAvailability,
getISODate,
getRelativeDateString,
getValidRange,
isEquipmentAvailable,
} from '../../../utils/EquipmentBooking';
import ConnectionManager from '../../../managers/ConnectionManager';
import CollapsibleScrollView from '../../../components/Collapsible/CollapsibleScrollView';
type Props = { type PropsType = {
navigation: StackNavigationProp, navigation: StackNavigationProp,
route: { route: {
params?: { params?: {
item?: Device, item?: DeviceType,
},
}, },
theme: CustomTheme, },
} theme: CustomTheme,
};
type State = { export type MarkedDatesObjectType = {
dialogVisible: boolean, [key: string]: {startingDay: boolean, endingDay: boolean, color: string},
errorDialogVisible: boolean, };
markedDates: { [key: string]: { startingDay: boolean, endingDay: boolean, color: string } },
currentError: number,
}
class EquipmentRentScreen extends React.Component<Props, State> { type StateType = {
dialogVisible: boolean,
errorDialogVisible: boolean,
markedDates: MarkedDatesObjectType,
currentError: number,
};
state = { class EquipmentRentScreen extends React.Component<PropsType, StateType> {
dialogVisible: false, item: DeviceType | null;
errorDialogVisible: false,
markedDates: {},
currentError: 0,
}
item: Device | null; bookedDates: Array<string>;
bookedDates: Array<string>;
bookRef: { current: null | Animatable.View } bookRef: {current: null | Animatable.View};
canBookEquipment: boolean;
lockedDates: { [key: string]: { startingDay: boolean, endingDay: boolean, color: string } } canBookEquipment: boolean;
constructor(props: Props) { lockedDates: {
super(props); [key: string]: {startingDay: boolean, endingDay: boolean, color: string},
this.resetSelection(); };
this.bookRef = React.createRef();
this.canBookEquipment = false;
this.bookedDates = [];
if (this.props.route.params != null) {
if (this.props.route.params.item != null)
this.item = this.props.route.params.item;
else
this.item = null;
}
const item = this.item;
if (item != null) {
this.lockedDates = {};
for (let i = 0; i < item.booked_at.length; i++) {
const range = getValidRange(new Date(item.booked_at[i].begin), new Date(item.booked_at[i].end), null);
this.lockedDates = {
...this.lockedDates,
...generateMarkedDates(
false,
this.props.theme,
range
)
};
}
}
} constructor(props: PropsType) {
super(props);
/** this.state = {
* Captures focus and blur events to hook on android back button dialogVisible: false,
*/ errorDialogVisible: false,
componentDidMount() { markedDates: {},
this.props.navigation.addListener( currentError: 0,
'focus',
() =>
BackHandler.addEventListener(
'hardwareBackPress',
this.onBackButtonPressAndroid
)
);
this.props.navigation.addListener(
'blur',
() =>
BackHandler.removeEventListener(
'hardwareBackPress',
this.onBackButtonPressAndroid
)
);
}
/**
* Overrides default android back button behaviour to deselect date if any is selected.
*
* @return {boolean}
*/
onBackButtonPressAndroid = () => {
if (this.bookedDates.length > 0) {
this.resetSelection();
this.updateMarkedSelection();
return true;
} else
return false;
}; };
this.resetSelection();
/** this.bookRef = React.createRef();
* Selects a new date on the calendar. this.canBookEquipment = false;
* If both start and end dates are already selected, unselect all. this.bookedDates = [];
* if (props.route.params != null) {
* @param day The day selected if (props.route.params.item != null) this.item = props.route.params.item;
*/ else this.item = null;
selectNewDate = (day: { dateString: string, day: number, month: number, timestamp: number, year: number }) => {
const selected = new Date(day.dateString);
const start = this.getBookStartDate();
if (!(this.lockedDates.hasOwnProperty(day.dateString))) {
if (start === null) {
this.updateSelectionRange(selected, selected);
this.enableBooking();
} else if (start.getTime() === selected.getTime()) {
this.resetSelection();
} else if (this.bookedDates.length === 1) {
this.updateSelectionRange(start, selected);
this.enableBooking();
} else
this.resetSelection();
this.updateMarkedSelection();
}
} }
const {item} = this;
updateSelectionRange(start: Date, end: Date) { if (item != null) {
this.bookedDates = getValidRange(start, end, this.item); this.lockedDates = {};
item.booked_at.forEach((date: {begin: string, end: string}) => {
const range = getValidRange(
new Date(date.begin),
new Date(date.end),
null,
);
this.lockedDates = {
...this.lockedDates,
...generateMarkedDates(false, props.theme, range),
};
});
} }
}
updateMarkedSelection() { /**
this.setState({ * Captures focus and blur events to hook on android back button
markedDates: generateMarkedDates( */
true, componentDidMount() {
this.props.theme, const {navigation} = this.props;
this.bookedDates navigation.addListener('focus', () => {
), BackHandler.addEventListener(
}); 'hardwareBackPress',
this.onBackButtonPressAndroid,
);
});
navigation.addListener('blur', () => {
BackHandler.removeEventListener(
'hardwareBackPress',
this.onBackButtonPressAndroid,
);
});
}
/**
* Overrides default android back button behaviour to deselect date if any is selected.
*
* @return {boolean}
*/
onBackButtonPressAndroid = (): boolean => {
if (this.bookedDates.length > 0) {
this.resetSelection();
this.updateMarkedSelection();
return true;
} }
return false;
};
enableBooking() { onDialogDismiss = () => {
if (!this.canBookEquipment) { this.setState({dialogVisible: false});
this.showBookButton(); };
this.canBookEquipment = true;
} onErrorDialogDismiss = () => {
this.setState({errorDialogVisible: false});
};
/**
* Sends the selected data to the server and waits for a response.
* If the request is a success, navigate to the recap screen.
* If it is an error, display the error to the user.
*
* @returns {Promise<void>}
*/
onDialogAccept = (): Promise<void> => {
return new Promise((resolve: () => void) => {
const {item, props} = this;
const start = this.getBookStartDate();
const end = this.getBookEndDate();
if (item != null && start != null && end != null) {
ConnectionManager.getInstance()
.authenticatedRequest('location/booking', {
device: item.id,
begin: getISODate(start),
end: getISODate(end),
})
.then(() => {
this.onDialogDismiss();
props.navigation.replace('equipment-confirm', {
item: this.item,
dates: [getISODate(start), getISODate(end)],
});
resolve();
})
.catch((error: number) => {
this.onDialogDismiss();
this.showErrorDialog(error);
resolve();
});
} else {
this.onDialogDismiss();
resolve();
}
});
};
getBookStartDate(): Date | null {
return this.bookedDates.length > 0 ? new Date(this.bookedDates[0]) : null;
}
getBookEndDate(): Date | null {
const {length} = this.bookedDates;
return length > 0 ? new Date(this.bookedDates[length - 1]) : null;
}
/**
* Selects a new date on the calendar.
* If both start and end dates are already selected, unselect all.
*
* @param day The day selected
*/
selectNewDate = (day: {
dateString: string,
day: number,
month: number,
timestamp: number,
year: number,
}) => {
const selected = new Date(day.dateString);
const start = this.getBookStartDate();
if (!this.lockedDates[day.dateString] != null) {
if (start === null) {
this.updateSelectionRange(selected, selected);
this.enableBooking();
} else if (start.getTime() === selected.getTime()) {
this.resetSelection();
} else if (this.bookedDates.length === 1) {
this.updateSelectionRange(start, selected);
this.enableBooking();
} else this.resetSelection();
this.updateMarkedSelection();
} }
};
resetSelection() { showErrorDialog = (error: number) => {
if (this.canBookEquipment) this.setState({
this.hideBookButton(); errorDialogVisible: true,
this.canBookEquipment = false; currentError: error,
this.bookedDates = []; });
};
showDialog = () => {
this.setState({dialogVisible: true});
};
/**
* Shows the book button by plying a fade animation
*/
showBookButton() {
if (this.bookRef.current != null) {
this.bookRef.current.fadeInUp(500);
} }
}
/** /**
* Shows the book button by plying a fade animation * Hides the book button by plying a fade animation
*/ */
showBookButton() { hideBookButton() {
if (this.bookRef.current != null) { if (this.bookRef.current != null) {
this.bookRef.current.fadeInUp(500); this.bookRef.current.fadeOutDown(500);
}
} }
}
/** enableBooking() {
* Hides the book button by plying a fade animation if (!this.canBookEquipment) {
*/ this.showBookButton();
hideBookButton() { this.canBookEquipment = true;
if (this.bookRef.current != null) {
this.bookRef.current.fadeOutDown(500);
}
} }
}
showDialog = () => { resetSelection() {
this.setState({dialogVisible: true}); if (this.canBookEquipment) this.hideBookButton();
} this.canBookEquipment = false;
this.bookedDates = [];
}
showErrorDialog = (error: number) => { updateSelectionRange(start: Date, end: Date) {
this.setState({ this.bookedDates = getValidRange(start, end, this.item);
errorDialogVisible: true, }
currentError: error,
});
}
onDialogDismiss = () => { updateMarkedSelection() {
this.setState({dialogVisible: false}); const {theme} = this.props;
} this.setState({
markedDates: generateMarkedDates(true, theme, this.bookedDates),
});
}
onErrorDialogDismiss = () => { render(): React.Node {
this.setState({errorDialogVisible: false}); const {item, props, state} = this;
} const start = this.getBookStartDate();
const end = this.getBookEndDate();
/** let subHeadingText;
* Sends the selected data to the server and waits for a response. if (start == null) subHeadingText = i18n.t('screens.equipment.booking');
* If the request is a success, navigate to the recap screen. else if (end != null && start.getTime() !== end.getTime())
* If it is an error, display the error to the user. subHeadingText = i18n.t('screens.equipment.bookingPeriod', {
* begin: getRelativeDateString(start),
* @returns {Promise<R>} end: getRelativeDateString(end),
*/ });
onDialogAccept = () => { else
return new Promise((resolve) => { i18n.t('screens.equipment.bookingDay', {
const item = this.item; date: getRelativeDateString(start),
const start = this.getBookStartDate(); });
const end = this.getBookEndDate(); if (item != null) {
if (item != null && start != null && end != null) { const isAvailable = isEquipmentAvailable(item);
console.log({ const firstAvailability = getFirstEquipmentAvailability(item);
"device": item.id, return (
"begin": getISODate(start), <View style={{flex: 1}}>
"end": getISODate(end), <CollapsibleScrollView>
}) <Card style={{margin: 5}}>
ConnectionManager.getInstance().authenticatedRequest( <Card.Content>
"location/booking",
{
"device": item.id,
"begin": getISODate(start),
"end": getISODate(end),
})
.then(() => {
this.onDialogDismiss();
this.props.navigation.replace("equipment-confirm", {
item: this.item,
dates: [getISODate(start), getISODate(end)]
});
resolve();
})
.catch((error: number) => {
this.onDialogDismiss();
this.showErrorDialog(error);
resolve();
});
} else {
this.onDialogDismiss();
resolve();
}
});
}
getBookStartDate() {
return this.bookedDates.length > 0 ? new Date(this.bookedDates[0]) : null;
}
getBookEndDate() {
const length = this.bookedDates.length;
return length > 0 ? new Date(this.bookedDates[length - 1]) : null;
}
render() {
const item = this.item;
const start = this.getBookStartDate();
const end = this.getBookEndDate();
if (item != null) {
const isAvailable = isEquipmentAvailable(item);
const firstAvailability = getFirstEquipmentAvailability(item);
return (
<View style={{flex: 1}}> <View style={{flex: 1}}>
<CollapsibleScrollView> <View
<Card style={{margin: 5}}> style={{
<Card.Content> marginLeft: 'auto',
<View style={{flex: 1}}> marginRight: 'auto',
<View style={{ flexDirection: 'row',
marginLeft: "auto", flexWrap: 'wrap',
marginRight: "auto", }}>
flexDirection: "row", <Headline style={{textAlign: 'center'}}>
flexWrap: "wrap", {item.name}
}}> </Headline>
<Headline style={{textAlign: "center"}}> <Caption
{item.name} style={{
</Headline> textAlign: 'center',
<Caption style={{ lineHeight: 35,
textAlign: "center", marginLeft: 10,
lineHeight: 35, }}>
marginLeft: 10, ({i18n.t('screens.equipment.bail', {cost: item.caution})})
}}> </Caption>
({i18n.t('screens.equipment.bail', {cost: item.caution})}) </View>
</Caption>
</View>
</View>
<Button
icon={isAvailable ? "check-circle-outline" : "update"}
color={isAvailable ? this.props.theme.colors.success : this.props.theme.colors.primary}
mode="text"
>
{i18n.t('screens.equipment.available', {date: getRelativeDateString(firstAvailability)})}
</Button>
<Subheading style={{
textAlign: "center",
marginBottom: 10,
minHeight: 50
}}>
{
start == null
? i18n.t('screens.equipment.booking')
: end != null && start.getTime() !== end.getTime()
? i18n.t('screens.equipment.bookingPeriod', {
begin: getRelativeDateString(start),
end: getRelativeDateString(end)
})
: i18n.t('screens.equipment.bookingDay', {
date: getRelativeDateString(start)
})
}
</Subheading>
</Card.Content>
</Card>
<CalendarList
// Minimum date that can be selected, dates before minDate will be grayed out. Default = undefined
minDate={new Date()}
// Max amount of months allowed to scroll to the past. Default = 50
pastScrollRange={0}
// Max amount of months allowed to scroll to the future. Default = 50
futureScrollRange={3}
// Enable horizontal scrolling, default = false
horizontal={true}
// Enable paging on horizontal, default = false
pagingEnabled={true}
// Handler which gets executed on day press. Default = undefined
onDayPress={this.selectNewDate}
// If firstDay=1 week starts from Monday. Note that dayNames and dayNamesShort should still start from Sunday.
firstDay={1}
// Disable all touch events for disabled days. can be override with disableTouchEvent in markedDates
disableAllTouchEventsForDisabledDays={true}
// Hide month navigation arrows.
hideArrows={false}
// Date marking style [simple/period/multi-dot/custom]. Default = 'simple'
markingType={'period'}
markedDates={{...this.lockedDates, ...this.state.markedDates}}
theme={{
backgroundColor: this.props.theme.colors.agendaBackgroundColor,
calendarBackground: this.props.theme.colors.background,
textSectionTitleColor: this.props.theme.colors.agendaDayTextColor,
selectedDayBackgroundColor: this.props.theme.colors.primary,
selectedDayTextColor: '#ffffff',
todayTextColor: this.props.theme.colors.text,
dayTextColor: this.props.theme.colors.text,
textDisabledColor: this.props.theme.colors.agendaDayTextColor,
dotColor: this.props.theme.colors.primary,
selectedDotColor: '#ffffff',
arrowColor: this.props.theme.colors.primary,
monthTextColor: this.props.theme.colors.text,
indicatorColor: this.props.theme.colors.primary,
textDayFontFamily: 'monospace',
textMonthFontFamily: 'monospace',
textDayHeaderFontFamily: 'monospace',
textDayFontWeight: '300',
textMonthFontWeight: 'bold',
textDayHeaderFontWeight: '300',
textDayFontSize: 16,
textMonthFontSize: 16,
textDayHeaderFontSize: 16,
'stylesheet.day.period': {
base: {
overflow: 'hidden',
height: 34,
width: 34,
alignItems: 'center',
}
}
}}
style={{marginBottom: 50}}
/>
</CollapsibleScrollView>
<LoadingConfirmDialog
visible={this.state.dialogVisible}
onDismiss={this.onDialogDismiss}
onAccept={this.onDialogAccept}
title={i18n.t('screens.equipment.dialogTitle')}
titleLoading={i18n.t('screens.equipment.dialogTitleLoading')}
message={i18n.t('screens.equipment.dialogMessage')}
/>
<ErrorDialog
visible={this.state.errorDialogVisible}
onDismiss={this.onErrorDialogDismiss}
errorCode={this.state.currentError}
/>
<Animatable.View
ref={this.bookRef}
style={{
position: "absolute",
bottom: 0,
left: 0,
width: "100%",
flex: 1,
transform: [
{translateY: 100},
]
}}>
<Button
icon="bookmark-check"
mode="contained"
onPress={this.showDialog}
style={{
width: "80%",
flex: 1,
marginLeft: "auto",
marginRight: "auto",
marginBottom: 20,
borderRadius: 10
}}
>
{i18n.t('screens.equipment.bookButton')}
</Button>
</Animatable.View>
</View> </View>
) <Button
} else icon={isAvailable ? 'check-circle-outline' : 'update'}
return <View/>; color={
} isAvailable
? props.theme.colors.success
: props.theme.colors.primary
}
mode="text">
{i18n.t('screens.equipment.available', {
date: getRelativeDateString(firstAvailability),
})}
</Button>
<Subheading
style={{
textAlign: 'center',
marginBottom: 10,
minHeight: 50,
}}>
{subHeadingText}
</Subheading>
</Card.Content>
</Card>
<CalendarList
// Minimum date that can be selected, dates before minDate will be grayed out. Default = undefined
minDate={new Date()}
// Max amount of months allowed to scroll to the past. Default = 50
pastScrollRange={0}
// Max amount of months allowed to scroll to the future. Default = 50
futureScrollRange={3}
// Enable horizontal scrolling, default = false
horizontal
// Enable paging on horizontal, default = false
pagingEnabled
// Handler which gets executed on day press. Default = undefined
onDayPress={this.selectNewDate}
// If firstDay=1 week starts from Monday. Note that dayNames and dayNamesShort should still start from Sunday.
firstDay={1}
// Disable all touch events for disabled days. can be override with disableTouchEvent in markedDates
disableAllTouchEventsForDisabledDays
// Hide month navigation arrows.
hideArrows={false}
// Date marking style [simple/period/multi-dot/custom]. Default = 'simple'
markingType="period"
markedDates={{...this.lockedDates, ...state.markedDates}}
theme={{
backgroundColor: props.theme.colors.agendaBackgroundColor,
calendarBackground: props.theme.colors.background,
textSectionTitleColor: props.theme.colors.agendaDayTextColor,
selectedDayBackgroundColor: props.theme.colors.primary,
selectedDayTextColor: '#ffffff',
todayTextColor: props.theme.colors.text,
dayTextColor: props.theme.colors.text,
textDisabledColor: props.theme.colors.agendaDayTextColor,
dotColor: props.theme.colors.primary,
selectedDotColor: '#ffffff',
arrowColor: props.theme.colors.primary,
monthTextColor: props.theme.colors.text,
indicatorColor: props.theme.colors.primary,
textDayFontFamily: 'monospace',
textMonthFontFamily: 'monospace',
textDayHeaderFontFamily: 'monospace',
textDayFontWeight: '300',
textMonthFontWeight: 'bold',
textDayHeaderFontWeight: '300',
textDayFontSize: 16,
textMonthFontSize: 16,
textDayHeaderFontSize: 16,
'stylesheet.day.period': {
base: {
overflow: 'hidden',
height: 34,
width: 34,
alignItems: 'center',
},
},
}}
style={{marginBottom: 50}}
/>
</CollapsibleScrollView>
<LoadingConfirmDialog
visible={state.dialogVisible}
onDismiss={this.onDialogDismiss}
onAccept={this.onDialogAccept}
title={i18n.t('screens.equipment.dialogTitle')}
titleLoading={i18n.t('screens.equipment.dialogTitleLoading')}
message={i18n.t('screens.equipment.dialogMessage')}
/>
<ErrorDialog
visible={state.errorDialogVisible}
onDismiss={this.onErrorDialogDismiss}
errorCode={state.currentError}
/>
<Animatable.View
ref={this.bookRef}
style={{
position: 'absolute',
bottom: 0,
left: 0,
width: '100%',
flex: 1,
transform: [{translateY: 100}],
}}>
<Button
icon="bookmark-check"
mode="contained"
onPress={this.showDialog}
style={{
width: '80%',
flex: 1,
marginLeft: 'auto',
marginRight: 'auto',
marginBottom: 20,
borderRadius: 10,
}}>
{i18n.t('screens.equipment.bookButton')}
</Button>
</Animatable.View>
</View>
);
}
return null;
}
} }
export default withTheme(EquipmentRentScreen); export default withTheme(EquipmentRentScreen);

View file

@ -1,148 +1,166 @@
// @flow // @flow
import * as React from 'react'; import * as React from 'react';
import {StackNavigationProp} from "@react-navigation/stack"; import {StackNavigationProp} from '@react-navigation/stack';
import type {CustomTheme} from "../../../managers/ThemeManager"; import {Button, Card, Paragraph, withTheme} from 'react-native-paper';
import {Button, Card, Paragraph, withTheme} from "react-native-paper"; import {FlatList} from 'react-native';
import type {ServiceCategory, ServiceItem} from "../../../managers/ServicesManager"; import {View} from 'react-native-animatable';
import DashboardManager from "../../../managers/DashboardManager"; import i18n from 'i18n-js';
import DashboardItem from "../../../components/Home/EventDashboardItem"; import type {
import {FlatList} from "react-native"; ServiceCategoryType,
import {View} from "react-native-animatable"; ServiceItemType,
import DashboardEditAccordion from "../../../components/Lists/DashboardEdit/DashboardEditAccordion"; } from '../../../managers/ServicesManager';
import DashboardEditPreviewItem from "../../../components/Lists/DashboardEdit/DashboardEditPreviewItem"; import DashboardManager from '../../../managers/DashboardManager';
import AsyncStorageManager from "../../../managers/AsyncStorageManager"; import DashboardItem from '../../../components/Home/EventDashboardItem';
import i18n from "i18n-js"; import DashboardEditAccordion from '../../../components/Lists/DashboardEdit/DashboardEditAccordion';
import CollapsibleFlatList from "../../../components/Collapsible/CollapsibleFlatList"; import DashboardEditPreviewItem from '../../../components/Lists/DashboardEdit/DashboardEditPreviewItem';
import AsyncStorageManager from '../../../managers/AsyncStorageManager';
import CollapsibleFlatList from '../../../components/Collapsible/CollapsibleFlatList';
type Props = { type PropsType = {
navigation: StackNavigationProp, navigation: StackNavigationProp,
theme: CustomTheme,
}; };
type State = { type StateType = {
currentDashboard: Array<ServiceItem>, currentDashboard: Array<ServiceItemType | null>,
currentDashboardIdList: Array<string>, currentDashboardIdList: Array<string>,
activeItem: number, activeItem: number,
}; };
/** /**
* Class defining the Settings screen. This screen shows controls to modify app preferences. * Class defining the Settings screen. This screen shows controls to modify app preferences.
*/ */
class DashboardEditScreen extends React.Component<Props, State> { class DashboardEditScreen extends React.Component<PropsType, StateType> {
content: Array<ServiceCategoryType>;
content: Array<ServiceCategory>; initialDashboard: Array<ServiceItemType | null>;
initialDashboard: Array<ServiceItem>;
initialDashboardIdList: Array<string>;
constructor(props: Props) { initialDashboardIdList: Array<string>;
super(props);
let dashboardManager = new DashboardManager(this.props.navigation);
this.initialDashboardIdList = AsyncStorageManager.getObject(AsyncStorageManager.PREFERENCES.dashboardItems.key);
this.initialDashboard = dashboardManager.getCurrentDashboard();
this.state = {
currentDashboard: [...this.initialDashboard],
currentDashboardIdList: [...this.initialDashboardIdList],
activeItem: 0,
}
this.content = dashboardManager.getCategories();
}
dashboardRowRenderItem = ({item, index}: { item: DashboardItem, index: number }) => { constructor(props: PropsType) {
return ( super(props);
<DashboardEditPreviewItem const dashboardManager = new DashboardManager(props.navigation);
image={item.image} this.initialDashboardIdList = AsyncStorageManager.getObject(
onPress={() => this.setState({activeItem: index})} AsyncStorageManager.PREFERENCES.dashboardItems.key,
isActive={this.state.activeItem === index} );
/> this.initialDashboard = dashboardManager.getCurrentDashboard();
); this.state = {
currentDashboard: [...this.initialDashboard],
currentDashboardIdList: [...this.initialDashboardIdList],
activeItem: 0,
}; };
this.content = dashboardManager.getCategories();
}
getDashboard(content: Array<DashboardItem>) { getDashboardRowRenderItem = ({
return ( item,
<FlatList index,
data={content} }: {
extraData={this.state} item: DashboardItem,
renderItem={this.dashboardRowRenderItem} index: number,
horizontal={true} }): React.Node => {
contentContainerStyle={{ const {activeItem} = this.state;
marginLeft: 'auto', return (
marginRight: 'auto', <DashboardEditPreviewItem
marginTop: 5, image={item.image}
}} onPress={() => {
/>); this.setState({activeItem: index});
} }}
isActive={activeItem === index}
/>
);
};
renderItem = ({item}: { item: ServiceCategory }) => { getDashboard(content: Array<DashboardItem>): React.Node {
return ( return (
<DashboardEditAccordion <FlatList
item={item} data={content}
onPress={this.updateDashboard} extraData={this.state}
activeDashboard={this.state.currentDashboardIdList} renderItem={this.getDashboardRowRenderItem}
/> horizontal
); contentContainerStyle={{
}; marginLeft: 'auto',
marginRight: 'auto',
marginTop: 5,
}}
/>
);
}
updateDashboard = (service: ServiceItem) => { getRenderItem = ({item}: {item: ServiceCategoryType}): React.Node => {
let currentDashboard = this.state.currentDashboard; const {currentDashboardIdList} = this.state;
let currentDashboardIdList = this.state.currentDashboardIdList; return (
currentDashboard[this.state.activeItem] = service; <DashboardEditAccordion
currentDashboardIdList[this.state.activeItem] = service.key; item={item}
this.setState({ onPress={this.updateDashboard}
currentDashboard: currentDashboard, activeDashboard={currentDashboardIdList}
currentDashboardIdList: currentDashboardIdList, />
}); );
AsyncStorageManager.set(AsyncStorageManager.PREFERENCES.dashboardItems.key, currentDashboardIdList); };
}
undoDashboard = () => { getListHeader(): React.Node {
this.setState({ const {currentDashboard} = this.state;
currentDashboard: [...this.initialDashboard], return (
currentDashboardIdList: [...this.initialDashboardIdList] <Card style={{margin: 5}}>
}); <Card.Content>
AsyncStorageManager.set(AsyncStorageManager.PREFERENCES.dashboardItems.key, this.initialDashboardIdList); <View style={{padding: 5}}>
} <Button
mode="contained"
onPress={this.undoDashboard}
style={{
marginLeft: 'auto',
marginRight: 'auto',
marginBottom: 10,
}}>
{i18n.t('screens.settings.dashboardEdit.undo')}
</Button>
<View style={{height: 50}}>
{this.getDashboard(currentDashboard)}
</View>
</View>
<Paragraph style={{textAlign: 'center'}}>
{i18n.t('screens.settings.dashboardEdit.message')}
</Paragraph>
</Card.Content>
</Card>
);
}
getListHeader() { updateDashboard = (service: ServiceItemType) => {
return ( const {currentDashboard, currentDashboardIdList, activeItem} = this.state;
<Card style={{margin: 5}}> currentDashboard[activeItem] = service;
<Card.Content> currentDashboardIdList[activeItem] = service.key;
<View style={{padding: 5}}> this.setState({
<Button currentDashboard,
mode={"contained"} currentDashboardIdList,
onPress={this.undoDashboard} });
style={{ AsyncStorageManager.set(
marginLeft: "auto", AsyncStorageManager.PREFERENCES.dashboardItems.key,
marginRight: "auto", currentDashboardIdList,
marginBottom: 10, );
}} };
>
{i18n.t("screens.settings.dashboardEdit.undo")}
</Button>
<View style={{height: 50}}>
{this.getDashboard(this.state.currentDashboard)}
</View>
</View>
<Paragraph style={{textAlign: "center"}}>
{i18n.t("screens.settings.dashboardEdit.message")}
</Paragraph>
</Card.Content>
</Card>
);
}
undoDashboard = () => {
this.setState({
currentDashboard: [...this.initialDashboard],
currentDashboardIdList: [...this.initialDashboardIdList],
});
AsyncStorageManager.set(
AsyncStorageManager.PREFERENCES.dashboardItems.key,
this.initialDashboardIdList,
);
};
render() { render(): React.Node {
return ( return (
<CollapsibleFlatList <CollapsibleFlatList
data={this.content} data={this.content}
renderItem={this.renderItem} renderItem={this.getRenderItem}
ListHeaderComponent={this.getListHeader()} ListHeaderComponent={this.getListHeader()}
style={{}} style={{}}
/> />
); );
} }
} }
export default withTheme(DashboardEditScreen); export default withTheme(DashboardEditScreen);

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);

View file

@ -2,58 +2,74 @@
import * as React from 'react'; import * as React from 'react';
import {Image, View} from 'react-native'; import {Image, View} from 'react-native';
import i18n from "i18n-js"; import i18n from 'i18n-js';
import {Card, List, Paragraph, Text} from 'react-native-paper'; import {Card, List, Paragraph, Text} from 'react-native-paper';
import CustomTabBar from "../../../components/Tabbar/CustomTabBar"; import CustomTabBar from '../../../components/Tabbar/CustomTabBar';
import {StackNavigationProp} from "@react-navigation/stack"; import CollapsibleScrollView from '../../../components/Collapsible/CollapsibleScrollView';
import CollapsibleScrollView from "../../../components/Collapsible/CollapsibleScrollView";
type Props = { const LOGO = 'https://etud.insa-toulouse.fr/~amicale_app/images/Proximo.png';
navigation: StackNavigationProp,
};
const LOGO = "https://etud.insa-toulouse.fr/~amicale_app/images/Proximo.png";
/** /**
* Class defining the proximo about screen. * Class defining the proximo about screen.
*/ */
export default class ProximoAboutScreen extends React.Component<Props> { // eslint-disable-next-line react/prefer-stateless-function
export default class ProximoAboutScreen extends React.Component<null> {
render() { render(): React.Node {
return ( return (
<CollapsibleScrollView style={{padding: 5}}> <CollapsibleScrollView style={{padding: 5}}>
<View style={{ <View
width: '100%', style={{
height: 100, width: '100%',
marginTop: 20, height: 100,
marginBottom: 20, marginTop: 20,
justifyContent: 'center', marginBottom: 20,
alignItems: 'center' justifyContent: 'center',
}}> alignItems: 'center',
<Image }}>
source={{uri: LOGO}} <Image
style={{height: '100%', width: '100%', resizeMode: "contain"}}/> source={{uri: LOGO}}
</View> style={{height: '100%', width: '100%', resizeMode: 'contain'}}
<Text>{i18n.t('screens.proximo.description')}</Text> />
<Card style={{margin: 5}}> </View>
<Card.Title <Text>{i18n.t('screens.proximo.description')}</Text>
title={i18n.t('screens.proximo.openingHours')} <Card style={{margin: 5}}>
left={props => <List.Icon {...props} icon={'clock-outline'}/>} <Card.Title
/> title={i18n.t('screens.proximo.openingHours')}
<Card.Content> left={({
<Paragraph>18h30 - 19h30</Paragraph> size,
</Card.Content> color,
</Card> }: {
<Card style={{margin: 5, marginBottom: CustomTabBar.TAB_BAR_HEIGHT + 20}}> size: number,
<Card.Title color: string,
title={i18n.t('screens.proximo.paymentMethods')} }): React.Node => (
left={props => <List.Icon {...props} icon={'cash'}/>} <List.Icon size={size} color={color} icon="clock-outline" />
/> )}
<Card.Content> />
<Paragraph>{i18n.t('screens.proximo.paymentMethodsDescription')}</Paragraph> <Card.Content>
</Card.Content> <Paragraph>18h30 - 19h30</Paragraph>
</Card> </Card.Content>
</CollapsibleScrollView> </Card>
); <Card
} style={{margin: 5, marginBottom: CustomTabBar.TAB_BAR_HEIGHT + 20}}>
<Card.Title
title={i18n.t('screens.proximo.paymentMethods')}
left={({
size,
color,
}: {
size: number,
color: string,
}): React.Node => (
<List.Icon size={size} color={color} icon="cash" />
)}
/>
<Card.Content>
<Paragraph>
{i18n.t('screens.proximo.paymentMethodsDescription')}
</Paragraph>
</Card.Content>
</Card>
</CollapsibleScrollView>
);
}
} }

View file

@ -1,323 +1,381 @@
// @flow // @flow
import * as React from 'react'; import * as React from 'react';
import {Image, Platform, ScrollView, View} from "react-native"; import {Image, Platform, ScrollView, View} from 'react-native';
import i18n from "i18n-js"; import i18n from 'i18n-js';
import CustomModal from "../../../components/Overrides/CustomModal"; import {
import {RadioButton, Searchbar, Subheading, Text, Title, withTheme} from "react-native-paper"; RadioButton,
import {stringMatchQuery} from "../../../utils/Search"; Searchbar,
import ProximoListItem from "../../../components/Lists/Proximo/ProximoListItem"; Subheading,
import MaterialHeaderButtons, {Item} from "../../../components/Overrides/CustomHeaderButton"; Text,
import {StackNavigationProp} from "@react-navigation/stack"; Title,
import type {CustomTheme} from "../../../managers/ThemeManager"; withTheme,
import CollapsibleFlatList from "../../../components/Collapsible/CollapsibleFlatList"; } from 'react-native-paper';
import {StackNavigationProp} from '@react-navigation/stack';
import {Modalize} from 'react-native-modalize';
import CustomModal from '../../../components/Overrides/CustomModal';
import {stringMatchQuery} from '../../../utils/Search';
import ProximoListItem from '../../../components/Lists/Proximo/ProximoListItem';
import MaterialHeaderButtons, {
Item,
} from '../../../components/Overrides/CustomHeaderButton';
import type {CustomTheme} from '../../../managers/ThemeManager';
import CollapsibleFlatList from '../../../components/Collapsible/CollapsibleFlatList';
import type {ProximoArticleType} from './ProximoMainScreen';
function sortPrice(a, b) { function sortPrice(a: ProximoArticleType, b: ProximoArticleType): number {
return a.price - b.price; return parseInt(a.price, 10) - parseInt(b.price, 10);
} }
function sortPriceReverse(a, b) { function sortPriceReverse(
return b.price - a.price; a: ProximoArticleType,
b: ProximoArticleType,
): number {
return parseInt(b.price, 10) - parseInt(a.price, 10);
} }
function sortName(a, b) { function sortName(a: ProximoArticleType, b: ProximoArticleType): number {
if (a.name.toLowerCase() < b.name.toLowerCase()) if (a.name.toLowerCase() < b.name.toLowerCase()) return -1;
return -1; if (a.name.toLowerCase() > b.name.toLowerCase()) return 1;
if (a.name.toLowerCase() > b.name.toLowerCase()) return 0;
return 1;
return 0;
} }
function sortNameReverse(a, b) { function sortNameReverse(a: ProximoArticleType, b: ProximoArticleType): number {
if (a.name.toLowerCase() < b.name.toLowerCase()) if (a.name.toLowerCase() < b.name.toLowerCase()) return 1;
return 1; if (a.name.toLowerCase() > b.name.toLowerCase()) return -1;
if (a.name.toLowerCase() > b.name.toLowerCase()) return 0;
return -1;
return 0;
} }
const LIST_ITEM_HEIGHT = 84; const LIST_ITEM_HEIGHT = 84;
type Props = { type PropsType = {
navigation: StackNavigationProp, navigation: StackNavigationProp,
route: { params: { data: { data: Object }, shouldFocusSearchBar: boolean } }, route: {
theme: CustomTheme, params: {
} data: {data: Array<ProximoArticleType>},
shouldFocusSearchBar: boolean,
},
},
theme: CustomTheme,
};
type State = { type StateType = {
currentSortMode: number, currentSortMode: number,
modalCurrentDisplayItem: React.Node, modalCurrentDisplayItem: React.Node,
currentSearchString: string, currentSearchString: string,
}; };
/** /**
* Class defining proximo's article list of a certain category. * Class defining Proximo article list of a certain category.
*/ */
class ProximoListScreen extends React.Component<Props, State> { class ProximoListScreen extends React.Component<PropsType, StateType> {
modalRef: Modalize | null;
modalRef: Object; listData: Array<ProximoArticleType>;
listData: Array<Object>;
shouldFocusSearchBar: boolean;
constructor(props) { shouldFocusSearchBar: boolean;
super(props);
this.listData = this.props.route.params['data']['data'].sort(sortName); constructor(props: PropsType) {
this.shouldFocusSearchBar = this.props.route.params['shouldFocusSearchBar']; super(props);
this.state = { this.listData = props.route.params.data.data.sort(sortName);
currentSearchString: '', this.shouldFocusSearchBar = props.route.params.shouldFocusSearchBar;
currentSortMode: 3, this.state = {
modalCurrentDisplayItem: null, currentSearchString: '',
}; currentSortMode: 3,
modalCurrentDisplayItem: null,
};
}
/**
* Creates the header content
*/
componentDidMount() {
const {navigation} = this.props;
navigation.setOptions({
headerRight: this.getSortMenuButton,
headerTitle: this.getSearchBar,
headerBackTitleVisible: false,
headerTitleContainerStyle:
Platform.OS === 'ios'
? {marginHorizontal: 0, width: '70%'}
: {marginHorizontal: 0, right: 50, left: 50},
});
}
/**
* Callback used when clicking on the sort menu button.
* It will open the modal to show a sort selection
*/
onSortMenuPress = () => {
this.setState({
modalCurrentDisplayItem: this.getModalSortMenu(),
});
if (this.modalRef) {
this.modalRef.open();
} }
};
/**
* Callback used when the search changes
*
* @param str The new search string
*/
onSearchStringChange = (str: string) => {
this.setState({currentSearchString: str});
};
/** /**
* Creates the header content * Callback used when clicking an article in the list.
*/ * It opens the modal to show detailed information about the article
componentDidMount() { *
this.props.navigation.setOptions({ * @param item The article pressed
headerRight: this.getSortMenuButton, */
headerTitle: this.getSearchBar, onListItemPress(item: ProximoArticleType) {
headerBackTitleVisible: false, this.setState({
headerTitleContainerStyle: Platform.OS === 'ios' ? modalCurrentDisplayItem: this.getModalItemContent(item),
{marginHorizontal: 0, width: '70%'} : });
{marginHorizontal: 0, right: 50, left: 50}, if (this.modalRef) {
}); this.modalRef.open();
} }
}
/** /**
* Gets the header search bar * Sets the current sort mode.
* *
* @return {*} * @param mode The number representing the mode
*/ */
getSearchBar = () => { setSortMode(mode: string) {
return ( const {currentSortMode} = this.state;
<Searchbar const currentMode = parseInt(mode, 10);
placeholder={i18n.t('screens.proximo.search')} this.setState({
onChangeText={this.onSearchStringChange} currentSortMode: currentMode,
});
switch (currentMode) {
case 1:
this.listData.sort(sortPrice);
break;
case 2:
this.listData.sort(sortPriceReverse);
break;
case 3:
this.listData.sort(sortName);
break;
case 4:
this.listData.sort(sortNameReverse);
break;
default:
this.listData.sort(sortName);
break;
}
if (this.modalRef && currentMode !== currentSortMode) this.modalRef.close();
}
/**
* Gets a color depending on the quantity available
*
* @param availableStock The quantity available
* @return
*/
getStockColor(availableStock: number): string {
const {theme} = this.props;
let color: string;
if (availableStock > 3) color = theme.colors.success;
else if (availableStock > 0) color = theme.colors.warning;
else color = theme.colors.danger;
return color;
}
/**
* Gets the sort menu header button
*
* @return {*}
*/
getSortMenuButton = (): React.Node => {
return (
<MaterialHeaderButtons>
<Item title="main" iconName="sort" onPress={this.onSortMenuPress} />
</MaterialHeaderButtons>
);
};
/**
* Gets the header search bar
*
* @return {*}
*/
getSearchBar = (): React.Node => {
return (
<Searchbar
placeholder={i18n.t('screens.proximo.search')}
onChangeText={this.onSearchStringChange}
/>
);
};
/**
* Gets the modal content depending on the given article
*
* @param item The article to display
* @return {*}
*/
getModalItemContent(item: ProximoArticleType): React.Node {
return (
<View
style={{
flex: 1,
padding: 20,
}}>
<Title>{item.name}</Title>
<View
style={{
flexDirection: 'row',
width: '100%',
marginTop: 10,
}}>
<Subheading
style={{
color: this.getStockColor(parseInt(item.quantity, 10)),
}}>
{`${item.quantity} ${i18n.t('screens.proximo.inStock')}`}
</Subheading>
<Subheading style={{marginLeft: 'auto'}}>{item.price}</Subheading>
</View>
<ScrollView>
<View
style={{
width: '100%',
height: 150,
marginTop: 20,
marginBottom: 20,
}}>
<Image
style={{flex: 1, resizeMode: 'contain'}}
source={{uri: item.image}}
/> />
); </View>
}; <Text>{item.description}</Text>
</ScrollView>
</View>
);
}
/** /**
* Gets the sort menu header button * Gets the modal content to display a sort menu
* *
* @return {*} * @return {*}
*/ */
getSortMenuButton = () => { getModalSortMenu(): React.Node {
return <MaterialHeaderButtons> const {currentSortMode} = this.state;
<Item title="main" iconName="sort" onPress={this.onSortMenuPress}/> return (
</MaterialHeaderButtons>; <View
}; style={{
flex: 1,
padding: 20,
}}>
<Title style={{marginBottom: 10}}>
{i18n.t('screens.proximo.sortOrder')}
</Title>
<RadioButton.Group
onValueChange={(value: string) => {
this.setSortMode(value);
}}
value={currentSortMode}>
<RadioButton.Item
label={i18n.t('screens.proximo.sortPrice')}
value={1}
/>
<RadioButton.Item
label={i18n.t('screens.proximo.sortPriceReverse')}
value={2}
/>
<RadioButton.Item
label={i18n.t('screens.proximo.sortName')}
value={3}
/>
<RadioButton.Item
label={i18n.t('screens.proximo.sortNameReverse')}
value={4}
/>
</RadioButton.Group>
</View>
);
}
/** /**
* Callback used when clicking on the sort menu button. * Gets a render item for the given article
* It will open the modal to show a sort selection *
*/ * @param item The article to render
onSortMenuPress = () => { * @return {*}
this.setState({ */
modalCurrentDisplayItem: this.getModalSortMenu() getRenderItem = ({item}: {item: ProximoArticleType}): React.Node => {
}); const {currentSearchString} = this.state;
if (this.modalRef) { if (stringMatchQuery(item.name, currentSearchString)) {
this.modalRef.open(); const onPress = () => {
} this.onListItemPress(item);
}; };
const color = this.getStockColor(parseInt(item.quantity, 10));
/** return (
* Sets the current sort mode. <ProximoListItem
* item={item}
* @param mode The number representing the mode onPress={onPress}
*/ color={color}
setSortMode(mode: number) { height={LIST_ITEM_HEIGHT}
this.setState({ />
currentSortMode: mode, );
});
switch (mode) {
case 1:
this.listData.sort(sortPrice);
break;
case 2:
this.listData.sort(sortPriceReverse);
break;
case 3:
this.listData.sort(sortName);
break;
case 4:
this.listData.sort(sortNameReverse);
break;
}
if (this.modalRef && mode !== this.state.currentSortMode) {
this.modalRef.close();
}
} }
return null;
};
/** /**
* Gets a color depending on the quantity available * Extracts a key for the given article
* *
* @param availableStock The quantity available * @param item The article to extract the key from
* @return * @return {string} The extracted key
*/ */
getStockColor(availableStock: number) { keyExtractor = (item: ProximoArticleType): string => item.name + item.code;
let color: string;
if (availableStock > 3)
color = this.props.theme.colors.success;
else if (availableStock > 0)
color = this.props.theme.colors.warning;
else
color = this.props.theme.colors.danger;
return color;
}
/** /**
* Callback used when the search changes * Callback used when receiving the modal ref
* *
* @param str The new search string * @param ref
*/ */
onSearchStringChange = (str: string) => { onModalRef = (ref: Modalize) => {
this.setState({currentSearchString: str}) this.modalRef = ref;
}; };
/** itemLayout = (
* Gets the modal content depending on the given article data: ProximoArticleType,
* index: number,
* @param item The article to display ): {length: number, offset: number, index: number} => ({
* @return {*} length: LIST_ITEM_HEIGHT,
*/ offset: LIST_ITEM_HEIGHT * index,
getModalItemContent(item: Object) { index,
return ( });
<View style={{
flex: 1,
padding: 20
}}>
<Title>{item.name}</Title>
<View style={{
flexDirection: 'row',
width: '100%',
marginTop: 10,
}}>
<Subheading style={{
color: this.getStockColor(parseInt(item.quantity)),
}}>
{item.quantity + ' ' + i18n.t('screens.proximo.inStock')}
</Subheading>
<Subheading style={{marginLeft: 'auto'}}>{item.price}</Subheading>
</View>
<ScrollView> render(): React.Node {
<View style={{width: '100%', height: 150, marginTop: 20, marginBottom: 20}}> const {state} = this;
<Image style={{flex: 1, resizeMode: "contain"}} return (
source={{uri: item.image}}/> <View
</View> style={{
<Text>{item.description}</Text> height: '100%',
</ScrollView> }}>
</View> <CustomModal onRef={this.onModalRef}>
); {state.modalCurrentDisplayItem}
} </CustomModal>
<CollapsibleFlatList
/** data={this.listData}
* Gets the modal content to display a sort menu extraData={state.currentSearchString + state.currentSortMode}
* keyExtractor={this.keyExtractor}
* @return {*} renderItem={this.getRenderItem}
*/ // Performance props, see https://reactnative.dev/docs/optimizing-flatlist-configuration
getModalSortMenu() { removeClippedSubviews
return ( getItemLayout={this.itemLayout}
<View style={{ initialNumToRender={10}
flex: 1, />
padding: 20 </View>
}}> );
<Title style={{marginBottom: 10}}>{i18n.t('screens.proximo.sortOrder')}</Title> }
<RadioButton.Group
onValueChange={value => this.setSortMode(value)}
value={this.state.currentSortMode}
>
<RadioButton.Item label={i18n.t('screens.proximo.sortPrice')} value={1}/>
<RadioButton.Item label={i18n.t('screens.proximo.sortPriceReverse')} value={2}/>
<RadioButton.Item label={i18n.t('screens.proximo.sortName')} value={3}/>
<RadioButton.Item label={i18n.t('screens.proximo.sortNameReverse')} value={4}/>
</RadioButton.Group>
</View>
);
}
/**
* 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: Object) {
this.setState({
modalCurrentDisplayItem: this.getModalItemContent(item)
});
if (this.modalRef) {
this.modalRef.open();
}
}
/**
* Gets a render item for the given article
*
* @param item The article to render
* @return {*}
*/
renderItem = ({item}: Object) => {
if (stringMatchQuery(item.name, this.state.currentSearchString)) {
const onPress = this.onListItemPress.bind(this, item);
const color = this.getStockColor(parseInt(item.quantity));
return (
<ProximoListItem
item={item}
onPress={onPress}
color={color}
height={LIST_ITEM_HEIGHT}
/>
);
} else
return null;
};
/**
* Extracts a key for the given article
*
* @param item The article to extract the key from
* @return {*} The extracted key
*/
keyExtractor(item: Object) {
return item.name + item.code;
}
/**
* Callback used when receiving the modal ref
*
* @param ref
*/
onModalRef = (ref: Object) => {
this.modalRef = ref;
};
itemLayout = (data, index) => ({length: LIST_ITEM_HEIGHT, offset: LIST_ITEM_HEIGHT * index, index});
render() {
return (
<View style={{
height: '100%'
}}>
<CustomModal onRef={this.onModalRef}>
{this.state.modalCurrentDisplayItem}
</CustomModal>
<CollapsibleFlatList
data={this.listData}
extraData={this.state.currentSearchString + this.state.currentSortMode}
keyExtractor={this.keyExtractor}
renderItem={this.renderItem}
// Performance props, see https://reactnative.dev/docs/optimizing-flatlist-configuration
removeClippedSubviews={true}
getItemLayout={this.itemLayout}
initialNumToRender={10}
/>
</View>
);
}
} }
export default withTheme(ProximoListScreen); export default withTheme(ProximoListScreen);

View file

@ -1,233 +1,289 @@
// @flow // @flow
import * as React from 'react'; import * as React from 'react';
import {View} from 'react-native' import i18n from 'i18n-js';
import i18n from "i18n-js";
import WebSectionList from "../../../components/Screens/WebSectionList";
import {List, withTheme} from 'react-native-paper'; import {List, withTheme} from 'react-native-paper';
import MaterialHeaderButtons, {Item} from "../../../components/Overrides/CustomHeaderButton"; import {StackNavigationProp} from '@react-navigation/stack';
import {StackNavigationProp} from "@react-navigation/stack"; import WebSectionList from '../../../components/Screens/WebSectionList';
import type {CustomTheme} from "../../../managers/ThemeManager"; import MaterialHeaderButtons, {
Item,
} from '../../../components/Overrides/CustomHeaderButton';
import type {CustomTheme} from '../../../managers/ThemeManager';
import type {SectionListDataType} from '../../../components/Screens/WebSectionList';
const DATA_URL = "https://etud.insa-toulouse.fr/~proximo/data/stock-v2.json"; const DATA_URL = 'https://etud.insa-toulouse.fr/~proximo/data/stock-v2.json';
const LIST_ITEM_HEIGHT = 84; const LIST_ITEM_HEIGHT = 84;
type Props = { export type ProximoCategoryType = {
navigation: StackNavigationProp, name: string,
theme: CustomTheme, icon: string,
} id: string,
};
type State = { export type ProximoArticleType = {
fetchedData: Object, name: string,
} description: string,
quantity: string,
price: string,
code: string,
id: string,
type: Array<string>,
image: string,
};
export type ProximoMainListItemType = {
type: ProximoCategoryType,
data: Array<ProximoArticleType>,
};
export type ProximoDataType = {
types: Array<ProximoCategoryType>,
articles: Array<ProximoArticleType>,
};
type PropsType = {
navigation: StackNavigationProp,
theme: CustomTheme,
};
/** /**
* Class defining the main proximo screen. * Class defining the main proximo screen.
* This screen shows the different categories of articles offered by proximo. * This screen shows the different categories of articles offered by proximo.
*/ */
class ProximoMainScreen extends React.Component<Props, State> { class ProximoMainScreen extends React.Component<PropsType> {
/**
* Function used to sort items in the list.
* Makes the All category sticks to the top and sorts the others by name ascending
*
* @param a
* @param b
* @return {number}
*/
static sortFinalData(
a: ProximoMainListItemType,
b: ProximoMainListItemType,
): number {
const str1 = a.type.name.toLowerCase();
const str2 = b.type.name.toLowerCase();
articles: Object; // Make 'All' category with id -1 stick to the top
if (a.type.id === -1) return -1;
if (b.type.id === -1) return 1;
/** // Sort others by name ascending
* Function used to sort items in the list. if (str1 < str2) return -1;
* Makes the All category stick to the top and sorts the others by name ascending if (str1 > str2) return 1;
* return 0;
* @param a }
* @param b
* @return {number}
*/
static sortFinalData(a: Object, b: Object) {
let str1 = a.type.name.toLowerCase();
let str2 = b.type.name.toLowerCase();
// Make 'All' category with id -1 stick to the top /**
if (a.type.id === -1) * Get an array of available articles (in stock) of the given type
return -1; *
if (b.type.id === -1) * @param articles The list of all articles
return 1; * @param type The type of articles to find (undefined for any type)
* @return {Array} The array of available articles
// Sort others by name ascending */
if (str1 < str2) static getAvailableArticles(
return -1; articles: Array<ProximoArticleType> | null,
if (str1 > str2) type: ?ProximoCategoryType,
return 1; ): Array<ProximoArticleType> {
return 0; const availableArticles = [];
if (articles != null) {
articles.forEach((article: ProximoArticleType) => {
if (
((type != null && article.type.includes(type.id)) || type == null) &&
parseInt(article.quantity, 10) > 0
)
availableArticles.push(article);
});
} }
return availableArticles;
}
/** articles: Array<ProximoArticleType> | null;
* Creates header button
*/
componentDidMount() {
const rightButton = this.getHeaderButtons.bind(this);
this.props.navigation.setOptions({
headerRight: rightButton,
});
}
/** /**
* Callback used when the search button is pressed. * Creates header button
* This will open a new ProximoListScreen with all items displayed */
*/ componentDidMount() {
onPressSearchBtn = () => { const {navigation} = this.props;
let searchScreenData = { navigation.setOptions({
shouldFocusSearchBar: true, headerRight: (): React.Node => this.getHeaderButtons(),
data: { });
type: { }
id: "0",
name: i18n.t('screens.proximo.all'), /**
icon: 'star' * Callback used when the search button is pressed.
}, * This will open a new ProximoListScreen with all items displayed
data: this.articles !== undefined ? */
this.getAvailableArticles(this.articles, undefined) : [] onPressSearchBtn = () => {
}, const {navigation} = this.props;
}; const searchScreenData = {
this.props.navigation.navigate('proximo-list', searchScreenData); shouldFocusSearchBar: true,
data: {
type: {
id: '0',
name: i18n.t('screens.proximo.all'),
icon: 'star',
},
data:
this.articles != null
? ProximoMainScreen.getAvailableArticles(this.articles)
: [],
},
}; };
navigation.navigate('proximo-list', searchScreenData);
};
/** /**
* Callback used when the about button is pressed. * Callback used when the about button is pressed.
* This will open the ProximoAboutScreen * This will open the ProximoAboutScreen
*/ */
onPressAboutBtn = () => { onPressAboutBtn = () => {
this.props.navigation.navigate('proximo-about'); const {navigation} = this.props;
navigation.navigate('proximo-about');
};
/**
* Gets the header buttons
* @return {*}
*/
getHeaderButtons(): React.Node {
return (
<MaterialHeaderButtons>
<Item
title="magnify"
iconName="magnify"
onPress={this.onPressSearchBtn}
/>
<Item
title="information"
iconName="information"
onPress={this.onPressAboutBtn}
/>
</MaterialHeaderButtons>
);
}
/**
* Extracts a key for the given category
*
* @param item The category to extract the key from
* @return {*} The extracted key
*/
getKeyExtractor = (item: ProximoMainListItemType): string => item.type.id;
/**
* Gets the given category render item
*
* @param item The category to render
* @return {*}
*/
getRenderItem = ({item}: {item: ProximoMainListItemType}): React.Node => {
const {navigation, theme} = this.props;
const dataToSend = {
shouldFocusSearchBar: false,
data: item,
};
const subtitle = `${item.data.length} ${
item.data.length > 1
? i18n.t('screens.proximo.articles')
: i18n.t('screens.proximo.article')
}`;
const onPress = () => {
navigation.navigate('proximo-list', dataToSend);
};
if (item.data.length > 0) {
return (
<List.Item
title={item.type.name}
description={subtitle}
onPress={onPress}
left={({size}: {size: number}): React.Node => (
<List.Icon
size={size}
icon={item.type.icon}
color={theme.colors.primary}
/>
)}
right={({size, color}: {size: number, color: string}): React.Node => (
<List.Icon size={size} color={color} icon="chevron-right" />
)}
style={{
height: LIST_ITEM_HEIGHT,
justifyContent: 'center',
}}
/>
);
} }
return null;
};
/** /**
* Gets the header buttons * Creates the dataset to be used in the FlatList
* @return {*} *
*/ * @param fetchedData
getHeaderButtons() { * @return {*}
return <MaterialHeaderButtons> * */
<Item title="magnify" iconName="magnify" onPress={this.onPressSearchBtn}/> createDataset = (
<Item title="information" iconName="information" onPress={this.onPressAboutBtn}/> fetchedData: ProximoDataType | null,
</MaterialHeaderButtons>; ): SectionListDataType<ProximoMainListItemType> => {
return [
{
title: '',
data: this.generateData(fetchedData),
keyExtractor: this.getKeyExtractor,
},
];
};
/**
* Generate the data using types and FetchedData.
* This will group items under the same type.
*
* @param fetchedData The array of articles represented by objects
* @returns {Array} The formatted dataset
*/
generateData(
fetchedData: ProximoDataType | null,
): Array<ProximoMainListItemType> {
const finalData: Array<ProximoMainListItemType> = [];
this.articles = null;
if (fetchedData != null) {
const {types} = fetchedData;
this.articles = fetchedData.articles;
finalData.push({
type: {
id: '-1',
name: i18n.t('screens.proximo.all'),
icon: 'star',
},
data: ProximoMainScreen.getAvailableArticles(this.articles),
});
types.forEach((type: ProximoCategoryType) => {
finalData.push({
type,
data: ProximoMainScreen.getAvailableArticles(this.articles, type),
});
});
} }
finalData.sort(ProximoMainScreen.sortFinalData);
return finalData;
}
/** render(): React.Node {
* Extracts a key for the given category const {navigation} = this.props;
* return (
* @param item The category to extract the key from <WebSectionList
* @return {*} The extracted key createDataset={this.createDataset}
*/ navigation={navigation}
getKeyExtractor(item: Object) { autoRefreshTime={0}
return item !== undefined ? item.type['id'] : undefined; refreshOnFocus={false}
} fetchUrl={DATA_URL}
renderItem={this.getRenderItem}
/** />
* Creates the dataset to be used in the FlatList );
* }
* @param fetchedData
* @return {*}
* */
createDataset = (fetchedData: Object) => {
return [
{
title: '',
data: this.generateData(fetchedData),
keyExtractor: this.getKeyExtractor
}
];
}
/**
* Generate the data using types and FetchedData.
* This will group items under the same type.
*
* @param fetchedData The array of articles represented by objects
* @returns {Array} The formatted dataset
*/
generateData(fetchedData: Object) {
let finalData = [];
this.articles = undefined;
if (fetchedData.types !== undefined && fetchedData.articles !== undefined) {
let types = fetchedData.types;
this.articles = fetchedData.articles;
finalData.push({
type: {
id: -1,
name: i18n.t('screens.proximo.all'),
icon: 'star'
},
data: this.getAvailableArticles(this.articles, undefined)
});
for (let i = 0; i < types.length; i++) {
finalData.push({
type: types[i],
data: this.getAvailableArticles(this.articles, types[i])
});
}
}
finalData.sort(ProximoMainScreen.sortFinalData);
return finalData;
}
/**
* Get an array of available articles (in stock) of the given type
*
* @param articles The list of all articles
* @param type The type of articles to find (undefined for any type)
* @return {Array} The array of available articles
*/
getAvailableArticles(articles: Array<Object>, type: ?Object) {
let availableArticles = [];
for (let k = 0; k < articles.length; k++) {
if ((type !== undefined && type !== null && articles[k]['type'].includes(type['id'])
|| type === undefined)
&& parseInt(articles[k]['quantity']) > 0) {
availableArticles.push(articles[k]);
}
}
return availableArticles;
}
/**
* Gets the given category render item
*
* @param item The category to render
* @return {*}
*/
getRenderItem = ({item}: Object) => {
let dataToSend = {
shouldFocusSearchBar: false,
data: item,
};
const subtitle = item.data.length + " " + (item.data.length > 1 ? i18n.t('screens.proximo.articles') : i18n.t('screens.proximo.article'));
const onPress = this.props.navigation.navigate.bind(this, 'proximo-list', dataToSend);
if (item.data.length > 0) {
return (
<List.Item
title={item.type.name}
description={subtitle}
onPress={onPress}
left={props => <List.Icon
{...props}
icon={item.type.icon}
color={this.props.theme.colors.primary}/>}
right={props => <List.Icon {...props} icon={'chevron-right'}/>}
style={{
height: LIST_ITEM_HEIGHT,
justifyContent: 'center',
}}
/>
);
} else
return <View/>;
}
render() {
const nav = this.props.navigation;
return (
<WebSectionList
createDataset={this.createDataset}
navigation={nav}
autoRefreshTime={0}
refreshOnFocus={false}
fetchUrl={DATA_URL}
renderItem={this.getRenderItem}/>
);
}
} }
export default withTheme(ProximoMainScreen); export default withTheme(ProximoMainScreen);

View file

@ -1,19 +1,20 @@
// @flow // @flow
import type {Device} from "../screens/Amicale/Equipment/EquipmentListScreen"; import i18n from 'i18n-js';
import i18n from "i18n-js"; import type {DeviceType} from '../screens/Amicale/Equipment/EquipmentListScreen';
import DateManager from "../managers/DateManager"; import DateManager from '../managers/DateManager';
import type {CustomTheme} from "../managers/ThemeManager"; import type {CustomTheme} from '../managers/ThemeManager';
import type {MarkedDatesObjectType} from '../screens/Amicale/Equipment/EquipmentRentScreen';
/** /**
* Gets the current day at midnight * Gets the current day at midnight
* *
* @returns {Date} * @returns {Date}
*/ */
export function getCurrentDay() { export function getCurrentDay(): Date {
let today = new Date(Date.now()); const today = new Date(Date.now());
today.setUTCHours(0, 0, 0, 0); today.setUTCHours(0, 0, 0, 0);
return today; return today;
} }
/** /**
@ -22,8 +23,8 @@ export function getCurrentDay() {
* @param date The date to recover the ISO format from * @param date The date to recover the ISO format from
* @returns {*} * @returns {*}
*/ */
export function getISODate(date: Date) { export function getISODate(date: Date): string {
return date.toISOString().split("T")[0]; return date.toISOString().split('T')[0];
} }
/** /**
@ -32,18 +33,16 @@ export function getISODate(date: Date) {
* @param item * @param item
* @returns {boolean} * @returns {boolean}
*/ */
export function isEquipmentAvailable(item: Device) { export function isEquipmentAvailable(item: DeviceType): boolean {
let isAvailable = true; let isAvailable = true;
const today = getCurrentDay(); const today = getCurrentDay();
const dates = item.booked_at; const dates = item.booked_at;
for (let i = 0; i < dates.length; i++) { dates.forEach((date: {begin: string, end: string}) => {
const start = new Date(dates[i].begin); const start = new Date(date.begin);
const end = new Date(dates[i].end); const end = new Date(date.end);
isAvailable = today < start || today > end; if (!(today < start || today > end)) isAvailable = false;
if (!isAvailable) });
break; return isAvailable;
}
return isAvailable;
} }
/** /**
@ -52,17 +51,16 @@ export function isEquipmentAvailable(item: Device) {
* @param item * @param item
* @returns {Date} * @returns {Date}
*/ */
export function getFirstEquipmentAvailability(item: Device) { export function getFirstEquipmentAvailability(item: DeviceType): Date {
let firstAvailability = getCurrentDay(); let firstAvailability = getCurrentDay();
const dates = item.booked_at; const dates = item.booked_at;
for (let i = 0; i < dates.length; i++) { dates.forEach((date: {begin: string, end: string}) => {
const start = new Date(dates[i].begin); const start = new Date(date.begin);
let end = new Date(dates[i].end); const end = new Date(date.end);
end.setDate(end.getDate() + 1); end.setDate(end.getDate() + 1);
if (firstAvailability >= start) if (firstAvailability >= start) firstAvailability = end;
firstAvailability = end; });
} return firstAvailability;
return firstAvailability;
} }
/** /**
@ -70,31 +68,31 @@ export function getFirstEquipmentAvailability(item: Device) {
* *
* @param date The date to translate * @param date The date to translate
*/ */
export function getRelativeDateString(date: Date) { export function getRelativeDateString(date: Date): string {
const today = getCurrentDay(); const today = getCurrentDay();
const yearDelta = date.getUTCFullYear() - today.getUTCFullYear(); const yearDelta = date.getUTCFullYear() - today.getUTCFullYear();
const monthDelta = date.getUTCMonth() - today.getUTCMonth(); const monthDelta = date.getUTCMonth() - today.getUTCMonth();
const dayDelta = date.getUTCDate() - today.getUTCDate(); const dayDelta = date.getUTCDate() - today.getUTCDate();
let translatedString = i18n.t('screens.equipment.today'); let translatedString = i18n.t('screens.equipment.today');
if (yearDelta > 0) if (yearDelta > 0)
translatedString = i18n.t('screens.equipment.otherYear', { translatedString = i18n.t('screens.equipment.otherYear', {
date: date.getDate(), date: date.getDate(),
month: DateManager.getInstance().getMonthsOfYear()[date.getMonth()], month: DateManager.getInstance().getMonthsOfYear()[date.getMonth()],
year: date.getFullYear() year: date.getFullYear(),
}); });
else if (monthDelta > 0) else if (monthDelta > 0)
translatedString = i18n.t('screens.equipment.otherMonth', { translatedString = i18n.t('screens.equipment.otherMonth', {
date: date.getDate(), date: date.getDate(),
month: DateManager.getInstance().getMonthsOfYear()[date.getMonth()], month: DateManager.getInstance().getMonthsOfYear()[date.getMonth()],
}); });
else if (dayDelta > 1) else if (dayDelta > 1)
translatedString = i18n.t('screens.equipment.thisMonth', { translatedString = i18n.t('screens.equipment.thisMonth', {
date: date.getDate(), date: date.getDate(),
}); });
else if (dayDelta === 1) else if (dayDelta === 1)
translatedString = i18n.t('screens.equipment.tomorrow'); translatedString = i18n.t('screens.equipment.tomorrow');
return translatedString; return translatedString;
} }
/** /**
@ -111,41 +109,45 @@ export function getRelativeDateString(date: Date) {
* @param item Item containing booked dates to look for * @param item Item containing booked dates to look for
* @returns {[string]} * @returns {[string]}
*/ */
export function getValidRange(start: Date, end: Date, item: Device | null) { export function getValidRange(
let direction = start <= end ? 1 : -1; start: Date,
let limit = new Date(end); end: Date,
limit.setDate(limit.getDate() + direction); // Limit is excluded, but we want to include range end item: DeviceType | null,
if (item != null) { ): Array<string> {
if (direction === 1) { const direction = start <= end ? 1 : -1;
for (let i = 0; i < item.booked_at.length; i++) { let limit = new Date(end);
const bookLimit = new Date(item.booked_at[i].begin); limit.setDate(limit.getDate() + direction); // Limit is excluded, but we want to include range end
if (start < bookLimit && limit > bookLimit) { if (item != null) {
limit = bookLimit; if (direction === 1) {
break; for (let i = 0; i < item.booked_at.length; i += 1) {
} const bookLimit = new Date(item.booked_at[i].begin);
} if (start < bookLimit && limit > bookLimit) {
} else { limit = bookLimit;
for (let i = item.booked_at.length - 1; i >= 0; i--) { break;
const bookLimit = new Date(item.booked_at[i].end);
if (start > bookLimit && limit < bookLimit) {
limit = bookLimit;
break;
}
}
} }
}
} else {
for (let i = item.booked_at.length - 1; i >= 0; i -= 1) {
const bookLimit = new Date(item.booked_at[i].end);
if (start > bookLimit && limit < bookLimit) {
limit = bookLimit;
break;
}
}
} }
}
const validRange = [];
let validRange = []; const date = new Date(start);
let date = new Date(start); while (
while ((direction === 1 && date < limit) || (direction === -1 && date > limit)) { (direction === 1 && date < limit) ||
if (direction === 1) (direction === -1 && date > limit)
validRange.push(getISODate(date)); ) {
else if (direction === 1) validRange.push(getISODate(date));
validRange.unshift(getISODate(date)); else validRange.unshift(getISODate(date));
date.setDate(date.getDate() + direction); date.setDate(date.getDate() + direction);
} }
return validRange; return validRange;
} }
/** /**
@ -157,20 +159,24 @@ export function getValidRange(start: Date, end: Date, item: Device | null) {
* @param range The range to mark dates for * @param range The range to mark dates for
* @returns {{}} * @returns {{}}
*/ */
export function generateMarkedDates(isSelection: boolean, theme: CustomTheme, range: Array<string>) { export function generateMarkedDates(
let markedDates = {} isSelection: boolean,
for (let i = 0; i < range.length; i++) { theme: CustomTheme,
const isStart = i === 0; range: Array<string>,
const isEnd = i === range.length - 1; ): MarkedDatesObjectType {
markedDates[range[i]] = { const markedDates = {};
startingDay: isStart, for (let i = 0; i < range.length; i += 1) {
endingDay: isEnd, const isStart = i === 0;
color: isSelection const isEnd = i === range.length - 1;
? isStart || isEnd let color;
? theme.colors.primary if (isSelection && (isStart || isEnd)) color = theme.colors.primary;
: theme.colors.danger else if (isSelection) color = theme.colors.danger;
: theme.colors.textDisabled else color = theme.colors.textDisabled;
}; markedDates[range[i]] = {
} startingDay: isStart,
return markedDates; endingDay: isEnd,
color,
};
}
return markedDates;
} }