Compare commits

...

4 commits

18 changed files with 2885 additions and 2616 deletions

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -1,233 +1,289 @@
// @flow
import * as React from 'react';
import {View} from 'react-native'
import i18n from "i18n-js";
import WebSectionList from "../../../components/Screens/WebSectionList";
import i18n from 'i18n-js';
import {List, withTheme} from 'react-native-paper';
import MaterialHeaderButtons, {Item} from "../../../components/Overrides/CustomHeaderButton";
import {StackNavigationProp} from "@react-navigation/stack";
import type {CustomTheme} from "../../../managers/ThemeManager";
import {StackNavigationProp} from '@react-navigation/stack';
import WebSectionList from '../../../components/Screens/WebSectionList';
import MaterialHeaderButtons, {
Item,
} from '../../../components/Overrides/CustomHeaderButton';
import type {CustomTheme} from '../../../managers/ThemeManager';
import type {SectionListDataType} from '../../../components/Screens/WebSectionList';
const DATA_URL = "https://etud.insa-toulouse.fr/~proximo/data/stock-v2.json";
const DATA_URL = 'https://etud.insa-toulouse.fr/~proximo/data/stock-v2.json';
const LIST_ITEM_HEIGHT = 84;
type Props = {
navigation: StackNavigationProp,
theme: CustomTheme,
}
export type ProximoCategoryType = {
name: string,
icon: string,
id: string,
};
type State = {
fetchedData: Object,
}
export type ProximoArticleType = {
name: string,
description: string,
quantity: string,
price: string,
code: string,
id: string,
type: Array<string>,
image: string,
};
export type ProximoMainListItemType = {
type: ProximoCategoryType,
data: Array<ProximoArticleType>,
};
export type ProximoDataType = {
types: Array<ProximoCategoryType>,
articles: Array<ProximoArticleType>,
};
type PropsType = {
navigation: StackNavigationProp,
theme: CustomTheme,
};
/**
* Class defining the main proximo screen.
* This screen shows the different categories of articles offered by proximo.
*/
class ProximoMainScreen extends React.Component<Props, State> {
class ProximoMainScreen extends React.Component<PropsType> {
/**
* Function used to sort items in the list.
* Makes the All category sticks to the top and sorts the others by name ascending
*
* @param a
* @param b
* @return {number}
*/
static sortFinalData(
a: ProximoMainListItemType,
b: ProximoMainListItemType,
): number {
const str1 = a.type.name.toLowerCase();
const str2 = b.type.name.toLowerCase();
articles: Object;
// Make 'All' category with id -1 stick to the top
if (a.type.id === -1) return -1;
if (b.type.id === -1) return 1;
/**
* Function used to sort items in the list.
* Makes the All category stick to the top and sorts the others by name ascending
*
* @param a
* @param b
* @return {number}
*/
static sortFinalData(a: Object, b: Object) {
let str1 = a.type.name.toLowerCase();
let str2 = b.type.name.toLowerCase();
// Sort others by name ascending
if (str1 < str2) return -1;
if (str1 > str2) return 1;
return 0;
}
// Make 'All' category with id -1 stick to the top
if (a.type.id === -1)
return -1;
if (b.type.id === -1)
return 1;
// Sort others by name ascending
if (str1 < str2)
return -1;
if (str1 > str2)
return 1;
return 0;
/**
* 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
*/
static getAvailableArticles(
articles: Array<ProximoArticleType> | null,
type: ?ProximoCategoryType,
): Array<ProximoArticleType> {
const availableArticles = [];
if (articles != null) {
articles.forEach((article: ProximoArticleType) => {
if (
((type != null && article.type.includes(type.id)) || type == null) &&
parseInt(article.quantity, 10) > 0
)
availableArticles.push(article);
});
}
return availableArticles;
}
/**
* Creates header button
*/
componentDidMount() {
const rightButton = this.getHeaderButtons.bind(this);
this.props.navigation.setOptions({
headerRight: rightButton,
});
}
articles: Array<ProximoArticleType> | null;
/**
* Callback used when the search button is pressed.
* This will open a new ProximoListScreen with all items displayed
*/
onPressSearchBtn = () => {
let searchScreenData = {
shouldFocusSearchBar: true,
data: {
type: {
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);
/**
* Creates header button
*/
componentDidMount() {
const {navigation} = this.props;
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 = () => {
this.props.navigation.navigate('proximo-about');
/**
* 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;
};
/**
* 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>;
/**
* 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;
}
/**
* 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}/>
);
}
render(): React.Node {
const {navigation} = this.props;
return (
<WebSectionList
createDataset={this.createDataset}
navigation={navigation}
autoRefreshTime={0}
refreshOnFocus={false}
fetchUrl={DATA_URL}
renderItem={this.getRenderItem}
/>
);
}
}
export default withTheme(ProximoMainScreen);

View file

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