Compare commits

..

No commits in common. "547af66977b346f6e22469a5d710b5f27f5203a3" and "93d12b27f8c19020caa6a2d422977e5597dadf12" have entirely different histories.

18 changed files with 2623 additions and 2892 deletions

View file

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

View file

@ -1,61 +1,55 @@
// @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 {ServiceItemType} from '../../../managers/ServicesManager'; import type {ServiceItem} from "../../../managers/ServicesManager";
type PropsType = { type Props = {
item: ServiceItemType, item: ServiceItem,
isActive: boolean, isActive: boolean,
height: number, height: number,
onPress: () => void, onPress: () => void,
theme: CustomTheme, theme: CustomTheme,
}; }
class DashboardEditItem extends React.Component<PropsType> { class DashboardEditItem extends React.Component<Props> {
shouldComponentUpdate(nextProps: PropsType): boolean {
const {isActive} = this.props;
return nextProps.isActive !== isActive;
}
render(): React.Node { shouldComponentUpdate(nextProps: Props) {
const {props} = this; return (nextProps.isActive !== this.props.isActive);
return ( }
<List.Item
title={props.item.title} render() {
description={props.item.subtitle} return (
onPress={props.isActive ? null : props.onPress} <List.Item
left={(): React.Node => ( title={this.props.item.title}
<Image description={this.props.item.subtitle}
source={{uri: props.item.image}} onPress={this.props.isActive ? null : this.props.onPress}
style={{ left={props =>
width: 40, <Image
height: 40, {...props}
}} source={{uri: this.props.item.image}}
/> style={{
)} width: 40,
right={({size}: {size: number}): React.Node => height: 40
props.isActive ? ( }}
<List.Icon />}
size={size} right={props => this.props.isActive
icon="check" ? <List.Icon
color={props.theme.colors.success} {...props}
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 PropsType = { type Props = {
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<PropsType> { class DashboardEditPreviewItem extends React.Component<Props> {
itemSize: number;
constructor(props: PropsType) { itemSize: number;
super(props);
this.itemSize = Dimensions.get('window').width / 8; constructor(props: Props) {
} 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,112 +2,111 @@
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 i18n from 'i18n-js'; import type {CustomTheme} from "../../../managers/ThemeManager";
import {StackNavigationProp} from '@react-navigation/stack'; import type {Device} from "../../../screens/Amicale/Equipment/EquipmentListScreen";
import type {CustomTheme} from '../../../managers/ThemeManager'; import i18n from "i18n-js";
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 PropsType = { type Props = {
navigation: StackNavigationProp, navigation: StackNavigationProp,
userDeviceRentDates: [string, string], userDeviceRentDates: [string, string],
item: DeviceType, item: Device,
height: number, height: number,
theme: CustomTheme, theme: CustomTheme,
}; }
class EquipmentListItem extends React.Component<PropsType> { class EquipmentListItem extends React.Component<Props> {
shouldComponentUpdate(nextProps: PropsType): boolean {
const {userDeviceRentDates} = this.props;
return nextProps.userDeviceRentDates !== userDeviceRentDates;
}
render(): React.Node { shouldComponentUpdate(nextProps: Props): boolean {
const {item, userDeviceRentDates, navigation, height, theme} = this.props; return nextProps.userDeviceRentDates !== this.props.userDeviceRentDates;
const isRented = userDeviceRentDates != null; }
const isAvailable = isEquipmentAvailable(item);
const firstAvailability = getFirstEquipmentAvailability(item);
let onPress; render() {
if (isRented) const colors = this.props.theme.colors;
onPress = () => { const item = this.props.item;
navigation.navigate('equipment-confirm', { const userDeviceRentDates = this.props.userDeviceRentDates;
item, const isRented = userDeviceRentDates != null;
dates: userDeviceRentDates, const isAvailable = isEquipmentAvailable(item);
}); const firstAvailability = getFirstEquipmentAvailability(item);
};
else
onPress = () => {
navigation.navigate('equipment-rent', {item});
};
let description; let onPress;
if (isRented) { if (isRented)
const start = new Date(userDeviceRentDates[0]); onPress = () => this.props.navigation.navigate("equipment-confirm", {
const end = new Date(userDeviceRentDates[1]); item: item,
if (start.getTime() !== end.getTime()) dates: userDeviceRentDates
description = i18n.t('screens.equipment.bookingPeriod', { });
begin: getRelativeDateString(start), else
end: getRelativeDateString(end), onPress = () => this.props.navigation.navigate("equipment-rent", {item: item});
});
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 description;
if (isRented) icon = 'bookmark-check'; if (isRented) {
else if (isAvailable) icon = 'check-circle-outline'; const start = new Date(userDeviceRentDates[0]);
else icon = 'update'; const end = new Date(userDeviceRentDates[1]);
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 color; let icon;
if (isRented) color = theme.colors.warning; if (isRented)
else if (isAvailable) color = theme.colors.success; icon = "bookmark-check";
else color = theme.colors.primary; else if (isAvailable)
icon = "check-circle-outline";
else
icon = "update";
return ( let color;
<List.Item if (isRented)
title={item.name} color = colors.warning;
description={description} else if (isAvailable)
onPress={onPress} color = colors.success;
left={({size}: {size: number}): React.Node => ( else
<Avatar.Icon color = colors.primary;
size={size}
style={{ return (
backgroundColor: 'transparent', <List.Item
}} title={item.name}
icon={icon} description={description}
color={color} onPress={onPress}
/> left={(props) => <Avatar.Icon
)} {...props}
right={(): React.Node => ( style={{
<Avatar.Icon backgroundColor: 'transparent',
style={{ }}
marginTop: 'auto', icon={icon}
marginBottom: 'auto', color={color}
backgroundColor: 'transparent', />}
}} right={(props) => <Avatar.Icon
size={48} {...props}
icon="chevron-right" style={{
/> marginTop: 'auto',
)} marginBottom: 'auto',
style={{ backgroundColor: 'transparent',
height, }}
justifyContent: 'center', size={48}
}} icon={"chevron-right"}
/> />}
); style={{
} height: this.props.height,
justifyContent: 'center',
}}
/>
);
}
} }
export default withTheme(EquipmentListItem); export default withTheme(EquipmentListItem);

View file

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

View file

@ -2,67 +2,65 @@
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 {PlanexGroupType} from '../../../screens/Planex/GroupSelectionScreen'; import type {group} from "../../../screens/Planex/GroupSelectionScreen";
type PropsType = { type Props = {
theme: CustomTheme, theme: CustomTheme,
onPress: () => void, onPress: () => void,
onStarPress: () => void, onStarPress: () => void,
item: PlanexGroupType, item: group,
height: number, height: number,
}; }
type StateType = { type State = {
isFav: boolean, isFav: boolean,
}; }
class GroupListItem extends React.Component<PropsType, StateType> { class GroupListItem extends React.Component<Props, State> {
constructor(props: PropsType) {
super(props);
this.state = {
isFav: props.item.isFav !== undefined && props.item.isFav,
};
}
shouldComponentUpdate(prevProps: PropsType, prevState: StateType): boolean { constructor(props) {
const {isFav} = this.state; super(props);
return prevState.isFav !== isFav; this.state = {
} isFav: (props.item.isFav !== undefined && props.item.isFav),
}
}
onStarPress = () => { shouldComponentUpdate(prevProps: Props, prevState: State) {
const {props} = this; return (prevState.isFav !== this.state.isFav);
this.setState((prevState: StateType): StateType => ({ }
isFav: !prevState.isFav,
}));
props.onStarPress();
};
render(): React.Node { onStarPress = () => {
const {props, state} = this; this.setState({isFav: !this.state.isFav});
const {colors} = props.theme; this.props.onStarPress();
return ( }
<List.Item
title={props.item.name} render() {
onPress={props.onPress} const colors = this.props.theme.colors;
left={({size}: {size: number}): React.Node => ( return (
<List.Icon size={size} icon="chevron-right" /> <List.Item
)} title={this.props.item.name}
right={({size, color}: {size: number, color: string}): React.Node => ( onPress={this.props.onPress}
<IconButton left={props =>
size={size} <List.Icon
icon="star" {...props}
onPress={this.onStarPress} icon={"chevron-right"}/>}
color={state.isFav ? colors.tetrisScore : color} right={props =>
/> <IconButton
)} {...props}
style={{ icon={"star"}
height: props.height, onPress={this.onStarPress}
justifyContent: 'center', color={this.state.isFav
}} ? 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 PropsType = { type Props = {
onPress: () => void, onPress: Function,
color: string, color: string,
item: ProximoArticleType, item: Object,
height: number, height: number,
}; }
class ProximoListItem extends React.Component<PropsType> { class ProximoListItem extends React.Component<Props> {
shouldComponentUpdate(): boolean {
return false;
}
render(): React.Node { colors: Object;
const {props} = this;
return ( constructor(props) {
<List.Item super(props);
title={props.item.name} this.colors = props.theme.colors;
description={`${props.item.quantity} ${i18n.t( }
'screens.proximo.inStock',
)}`} shouldComponentUpdate() {
descriptionStyle={{color: props.color}} return false;
onPress={props.onPress} }
left={(): React.Node => (
<Avatar.Image render() {
style={{backgroundColor: 'transparent'}} return (
size={64} <List.Item
source={{uri: props.item.image}} title={this.props.item.name}
/> description={this.props.item.quantity + ' ' + i18n.t('screens.proximo.inStock')}
)} descriptionStyle={{color: this.props.color}}
right={(): React.Node => ( onPress={this.props.onPress}
<Text style={{fontWeight: 'bold'}}>{props.item.price}</Text> left={() => <Avatar.Image style={{backgroundColor: 'transparent'}} size={64}
)} source={{uri: this.props.item.image}}/>}
style={{ right={() =>
height: props.height, <Text style={{fontWeight: "bold"}}>
justifyContent: 'center', {this.props.item.price}
}} </Text>}
/> style={{
); height: this.props.height,
} justifyContent: 'center',
}}
/>
);
}
} }
export default withTheme(ProximoListItem); export default withTheme(ProximoListItem);

View file

@ -1,55 +1,44 @@
// @flow // @flow
import * as React from 'react'; import * as React from 'react';
import i18n from 'i18n-js'; import {ERROR_TYPE, readData} from "../../utils/WebData";
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 {Collapsible} from 'react-navigation-collapsible'; import CustomTabBar from "../Tabbar/CustomTabBar";
import {StackNavigationProp} from '@react-navigation/stack'; import {Collapsible} from "react-navigation-collapsible";
import ErrorView from './ErrorView'; import {StackNavigationProp} from "@react-navigation/stack";
import BasicLoadingScreen from './BasicLoadingScreen'; import CollapsibleSectionList from "../Collapsible/CollapsibleSectionList";
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';
export type SectionListDataType<T> = Array<{ type Props = {
title: string, navigation: StackNavigationProp,
data: Array<T>, fetchUrl: string,
keyExtractor?: (T) => string, autoRefreshTime: number,
}>; 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,
type PropsType<T> = { showError: boolean,
navigation: StackNavigationProp, itemHeight?: number,
fetchUrl: string, updateData?: number,
autoRefreshTime: number, renderListHeaderComponent?: (data: { [key: string]: any } | null) => React.Node,
refreshOnFocus: boolean, renderSectionHeader?: (data: { section: { [key: string]: any } }, isLoading?: boolean) => React.Node,
renderItem: (data: {item: T}) => React.Node, stickyHeader?: boolean,
createDataset: ( }
data: ApiGenericDataType | null,
isLoading?: boolean,
) => SectionListDataType<T>,
onScroll: (event: SyntheticEvent<EventTarget>) => void,
collapsibleStack: Collapsible,
showError?: boolean, type State = {
itemHeight?: number | null, refreshing: boolean,
updateData?: number, firstLoading: boolean,
renderListHeaderComponent?: (data: ApiGenericDataType | null) => React.Node, fetchedData: { [key: string]: any } | null,
renderSectionHeader?: ( snackbarVisible: boolean
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;
@ -59,216 +48,211 @@ 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<T> extends React.PureComponent<PropsType<T>, StateType> { class WebSectionList extends React.PureComponent<Props, State> {
static defaultProps = {
showError: true,
itemHeight: null,
updateData: 0,
renderListHeaderComponent: (): React.Node => null,
renderSectionHeader: (): React.Node => null,
stickyHeader: false,
};
refreshInterval: IntervalID; static defaultProps = {
stickyHeader: false,
lastRefresh: Date | null; updateData: 0,
showError: true,
constructor() {
super();
this.state = {
refreshing: false,
fetchedData: null,
snackbarVisible: false,
}; };
}
/** refreshInterval: IntervalID;
* Registers react navigation events on first screen load. lastRefresh: Date | null;
* 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 = {
* Refreshes data when focusing the screen and setup a refresh interval if asked to refreshing: false,
*/ firstLoading: true,
onScreenFocus = () => { fetchedData: null,
const {props} = this; snackbarVisible: false
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 => { /**
const {renderSectionHeader} = this.props; * Registers react navigation events on first screen load.
const {refreshing} = this.state; * Allows to detect when the screen is focused
if (renderSectionHeader != null) { */
return ( componentDidMount() {
<Animatable.View animation="fadeInUp" duration={500} useNativeDriver> this.props.navigation.addListener('focus', this.onScreenFocus);
{renderSectionHeader(data, refreshing)} this.props.navigation.addListener('blur', this.onScreenBlur);
</Animatable.View> this.lastRefresh = null;
); this.onRefresh();
} }
return null;
};
getRenderItem = (data: {item: T}): React.Node => { /**
const {renderItem} = this.props; * Refreshes data when focusing the screen and setup a refresh interval if asked to
return ( */
<Animatable.View animation="fadeInUp" duration={500} useNativeDriver> onScreenFocus = () => {
{renderItem(data)} if (this.props.refreshOnFocus && this.lastRefresh)
</Animatable.View> this.onRefresh();
); if (this.props.autoRefreshTime > 0)
}; this.refreshInterval = setInterval(this.onRefresh, this.props.autoRefreshTime)
}
onScroll = (event: SyntheticEvent<EventTarget>) => { /**
const {onScroll} = this.props; * Removes any interval on un-focus
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; /**
return ( * Callback used when fetch is successful.
<View> * It will update the displayed data and stop the refresh animation
<CollapsibleSectionList *
sections={dataset} * @param fetchedData The newly fetched data
extraData={props.updateData} */
refreshControl={ onFetchSuccess = (fetchedData: { [key: string]: any }) => {
<RefreshControl this.setState({
progressViewOffset={containerPaddingTop} fetchedData: fetchedData,
refreshing={state.refreshing} refreshing: false,
onRefresh={this.onRefresh} firstLoading: false
/> });
} this.lastRefresh = new Date();
renderSectionHeader={this.getRenderSectionHeader} };
renderItem={this.getRenderItem}
stickySectionHeadersEnabled={props.stickyHeader} /**
style={{minHeight: '100%'}} * Callback used when fetch encountered an error.
ListHeaderComponent={ * It will reset the displayed data and show an error.
props.renderListHeaderComponent != null */
? props.renderListHeaderComponent(state.fetchedData) onFetchError = () => {
: null this.setState({
} fetchedData: null,
ListEmptyComponent={ refreshing: false,
state.refreshing ? ( firstLoading: false
<BasicLoadingScreen /> });
) : ( this.showSnackBar();
<ErrorView };
navigation={props.navigation}
errorCode={ERROR_TYPE.CONNECTION_ERROR} /**
onRefresh={this.onRefresh} * Refreshes data and shows an animations while doing it
/> */
) onRefresh = () => {
} let canRefresh;
getItemLayout={props.itemHeight != null ? this.getItemLayout : null} if (this.lastRefresh != null) {
onScroll={this.onScroll} const last = this.lastRefresh;
hasTab canRefresh = (new Date().getTime() - last.getTime()) > MIN_REFRESH_TIME;
/> } else
<Snackbar canRefresh = true;
visible={state.snackbarVisible} if (canRefresh) {
onDismiss={this.hideSnackBar} this.setState({refreshing: true});
action={{ readData(this.props.fetchUrl)
label: 'OK', .then(this.onFetchSuccess)
onPress: () => {}, .catch(this.onFetchError);
}} }
duration={4000} };
style={{
bottom: CustomTabBar.TAB_BAR_HEIGHT, /**
}}> * Shows the error popup
{i18n.t('general.listUpdateFail')} */
</Snackbar> showSnackBar = () => this.setState({snackbarVisible: true});
</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,102 +1,105 @@
// @flow // @flow
import * as React from 'react'; import * as React from 'react';
import { import {Button, Caption, Card, Headline, Paragraph, withTheme} from 'react-native-paper';
Button, import {StackNavigationProp} from "@react-navigation/stack";
Caption, import type {CustomTheme} from "../../../managers/ThemeManager";
Card, import type {Device} from "./EquipmentListScreen";
Headline, import {View} from "react-native";
Paragraph, import i18n from "i18n-js";
withTheme, import {getRelativeDateString} from "../../../utils/EquipmentBooking";
} from 'react-native-paper'; import CollapsibleScrollView from "../../../components/Collapsible/CollapsibleScrollView";
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 PropsType = { type Props = {
route: { navigation: StackNavigationProp,
params?: { route: {
item?: DeviceType, params?: {
dates: [string, string], item?: Device,
dates: [string, string]
},
}, },
}, theme: CustomTheme,
theme: CustomTheme, }
};
class EquipmentConfirmScreen extends React.Component<PropsType> {
item: DeviceType | null;
dates: [string, string] | null; class EquipmentConfirmScreen extends React.Component<Props> {
constructor(props: PropsType) { item: Device | null;
super(props); dates: [string, string] | null;
if (props.route.params != null) {
if (props.route.params.item != null) this.item = props.route.params.item; constructor(props: Props) {
else this.item = null; super(props);
if (props.route.params.dates != null) if (this.props.route.params != null) {
this.dates = props.route.params.dates; if (this.props.route.params.item != null)
else this.dates = null; this.item = this.props.route.params.item;
else
this.item = null;
if (this.props.route.params.dates != null)
this.dates = this.props.route.params.dates;
else
this.dates = null;
}
} }
}
render(): React.Node { render() {
const {item, dates, props} = this; const item = this.item;
if (item != null && dates != null) { const dates = this.dates;
const start = new Date(dates[0]); if (item != null && dates != null) {
const end = new Date(dates[1]); const start = new Date(dates[0]);
let buttonText; const end = new Date(dates[1]);
if (start == null) buttonText = i18n.t('screens.equipment.booking'); return (
else if (end != null && start.getTime() !== end.getTime()) <CollapsibleScrollView>
buttonText = i18n.t('screens.equipment.bookingPeriod', { <Card style={{margin: 5}}>
begin: getRelativeDateString(start), <Card.Content>
end: getRelativeDateString(end), <View style={{flex: 1}}>
}); <View style={{
else marginLeft: "auto",
buttonText = i18n.t('screens.equipment.bookingDay', { marginRight: "auto",
date: getRelativeDateString(start), flexDirection: "row",
}); flexWrap: "wrap",
return ( }}>
<CollapsibleScrollView> <Headline style={{textAlign: "center"}}>
<Card style={{margin: 5}}> {item.name}
<Card.Content> </Headline>
<View style={{flex: 1}}> <Caption style={{
<View textAlign: "center",
style={{ lineHeight: 35,
marginLeft: 'auto', marginLeft: 10,
marginRight: 'auto', }}>
flexDirection: 'row', ({i18n.t('screens.equipment.bail', {cost: item.caution})})
flexWrap: 'wrap', </Caption>
}}> </View>
<Headline style={{textAlign: 'center'}}>{item.name}</Headline> </View>
<Caption <Button
style={{ icon={"check-circle-outline"}
textAlign: 'center', color={this.props.theme.colors.success}
lineHeight: 35, mode="text"
marginLeft: 10, >
}}> {
({i18n.t('screens.equipment.bail', {cost: item.caution})}) start == null
</Caption> ? i18n.t('screens.equipment.booking')
</View> : end != null && start.getTime() !== end.getTime()
</View> ? i18n.t('screens.equipment.bookingPeriod', {
<Button begin: getRelativeDateString(start),
icon="check-circle-outline" end: getRelativeDateString(end)
color={props.theme.colors.success} })
mode="text"> : i18n.t('screens.equipment.bookingDay', {
{buttonText} date: getRelativeDateString(start)
</Button> })
<Paragraph style={{textAlign: 'center'}}> }
{i18n.t('screens.equipment.bookingConfirmedMessage')} </Button>
</Paragraph> <Paragraph style={{textAlign: "center"}}>
</Card.Content> {i18n.t("screens.equipment.bookingConfirmedMessage")}
</Card> </Paragraph>
</CollapsibleScrollView> </Card.Content>
); </Card>
</CollapsibleScrollView>
);
} else
return null;
} }
return null;
}
} }
export default withTheme(EquipmentConfirmScreen); export default withTheme(EquipmentConfirmScreen);

View file

@ -1,197 +1,193 @@
// @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 {StackNavigationProp} from '@react-navigation/stack'; import AuthenticatedScreen from "../../../components/Amicale/AuthenticatedScreen";
import i18n from 'i18n-js'; import {StackNavigationProp} from "@react-navigation/stack";
import AuthenticatedScreen from '../../../components/Amicale/AuthenticatedScreen'; import type {CustomTheme} from "../../../managers/ThemeManager";
import type {ClubType} from '../Clubs/ClubListScreen'; import i18n from "i18n-js";
import EquipmentListItem from '../../../components/Lists/Equipment/EquipmentListItem'; import type {club} from "../Clubs/ClubListScreen";
import MascotPopup from '../../../components/Mascot/MascotPopup'; import EquipmentListItem from "../../../components/Lists/Equipment/EquipmentListItem";
import {MASCOT_STYLE} from '../../../components/Mascot/Mascot'; import MascotPopup from "../../../components/Mascot/MascotPopup";
import AsyncStorageManager from '../../../managers/AsyncStorageManager'; import {MASCOT_STYLE} from "../../../components/Mascot/Mascot";
import CollapsibleFlatList from '../../../components/Collapsible/CollapsibleFlatList'; import AsyncStorageManager from "../../../managers/AsyncStorageManager";
import type {ApiGenericDataType} from '../../../utils/WebData'; import CollapsibleFlatList from "../../../components/Collapsible/CollapsibleFlatList";
type PropsType = { type Props = {
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 }>,
}; };
type StateType = { export type RentedDevice = {
mascotDialogVisible: boolean, device_id: number,
}; device_name: string,
begin: string,
export type DeviceType = { end: string,
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<PropsType, StateType> { class EquipmentListScreen extends React.Component<Props, State> {
data: Array<DeviceType>;
userRents: Array<RentedDeviceType>; state = {
mascotDialogVisible: AsyncStorageManager.getBool(AsyncStorageManager.PREFERENCES.equipmentShowBanner.key),
}
authRef: {current: null | AuthenticatedScreen}; data: Array<Device>;
userRents: Array<RentedDevice>;
canRefresh: boolean; authRef: { current: null | AuthenticatedScreen };
canRefresh: boolean;
constructor(props: PropsType) { constructor(props: Props) {
super(props); super(props);
this.state = { this.canRefresh = false;
mascotDialogVisible: AsyncStorageManager.getBool( this.authRef = React.createRef();
AsyncStorageManager.PREFERENCES.equipmentShowBanner.key, this.props.navigation.addListener('focus', this.onScreenFocus);
), }
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);
}
onScreenFocus = () => { getRenderItem = ({item}: { item: Device }) => {
if (this.canRefresh && this.authRef.current != null) return (
this.authRef.current.reload(); <EquipmentListItem
this.canRefresh = true; navigation={this.props.navigation}
}; item={item}
userDeviceRentDates={this.getUserDeviceRentDates(item)}
height={LIST_ITEM_HEIGHT}/>
);
};
getRenderItem = ({item}: {item: DeviceType}): React.Node => { getUserDeviceRentDates(item: Device) {
const {navigation} = this.props; let dates = null;
return ( for (let i = 0; i < this.userRents.length; i++) {
<EquipmentListItem let device = this.userRents[i];
navigation={navigation} if (item.id === device.device_id) {
item={item} dates = [device.begin, device.end];
userDeviceRentDates={this.getUserDeviceRentDates(item)} break;
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]; /**
if (fetchedData != null) this.userRents = fetchedData.locations; * Gets the list header, with explains this screen's purpose
*
* @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}
/>
);
};
showMascotDialog = () => { keyExtractor = (item: club) => item.id.toString();
this.setState({mascotDialogVisible: true});
};
hideMascotDialog = () => { /**
AsyncStorageManager.set( * Gets the main screen component with the fetched data
AsyncStorageManager.PREFERENCES.equipmentShowBanner.key, *
false, * @param data The data fetched from the server
); * @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}
/>
)
};
render(): React.Node { showMascotDialog = () => {
const {props, state} = this; this.setState({mascotDialogVisible: true})
return ( };
<View style={{flex: 1}}>
<AuthenticatedScreen hideMascotDialog = () => {
navigation={props.navigation} AsyncStorageManager.set(AsyncStorageManager.PREFERENCES.equipmentShowBanner.key, false);
ref={this.authRef} this.setState({mascotDialogVisible: false})
requests={[ };
{
link: 'location/all', render() {
params: {}, return (
mandatory: true, <View style={{flex: 1}}>
}, <AuthenticatedScreen
{ {...this.props}
link: 'location/my', ref={this.authRef}
params: {}, requests={[
mandatory: false, {
}, link: 'location/all',
]} params: {},
renderFunction={this.getScreen} mandatory: true,
/> },
<MascotPopup {
visible={state.mascotDialogVisible} link: 'location/my',
title={i18n.t('screens.equipment.mascotDialog.title')} params: {},
message={i18n.t('screens.equipment.mascotDialog.message')} mandatory: false,
icon="vote" }
buttons={{ ]}
action: null, renderFunction={this.getScreen}
cancel: { />
message: i18n.t('screens.equipment.mascotDialog.button'), <MascotPopup
icon: 'check', visible={this.state.mascotDialogVisible}
onPress: this.hideMascotDialog, title={i18n.t("screens.equipment.mascotDialog.title")}
}, message={i18n.t("screens.equipment.mascotDialog.message")}
}} icon={"vote"}
emotion={MASCOT_STYLE.WINK} buttons={{
/> action: null,
</View> cancel: {
); 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 {
Button, generateMarkedDates,
Caption, getFirstEquipmentAvailability,
Card, getISODate,
Headline, getRelativeDateString,
Subheading, getValidRange,
withTheme, isEquipmentAvailable
} from 'react-native-paper'; } from "../../../utils/EquipmentBooking";
import {StackNavigationProp} from '@react-navigation/stack'; import ConnectionManager from "../../../managers/ConnectionManager";
import {BackHandler, View} from 'react-native'; import CollapsibleScrollView from "../../../components/Collapsible/CollapsibleScrollView";
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 PropsType = { type Props = {
navigation: StackNavigationProp, navigation: StackNavigationProp,
route: { route: {
params?: { params?: {
item?: DeviceType, item?: Device,
},
}, },
}, theme: CustomTheme,
theme: CustomTheme, }
};
export type MarkedDatesObjectType = { type State = {
[key: string]: {startingDay: boolean, endingDay: boolean, color: string}, dialogVisible: boolean,
}; errorDialogVisible: boolean,
markedDates: { [key: string]: { startingDay: boolean, endingDay: boolean, color: string } },
currentError: number,
}
type StateType = { class EquipmentRentScreen extends React.Component<Props, State> {
dialogVisible: boolean,
errorDialogVisible: boolean,
markedDates: MarkedDatesObjectType,
currentError: number,
};
class EquipmentRentScreen extends React.Component<PropsType, StateType> { state = {
item: DeviceType | null; dialogVisible: false,
errorDialogVisible: false,
bookedDates: Array<string>; markedDates: {},
currentError: 0,
bookRef: {current: null | Animatable.View};
canBookEquipment: boolean;
lockedDates: {
[key: string]: {startingDay: boolean, endingDay: boolean, color: string},
};
constructor(props: PropsType) {
super(props);
this.state = {
dialogVisible: false,
errorDialogVisible: false,
markedDates: {},
currentError: 0,
};
this.resetSelection();
this.bookRef = React.createRef();
this.canBookEquipment = false;
this.bookedDates = [];
if (props.route.params != null) {
if (props.route.params.item != null) this.item = props.route.params.item;
else this.item = null;
} }
const {item} = this;
if (item != null) {
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),
};
});
}
}
/** item: Device | null;
* Captures focus and blur events to hook on android back button bookedDates: Array<string>;
*/
componentDidMount() {
const {navigation} = this.props;
navigation.addListener('focus', () => {
BackHandler.addEventListener(
'hardwareBackPress',
this.onBackButtonPressAndroid,
);
});
navigation.addListener('blur', () => {
BackHandler.removeEventListener(
'hardwareBackPress',
this.onBackButtonPressAndroid,
);
});
}
/** bookRef: { current: null | Animatable.View }
* Overrides default android back button behaviour to deselect date if any is selected. canBookEquipment: boolean;
*
* @return {boolean}
*/
onBackButtonPressAndroid = (): boolean => {
if (this.bookedDates.length > 0) {
this.resetSelection();
this.updateMarkedSelection();
return true;
}
return false;
};
onDialogDismiss = () => { lockedDates: { [key: string]: { startingDay: boolean, endingDay: boolean, color: string } }
this.setState({dialogVisible: false});
};
onErrorDialogDismiss = () => { constructor(props: Props) {
this.setState({errorDialogVisible: false}); super(props);
};
/**
* 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(); this.resetSelection();
} else if (this.bookedDates.length === 1) { this.bookRef = React.createRef();
this.updateSelectionRange(start, selected); this.canBookEquipment = false;
this.enableBooking(); this.bookedDates = [];
} else this.resetSelection(); if (this.props.route.params != null) {
this.updateMarkedSelection(); 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
)
};
}
}
} }
};
showErrorDialog = (error: number) => { /**
this.setState({ * Captures focus and blur events to hook on android back button
errorDialogVisible: true, */
currentError: error, componentDidMount() {
}); this.props.navigation.addListener(
}; 'focus',
() =>
showDialog = () => { BackHandler.addEventListener(
this.setState({dialogVisible: true}); 'hardwareBackPress',
}; this.onBackButtonPressAndroid
)
/** );
* Shows the book button by plying a fade animation this.props.navigation.addListener(
*/ 'blur',
showBookButton() { () =>
if (this.bookRef.current != null) { BackHandler.removeEventListener(
this.bookRef.current.fadeInUp(500); 'hardwareBackPress',
this.onBackButtonPressAndroid
)
);
} }
}
/** /**
* Hides the book button by plying a fade animation * Overrides default android back button behaviour to deselect date if any is selected.
*/ *
hideBookButton() { * @return {boolean}
if (this.bookRef.current != null) { */
this.bookRef.current.fadeOutDown(500); onBackButtonPressAndroid = () => {
if (this.bookedDates.length > 0) {
this.resetSelection();
this.updateMarkedSelection();
return true;
} else
return false;
};
/**
* 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.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();
}
} }
}
enableBooking() { updateSelectionRange(start: Date, end: Date) {
if (!this.canBookEquipment) { this.bookedDates = getValidRange(start, end, this.item);
this.showBookButton();
this.canBookEquipment = true;
} }
}
resetSelection() { updateMarkedSelection() {
if (this.canBookEquipment) this.hideBookButton(); this.setState({
this.canBookEquipment = false; markedDates: generateMarkedDates(
this.bookedDates = []; true,
} this.props.theme,
this.bookedDates
),
});
}
updateSelectionRange(start: Date, end: Date) { enableBooking() {
this.bookedDates = getValidRange(start, end, this.item); if (!this.canBookEquipment) {
} this.showBookButton();
this.canBookEquipment = true;
}
}
updateMarkedSelection() { resetSelection() {
const {theme} = this.props; if (this.canBookEquipment)
this.setState({ this.hideBookButton();
markedDates: generateMarkedDates(true, theme, this.bookedDates), this.canBookEquipment = false;
}); this.bookedDates = [];
} }
render(): React.Node { /**
const {item, props, state} = this; * Shows the book button by plying a fade animation
const start = this.getBookStartDate(); */
const end = this.getBookEndDate(); showBookButton() {
let subHeadingText; if (this.bookRef.current != null) {
if (start == null) subHeadingText = i18n.t('screens.equipment.booking'); this.bookRef.current.fadeInUp(500);
else if (end != null && start.getTime() !== end.getTime()) }
subHeadingText = i18n.t('screens.equipment.bookingPeriod', { }
begin: getRelativeDateString(start),
end: getRelativeDateString(end), /**
}); * Hides the book button by plying a fade animation
else */
i18n.t('screens.equipment.bookingDay', { hideBookButton() {
date: getRelativeDateString(start), if (this.bookRef.current != null) {
}); this.bookRef.current.fadeOutDown(500);
if (item != null) { }
const isAvailable = isEquipmentAvailable(item); }
const firstAvailability = getFirstEquipmentAvailability(item);
return ( showDialog = () => {
<View style={{flex: 1}}> this.setState({dialogVisible: true});
<CollapsibleScrollView> }
<Card style={{margin: 5}}>
<Card.Content> showErrorDialog = (error: number) => {
this.setState({
errorDialogVisible: true,
currentError: error,
});
}
onDialogDismiss = () => {
this.setState({dialogVisible: false});
}
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<R>}
*/
onDialogAccept = () => {
return new Promise((resolve) => {
const item = this.item;
const start = this.getBookStartDate();
const end = this.getBookEndDate();
if (item != null && start != null && end != null) {
console.log({
"device": item.id,
"begin": getISODate(start),
"end": getISODate(end),
})
ConnectionManager.getInstance().authenticatedRequest(
"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}}>
<View <CollapsibleScrollView>
style={{ <Card style={{margin: 5}}>
marginLeft: 'auto', <Card.Content>
marginRight: 'auto', <View style={{flex: 1}}>
flexDirection: 'row', <View style={{
flexWrap: 'wrap', marginLeft: "auto",
}}> marginRight: "auto",
<Headline style={{textAlign: 'center'}}> flexDirection: "row",
{item.name} flexWrap: "wrap",
</Headline> }}>
<Caption <Headline style={{textAlign: "center"}}>
style={{ {item.name}
textAlign: 'center', </Headline>
lineHeight: 35, <Caption style={{
marginLeft: 10, textAlign: "center",
}}> lineHeight: 35,
({i18n.t('screens.equipment.bail', {cost: item.caution})}) marginLeft: 10,
</Caption> }}>
</View> ({i18n.t('screens.equipment.bail', {cost: item.caution})})
</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 )
icon={isAvailable ? 'check-circle-outline' : 'update'} } else
color={ return <View/>;
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,166 +1,148 @@
// @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 {Button, Card, Paragraph, withTheme} from 'react-native-paper'; import type {CustomTheme} from "../../../managers/ThemeManager";
import {FlatList} from 'react-native'; import {Button, Card, Paragraph, withTheme} from "react-native-paper";
import {View} from 'react-native-animatable'; import type {ServiceCategory, ServiceItem} from "../../../managers/ServicesManager";
import i18n from 'i18n-js'; import DashboardManager from "../../../managers/DashboardManager";
import type { import DashboardItem from "../../../components/Home/EventDashboardItem";
ServiceCategoryType, import {FlatList} from "react-native";
ServiceItemType, import {View} from "react-native-animatable";
} from '../../../managers/ServicesManager'; import DashboardEditAccordion from "../../../components/Lists/DashboardEdit/DashboardEditAccordion";
import DashboardManager from '../../../managers/DashboardManager'; import DashboardEditPreviewItem from "../../../components/Lists/DashboardEdit/DashboardEditPreviewItem";
import DashboardItem from '../../../components/Home/EventDashboardItem'; import AsyncStorageManager from "../../../managers/AsyncStorageManager";
import DashboardEditAccordion from '../../../components/Lists/DashboardEdit/DashboardEditAccordion'; import i18n from "i18n-js";
import DashboardEditPreviewItem from '../../../components/Lists/DashboardEdit/DashboardEditPreviewItem'; import CollapsibleFlatList from "../../../components/Collapsible/CollapsibleFlatList";
import AsyncStorageManager from '../../../managers/AsyncStorageManager';
import CollapsibleFlatList from '../../../components/Collapsible/CollapsibleFlatList';
type PropsType = { type Props = {
navigation: StackNavigationProp, navigation: StackNavigationProp,
theme: CustomTheme,
}; };
type StateType = { type State = {
currentDashboard: Array<ServiceItemType | null>, currentDashboard: Array<ServiceItem>,
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<PropsType, StateType> { class DashboardEditScreen extends React.Component<Props, State> {
content: Array<ServiceCategoryType>;
initialDashboard: Array<ServiceItemType | null>; content: Array<ServiceCategory>;
initialDashboard: Array<ServiceItem>;
initialDashboardIdList: Array<string>;
initialDashboardIdList: Array<string>; constructor(props: Props) {
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();
}
constructor(props: PropsType) { dashboardRowRenderItem = ({item, index}: { item: DashboardItem, index: number }) => {
super(props); return (
const dashboardManager = new DashboardManager(props.navigation); <DashboardEditPreviewItem
this.initialDashboardIdList = AsyncStorageManager.getObject( image={item.image}
AsyncStorageManager.PREFERENCES.dashboardItems.key, onPress={() => this.setState({activeItem: index})}
); isActive={this.state.activeItem === index}
this.initialDashboard = dashboardManager.getCurrentDashboard(); />
this.state = { );
currentDashboard: [...this.initialDashboard],
currentDashboardIdList: [...this.initialDashboardIdList],
activeItem: 0,
}; };
this.content = dashboardManager.getCategories();
}
getDashboardRowRenderItem = ({ getDashboard(content: Array<DashboardItem>) {
item, return (
index, <FlatList
}: { data={content}
item: DashboardItem, extraData={this.state}
index: number, renderItem={this.dashboardRowRenderItem}
}): React.Node => { horizontal={true}
const {activeItem} = this.state; contentContainerStyle={{
return ( marginLeft: 'auto',
<DashboardEditPreviewItem marginRight: 'auto',
image={item.image} marginTop: 5,
onPress={() => { }}
this.setState({activeItem: index}); />);
}} }
isActive={activeItem === index}
/>
);
};
getDashboard(content: Array<DashboardItem>): React.Node { renderItem = ({item}: { item: ServiceCategory }) => {
return ( return (
<FlatList <DashboardEditAccordion
data={content} item={item}
extraData={this.state} onPress={this.updateDashboard}
renderItem={this.getDashboardRowRenderItem} activeDashboard={this.state.currentDashboardIdList}
horizontal />
contentContainerStyle={{ );
marginLeft: 'auto', };
marginRight: 'auto',
marginTop: 5,
}}
/>
);
}
getRenderItem = ({item}: {item: ServiceCategoryType}): React.Node => { updateDashboard = (service: ServiceItem) => {
const {currentDashboardIdList} = this.state; let currentDashboard = this.state.currentDashboard;
return ( let currentDashboardIdList = this.state.currentDashboardIdList;
<DashboardEditAccordion currentDashboard[this.state.activeItem] = service;
item={item} currentDashboardIdList[this.state.activeItem] = service.key;
onPress={this.updateDashboard} this.setState({
activeDashboard={currentDashboardIdList} currentDashboard: currentDashboard,
/> currentDashboardIdList: currentDashboardIdList,
); });
}; AsyncStorageManager.set(AsyncStorageManager.PREFERENCES.dashboardItems.key, currentDashboardIdList);
}
getListHeader(): React.Node { undoDashboard = () => {
const {currentDashboard} = this.state; this.setState({
return ( currentDashboard: [...this.initialDashboard],
<Card style={{margin: 5}}> currentDashboardIdList: [...this.initialDashboardIdList]
<Card.Content> });
<View style={{padding: 5}}> AsyncStorageManager.set(AsyncStorageManager.PREFERENCES.dashboardItems.key, this.initialDashboardIdList);
<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>
);
}
updateDashboard = (service: ServiceItemType) => { getListHeader() {
const {currentDashboard, currentDashboardIdList, activeItem} = this.state; return (
currentDashboard[activeItem] = service; <Card style={{margin: 5}}>
currentDashboardIdList[activeItem] = service.key; <Card.Content>
this.setState({ <View style={{padding: 5}}>
currentDashboard, <Button
currentDashboardIdList, mode={"contained"}
}); onPress={this.undoDashboard}
AsyncStorageManager.set( style={{
AsyncStorageManager.PREFERENCES.dashboardItems.key, marginLeft: "auto",
currentDashboardIdList, marginRight: "auto",
); 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(): React.Node { render() {
return ( return (
<CollapsibleFlatList <CollapsibleFlatList
data={this.content} data={this.content}
renderItem={this.getRenderItem} renderItem={this.renderItem}
ListHeaderComponent={this.getListHeader()} ListHeaderComponent={this.getListHeader()}
style={{}} style={{}}
/> />
); );
} }
} }
export default withTheme(DashboardEditScreen); export default withTheme(DashboardEditScreen);

View file

@ -1,45 +1,44 @@
// @flow // @flow
import * as React from 'react'; import * as React from 'react';
import {Platform} from 'react-native'; import {Platform} from "react-native";
import i18n from 'i18n-js'; import i18n from "i18n-js";
import {Searchbar} from 'react-native-paper'; import {Searchbar} from "react-native-paper";
import {StackNavigationProp} from '@react-navigation/stack'; import {stringMatchQuery} from "../../utils/Search";
import {stringMatchQuery} from '../../utils/Search'; import WebSectionList from "../../components/Screens/WebSectionList";
import WebSectionList from '../../components/Screens/WebSectionList'; import GroupListAccordion from "../../components/Lists/PlanexGroups/GroupListAccordion";
import GroupListAccordion from '../../components/Lists/PlanexGroups/GroupListAccordion'; import AsyncStorageManager from "../../managers/AsyncStorageManager";
import AsyncStorageManager from '../../managers/AsyncStorageManager'; import {StackNavigationProp} from "@react-navigation/stack";
const LIST_ITEM_HEIGHT = 70; const LIST_ITEM_HEIGHT = 70;
export type PlanexGroupType = { export type group = {
name: string, name: string,
id: number, id: number,
isFav: boolean, isFav: boolean,
}; };
export type PlanexGroupCategoryType = { export type groupCategory = {
name: string, name: string,
id: number, id: number,
content: Array<PlanexGroupType>, content: Array<group>,
}; };
type PropsType = { type Props = {
navigation: StackNavigationProp, navigation: StackNavigationProp,
}
type State = {
currentSearchString: string,
favoriteGroups: Array<group>,
}; };
type StateType = { function sortName(a: group | groupCategory, b: group | groupCategory) {
currentSearchString: string, if (a.name.toLowerCase() < b.name.toLowerCase())
favoriteGroups: Array<PlanexGroupType>, return -1;
}; if (a.name.toLowerCase() > b.name.toLowerCase())
return 1;
function sortName( return 0;
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';
@ -48,263 +47,232 @@ const REPLACE_REGEX = /_/g;
/** /**
* Class defining planex group selection screen. * Class defining planex group selection screen.
*/ */
class GroupSelectionScreen extends React.Component<PropsType, StateType> { class GroupSelectionScreen extends React.Component<Props, State> {
/**
* Removes the given group from the given array constructor(props: Props) {
* super(props);
* @param favorites The array containing favorites groups this.state = {
* @param group The group to remove from the array currentSearchString: '',
*/ 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;
}
} }
}
/** /**
* Adds the given group to the given array * Creates the header content
* */
* @param favorites The array containing favorites groups componentDidMount() {
* @param group The group to add to the array this.props.navigation.setOptions({
*/ headerTitle: this.getSearchBar,
static addGroupToFavorites( headerBackTitleVisible: false,
favorites: Array<PlanexGroupType>, headerTitleContainerStyle: Platform.OS === 'ios' ?
group: PlanexGroupType, {marginHorizontal: 0, width: '70%'} :
) { {marginHorizontal: 0, right: 50, left: 50},
const favGroup = {...group}; });
favGroup.isFav = true; }
favorites.push(favGroup);
favorites.sort(sortName);
}
constructor(props: PropsType) { /**
super(props); * Gets the header search bar
this.state = { *
currentSearchString: '', * @return {*}
favoriteGroups: AsyncStorageManager.getObject( */
AsyncStorageManager.PREFERENCES.planexFavoriteGroups.key, getSearchBar = () => {
), return (
<Searchbar
placeholder={i18n.t('screens.proximo.search')}
onChangeText={this.onSearchStringChange}
/>
);
}; };
}
/** /**
* Creates the header content * Callback used when the search changes
*/ *
componentDidMount() { * @param str The new search string
const [navigation] = this.props; */
navigation.setOptions({ onSearchStringChange = (str: string) => {
headerTitle: this.getSearchBar, this.setState({currentSearchString: str})
headerBackTitleVisible: false, };
headerTitleContainerStyle:
Platform.OS === 'ios'
? {marginHorizontal: 0, width: '70%'}
: {marginHorizontal: 0, right: 50, left: 50},
});
}
/** /**
* Gets the header search bar * Callback used when clicking an article in the list.
* * It opens the modal to show detailed information about the article
* @return {*} *
*/ * @param item The article pressed
getSearchBar = (): React.Node => { */
return ( onListItemPress = (item: group) => {
<Searchbar this.props.navigation.navigate("planex", {
placeholder={i18n.t('screens.proximo.search')} screen: "index",
onChangeText={this.onSearchStringChange} params: {group: item}
/> });
); };
};
/** /**
* Gets a render item for the given article * Callback used when the user clicks on the favorite button
* *
* @param item The article to render * @param item The item to add/remove from favorites
* @return {*} */
*/ onListFavoritePress = (item: group) => {
getRenderItem = ({item}: {item: PlanexGroupCategoryType}): React.Node => { this.updateGroupFavorites(item);
const {currentSearchString, favoriteGroups} = this.state; };
if (this.shouldDisplayAccordion(item)) {
return ( /**
<GroupListAccordion * Checks if the given group is in the favorites list
item={item} *
onGroupPress={this.onListItemPress} * @param group The group to check
onFavoritePress={this.onListFavoritePress} * @returns {boolean}
currentSearchString={currentSearchString} */
favoriteNumber={favoriteGroups.length} isGroupInFavorites(group: group) {
height={LIST_ITEM_HEIGHT} let isFav = false;
/> for (let i = 0; i < this.state.favoriteGroups.length; i++) {
); if (group.id === this.state.favoriteGroups[i].id) {
isFav = true;
break;
}
}
return isFav;
} }
return null;
};
/** /**
* Replaces underscore by spaces and sets the favorite state of every group in the given category * Removes the given group from the given array
* *
* @param groups The groups to format * @param favorites The array containing favorites groups
* @return {Array<PlanexGroupType>} * @param group The group to remove from the array
*/ */
getFormattedGroups(groups: Array<PlanexGroupType>): Array<PlanexGroupType> { removeGroupFromFavorites(favorites: Array<group>, group: group) {
return groups.map((group: PlanexGroupType): PlanexGroupType => { for (let i = 0; i < favorites.length; i++) {
const newGroup = {...group}; if (group.id === favorites[i].id) {
newGroup.name = group.name.replace(REPLACE_REGEX, ' '); favorites.splice(i, 1);
newGroup.isFav = this.isGroupInFavorites(group); break;
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;
}
/** /**
* Generates the dataset to be used in the FlatList. * Adds the given group to the given array
* This improves formatting of group names, sorts alphabetically the categories, and adds favorites at the top. *
* * @param favorites The array containing favorites groups
* @param fetchedData The raw data fetched from the server * @param group The group to add to the array
* @returns {[]} */
*/ addGroupToFavorites(favorites: Array<group>, group: group) {
generateData(fetchedData: { group.isFav = true;
[key: string]: PlanexGroupCategoryType, favorites.push(group);
}): Array<PlanexGroupCategoryType> { favorites.sort(sortName);
const {favoriteGroups} = this.state; }
const data = [];
// eslint-disable-next-line flowtype/no-weak-types
(Object.values(fetchedData): Array<any>).forEach(
(category: PlanexGroupCategoryType) => {
const newCat = {...category};
newCat.content = this.getFormattedGroups(category.content);
data.push(newCat);
},
);
data.sort(sortName);
data.unshift({
name: i18n.t('screens.planex.favorites'),
id: 0,
content: favoriteGroups,
});
return data;
}
render(): React.Node { /**
const {props, state} = this; * Adds or removes the given group to the favorites list, depending on whether it is already in it or not.
return ( * Favorites are then saved in user preferences
<WebSectionList *
navigation={props.navigation} * @param group The group to add/remove to favorites
createDataset={this.createDataset} */
autoRefreshTime={0} updateGroupFavorites(group: group) {
refreshOnFocus={false} let newFavorites = [...this.state.favoriteGroups]
fetchUrl={GROUPS_URL} if (this.isGroupInFavorites(group))
renderItem={this.getRenderItem} this.removeGroupFromFavorites(newFavorites, group);
updateData={state.currentSearchString + state.favoriteGroups.length} else
itemHeight={LIST_ITEM_HEIGHT} this.addGroupToFavorites(newFavorites, group);
/> this.setState({favoriteGroups: newFavorites})
); AsyncStorageManager.set(AsyncStorageManager.PREFERENCES.planexFavoriteGroups.key, newFavorites);
} }
/**
* Checks whether to display the given group category, depending on user search query
*
* @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,36 +1,37 @@
// @flow // @flow
import * as React from 'react'; import * as React from 'react';
import {withTheme} from 'react-native-paper'; import type {CustomTheme} from "../../managers/ThemeManager";
import i18n from 'i18n-js'; import ThemeManager from "../../managers/ThemeManager";
import {View} from 'react-native'; import WebViewScreen from "../../components/Screens/WebViewScreen";
import {CommonActions} from '@react-navigation/native'; import {withTheme} from "react-native-paper";
import {StackNavigationProp} from '@react-navigation/stack'; import i18n from "i18n-js";
import type {CustomTheme} from '../../managers/ThemeManager'; import {View} from "react-native";
import ThemeManager from '../../managers/ThemeManager'; import AsyncStorageManager from "../../managers/AsyncStorageManager";
import WebViewScreen from '../../components/Screens/WebViewScreen'; import AlertDialog from "../../components/Dialogs/AlertDialog";
import AsyncStorageManager from '../../managers/AsyncStorageManager'; import {dateToString, getTimeOnlyString} from "../../utils/Planning";
import AlertDialog from '../../components/Dialogs/AlertDialog'; import DateManager from "../../managers/DateManager";
import {dateToString, getTimeOnlyString} from '../../utils/Planning'; import AnimatedBottomBar from "../../components/Animations/AnimatedBottomBar";
import DateManager from '../../managers/DateManager'; import {CommonActions} from "@react-navigation/native";
import AnimatedBottomBar from '../../components/Animations/AnimatedBottomBar'; import ErrorView from "../../components/Screens/ErrorView";
import ErrorView from '../../components/Screens/ErrorView'; import {StackNavigationProp} from "@react-navigation/stack";
import type {PlanexGroupType} from './GroupSelectionScreen'; import type {group} 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 PropsType = { type Props = {
navigation: StackNavigationProp, navigation: StackNavigationProp,
route: {params: {group: PlanexGroupType}}, route: { params: { group: group } },
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/';
@ -65,32 +66,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 = `
@ -107,294 +108,272 @@ calendar.option({
} }
});`; });`;
const CUSTOM_CSS = 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}";
'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 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<PropsType, StateType> { class PlanexScreen extends React.Component<Props, State> {
webScreenRef: {current: null | WebViewScreen};
barRef: {current: null | AnimatedBottomBar}; webScreenRef: { current: null | WebViewScreen };
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: PropsType) { constructor(props) {
super(props); super(props);
this.webScreenRef = React.createRef(); this.webScreenRef = React.createRef();
this.barRef = React.createRef(); this.barRef = React.createRef();
let currentGroup = AsyncStorageManager.getString( let currentGroup = AsyncStorageManager.getString(AsyncStorageManager.PREFERENCES.planexCurrentGroup.key);
AsyncStorageManager.PREFERENCES.planexCurrentGroup.key, if (currentGroup === '')
); currentGroup = {name: "SELECT GROUP", id: -1, isFav: false};
if (currentGroup === '') else {
currentGroup = {name: 'SELECT GROUP', id: -1, isFav: false}; currentGroup = JSON.parse(currentGroup);
else { props.navigation.setOptions({title: currentGroup.name})
currentGroup = JSON.parse(currentGroup); }
props.navigation.setOptions({title: currentGroup.name}); this.state = {
dialogVisible: false,
dialogTitle: "",
dialogMessage: "",
currentGroup: currentGroup,
};
this.generateInjectedJS(currentGroup.id);
} }
this.state = {
dialogVisible: false, /**
dialogTitle: '', * Register for events and show the banner after 2 seconds
dialogMessage: '', */
currentGroup, componentDidMount() {
this.props.navigation.addListener('focus', this.onScreenFocus);
}
/**
* Callback used when the user clicks on the navigate to settings button.
* This will hide the banner and open the SettingsScreen
*/
onGoToSettings = () => this.props.navigation.navigate('settings');
onScreenFocus = () => {
this.handleNavigationParams();
}; };
this.generateInjectedJS(currentGroup.id);
}
/** /**
* Register for events and show the banner after 2 seconds * If navigations parameters contain a group, set it as selected
*/ */
componentDidMount() { handleNavigationParams = () => {
const {navigation} = this.props; if (this.props.route.params != null) {
navigation.addListener('focus', this.onScreenFocus); 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}));
}
}
};
/** /**
* Only update the screen if the dark theme changed * Sends the webpage a message with the new group to select and save it to preferences
* *
* @param nextProps * @param group The group object selected
* @returns {boolean} */
*/ selectNewGroup(group: group) {
shouldComponentUpdate(nextProps: PropsType): boolean { this.sendMessage('setGroup', group.id);
const {props, state} = this; this.setState({currentGroup: group});
if (nextProps.theme.dark !== props.theme.dark) AsyncStorageManager.set(AsyncStorageManager.PREFERENCES.planexCurrentGroup.key, group);
this.generateInjectedJS(state.currentGroup.id); this.props.navigation.setOptions({title: group.name});
return true; this.generateInjectedJS(group.id);
}
/**
* 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}));
}
} }
};
/** /**
* Sends the webpage a message with the new group to select and save it to preferences * Generates custom JavaScript to be injected into the webpage
* *
* @param group The group object selected * @param groupID The current group selected
*/ */
selectNewGroup(group: PlanexGroupType) { generateInjectedJS(groupID: number) {
const {navigation} = this.props; this.customInjectedJS = "$(document).ready(function() {"
this.sendMessage('setGroup', group.id.toString()); + OBSERVE_MUTATIONS_INJECTED
this.setState({currentGroup: group}); + FULL_CALENDAR_SETTINGS
AsyncStorageManager.set( + "displayAde(" + groupID + ");" // Reset Ade
AsyncStorageManager.PREFERENCES.planexCurrentGroup.key, + (DateManager.isWeekend(new Date()) ? "calendar.next()" : "")
group, + INJECT_STYLE;
);
navigation.setOptions({title: group.name});
this.generateInjectedJS(group.id);
}
/** if (ThemeManager.getNightMode())
* Generates custom JavaScript to be injected into the webpage this.customInjectedJS += "$('head').append('<style>" + CUSTOM_CSS_DARK + "</style>');";
*
* @param groupID The current group selected
*/
generateInjectedJS(groupID: number) {
this.customInjectedJS = `$(document).ready(function() {${OBSERVE_MUTATIONS_INJECTED}${FULL_CALENDAR_SETTINGS}displayAde(${groupID});${
// Reset Ade
DateManager.isWeekend(new Date()) ? 'calendar.next()' : ''
}${INJECT_STYLE}`;
if (ThemeManager.getNightMode()) this.customInjectedJS += 'removeAlpha();});true;'; // Prevents crash on ios
this.customInjectedJS += `$('head').append('<style>${CUSTOM_CSS_DARK}</style>');`; }
this.customInjectedJS += 'removeAlpha();});true;'; // Prevents crash on ios /**
} * Only update the screen if the dark theme changed
*
* @param nextProps
* @returns {boolean}
*/
shouldComponentUpdate(nextProps: Props): boolean {
if (nextProps.theme.dark !== this.props.theme.dark)
this.generateInjectedJS(this.state.currentGroup.id);
return true;
}
render(): React.Node {
const {props, state} = this; /**
return ( * Sends a FullCalendar action to the web page inside the webview.
<View style={{flex: 1}}> *
{/* Allow to draw webview bellow banner */} * @param action The action to perform, as described in the FullCalendar doc https://fullcalendar.io/docs/v3.
<View * Or "setGroup" with the group id as data to set the selected group
style={{ * @param data Data to pass to the action
position: 'absolute', */
height: '100%', sendMessage = (action: string, data: any) => {
width: '100%', let command;
}}> if (action === "setGroup")
{props.theme.dark ? ( // Force component theme update by recreating it on theme change command = "displayAde(" + data + ")";
this.getWebView() else
) : ( command = "$('#calendar').fullCalendar('" + action + "', '" + data + "')";
<View style={{height: '100%'}}>{this.getWebView()}</View> if (this.webScreenRef.current != null)
)} this.webScreenRef.current.injectJavaScript(command + ';true;'); // Injected javascript must end with true
</View> };
{AsyncStorageManager.getString(
AsyncStorageManager.PREFERENCES.defaultStartScreen.key, /**
).toLowerCase() !== 'planex' ? ( * Shows a dialog when the user clicks on an event.
<MascotPopup *
prefKey={AsyncStorageManager.PREFERENCES.planexShowBanner.key} * @param event
title={i18n.t('screens.planex.mascotDialog.title')} */
message={i18n.t('screens.planex.mascotDialog.message')} onMessage = (event: { nativeEvent: { data: string } }) => {
icon="emoticon-kiss" const data: { start: string, end: string, title: string, color: string } = JSON.parse(event.nativeEvent.data);
buttons={{ const startDate = dateToString(new Date(data.start), true);
action: { const endDate = dateToString(new Date(data.end), true);
message: i18n.t('screens.planex.mascotDialog.ok'), const startString = getTimeOnlyString(startDate);
icon: 'cog', const endString = getTimeOnlyString(endDate);
onPress: this.onGoToSettings,
}, let msg = DateManager.getInstance().getTranslatedDate(startDate) + "\n";
cancel: { if (startString != null && endString != null)
message: i18n.t('screens.planex.mascotDialog.cancel'), msg += startString + ' - ' + endString;
icon: 'close', this.showDialog(data.title, msg)
color: props.theme.colors.warning, };
},
}} /**
emotion={MASCOT_STYLE.INTELLO} * Shows a simple dialog to the user.
/> *
) : null} * @param title The dialog's title
<AlertDialog * @param message The message to show
visible={state.dialogVisible} */
onDismiss={this.hideDialog} showDialog = (title: string, message: string) => {
title={state.dialogTitle} this.setState({
message={state.dialogMessage} dialogVisible: true,
/> dialogTitle: title,
<AnimatedBottomBar dialogMessage: message,
navigation={props.navigation} });
ref={this.barRef} };
onPress={this.sendMessage}
seekAttention={state.currentGroup.id === -1} /**
/> * Hides the dialog
</View> */
); 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,74 +2,58 @@
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 CollapsibleScrollView from '../../../components/Collapsible/CollapsibleScrollView'; import {StackNavigationProp} from "@react-navigation/stack";
import CollapsibleScrollView from "../../../components/Collapsible/CollapsibleScrollView";
const LOGO = 'https://etud.insa-toulouse.fr/~amicale_app/images/Proximo.png'; type Props = {
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.
*/ */
// eslint-disable-next-line react/prefer-stateless-function export default class ProximoAboutScreen extends React.Component<Props> {
export default class ProximoAboutScreen extends React.Component<null> {
render(): React.Node { render() {
return ( return (
<CollapsibleScrollView style={{padding: 5}}> <CollapsibleScrollView style={{padding: 5}}>
<View <View style={{
style={{ width: '100%',
width: '100%', height: 100,
height: 100, marginTop: 20,
marginTop: 20, marginBottom: 20,
marginBottom: 20, justifyContent: 'center',
justifyContent: 'center', alignItems: 'center'
alignItems: 'center', }}>
}}> <Image
<Image source={{uri: LOGO}}
source={{uri: LOGO}} style={{height: '100%', width: '100%', resizeMode: "contain"}}/>
style={{height: '100%', width: '100%', resizeMode: 'contain'}} </View>
/> <Text>{i18n.t('screens.proximo.description')}</Text>
</View> <Card style={{margin: 5}}>
<Text>{i18n.t('screens.proximo.description')}</Text> <Card.Title
<Card style={{margin: 5}}> title={i18n.t('screens.proximo.openingHours')}
<Card.Title left={props => <List.Icon {...props} icon={'clock-outline'}/>}
title={i18n.t('screens.proximo.openingHours')} />
left={({ <Card.Content>
size, <Paragraph>18h30 - 19h30</Paragraph>
color, </Card.Content>
}: { </Card>
size: number, <Card style={{margin: 5, marginBottom: CustomTabBar.TAB_BAR_HEIGHT + 20}}>
color: string, <Card.Title
}): React.Node => ( title={i18n.t('screens.proximo.paymentMethods')}
<List.Icon size={size} color={color} icon="clock-outline" /> left={props => <List.Icon {...props} icon={'cash'}/>}
)} />
/> <Card.Content>
<Card.Content> <Paragraph>{i18n.t('screens.proximo.paymentMethodsDescription')}</Paragraph>
<Paragraph>18h30 - 19h30</Paragraph> </Card.Content>
</Card.Content> </Card>
</Card> </CollapsibleScrollView>
<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,381 +1,323 @@
// @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 { import CustomModal from "../../../components/Overrides/CustomModal";
RadioButton, import {RadioButton, Searchbar, Subheading, Text, Title, withTheme} from "react-native-paper";
Searchbar, import {stringMatchQuery} from "../../../utils/Search";
Subheading, import ProximoListItem from "../../../components/Lists/Proximo/ProximoListItem";
Text, import MaterialHeaderButtons, {Item} from "../../../components/Overrides/CustomHeaderButton";
Title, import {StackNavigationProp} from "@react-navigation/stack";
withTheme, import type {CustomTheme} from "../../../managers/ThemeManager";
} from 'react-native-paper'; import CollapsibleFlatList from "../../../components/Collapsible/CollapsibleFlatList";
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: ProximoArticleType, b: ProximoArticleType): number { function sortPrice(a, b) {
return parseInt(a.price, 10) - parseInt(b.price, 10); return a.price - b.price;
} }
function sortPriceReverse( function sortPriceReverse(a, b) {
a: ProximoArticleType, return b.price - a.price;
b: ProximoArticleType,
): number {
return parseInt(b.price, 10) - parseInt(a.price, 10);
} }
function sortName(a: ProximoArticleType, b: ProximoArticleType): number { function sortName(a, b) {
if (a.name.toLowerCase() < b.name.toLowerCase()) return -1; if (a.name.toLowerCase() < b.name.toLowerCase())
if (a.name.toLowerCase() > b.name.toLowerCase()) return 1; return -1;
return 0; if (a.name.toLowerCase() > b.name.toLowerCase())
return 1;
return 0;
} }
function sortNameReverse(a: ProximoArticleType, b: ProximoArticleType): number { function sortNameReverse(a, b) {
if (a.name.toLowerCase() < b.name.toLowerCase()) return 1; if (a.name.toLowerCase() < b.name.toLowerCase())
if (a.name.toLowerCase() > b.name.toLowerCase()) return -1; return 1;
return 0; if (a.name.toLowerCase() > b.name.toLowerCase())
return -1;
return 0;
} }
const LIST_ITEM_HEIGHT = 84; const LIST_ITEM_HEIGHT = 84;
type PropsType = { type Props = {
navigation: StackNavigationProp, navigation: StackNavigationProp,
route: { route: { params: { data: { data: Object }, shouldFocusSearchBar: boolean } },
params: { theme: CustomTheme,
data: {data: Array<ProximoArticleType>}, }
shouldFocusSearchBar: boolean,
},
},
theme: CustomTheme,
};
type StateType = { type State = {
currentSortMode: number, currentSortMode: number,
modalCurrentDisplayItem: React.Node, modalCurrentDisplayItem: React.Node,
currentSearchString: string, currentSearchString: string,
}; };
/** /**
* Class defining Proximo article list of a certain category. * Class defining proximo's article list of a certain category.
*/ */
class ProximoListScreen extends React.Component<PropsType, StateType> { class ProximoListScreen extends React.Component<Props, State> {
modalRef: Modalize | null;
listData: Array<ProximoArticleType>; modalRef: Object;
listData: Array<Object>;
shouldFocusSearchBar: boolean;
shouldFocusSearchBar: boolean; constructor(props) {
super(props);
constructor(props: PropsType) { this.listData = this.props.route.params['data']['data'].sort(sortName);
super(props); this.shouldFocusSearchBar = this.props.route.params['shouldFocusSearchBar'];
this.listData = props.route.params.data.data.sort(sortName); this.state = {
this.shouldFocusSearchBar = props.route.params.shouldFocusSearchBar; currentSearchString: '',
this.state = { currentSortMode: 3,
currentSearchString: '', modalCurrentDisplayItem: null,
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});
};
/** /**
* Callback used when clicking an article in the list. * Creates the header content
* It opens the modal to show detailed information about the article */
* componentDidMount() {
* @param item The article pressed this.props.navigation.setOptions({
*/ headerRight: this.getSortMenuButton,
onListItemPress(item: ProximoArticleType) { headerTitle: this.getSearchBar,
this.setState({ headerBackTitleVisible: false,
modalCurrentDisplayItem: this.getModalItemContent(item), headerTitleContainerStyle: Platform.OS === 'ios' ?
}); {marginHorizontal: 0, width: '70%'} :
if (this.modalRef) { {marginHorizontal: 0, right: 50, left: 50},
this.modalRef.open(); });
} }
}
/** /**
* Sets the current sort mode. * Gets the header search bar
* *
* @param mode The number representing the mode * @return {*}
*/ */
setSortMode(mode: string) { getSearchBar = () => {
const {currentSortMode} = this.state; return (
const currentMode = parseInt(mode, 10); <Searchbar
this.setState({ placeholder={i18n.t('screens.proximo.search')}
currentSortMode: currentMode, onChangeText={this.onSearchStringChange}
});
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 modal content to display a sort menu * Gets the sort menu header button
* *
* @return {*} * @return {*}
*/ */
getModalSortMenu(): React.Node { getSortMenuButton = () => {
const {currentSortMode} = this.state; return <MaterialHeaderButtons>
return ( <Item title="main" iconName="sort" onPress={this.onSortMenuPress}/>
<View </MaterialHeaderButtons>;
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>
);
}
/** /**
* Gets a render item for the given article * Callback used when clicking on the sort menu button.
* * It will open the modal to show a sort selection
* @param item The article to render */
* @return {*} onSortMenuPress = () => {
*/ this.setState({
getRenderItem = ({item}: {item: ProximoArticleType}): React.Node => { modalCurrentDisplayItem: this.getModalSortMenu()
const {currentSearchString} = this.state; });
if (stringMatchQuery(item.name, currentSearchString)) { if (this.modalRef) {
const onPress = () => { this.modalRef.open();
this.onListItemPress(item); }
}; };
const color = this.getStockColor(parseInt(item.quantity, 10));
return ( /**
<ProximoListItem * Sets the current sort mode.
item={item} *
onPress={onPress} * @param mode The number representing the mode
color={color} */
height={LIST_ITEM_HEIGHT} setSortMode(mode: number) {
/> 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;
};
/** /**
* Extracts a key for the given article * Gets a color depending on the quantity available
* *
* @param item The article to extract the key from * @param availableStock The quantity available
* @return {string} The extracted key * @return
*/ */
keyExtractor = (item: ProximoArticleType): string => item.name + item.code; getStockColor(availableStock: number) {
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 receiving the modal ref * Callback used when the search changes
* *
* @param ref * @param str The new search string
*/ */
onModalRef = (ref: Modalize) => { onSearchStringChange = (str: string) => {
this.modalRef = ref; this.setState({currentSearchString: str})
}; };
itemLayout = ( /**
data: ProximoArticleType, * Gets the modal content depending on the given article
index: number, *
): {length: number, offset: number, index: number} => ({ * @param item The article to display
length: LIST_ITEM_HEIGHT, * @return {*}
offset: LIST_ITEM_HEIGHT * index, */
index, getModalItemContent(item: Object) {
}); 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>
render(): React.Node { <ScrollView>
const {state} = this; <View style={{width: '100%', height: 150, marginTop: 20, marginBottom: 20}}>
return ( <Image style={{flex: 1, resizeMode: "contain"}}
<View source={{uri: item.image}}/>
style={{ </View>
height: '100%', <Text>{item.description}</Text>
}}> </ScrollView>
<CustomModal onRef={this.onModalRef}> </View>
{state.modalCurrentDisplayItem} );
</CustomModal> }
<CollapsibleFlatList
data={this.listData} /**
extraData={state.currentSearchString + state.currentSortMode} * Gets the modal content to display a sort menu
keyExtractor={this.keyExtractor} *
renderItem={this.getRenderItem} * @return {*}
// Performance props, see https://reactnative.dev/docs/optimizing-flatlist-configuration */
removeClippedSubviews getModalSortMenu() {
getItemLayout={this.itemLayout} return (
initialNumToRender={10} <View style={{
/> flex: 1,
</View> padding: 20
); }}>
} <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,289 +1,233 @@
// @flow // @flow
import * as React from 'react'; import * as React from 'react';
import i18n from 'i18n-js'; import {View} from 'react-native'
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 {StackNavigationProp} from '@react-navigation/stack'; import MaterialHeaderButtons, {Item} from "../../../components/Overrides/CustomHeaderButton";
import WebSectionList from '../../../components/Screens/WebSectionList'; import {StackNavigationProp} from "@react-navigation/stack";
import MaterialHeaderButtons, { import type {CustomTheme} from "../../../managers/ThemeManager";
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;
export type ProximoCategoryType = { type Props = {
name: string, navigation: StackNavigationProp,
icon: string, theme: CustomTheme,
id: string, }
};
export type ProximoArticleType = { type State = {
name: string, fetchedData: Object,
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<PropsType> { class ProximoMainScreen extends React.Component<Props, State> {
/**
* 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();
// Make 'All' category with id -1 stick to the top articles: Object;
if (a.type.id === -1) return -1;
if (b.type.id === -1) return 1;
// Sort others by name ascending /**
if (str1 < str2) return -1; * 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
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
* Get an array of available articles (in stock) of the given type if (a.type.id === -1)
* return -1;
* @param articles The list of all articles if (b.type.id === -1)
* @param type The type of articles to find (undefined for any type) return 1;
* @return {Array} The array of available articles
*/ // Sort others by name ascending
static getAvailableArticles( if (str1 < str2)
articles: Array<ProximoArticleType> | null, return -1;
type: ?ProximoCategoryType, if (str1 > str2)
): Array<ProximoArticleType> { return 1;
const availableArticles = []; return 0;
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
/** */
* Creates header button componentDidMount() {
*/ const rightButton = this.getHeaderButtons.bind(this);
componentDidMount() { this.props.navigation.setOptions({
const {navigation} = this.props; headerRight: rightButton,
navigation.setOptions({
headerRight: (): React.Node => this.getHeaderButtons(),
});
}
/**
* Callback used when the search button is pressed.
* This will open a new ProximoListScreen with all items displayed
*/
onPressSearchBtn = () => {
const {navigation} = this.props;
const 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.
* This will open the ProximoAboutScreen
*/
onPressAboutBtn = () => {
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;
};
/**
* Creates the dataset to be used in the FlatList
*
* @param fetchedData
* @return {*}
* */
createDataset = (
fetchedData: ProximoDataType | null,
): 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 { /**
const {navigation} = this.props; * Callback used when the search button is pressed.
return ( * This will open a new ProximoListScreen with all items displayed
<WebSectionList */
createDataset={this.createDataset} onPressSearchBtn = () => {
navigation={navigation} let searchScreenData = {
autoRefreshTime={0} shouldFocusSearchBar: true,
refreshOnFocus={false} data: {
fetchUrl={DATA_URL} type: {
renderItem={this.getRenderItem} id: "0",
/> name: i18n.t('screens.proximo.all'),
); icon: 'star'
} },
data: this.articles !== undefined ?
this.getAvailableArticles(this.articles, undefined) : []
},
};
this.props.navigation.navigate('proximo-list', searchScreenData);
};
/**
* Callback used when the about button is pressed.
* This will open the ProximoAboutScreen
*/
onPressAboutBtn = () => {
this.props.navigation.navigate('proximo-about');
}
/**
* Gets the header buttons
* @return {*}
*/
getHeaderButtons() {
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: Object) {
return item !== undefined ? item.type['id'] : undefined;
}
/**
* 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,20 +1,19 @@
// @flow // @flow
import i18n from 'i18n-js'; import type {Device} from "../screens/Amicale/Equipment/EquipmentListScreen";
import type {DeviceType} from '../screens/Amicale/Equipment/EquipmentListScreen'; import i18n from "i18n-js";
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(): Date { export function getCurrentDay() {
const today = new Date(Date.now()); let today = new Date(Date.now());
today.setUTCHours(0, 0, 0, 0); today.setUTCHours(0, 0, 0, 0);
return today; return today;
} }
/** /**
@ -23,8 +22,8 @@ export function getCurrentDay(): Date {
* @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): string { export function getISODate(date: Date) {
return date.toISOString().split('T')[0]; return date.toISOString().split("T")[0];
} }
/** /**
@ -33,16 +32,18 @@ export function getISODate(date: Date): string {
* @param item * @param item
* @returns {boolean} * @returns {boolean}
*/ */
export function isEquipmentAvailable(item: DeviceType): boolean { export function isEquipmentAvailable(item: Device) {
let isAvailable = true; let isAvailable = true;
const today = getCurrentDay(); const today = getCurrentDay();
const dates = item.booked_at; const dates = item.booked_at;
dates.forEach((date: {begin: string, end: string}) => { for (let i = 0; i < dates.length; i++) {
const start = new Date(date.begin); const start = new Date(dates[i].begin);
const end = new Date(date.end); const end = new Date(dates[i].end);
if (!(today < start || today > end)) isAvailable = false; isAvailable = today < start || today > end;
}); if (!isAvailable)
return isAvailable; break;
}
return isAvailable;
} }
/** /**
@ -51,16 +52,17 @@ export function isEquipmentAvailable(item: DeviceType): boolean {
* @param item * @param item
* @returns {Date} * @returns {Date}
*/ */
export function getFirstEquipmentAvailability(item: DeviceType): Date { export function getFirstEquipmentAvailability(item: Device) {
let firstAvailability = getCurrentDay(); let firstAvailability = getCurrentDay();
const dates = item.booked_at; const dates = item.booked_at;
dates.forEach((date: {begin: string, end: string}) => { for (let i = 0; i < dates.length; i++) {
const start = new Date(date.begin); const start = new Date(dates[i].begin);
const end = new Date(date.end); let end = new Date(dates[i].end);
end.setDate(end.getDate() + 1); end.setDate(end.getDate() + 1);
if (firstAvailability >= start) firstAvailability = end; if (firstAvailability >= start)
}); firstAvailability = end;
return firstAvailability; }
return firstAvailability;
} }
/** /**
@ -68,31 +70,31 @@ export function getFirstEquipmentAvailability(item: DeviceType): Date {
* *
* @param date The date to translate * @param date The date to translate
*/ */
export function getRelativeDateString(date: Date): string { export function getRelativeDateString(date: Date) {
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;
} }
/** /**
@ -109,45 +111,41 @@ export function getRelativeDateString(date: Date): string {
* @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( export function getValidRange(start: Date, end: Date, item: Device | null) {
start: Date, let direction = start <= end ? 1 : -1;
end: Date, let limit = new Date(end);
item: DeviceType | null, limit.setDate(limit.getDate() + direction); // Limit is excluded, but we want to include range end
): Array<string> { if (item != null) {
const direction = start <= end ? 1 : -1; if (direction === 1) {
let limit = new Date(end); for (let i = 0; i < item.booked_at.length; i++) {
limit.setDate(limit.getDate() + direction); // Limit is excluded, but we want to include range end const bookLimit = new Date(item.booked_at[i].begin);
if (item != null) { if (start < bookLimit && limit > bookLimit) {
if (direction === 1) { limit = bookLimit;
for (let i = 0; i < item.booked_at.length; i += 1) { break;
const bookLimit = new Date(item.booked_at[i].begin); }
if (start < bookLimit && limit > bookLimit) { }
limit = bookLimit; } else {
break; for (let i = item.booked_at.length - 1; i >= 0; i--) {
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 = [];
const date = new Date(start); let validRange = [];
while ( let date = new Date(start);
(direction === 1 && date < limit) || while ((direction === 1 && date < limit) || (direction === -1 && date > limit)) {
(direction === -1 && date > limit) if (direction === 1)
) { validRange.push(getISODate(date));
if (direction === 1) validRange.push(getISODate(date)); else
else validRange.unshift(getISODate(date)); validRange.unshift(getISODate(date));
date.setDate(date.getDate() + direction); date.setDate(date.getDate() + direction);
} }
return validRange; return validRange;
} }
/** /**
@ -159,24 +157,20 @@ export function getValidRange(
* @param range The range to mark dates for * @param range The range to mark dates for
* @returns {{}} * @returns {{}}
*/ */
export function generateMarkedDates( export function generateMarkedDates(isSelection: boolean, theme: CustomTheme, range: Array<string>) {
isSelection: boolean, let markedDates = {}
theme: CustomTheme, for (let i = 0; i < range.length; i++) {
range: Array<string>, const isStart = i === 0;
): MarkedDatesObjectType { const isEnd = i === range.length - 1;
const markedDates = {}; markedDates[range[i]] = {
for (let i = 0; i < range.length; i += 1) { startingDay: isStart,
const isStart = i === 0; endingDay: isEnd,
const isEnd = i === range.length - 1; color: isSelection
let color; ? isStart || isEnd
if (isSelection && (isStart || isEnd)) color = theme.colors.primary; ? theme.colors.primary
else if (isSelection) color = theme.colors.danger; : theme.colors.danger
else color = theme.colors.textDisabled; : theme.colors.textDisabled
markedDates[range[i]] = { };
startingDay: isStart, }
endingDay: isEnd, return markedDates;
color,
};
}
return markedDates;
} }