Improve Home components to match linter

This commit is contained in:
Arnaud Vergnet 2020-08-03 18:36:52 +02:00
parent 34ccf9c4c9
commit 6b12b4cde2
9 changed files with 1273 additions and 1198 deletions

View file

@ -2,35 +2,44 @@
import * as React from 'react';
import {List, withTheme} from 'react-native-paper';
import {View} from "react-native";
import type {CustomTheme} from "../../managers/ThemeManager";
import {View} from 'react-native';
import i18n from 'i18n-js';
import {StackNavigationProp} from "@react-navigation/stack";
import {StackNavigationProp} from '@react-navigation/stack';
import type {CustomTheme} from '../../managers/ThemeManager';
type Props = {
type PropsType = {
navigation: StackNavigationProp,
theme: CustomTheme,
}
};
class ActionsDashBoardItem extends React.Component<Props> {
shouldComponentUpdate(nextProps: Props): boolean {
return (nextProps.theme.dark !== this.props.theme.dark);
class ActionsDashBoardItem extends React.Component<PropsType> {
shouldComponentUpdate(nextProps: PropsType): boolean {
const {props} = this;
return nextProps.theme.dark !== props.theme.dark;
}
render() {
render(): React.Node {
const {props} = this;
return (
<View>
<List.Item
title={i18n.t("screens.feedback.homeButtonTitle")}
description={i18n.t("screens.feedback.homeButtonSubtitle")}
left={props => <List.Icon {...props} icon={"comment-quote"}/>}
right={props => <List.Icon {...props} icon={"chevron-right"}/>}
onPress={() => this.props.navigation.navigate("feedback")}
style={{paddingTop: 0, paddingBottom: 0, marginLeft: 10, marginRight: 10}}
title={i18n.t('screens.feedback.homeButtonTitle')}
description={i18n.t('screens.feedback.homeButtonSubtitle')}
left={({size}: {size: number}): React.Node => (
<List.Icon size={size} icon="comment-quote" />
)}
right={({size}: {size: number}): React.Node => (
<List.Icon size={size} icon="chevron-right" />
)}
onPress={(): void => props.navigation.navigate('feedback')}
style={{
paddingTop: 0,
paddingBottom: 0,
marginLeft: 10,
marginRight: 10,
}}
/>
</View>
);
}
}

View file

@ -1,79 +1,23 @@
// @flow
import * as React from 'react';
import {Avatar, Card, Text, TouchableRipple, withTheme} from 'react-native-paper';
import {StyleSheet, View} from "react-native";
import i18n from "i18n-js";
import type {CustomTheme} from "../../managers/ThemeManager";
import {
Avatar,
Card,
Text,
TouchableRipple,
withTheme,
} from 'react-native-paper';
import {StyleSheet, View} from 'react-native';
import i18n from 'i18n-js';
import type {CustomTheme} from '../../managers/ThemeManager';
type Props = {
eventNumber: number;
type PropsType = {
eventNumber: number,
clickAction: () => void,
theme: CustomTheme,
children?: React.Node
}
/**
* Component used to display a dashboard item containing a preview event
*/
class EventDashBoardItem extends React.Component<Props> {
shouldComponentUpdate(nextProps: Props) {
return (nextProps.theme.dark !== this.props.theme.dark)
|| (nextProps.eventNumber !== this.props.eventNumber);
}
render() {
const props = this.props;
const colors = props.theme.colors;
const isAvailable = props.eventNumber > 0;
const iconColor = isAvailable ?
colors.planningColor :
colors.textDisabled;
const textColor = isAvailable ?
colors.text :
colors.textDisabled;
let subtitle;
if (isAvailable) {
subtitle =
<Text>
<Text style={{fontWeight: "bold"}}>{props.eventNumber}</Text>
<Text>
{props.eventNumber > 1
? i18n.t('screens.home.dashboard.todayEventsSubtitlePlural')
: i18n.t('screens.home.dashboard.todayEventsSubtitle')}
</Text>
</Text>;
} else
subtitle = i18n.t('screens.home.dashboard.todayEventsSubtitleNA');
return (
<Card style={styles.card}>
<TouchableRipple
style={{flex: 1}}
onPress={props.clickAction}>
<View>
<Card.Title
title={i18n.t('screens.home.dashboard.todayEventsTitle')}
titleStyle={{color: textColor}}
subtitle={subtitle}
subtitleStyle={{color: textColor}}
left={() =>
<Avatar.Icon
icon={'calendar-range'}
color={iconColor}
size={60}
style={styles.avatar}/>}
/>
<Card.Content>
{props.children}
</Card.Content>
</View>
</TouchableRipple>
</Card>
);
}
}
children?: React.Node,
};
const styles = StyleSheet.create({
card: {
@ -84,8 +28,69 @@ const styles = StyleSheet.create({
overflow: 'hidden',
},
avatar: {
backgroundColor: 'transparent'
}
backgroundColor: 'transparent',
},
});
/**
* Component used to display a dashboard item containing a preview event
*/
class EventDashBoardItem extends React.Component<PropsType> {
static defaultProps = {
children: null,
};
shouldComponentUpdate(nextProps: PropsType): boolean {
const {props} = this;
return (
nextProps.theme.dark !== props.theme.dark ||
nextProps.eventNumber !== props.eventNumber
);
}
render(): React.Node {
const {props} = this;
const {colors} = props.theme;
const isAvailable = props.eventNumber > 0;
const iconColor = isAvailable ? colors.planningColor : colors.textDisabled;
const textColor = isAvailable ? colors.text : colors.textDisabled;
let subtitle;
if (isAvailable) {
subtitle = (
<Text>
<Text style={{fontWeight: 'bold'}}>{props.eventNumber}</Text>
<Text>
{props.eventNumber > 1
? i18n.t('screens.home.dashboard.todayEventsSubtitlePlural')
: i18n.t('screens.home.dashboard.todayEventsSubtitle')}
</Text>
</Text>
);
} else subtitle = i18n.t('screens.home.dashboard.todayEventsSubtitleNA');
return (
<Card style={styles.card}>
<TouchableRipple style={{flex: 1}} onPress={props.clickAction}>
<View>
<Card.Title
title={i18n.t('screens.home.dashboard.todayEventsTitle')}
titleStyle={{color: textColor}}
subtitle={subtitle}
subtitleStyle={{color: textColor}}
left={(): React.Node => (
<Avatar.Icon
icon="calendar-range"
color={iconColor}
size={60}
style={styles.avatar}
/>
)}
/>
<Card.Content>{props.children}</Card.Content>
</View>
</TouchableRipple>
</Card>
);
}
}
export default withTheme(EventDashBoardItem);

View file

@ -2,67 +2,47 @@
import * as React from 'react';
import {Button, Card, Text, TouchableRipple} from 'react-native-paper';
import {Image, View} from "react-native";
import Autolink from "react-native-autolink";
import i18n from "i18n-js";
import {Image, View} from 'react-native';
import Autolink from 'react-native-autolink';
import i18n from 'i18n-js';
import ImageModal from 'react-native-image-modal';
import {StackNavigationProp} from "@react-navigation/stack";
import type {CustomTheme} from "../../managers/ThemeManager";
import type {feedItem} from "../../screens/Home/HomeScreen";
import {StackNavigationProp} from '@react-navigation/stack';
import type {FeedItemType} from '../../screens/Home/HomeScreen';
const ICON_AMICALE = require('../../../assets/amicale.png');
type Props = {
type PropsType = {
navigation: StackNavigationProp,
theme: CustomTheme,
item: feedItem,
item: FeedItemType,
title: string,
subtitle: string,
height: number,
}
};
/**
* Component used to display a feed item
*/
class FeedItem extends React.Component<Props> {
shouldComponentUpdate() {
class FeedItem extends React.Component<PropsType> {
shouldComponentUpdate(): boolean {
return false;
}
/**
* Gets the amicale INSAT logo
*
* @return {*}
*/
getAvatar() {
return (
<Image
size={48}
source={ICON_AMICALE}
style={{
width: 48,
height: 48,
}}/>
);
}
onPress = () => {
this.props.navigation.navigate(
'feed-information',
{
data: this.props.item,
date: this.props.subtitle
const {props} = this;
props.navigation.navigate('feed-information', {
data: props.item,
date: props.subtitle,
});
};
render() {
const item = this.props.item;
const hasImage = item.full_picture !== '' && item.full_picture !== undefined;
render(): React.Node {
const {props} = this;
const {item} = props;
const hasImage =
item.full_picture !== '' && item.full_picture !== undefined;
const cardMargin = 10;
const cardHeight = this.props.height - 2 * cardMargin;
const cardHeight = props.height - 2 * cardMargin;
const imageSize = 250;
const titleHeight = 80;
const actionsHeight = 60;
@ -74,23 +54,29 @@ class FeedItem extends React.Component<Props> {
style={{
margin: cardMargin,
height: cardHeight,
}}
>
<TouchableRipple
style={{flex: 1}}
onPress={this.onPress}>
}}>
<TouchableRipple style={{flex: 1}} onPress={this.onPress}>
<View>
<Card.Title
title={this.props.title}
subtitle={this.props.subtitle}
left={this.getAvatar}
title={props.title}
subtitle={props.subtitle}
left={(): React.Node => (
<Image
size={48}
source={ICON_AMICALE}
style={{
width: 48,
height: 48,
}}
/>
)}
style={{height: titleHeight}}
/>
{hasImage ?
{hasImage ? (
<View style={{marginLeft: 'auto', marginRight: 'auto'}}>
<ImageModal
resizeMode="contain"
imageBackgroundColor={"#000"}
imageBackgroundColor="#000"
style={{
width: imageSize,
height: imageSize,
@ -98,21 +84,23 @@ class FeedItem extends React.Component<Props> {
source={{
uri: item.full_picture,
}}
/></View> : null}
/>
</View>
) : null}
<Card.Content>
{item.message !== undefined ?
{item.message !== undefined ? (
<Autolink
text={item.message}
hashtag="facebook"
component={Text}
style={{height: textHeight}}
/> : null
}
/>
) : null}
</Card.Content>
<Card.Actions style={{height: actionsHeight}}>
<Button
onPress={this.onPress}
icon={'plus'}
icon="plus"
style={{marginLeft: 'auto'}}>
{i18n.t('screens.home.dashboard.seeMore')}
</Button>

View file

@ -1,81 +1,21 @@
// @flow
import * as React from 'react';
import {StyleSheet, View} from "react-native";
import i18n from "i18n-js";
import {StyleSheet, View} from 'react-native';
import i18n from 'i18n-js';
import {Avatar, Button, Card, TouchableRipple} from 'react-native-paper';
import {getFormattedEventTime, isDescriptionEmpty} from "../../utils/Planning";
import CustomHTML from "../Overrides/CustomHTML";
import type {CustomTheme} from "../../managers/ThemeManager";
import type {event} from "../../screens/Home/HomeScreen";
import {getFormattedEventTime, isDescriptionEmpty} from '../../utils/Planning';
import CustomHTML from '../Overrides/CustomHTML';
import type {EventType} from '../../screens/Home/HomeScreen';
type Props = {
event?: event,
type PropsType = {
event?: EventType | null,
clickAction: () => void,
theme?: CustomTheme,
}
/**
* Component used to display an event preview if an event is available
*/
class PreviewEventDashboardItem extends React.Component<Props> {
render() {
const props = this.props;
const isEmpty = props.event == null
? true
: isDescriptionEmpty(props.event.description);
if (props.event != null) {
const event = props.event;
const hasImage = event.logo !== '' && event.logo != null;
const getImage = () => <Avatar.Image
source={{uri: event.logo}}
size={50}
style={styles.avatar}/>;
return (
<Card
style={styles.card}
elevation={3}
>
<TouchableRipple
style={{flex: 1}}
onPress={props.clickAction}>
<View>
{hasImage ?
<Card.Title
title={event.title}
subtitle={getFormattedEventTime(event.date_begin, event.date_end)}
left={getImage}
/> :
<Card.Title
title={event.title}
subtitle={getFormattedEventTime(event.date_begin, event.date_end)}
/>}
{!isEmpty ?
<Card.Content style={styles.content}>
<CustomHTML html={event.description}/>
</Card.Content> : null}
<Card.Actions style={styles.actions}>
<Button
icon={'chevron-right'}
>
{i18n.t("screens.home.dashboard.seeMore")}
</Button>
</Card.Actions>
</View>
</TouchableRipple>
</Card>
);
} else
return null;
}
}
};
const styles = StyleSheet.create({
card: {
marginBottom: 10
marginBottom: 10,
},
content: {
maxHeight: 150,
@ -84,11 +24,77 @@ const styles = StyleSheet.create({
actions: {
marginLeft: 'auto',
marginTop: 'auto',
flexDirection: 'row'
flexDirection: 'row',
},
avatar: {
backgroundColor: 'transparent'
}
backgroundColor: 'transparent',
},
});
/**
* Component used to display an event preview if an event is available
*/
// eslint-disable-next-line react/prefer-stateless-function
class PreviewEventDashboardItem extends React.Component<PropsType> {
static defaultProps = {
event: null,
};
render(): React.Node {
const {props} = this;
const {event} = props;
const isEmpty =
event == null ? true : isDescriptionEmpty(event.description);
if (event != null) {
const hasImage = event.logo !== '' && event.logo != null;
const getImage = (): React.Node => (
<Avatar.Image
source={{uri: event.logo}}
size={50}
style={styles.avatar}
/>
);
return (
<Card style={styles.card} elevation={3}>
<TouchableRipple style={{flex: 1}} onPress={props.clickAction}>
<View>
{hasImage ? (
<Card.Title
title={event.title}
subtitle={getFormattedEventTime(
event.date_begin,
event.date_end,
)}
left={getImage}
/>
) : (
<Card.Title
title={event.title}
subtitle={getFormattedEventTime(
event.date_begin,
event.date_end,
)}
/>
)}
{!isEmpty ? (
<Card.Content style={styles.content}>
<CustomHTML html={event.description} />
</Card.Content>
) : null}
<Card.Actions style={styles.actions}>
<Button icon="chevron-right">
{i18n.t('screens.home.dashboard.seeMore')}
</Button>
</Card.Actions>
</View>
</TouchableRipple>
</Card>
);
}
return null;
}
}
export default PreviewEventDashboardItem;

View file

@ -2,13 +2,13 @@
import * as React from 'react';
import {Badge, TouchableRipple, withTheme} from 'react-native-paper';
import {Dimensions, Image, View} from "react-native";
import type {CustomTheme} from "../../managers/ThemeManager";
import * as Animatable from "react-native-animatable";
import {Dimensions, Image, View} from 'react-native';
import * as Animatable from 'react-native-animatable';
import type {CustomTheme} from '../../managers/ThemeManager';
type Props = {
image: string,
onPress: () => void,
type PropsType = {
image: string | null,
onPress: () => void | null,
badgeCount: number | null,
theme: CustomTheme,
};
@ -18,50 +18,51 @@ const AnimatableBadge = Animatable.createAnimatableComponent(Badge);
/**
* Component used to render a small dashboard item
*/
class SmallDashboardItem extends React.Component<Props> {
class SmallDashboardItem extends React.Component<PropsType> {
itemSize: number;
constructor(props: Props) {
constructor(props: PropsType) {
super(props);
this.itemSize = Dimensions.get('window').width / 8;
}
shouldComponentUpdate(nextProps: Props) {
return (nextProps.theme.dark !== this.props.theme.dark)
|| (nextProps.badgeCount !== this.props.badgeCount);
shouldComponentUpdate(nextProps: PropsType): boolean {
const {props} = this;
return (
nextProps.theme.dark !== props.theme.dark ||
nextProps.badgeCount !== props.badgeCount
);
}
render() {
const props = this.props;
render(): React.Node {
const {props} = this;
return (
<TouchableRipple
onPress={this.props.onPress}
borderless={true}
onPress={props.onPress}
borderless
style={{
marginLeft: this.itemSize / 6,
marginRight: this.itemSize / 6,
}}
>
<View style={{
}}>
<View
style={{
width: this.itemSize,
height: this.itemSize,
}}>
<Image
source={{uri: props.image}}
style={{
width: "80%",
height: "80%",
marginLeft: "auto",
marginRight: "auto",
marginTop: "auto",
marginBottom: "auto",
width: '80%',
height: '80%',
marginLeft: 'auto',
marginRight: 'auto',
marginTop: 'auto',
marginBottom: 'auto',
}}
/>
{
props.badgeCount != null && props.badgeCount > 0 ?
{props.badgeCount != null && props.badgeCount > 0 ? (
<AnimatableBadge
animation={"zoomIn"}
animation="zoomIn"
duration={300}
useNativeDriver
style={{
@ -73,14 +74,12 @@ class SmallDashboardItem extends React.Component<Props> {
borderWidth: 2,
}}>
{props.badgeCount}
</AnimatableBadge> : null
}
</AnimatableBadge>
) : null}
</View>
</TouchableRipple>
);
}
}
export default withTheme(SmallDashboardItem);

View file

@ -4,37 +4,41 @@ import * as React from 'react';
import {Linking, View} from 'react-native';
import {Avatar, Card, Text, withTheme} from 'react-native-paper';
import ImageModal from 'react-native-image-modal';
import Autolink from "react-native-autolink";
import MaterialHeaderButtons, {Item} from "../../components/Overrides/CustomHeaderButton";
import CustomTabBar from "../../components/Tabbar/CustomTabBar";
import {StackNavigationProp} from "@react-navigation/stack";
import type {feedItem} from "./HomeScreen";
import CollapsibleScrollView from "../../components/Collapsible/CollapsibleScrollView";
import Autolink from 'react-native-autolink';
import {StackNavigationProp} from '@react-navigation/stack';
import MaterialHeaderButtons, {
Item,
} from '../../components/Overrides/CustomHeaderButton';
import CustomTabBar from '../../components/Tabbar/CustomTabBar';
import type {FeedItemType} from './HomeScreen';
import CollapsibleScrollView from '../../components/Collapsible/CollapsibleScrollView';
type Props = {
type PropsType = {
navigation: StackNavigationProp,
route: { params: { data: feedItem, date: string } }
route: {params: {data: FeedItemType, date: string}},
};
const ICON_AMICALE = require('../../../assets/amicale.png');
const NAME_AMICALE = 'Amicale INSA Toulouse';
/**
* Class defining a feed item page.
*/
class FeedItemScreen extends React.Component<Props> {
class FeedItemScreen extends React.Component<PropsType> {
displayData: FeedItemType;
displayData: feedItem;
date: string;
constructor(props) {
constructor(props: PropsType) {
super(props);
this.displayData = props.route.params.data;
this.date = props.route.params.date;
}
componentDidMount() {
this.props.navigation.setOptions({
const {props} = this;
props.navigation.setOptions({
headerRight: this.getHeaderButton,
});
}
@ -51,41 +55,41 @@ class FeedItemScreen extends React.Component<Props> {
*
* @returns {*}
*/
getHeaderButton = () => {
return <MaterialHeaderButtons>
<Item title="main" iconName={'facebook'} color={"#2e88fe"} onPress={this.onOutLinkPress}/>
</MaterialHeaderButtons>;
getHeaderButton = (): React.Node => {
return (
<MaterialHeaderButtons>
<Item
title="main"
iconName="facebook"
color="#2e88fe"
onPress={this.onOutLinkPress}
/>
</MaterialHeaderButtons>
);
};
/**
* Gets the Amicale INSA avatar
*
* @returns {*}
*/
getAvatar() {
render(): React.Node {
const hasImage =
this.displayData.full_picture !== '' &&
this.displayData.full_picture != null;
return (
<Avatar.Image size={48} source={ICON_AMICALE}
style={{backgroundColor: 'transparent'}}/>
);
}
render() {
const hasImage = this.displayData.full_picture !== '' && this.displayData.full_picture != null;
return (
<CollapsibleScrollView
style={{margin: 5,}}
hasTab={true}
>
<CollapsibleScrollView style={{margin: 5}} hasTab>
<Card.Title
title={NAME_AMICALE}
subtitle={this.date}
left={this.getAvatar}
left={(): React.Node => (
<Avatar.Image
size={48}
source={ICON_AMICALE}
style={{backgroundColor: 'transparent'}}
/>
{hasImage ?
)}
/>
{hasImage ? (
<View style={{marginLeft: 'auto', marginRight: 'auto'}}>
<ImageModal
resizeMode="contain"
imageBackgroundColor={"#000"}
imageBackgroundColor="#000"
style={{
width: 250,
height: 250,
@ -93,15 +97,17 @@ class FeedItemScreen extends React.Component<Props> {
source={{
uri: this.displayData.full_picture,
}}
/></View> : null}
/>
</View>
) : null}
<Card.Content style={{paddingBottom: CustomTabBar.TAB_BAR_HEIGHT + 20}}>
{this.displayData.message !== undefined ?
{this.displayData.message !== undefined ? (
<Autolink
text={this.displayData.message}
hashtag="facebook"
component={Text}
/> : null
}
/>
) : null}
</Card.Content>
</CollapsibleScrollView>
);

View file

@ -2,52 +2,44 @@
import * as React from 'react';
import {FlatList} from 'react-native';
import i18n from "i18n-js";
import DashboardItem from "../../components/Home/EventDashboardItem";
import WebSectionList from "../../components/Screens/WebSectionList";
import i18n from 'i18n-js';
import {ActivityIndicator, Headline, withTheme} from 'react-native-paper';
import FeedItem from "../../components/Home/FeedItem";
import SmallDashboardItem from "../../components/Home/SmallDashboardItem";
import PreviewEventDashboardItem from "../../components/Home/PreviewEventDashboardItem";
import {stringToDate} from "../../utils/Planning";
import ActionsDashBoardItem from "../../components/Home/ActionsDashboardItem";
import {CommonActions} from '@react-navigation/native';
import MaterialHeaderButtons, {Item} from "../../components/Overrides/CustomHeaderButton";
import AnimatedFAB from "../../components/Animations/AnimatedFAB";
import {StackNavigationProp} from "@react-navigation/stack";
import type {CustomTheme} from "../../managers/ThemeManager";
import * as Animatable from "react-native-animatable";
import {View} from "react-native-animatable";
import ConnectionManager from "../../managers/ConnectionManager";
import LogoutDialog from "../../components/Amicale/LogoutDialog";
import AsyncStorageManager from "../../managers/AsyncStorageManager";
import {MASCOT_STYLE} from "../../components/Mascot/Mascot";
import MascotPopup from "../../components/Mascot/MascotPopup";
import DashboardManager from "../../managers/DashboardManager";
import type {ServiceItem} from "../../managers/ServicesManager";
import MaterialCommunityIcons from "react-native-vector-icons/MaterialCommunityIcons";
import {StackNavigationProp} from '@react-navigation/stack';
import * as Animatable from 'react-native-animatable';
import {View} from 'react-native-animatable';
import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons';
import DashboardItem from '../../components/Home/EventDashboardItem';
import WebSectionList from '../../components/Screens/WebSectionList';
import FeedItem from '../../components/Home/FeedItem';
import SmallDashboardItem from '../../components/Home/SmallDashboardItem';
import PreviewEventDashboardItem from '../../components/Home/PreviewEventDashboardItem';
import ActionsDashBoardItem from '../../components/Home/ActionsDashboardItem';
import MaterialHeaderButtons, {
Item,
} from '../../components/Overrides/CustomHeaderButton';
import AnimatedFAB from '../../components/Animations/AnimatedFAB';
import type {CustomTheme} from '../../managers/ThemeManager';
import ConnectionManager from '../../managers/ConnectionManager';
import LogoutDialog from '../../components/Amicale/LogoutDialog';
import AsyncStorageManager from '../../managers/AsyncStorageManager';
import {MASCOT_STYLE} from '../../components/Mascot/Mascot';
import MascotPopup from '../../components/Mascot/MascotPopup';
import DashboardManager from '../../managers/DashboardManager';
import type {ServiceItem} from '../../managers/ServicesManager';
import {getDisplayEvent, getFutureEvents} from '../../utils/Home';
// import DATA from "../dashboard_data.json";
const NAME_AMICALE = 'Amicale INSA Toulouse';
const DATA_URL = "https://etud.insa-toulouse.fr/~amicale_app/v2/dashboard/dashboard_data.json";
const DATA_URL =
'https://etud.insa-toulouse.fr/~amicale_app/v2/dashboard/dashboard_data.json';
const FEED_ITEM_HEIGHT = 500;
const SECTIONS_ID = [
'dashboard',
'news_feed'
];
const SECTIONS_ID = ['dashboard', 'news_feed'];
const REFRESH_TIME = 1000 * 20; // Refresh every 20 seconds
type rawDashboard = {
news_feed: {
data: Array<feedItem>,
},
dashboard: fullDashboard,
}
export type feedItem = {
export type FeedItemType = {
full_picture: string,
message: string,
permalink_url: string,
@ -55,16 +47,7 @@ export type feedItem = {
id: string,
};
export type fullDashboard = {
today_menu: Array<{ [key: string]: any }>,
proximo_articles: number,
available_dryers: number,
available_washers: number,
today_events: Array<{ [key: string]: any }>,
available_tutorials: number,
}
export type event = {
export type EventType = {
id: number,
title: string,
logo: string | null,
@ -74,44 +57,68 @@ export type event = {
club: string,
category_id: number,
url: string,
}
};
type Props = {
export type FullDashboardType = {
today_menu: Array<{[key: string]: {...}}>,
proximo_articles: number,
available_dryers: number,
available_washers: number,
today_events: Array<EventType>,
available_tutorials: number,
};
type RawDashboardType = {
news_feed: {
data: Array<FeedItemType>,
},
dashboard: FullDashboardType,
};
type PropsType = {
navigation: StackNavigationProp,
route: { params: any, ... },
route: {params: {nextScreen: string, data: {...}}},
theme: CustomTheme,
}
};
type State = {
type StateType = {
dialogVisible: boolean,
}
};
/**
* Class defining the app's home screen
*/
class HomeScreen extends React.Component<Props, State> {
class HomeScreen extends React.Component<PropsType, StateType> {
isLoggedIn: boolean | null;
fabRef: { current: null | AnimatedFAB };
currentNewFeed: Array<feedItem>;
currentDashboard: fullDashboard | null;
fabRef: {current: null | AnimatedFAB};
currentNewFeed: Array<FeedItemType>;
currentDashboard: FullDashboardType | null;
dashboardManager: DashboardManager;
constructor(props) {
constructor(props: PropsType) {
super(props);
this.fabRef = React.createRef();
this.dashboardManager = new DashboardManager(this.props.navigation);
this.dashboardManager = new DashboardManager(props.navigation);
this.currentNewFeed = [];
this.currentDashboard = null;
this.isLoggedIn = ConnectionManager.getInstance().isLoggedIn();
this.props.navigation.setOptions({
props.navigation.setOptions({
headerRight: this.getHeaderButton,
});
this.state = {
dialogVisible: false,
};
}
componentDidMount() {
const {props} = this;
props.navigation.addListener('focus', this.onScreenFocus);
// Handle link open when home is focused
props.navigation.addListener('state', this.handleNavigationParams);
}
/**
@ -120,24 +127,19 @@ class HomeScreen extends React.Component<Props, State> {
* @param dateString {string} The Unix Timestamp representation of a date
* @return {string} The formatted output date
*/
static getFormattedDate(dateString: number) {
let date = new Date(dateString * 1000);
static getFormattedDate(dateString: number): string {
const date = new Date(dateString * 1000);
return date.toLocaleString();
}
componentDidMount() {
this.props.navigation.addListener('focus', this.onScreenFocus);
// Handle link open when home is focused
this.props.navigation.addListener('state', this.handleNavigationParams);
}
/**
* Updates login state and navigation parameters on screen focus
*/
onScreenFocus = () => {
const {props} = this;
if (ConnectionManager.getInstance().isLoggedIn() !== this.isLoggedIn) {
this.isLoggedIn = ConnectionManager.getInstance().isLoggedIn();
this.props.navigation.setOptions({
props.navigation.setOptions({
headerRight: this.getHeaderButton,
});
}
@ -145,197 +147,41 @@ class HomeScreen extends React.Component<Props, State> {
this.handleNavigationParams();
};
/**
* Navigates to the a new screen if navigation parameters specify one
*/
handleNavigationParams = () => {
if (this.props.route.params != null) {
if (this.props.route.params.nextScreen != null) {
this.props.navigation.navigate(this.props.route.params.nextScreen, this.props.route.params.data);
// reset params to prevent infinite loop
this.props.navigation.dispatch(CommonActions.setParams({nextScreen: null}));
}
}
};
/**
* Gets header buttons based on login state
*
* @returns {*}
*/
getHeaderButton = () => {
let onPressLog = () => this.props.navigation.navigate("login", {nextScreen: "profile"});
let logIcon = "login";
let logColor = this.props.theme.colors.primary;
getHeaderButton = (): React.Node => {
const {props} = this;
let onPressLog = (): void =>
props.navigation.navigate('login', {nextScreen: 'profile'});
let logIcon = 'login';
let logColor = props.theme.colors.primary;
if (this.isLoggedIn) {
onPressLog = () => this.showDisconnectDialog();
logIcon = "logout";
logColor = this.props.theme.colors.text;
onPressLog = (): void => this.showDisconnectDialog();
logIcon = 'logout';
logColor = props.theme.colors.text;
}
const onPressSettings = () => this.props.navigation.navigate("settings");
return <MaterialHeaderButtons>
<Item title="log" iconName={logIcon} color={logColor} onPress={onPressLog}/>
<Item title={i18n.t("screens.settings.title")} iconName={"cog"} onPress={onPressSettings}/>
</MaterialHeaderButtons>;
const onPressSettings = (): void => props.navigation.navigate('settings');
return (
<MaterialHeaderButtons>
<Item
title="log"
iconName={logIcon}
color={logColor}
onPress={onPressLog}
/>
<Item
title={i18n.t('screens.settings.title')}
iconName="cog"
onPress={onPressSettings}
/>
</MaterialHeaderButtons>
);
};
showDisconnectDialog = () => this.setState({dialogVisible: true});
hideDisconnectDialog = () => this.setState({dialogVisible: false});
openScanner = () => this.props.navigation.navigate("scanner");
/**
* Creates the dataset to be used in the FlatList
*
* @param fetchedData
* @param isLoading
* @return {*}
*/
createDataset = (fetchedData: rawDashboard | null, isLoading: boolean) => {
// fetchedData = DATA;
if (fetchedData != null) {
if (fetchedData.news_feed != null)
this.currentNewFeed = fetchedData.news_feed.data;
if (fetchedData.dashboard != null)
this.currentDashboard = fetchedData.dashboard;
}
if (this.currentNewFeed.length > 0)
return [
{
title: i18n.t("screens.home.feedTitle"),
data: this.currentNewFeed,
id: SECTIONS_ID[1]
}
];
else
return [
{
title: isLoading ? i18n.t("screens.home.feedLoading") : i18n.t("screens.home.feedError"),
data: [],
id: SECTIONS_ID[1]
}
];
};
/**
* Gets the time limit depending on the current day:
* 17:30 for every day of the week except for thursday 11:30
* 00:00 on weekends
*/
getTodayEventTimeLimit() {
let now = new Date();
if (now.getDay() === 4) // Thursday
now.setHours(11, 30, 0);
else if (now.getDay() === 6 || now.getDay() === 0) // Weekend
now.setHours(0, 0, 0);
else
now.setHours(17, 30, 0);
return now;
}
/**
* Gets the duration (in milliseconds) of an event
*
* @param event {event}
* @return {number} The number of milliseconds
*/
getEventDuration(event: event): number {
let start = stringToDate(event.date_begin);
let end = stringToDate(event.date_end);
let duration = 0;
if (start != null && end != null)
duration = end - start;
return duration;
}
/**
* Gets events starting after the limit
*
* @param events
* @param limit
* @return {Array<Object>}
*/
getEventsAfterLimit(events: Array<event>, limit: Date): Array<event> {
let validEvents = [];
for (let event of events) {
let startDate = stringToDate(event.date_begin);
if (startDate != null && startDate >= limit) {
validEvents.push(event);
}
}
return validEvents;
}
/**
* Gets the event with the longest duration in the given array.
* If all events have the same duration, return the first in the array.
*
* @param events
*/
getLongestEvent(events: Array<event>): event {
let longestEvent = events[0];
let longestTime = 0;
for (let event of events) {
let time = this.getEventDuration(event);
if (time > longestTime) {
longestTime = time;
longestEvent = event;
}
}
return longestEvent;
}
/**
* Gets events that have not yet ended/started
*
* @param events
*/
getFutureEvents(events: Array<event>): Array<event> {
let validEvents = [];
let now = new Date();
for (let event of events) {
let startDate = stringToDate(event.date_begin);
let endDate = stringToDate(event.date_end);
if (startDate != null) {
if (startDate > now)
validEvents.push(event);
else if (endDate != null) {
if (endDate > now || endDate < startDate) // Display event if it ends the following day
validEvents.push(event);
}
}
}
return validEvents;
}
/**
* Gets the event to display in the preview
*
* @param events
* @return {Object}
*/
getDisplayEvent(events: Array<event>): event | null {
let displayEvent = null;
if (events.length > 1) {
let eventsAfterLimit = this.getEventsAfterLimit(events, this.getTodayEventTimeLimit());
if (eventsAfterLimit.length > 0) {
if (eventsAfterLimit.length === 1)
displayEvent = eventsAfterLimit[0];
else
displayEvent = this.getLongestEvent(events);
} else {
displayEvent = this.getLongestEvent(events);
}
} else if (events.length === 1) {
displayEvent = events[0];
}
return displayEvent;
}
onEventContainerClick = () => this.props.navigation.navigate('planning');
/**
* Gets the event dashboard render item.
* If a preview is available, it will be rendered inside
@ -343,9 +189,9 @@ class HomeScreen extends React.Component<Props, State> {
* @param content
* @return {*}
*/
getDashboardEvent(content: Array<event>) {
let futureEvents = this.getFutureEvents(content);
let displayEvent = this.getDisplayEvent(futureEvents);
getDashboardEvent(content: Array<EventType>): React.Node {
const futureEvents = getFutureEvents(content);
const displayEvent = getDisplayEvent(futureEvents);
// const clickPreviewAction = () =>
// this.props.navigation.navigate('students', {
// screen: 'planning-information',
@ -354,10 +200,9 @@ class HomeScreen extends React.Component<Props, State> {
return (
<DashboardItem
eventNumber={futureEvents.length}
clickAction={this.onEventContainerClick}
>
clickAction={this.onEventContainerClick}>
<PreviewEventDashboardItem
event={displayEvent != null ? displayEvent : undefined}
event={displayEvent}
clickAction={this.onEventContainerClick}
/>
</DashboardItem>
@ -369,8 +214,14 @@ class HomeScreen extends React.Component<Props, State> {
*
* @returns {*}
*/
getDashboardActions() {
return <ActionsDashBoardItem {...this.props} isLoggedIn={this.isLoggedIn}/>;
getDashboardActions(): React.Node {
const {props} = this;
return (
<ActionsDashBoardItem
navigation={props.navigation}
isLoggedIn={this.isLoggedIn}
/>
);
}
/**
@ -379,20 +230,21 @@ class HomeScreen extends React.Component<Props, State> {
* @param content
* @return {*}
*/
getDashboardRow(content: Array<ServiceItem>) {
getDashboardRow(content: Array<ServiceItem | null>): React.Node {
return (
//$FlowFixMe
// $FlowFixMe
<FlatList
data={content}
renderItem={this.dashboardRowRenderItem}
horizontal={true}
renderItem={this.getDashboardRowRenderItem}
horizontal
contentContainerStyle={{
marginLeft: 'auto',
marginRight: 'auto',
marginTop: 10,
marginBottom: 10,
}}
/>);
/>
);
}
/**
@ -401,16 +253,24 @@ class HomeScreen extends React.Component<Props, State> {
* @param item
* @returns {*}
*/
dashboardRowRenderItem = ({item}: { item: ServiceItem }) => {
getDashboardRowRenderItem = ({
item,
}: {
item: ServiceItem | null,
}): React.Node => {
if (item != null)
return (
<SmallDashboardItem
image={item.image}
onPress={item.onPress}
badgeCount={this.currentDashboard != null && item.badgeFunction != null
badgeCount={
this.currentDashboard != null && item.badgeFunction != null
? item.badgeFunction(this.currentDashboard)
: null}
: null
}
/>
);
return <SmallDashboardItem image={null} onPress={null} badgeCount={null} />;
};
/**
@ -419,10 +279,11 @@ class HomeScreen extends React.Component<Props, State> {
* @param item The feed item to display
* @return {*}
*/
getFeedItem(item: feedItem) {
getFeedItem(item: FeedItemType): React.Node {
const {props} = this;
return (
<FeedItem
{...this.props}
navigation={props.navigation}
item={item}
title={NAME_AMICALE}
subtitle={HomeScreen.getFormattedDate(item.created_time)}
@ -438,139 +299,218 @@ class HomeScreen extends React.Component<Props, State> {
* @param section The current section
* @return {*}
*/
getRenderItem = ({item}: { item: feedItem, }) => this.getFeedItem(item);
getRenderItem = ({item}: {item: FeedItemType}): React.Node =>
this.getFeedItem(item);
onScroll = (event: SyntheticEvent<EventTarget>) => {
if (this.fabRef.current != null)
this.fabRef.current.onScroll(event);
};
renderSectionHeader = (data: { section: { [key: string]: any } }, isLoading: boolean) => {
getRenderSectionHeader = (
data: {
section: {
data: Array<{...}>,
title: string,
},
},
isLoading: boolean,
): React.Node => {
const {props} = this;
if (data.section.data.length > 0)
return (
<Headline style={{
textAlign: "center",
<Headline
style={{
textAlign: 'center',
marginTop: 50,
marginBottom: 10,
}}>
{data.section.title}
</Headline>
)
else
);
return (
<View>
<Headline style={{
textAlign: "center",
<Headline
style={{
textAlign: 'center',
marginTop: 50,
marginBottom: 10,
marginLeft: 20,
marginRight: 20,
color: this.props.theme.colors.textDisabled
color: props.theme.colors.textDisabled,
}}>
{data.section.title}
</Headline>
{isLoading
? <ActivityIndicator
{isLoading ? (
<ActivityIndicator
style={{
marginTop: 10
marginTop: 10,
}}
/>
: <MaterialCommunityIcons
name={"access-point-network-off"}
) : (
<MaterialCommunityIcons
name="access-point-network-off"
size={100}
color={this.props.theme.colors.textDisabled}
color={props.theme.colors.textDisabled}
style={{
marginLeft: "auto",
marginRight: "auto",
marginLeft: 'auto',
marginRight: 'auto',
}}
/>}
/>
)}
</View>
);
}
};
getListHeader = (fetchedData: rawDashboard) => {
getListHeader = (fetchedData: RawDashboardType): React.Node => {
let dashboard = null;
if (fetchedData != null) {
dashboard = fetchedData.dashboard;
}
if (fetchedData != null) dashboard = fetchedData.dashboard;
return (
<Animatable.View
animation={"fadeInDown"}
duration={500}
useNativeDriver={true}
>
<Animatable.View animation="fadeInDown" duration={500} useNativeDriver>
{this.getDashboardActions()}
{this.getDashboardRow(this.dashboardManager.getCurrentDashboard())}
{this.getDashboardEvent(
dashboard == null
? []
: dashboard.today_events
dashboard == null ? [] : dashboard.today_events,
)}
</Animatable.View>
);
};
/**
* Navigates to the a new screen if navigation parameters specify one
*/
handleNavigationParams = () => {
const {props} = this;
if (props.route.params != null) {
if (props.route.params.nextScreen != null) {
props.navigation.navigate(
props.route.params.nextScreen,
props.route.params.data,
);
// reset params to prevent infinite loop
props.navigation.dispatch(CommonActions.setParams({nextScreen: null}));
}
}
};
showDisconnectDialog = (): void => this.setState({dialogVisible: true});
hideDisconnectDialog = (): void => this.setState({dialogVisible: false});
openScanner = () => {
const {props} = this;
props.navigation.navigate('scanner');
};
/**
* Creates the dataset to be used in the FlatList
*
* @param fetchedData
* @param isLoading
* @return {*}
*/
createDataset = (
fetchedData: RawDashboardType | null,
isLoading: boolean,
): Array<{
title: string,
data: [] | Array<FeedItemType>,
id: string,
}> => {
// fetchedData = DATA;
if (fetchedData != null) {
if (fetchedData.news_feed != null)
this.currentNewFeed = fetchedData.news_feed.data;
if (fetchedData.dashboard != null)
this.currentDashboard = fetchedData.dashboard;
}
if (this.currentNewFeed.length > 0)
return [
{
title: i18n.t('screens.home.feedTitle'),
data: this.currentNewFeed,
id: SECTIONS_ID[1],
},
];
return [
{
title: isLoading
? i18n.t('screens.home.feedLoading')
: i18n.t('screens.home.feedError'),
data: [],
id: SECTIONS_ID[1],
},
];
};
onEventContainerClick = () => {
const {props} = this;
props.navigation.navigate('planning');
};
onScroll = (event: SyntheticEvent<EventTarget>) => {
if (this.fabRef.current != null) this.fabRef.current.onScroll(event);
};
/**
* Callback when pressing the login button on the banner.
* This hides the banner and takes the user to the login page.
*/
onLogin = () => this.props.navigation.navigate("login", {nextScreen: "profile"});
onLogin = () => {
const {props} = this;
props.navigation.navigate('login', {
nextScreen: 'profile',
});
};
render() {
render(): React.Node {
const {props, state} = this;
return (
<View style={{flex: 1}}>
<View
style={{flex: 1}}
>
<View style={{
position: "absolute",
width: "100%",
height: "100%",
style={{
position: 'absolute',
width: '100%',
height: '100%',
}}>
<WebSectionList
{...this.props}
navigation={props.navigation}
createDataset={this.createDataset}
autoRefreshTime={REFRESH_TIME}
refreshOnFocus={true}
refreshOnFocus
fetchUrl={DATA_URL}
renderItem={this.getRenderItem}
itemHeight={FEED_ITEM_HEIGHT}
onScroll={this.onScroll}
showError={false}
renderSectionHeader={this.renderSectionHeader}
renderSectionHeader={this.getRenderSectionHeader}
renderListHeaderComponent={this.getListHeader}
/>
</View>
{!this.isLoggedIn
? <MascotPopup
{!this.isLoggedIn ? (
<MascotPopup
prefKey={AsyncStorageManager.PREFERENCES.homeShowBanner.key}
title={i18n.t("screens.home.mascotDialog.title")}
message={i18n.t("screens.home.mascotDialog.message")}
icon={"human-greeting"}
title={i18n.t('screens.home.mascotDialog.title')}
message={i18n.t('screens.home.mascotDialog.message')}
icon="human-greeting"
buttons={{
action: {
message: i18n.t("screens.home.mascotDialog.login"),
icon: "login",
message: i18n.t('screens.home.mascotDialog.login'),
icon: 'login',
onPress: this.onLogin,
},
cancel: {
message: i18n.t("screens.home.mascotDialog.later"),
icon: "close",
color: this.props.theme.colors.warning,
}
message: i18n.t('screens.home.mascotDialog.later'),
icon: 'close',
color: props.theme.colors.warning,
},
}}
emotion={MASCOT_STYLE.CUTE}
/> : null}
/>
) : null}
<AnimatedFAB
{...this.props}
ref={this.fabRef}
icon="qrcode-scan"
onPress={this.openScanner}
/>
<LogoutDialog
{...this.props}
visible={this.state.dialogVisible}
navigation={props.navigation}
visible={state.dialogVisible}
onDismiss={this.hideDisconnectDialog}
/>
</View>

View file

@ -1,90 +1,65 @@
// @flow
import * as React from 'react';
import {Linking, Platform, StyleSheet, View} from "react-native";
import {Linking, Platform, StyleSheet, View} from 'react-native';
import {Button, Text, withTheme} from 'react-native-paper';
import {RNCamera} from 'react-native-camera';
import {BarcodeMask} from '@nartc/react-native-barcode-mask';
import URLHandler from "../../utils/URLHandler";
import AlertDialog from "../../components/Dialogs/AlertDialog";
import i18n from 'i18n-js';
import CustomTabBar from "../../components/Tabbar/CustomTabBar";
import LoadingConfirmDialog from "../../components/Dialogs/LoadingConfirmDialog";
import {PERMISSIONS, request, RESULTS} from 'react-native-permissions';
import {MASCOT_STYLE} from "../../components/Mascot/Mascot";
import MascotPopup from "../../components/Mascot/MascotPopup";
import URLHandler from '../../utils/URLHandler';
import AlertDialog from '../../components/Dialogs/AlertDialog';
import CustomTabBar from '../../components/Tabbar/CustomTabBar';
import LoadingConfirmDialog from '../../components/Dialogs/LoadingConfirmDialog';
import {MASCOT_STYLE} from '../../components/Mascot/Mascot';
import MascotPopup from '../../components/Mascot/MascotPopup';
type Props = {};
type State = {
type StateType = {
hasPermission: boolean,
scanned: boolean,
dialogVisible: boolean,
mascotDialogVisible: boolean,
dialogTitle: string,
dialogMessage: string,
loading: boolean,
};
class ScannerScreen extends React.Component<Props, State> {
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
},
button: {
position: 'absolute',
bottom: 20,
width: '80%',
left: '10%',
},
});
state = {
class ScannerScreen extends React.Component<null, StateType> {
constructor() {
super();
this.state = {
hasPermission: false,
scanned: false,
mascotDialogVisible: false,
dialogVisible: false,
dialogTitle: "",
dialogMessage: "",
loading: false,
};
constructor() {
super();
}
componentDidMount() {
this.requestPermissions();
}
/**
* Requests permission to use the camera
*/
requestPermissions = () => {
if (Platform.OS === 'android')
request(PERMISSIONS.ANDROID.CAMERA).then(this.updatePermissionStatus)
else
request(PERMISSIONS.IOS.CAMERA).then(this.updatePermissionStatus)
};
/**
* Updates the state permission status
*
* @param result
*/
updatePermissionStatus = (result) => this.setState({hasPermission: result === RESULTS.GRANTED});
/**
* Opens scanned link if it is a valid app link or shows and error dialog
*
* @param type The barcode type
* @param data The scanned value
*/
handleCodeScanned = ({type, data}) => {
if (!URLHandler.isUrlValid(data))
this.showErrorDialog();
else {
this.showOpeningDialog();
Linking.openURL(data);
}
};
/**
* Gets a view asking user for permission to use the camera
*
* @returns {*}
*/
getPermissionScreen() {
return <View style={{marginLeft: 10, marginRight: 10}}>
<Text>{i18n.t("screens.scanner.permissions.error")}</Text>
getPermissionScreen(): React.Node {
return (
<View style={{marginLeft: 10, marginRight: 10}}>
<Text>{i18n.t('screens.scanner.permissions.error')}</Text>
<Button
icon="camera"
mode="contained"
@ -93,11 +68,72 @@ class ScannerScreen extends React.Component<Props, State> {
marginTop: 10,
marginLeft: 'auto',
marginRight: 'auto',
}}
>
{i18n.t("screens.scanner.permissions.button")}
}}>
{i18n.t('screens.scanner.permissions.button')}
</Button>
</View>
);
}
/**
* Gets a view with the scanner.
* This scanner uses the back camera, can only scan qr codes and has a square mask on the center.
* The mask is only for design purposes as a code is scanned as soon as it enters the camera view
*
* @returns {*}
*/
getScanner(): React.Node {
const {state} = this;
return (
<RNCamera
onBarCodeRead={state.scanned ? null : this.onCodeScanned}
type={RNCamera.Constants.Type.back}
barCodeScannerSettings={{
barCodeTypes: [RNCamera.Constants.BarCodeType.qr],
}}
style={StyleSheet.absoluteFill}
captureAudio={false}>
<BarcodeMask
backgroundColor="#000"
maskOpacity={0.5}
animatedLineThickness={1}
animationDuration={1000}
width={250}
height={250}
/>
</RNCamera>
);
}
/**
* Requests permission to use the camera
*/
requestPermissions = () => {
if (Platform.OS === 'android')
request(PERMISSIONS.ANDROID.CAMERA).then(this.updatePermissionStatus);
else request(PERMISSIONS.IOS.CAMERA).then(this.updatePermissionStatus);
};
/**
* Updates the state permission status
*
* @param result
*/
updatePermissionStatus = (result: RESULTS) => {
this.setState({
hasPermission: result === RESULTS.GRANTED,
});
};
/**
* Shows a dialog indicating the user the scanned code was invalid
*/
// eslint-disable-next-line react/sort-comp
showErrorDialog() {
this.setState({
dialogVisible: true,
scanned: true,
});
}
/**
@ -120,119 +156,82 @@ class ScannerScreen extends React.Component<Props, State> {
});
};
/**
* Shows a dialog indicating the user the scanned code was invalid
*/
showErrorDialog() {
this.setState({
dialogVisible: true,
scanned: true,
});
}
/**
* Hide any dialog
*/
onDialogDismiss = () => this.setState({
onDialogDismiss = () => {
this.setState({
dialogVisible: false,
scanned: false,
});
};
onMascotDialogDismiss = () => this.setState({
onMascotDialogDismiss = () => {
this.setState({
mascotDialogVisible: false,
scanned: false,
});
};
/**
* Gets a view with the scanner.
* This scanner uses the back camera, can only scan qr codes and has a square mask on the center.
* The mask is only for design purposes as a code is scanned as soon as it enters the camera view
* Opens scanned link if it is a valid app link or shows and error dialog
*
* @returns {*}
* @param type The barcode type
* @param data The scanned value
*/
getScanner() {
return (
<RNCamera
onBarCodeRead={this.state.scanned ? undefined : this.handleCodeScanned}
type={RNCamera.Constants.Type.back}
barCodeScannerSettings={{
barCodeTypes: [RNCamera.Constants.BarCodeType.qr],
}}
style={StyleSheet.absoluteFill}
captureAudio={false}
>
<BarcodeMask
backgroundColor={"#000"}
maskOpacity={0.5}
animatedLineThickness={1}
animationDuration={1000}
width={250}
height={250}
/>
</RNCamera>
);
onCodeScanned = ({data}: {data: string}) => {
if (!URLHandler.isUrlValid(data)) this.showErrorDialog();
else {
this.showOpeningDialog();
Linking.openURL(data);
}
};
render() {
render(): React.Node {
const {state} = this;
return (
<View style={{
<View
style={{
...styles.container,
marginBottom: CustomTabBar.TAB_BAR_HEIGHT
marginBottom: CustomTabBar.TAB_BAR_HEIGHT,
}}>
{this.state.hasPermission
? this.getScanner()
: this.getPermissionScreen()
}
{state.hasPermission ? this.getScanner() : this.getPermissionScreen()}
<Button
icon="information"
mode="contained"
onPress={this.showHelpDialog}
style={styles.button}
>
{i18n.t("screens.scanner.help.button")}
style={styles.button}>
{i18n.t('screens.scanner.help.button')}
</Button>
<MascotPopup
visible={this.state.mascotDialogVisible}
title={i18n.t("screens.scanner.mascotDialog.title")}
message={i18n.t("screens.scanner.mascotDialog.message")}
icon={"camera-iris"}
visible={state.mascotDialogVisible}
title={i18n.t('screens.scanner.mascotDialog.title')}
message={i18n.t('screens.scanner.mascotDialog.message')}
icon="camera-iris"
buttons={{
action: null,
cancel: {
message: i18n.t("screens.scanner.mascotDialog.button"),
icon: "check",
message: i18n.t('screens.scanner.mascotDialog.button'),
icon: 'check',
onPress: this.onMascotDialogDismiss,
}
},
}}
emotion={MASCOT_STYLE.NORMAL}
/>
<AlertDialog
visible={this.state.dialogVisible}
visible={state.dialogVisible}
onDismiss={this.onDialogDismiss}
title={i18n.t("screens.scanner.error.title")}
message={i18n.t("screens.scanner.error.message")}
title={i18n.t('screens.scanner.error.title')}
message={i18n.t('screens.scanner.error.message')}
/>
<LoadingConfirmDialog
visible={this.state.loading}
titleLoading={i18n.t("general.loading")}
startLoading={true}
visible={state.loading}
titleLoading={i18n.t('general.loading')}
startLoading
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
},
button: {
position: 'absolute',
bottom: 20,
width: '80%',
left: '10%'
},
});
export default withTheme(ScannerScreen);

123
src/utils/Home.js Normal file
View file

@ -0,0 +1,123 @@
// @flow
import {stringToDate} from './Planning';
import type {EventType} from '../screens/Home/HomeScreen';
/**
* Gets the time limit depending on the current day:
* 17:30 for every day of the week except for thursday 11:30
* 00:00 on weekends
*/
export function getTodayEventTimeLimit(): Date {
const now = new Date();
if (now.getDay() === 4)
// Thursday
now.setHours(11, 30, 0);
else if (now.getDay() === 6 || now.getDay() === 0)
// Weekend
now.setHours(0, 0, 0);
else now.setHours(17, 30, 0);
return now;
}
/**
* Gets the duration (in milliseconds) of an event
*
* @param event {EventType}
* @return {number} The number of milliseconds
*/
export function getEventDuration(event: EventType): number {
const start = stringToDate(event.date_begin);
const end = stringToDate(event.date_end);
let duration = 0;
if (start != null && end != null) duration = end - start;
return duration;
}
/**
* Gets events starting after the limit
*
* @param events
* @param limit
* @return {Array<Object>}
*/
export function getEventsAfterLimit(
events: Array<EventType>,
limit: Date,
): Array<EventType> {
const validEvents = [];
events.forEach((event: EventType) => {
const startDate = stringToDate(event.date_begin);
if (startDate != null && startDate >= limit) {
validEvents.push(event);
}
});
return validEvents;
}
/**
* Gets the event with the longest duration in the given array.
* If all events have the same duration, return the first in the array.
*
* @param events
*/
export function getLongestEvent(events: Array<EventType>): EventType {
let longestEvent = events[0];
let longestTime = 0;
events.forEach((event: EventType) => {
const time = getEventDuration(event);
if (time > longestTime) {
longestTime = time;
longestEvent = event;
}
});
return longestEvent;
}
/**
* Gets events that have not yet ended/started
*
* @param events
*/
export function getFutureEvents(events: Array<EventType>): Array<EventType> {
const validEvents = [];
const now = new Date();
events.forEach((event: EventType) => {
const startDate = stringToDate(event.date_begin);
const endDate = stringToDate(event.date_end);
if (startDate != null) {
if (startDate > now) validEvents.push(event);
else if (endDate != null) {
if (endDate > now || endDate < startDate)
// Display event if it ends the following day
validEvents.push(event);
}
}
});
return validEvents;
}
/**
* Gets the event to display in the preview
*
* @param events
* @return {EventType | null}
*/
export function getDisplayEvent(events: Array<EventType>): EventType | null {
let displayEvent = null;
if (events.length > 1) {
const eventsAfterLimit = getEventsAfterLimit(
events,
getTodayEventTimeLimit(),
);
if (eventsAfterLimit.length > 0) {
if (eventsAfterLimit.length === 1) [displayEvent] = eventsAfterLimit;
else displayEvent = getLongestEvent(events);
} else {
displayEvent = getLongestEvent(events);
}
} else if (events.length === 1) {
[displayEvent] = events;
}
return displayEvent;
}