Compare commits

..

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

18 changed files with 2623 additions and 2892 deletions

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -1,44 +1,43 @@
// @flow // @flow
import * as React from 'react'; import * as React from 'react';
import {Platform} from 'react-native'; import {Platform} from "react-native";
import i18n from 'i18n-js'; import i18n from "i18n-js";
import {Searchbar} from 'react-native-paper'; import {Searchbar} from "react-native-paper";
import {StackNavigationProp} from '@react-navigation/stack'; import {stringMatchQuery} from "../../utils/Search";
import {stringMatchQuery} from '../../utils/Search'; import WebSectionList from "../../components/Screens/WebSectionList";
import WebSectionList from '../../components/Screens/WebSectionList'; import GroupListAccordion from "../../components/Lists/PlanexGroups/GroupListAccordion";
import GroupListAccordion from '../../components/Lists/PlanexGroups/GroupListAccordion'; import AsyncStorageManager from "../../managers/AsyncStorageManager";
import AsyncStorageManager from '../../managers/AsyncStorageManager'; import {StackNavigationProp} from "@react-navigation/stack";
const LIST_ITEM_HEIGHT = 70; const LIST_ITEM_HEIGHT = 70;
export type PlanexGroupType = { export type group = {
name: string, name: string,
id: number, id: number,
isFav: boolean, isFav: boolean,
}; };
export type PlanexGroupCategoryType = { export type groupCategory = {
name: string, name: string,
id: number, id: number,
content: Array<PlanexGroupType>, content: Array<group>,
}; };
type PropsType = { type Props = {
navigation: StackNavigationProp, navigation: StackNavigationProp,
}; }
type StateType = { type State = {
currentSearchString: string, currentSearchString: string,
favoriteGroups: Array<PlanexGroupType>, favoriteGroups: Array<group>,
}; };
function sortName( function sortName(a: group | groupCategory, b: group | groupCategory) {
a: PlanexGroupType | PlanexGroupCategoryType, if (a.name.toLowerCase() < b.name.toLowerCase())
b: PlanexGroupType | PlanexGroupCategoryType, return -1;
): number { if (a.name.toLowerCase() > b.name.toLowerCase())
if (a.name.toLowerCase() < b.name.toLowerCase()) return -1; return 1;
if (a.name.toLowerCase() > b.name.toLowerCase()) return 1;
return 0; return 0;
} }
@ -48,18 +47,99 @@ const REPLACE_REGEX = /_/g;
/** /**
* Class defining planex group selection screen. * Class defining planex group selection screen.
*/ */
class GroupSelectionScreen extends React.Component<PropsType, StateType> { class GroupSelectionScreen extends React.Component<Props, State> {
constructor(props: Props) {
super(props);
this.state = {
currentSearchString: '',
favoriteGroups: AsyncStorageManager.getObject(AsyncStorageManager.PREFERENCES.planexFavoriteGroups.key),
};
}
/**
* Creates the header content
*/
componentDidMount() {
this.props.navigation.setOptions({
headerTitle: this.getSearchBar,
headerBackTitleVisible: false,
headerTitleContainerStyle: Platform.OS === 'ios' ?
{marginHorizontal: 0, width: '70%'} :
{marginHorizontal: 0, right: 50, left: 50},
});
}
/**
* Gets the header search bar
*
* @return {*}
*/
getSearchBar = () => {
return (
<Searchbar
placeholder={i18n.t('screens.proximo.search')}
onChangeText={this.onSearchStringChange}
/>
);
};
/**
* Callback used when the search changes
*
* @param str The new search string
*/
onSearchStringChange = (str: string) => {
this.setState({currentSearchString: str})
};
/**
* Callback used when clicking an article in the list.
* It opens the modal to show detailed information about the article
*
* @param item The article pressed
*/
onListItemPress = (item: group) => {
this.props.navigation.navigate("planex", {
screen: "index",
params: {group: item}
});
};
/**
* Callback used when the user clicks on the favorite button
*
* @param item The item to add/remove from favorites
*/
onListFavoritePress = (item: group) => {
this.updateGroupFavorites(item);
};
/**
* Checks if the given group is in the favorites list
*
* @param group The group to check
* @returns {boolean}
*/
isGroupInFavorites(group: group) {
let isFav = false;
for (let i = 0; i < this.state.favoriteGroups.length; i++) {
if (group.id === this.state.favoriteGroups[i].id) {
isFav = true;
break;
}
}
return isFav;
}
/** /**
* Removes the given group from the given array * Removes the given group from the given array
* *
* @param favorites The array containing favorites groups * @param favorites The array containing favorites groups
* @param group The group to remove from the array * @param group The group to remove from the array
*/ */
static removeGroupFromFavorites( removeGroupFromFavorites(favorites: Array<group>, group: group) {
favorites: Array<PlanexGroupType>, for (let i = 0; i < favorites.length; i++) {
group: PlanexGroupType,
) {
for (let i = 0; i < favorites.length; i += 1) {
if (group.id === favorites[i].id) { if (group.id === favorites[i].id) {
favorites.splice(i, 1); favorites.splice(i, 1);
break; break;
@ -73,174 +153,26 @@ class GroupSelectionScreen extends React.Component<PropsType, StateType> {
* @param favorites The array containing favorites groups * @param favorites The array containing favorites groups
* @param group The group to add to the array * @param group The group to add to the array
*/ */
static addGroupToFavorites( addGroupToFavorites(favorites: Array<group>, group: group) {
favorites: Array<PlanexGroupType>, group.isFav = true;
group: PlanexGroupType, favorites.push(group);
) {
const favGroup = {...group};
favGroup.isFav = true;
favorites.push(favGroup);
favorites.sort(sortName); favorites.sort(sortName);
} }
constructor(props: PropsType) {
super(props);
this.state = {
currentSearchString: '',
favoriteGroups: AsyncStorageManager.getObject(
AsyncStorageManager.PREFERENCES.planexFavoriteGroups.key,
),
};
}
/**
* 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},
});
}
/**
* Gets the header search bar
*
* @return {*}
*/
getSearchBar = (): React.Node => {
return (
<Searchbar
placeholder={i18n.t('screens.proximo.search')}
onChangeText={this.onSearchStringChange}
/>
);
};
/**
* Gets a render item for the given article
*
* @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;
};
/**
* 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. * 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 * Favorites are then saved in user preferences
* *
* @param group The group to add/remove to favorites * @param group The group to add/remove to favorites
*/ */
updateGroupFavorites(group: PlanexGroupType) { updateGroupFavorites(group: group) {
const {favoriteGroups} = this.state; let newFavorites = [...this.state.favoriteGroups]
const newFavorites = [...favoriteGroups];
if (this.isGroupInFavorites(group)) if (this.isGroupInFavorites(group))
GroupSelectionScreen.removeGroupFromFavorites(newFavorites, group); this.removeGroupFromFavorites(newFavorites, group);
else GroupSelectionScreen.addGroupToFavorites(newFavorites, group); else
this.setState({favoriteGroups: newFavorites}); this.addGroupToFavorites(newFavorites, group);
AsyncStorageManager.set( this.setState({favoriteGroups: newFavorites})
AsyncStorageManager.PREFERENCES.planexFavoriteGroups.key, AsyncStorageManager.set(AsyncStorageManager.PREFERENCES.planexFavoriteGroups.key, newFavorites);
newFavorites,
);
} }
/** /**
@ -249,11 +181,10 @@ class GroupSelectionScreen extends React.Component<PropsType, StateType> {
* @param item The group category * @param item The group category
* @returns {boolean} * @returns {boolean}
*/ */
shouldDisplayAccordion(item: PlanexGroupCategoryType): boolean { shouldDisplayAccordion(item: groupCategory) {
const {currentSearchString} = this.state;
let shouldDisplay = false; let shouldDisplay = false;
for (let i = 0; i < item.content.length; i += 1) { for (let i = 0; i < item.content.length; i++) {
if (stringMatchQuery(item.content[i].name, currentSearchString)) { if (stringMatchQuery(item.content[i].name, this.state.currentSearchString)) {
shouldDisplay = true; shouldDisplay = true;
break; break;
} }
@ -261,6 +192,28 @@ class GroupSelectionScreen extends React.Component<PropsType, StateType> {
return shouldDisplay; 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. * 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. * This improves formatting of group names, sorts alphabetically the categories, and adds favorites at the top.
@ -268,39 +221,54 @@ class GroupSelectionScreen extends React.Component<PropsType, StateType> {
* @param fetchedData The raw data fetched from the server * @param fetchedData The raw data fetched from the server
* @returns {[]} * @returns {[]}
*/ */
generateData(fetchedData: { generateData(fetchedData: { [key: string]: groupCategory }) {
[key: string]: PlanexGroupCategoryType, let data = [];
}): Array<PlanexGroupCategoryType> { for (let key in fetchedData) {
const {favoriteGroups} = this.state; this.formatGroups(fetchedData[key]);
const data = []; data.push(fetchedData[key]);
// 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.sort(sortName);
data.unshift({ data.unshift({name: i18n.t("screens.planex.favorites"), id: 0, content: this.state.favoriteGroups});
name: i18n.t('screens.planex.favorites'),
id: 0,
content: favoriteGroups,
});
return data; return data;
} }
render(): React.Node { /**
const {props, state} = this; * 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 ( return (
<WebSectionList <WebSectionList
navigation={props.navigation} {...this.props}
createDataset={this.createDataset} createDataset={this.createDataset}
autoRefreshTime={0} autoRefreshTime={0}
refreshOnFocus={false} refreshOnFocus={false}
fetchUrl={GROUPS_URL} fetchUrl={GROUPS_URL}
renderItem={this.getRenderItem} renderItem={this.renderItem}
updateData={state.currentSearchString + state.favoriteGroups.length} updateData={this.state.currentSearchString + this.state.favoriteGroups.length}
itemHeight={LIST_ITEM_HEIGHT} itemHeight={LIST_ITEM_HEIGHT}
/> />
); );

View file

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

View file

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

View file

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

View file

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

View file

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