Improve vote screen to match linter

This commit is contained in:
Arnaud Vergnet 2020-08-02 19:52:19 +02:00
parent 142b861ccb
commit 3d9bfdea4c

View file

@ -1,46 +1,47 @@
// @flow // @flow
import * as React from 'react'; import * as React from 'react';
import {RefreshControl, View} from "react-native"; import {RefreshControl, View} from 'react-native';
import AuthenticatedScreen from "../../components/Amicale/AuthenticatedScreen"; import {StackNavigationProp} from '@react-navigation/stack';
import {getTimeOnlyString, stringToDate} from "../../utils/Planning"; import i18n from 'i18n-js';
import VoteTease from "../../components/Amicale/Vote/VoteTease"; import {Button} from 'react-native-paper';
import VoteSelect from "../../components/Amicale/Vote/VoteSelect"; import AuthenticatedScreen from '../../components/Amicale/AuthenticatedScreen';
import VoteResults from "../../components/Amicale/Vote/VoteResults"; import {getTimeOnlyString, stringToDate} from '../../utils/Planning';
import VoteWait from "../../components/Amicale/Vote/VoteWait"; import VoteTease from '../../components/Amicale/Vote/VoteTease';
import {StackNavigationProp} from "@react-navigation/stack"; import VoteSelect from '../../components/Amicale/Vote/VoteSelect';
import i18n from "i18n-js"; import VoteResults from '../../components/Amicale/Vote/VoteResults';
import {MASCOT_STYLE} from "../../components/Mascot/Mascot"; import VoteWait from '../../components/Amicale/Vote/VoteWait';
import MascotPopup from "../../components/Mascot/MascotPopup"; import {MASCOT_STYLE} from '../../components/Mascot/Mascot';
import AsyncStorageManager from "../../managers/AsyncStorageManager"; import MascotPopup from '../../components/Mascot/MascotPopup';
import {Button} from "react-native-paper"; import AsyncStorageManager from '../../managers/AsyncStorageManager';
import VoteNotAvailable from "../../components/Amicale/Vote/VoteNotAvailable"; import VoteNotAvailable from '../../components/Amicale/Vote/VoteNotAvailable';
import CollapsibleFlatList from "../../components/Collapsible/CollapsibleFlatList"; import CollapsibleFlatList from '../../components/Collapsible/CollapsibleFlatList';
import type {ApiGenericDataType} from '../../utils/WebData';
export type team = { export type VoteTeamType = {
id: number, id: number,
name: string, name: string,
votes: number, votes: number,
}
type teamResponse = {
has_voted: boolean,
teams: Array<team>,
}; };
type stringVoteDates = { type TeamResponseType = {
date_begin: string, has_voted: boolean,
date_end: string, teams: Array<VoteTeamType>,
date_result_begin: string, };
date_result_end: string,
}
type objectVoteDates = { type VoteDatesStringType = {
date_begin: Date, date_begin: string,
date_end: Date, date_end: string,
date_result_begin: Date, date_result_begin: string,
date_result_end: Date, date_result_end: string,
} };
type VoteDatesObjectType = {
date_begin: Date,
date_end: Date,
date_result_begin: Date,
date_result_end: Date,
};
// const FAKE_DATE = { // const FAKE_DATE = {
// "date_begin": "2020-08-19 15:50", // "date_begin": "2020-08-19 15:50",
@ -92,287 +93,322 @@ type objectVoteDates = {
const MIN_REFRESH_TIME = 5 * 1000; const MIN_REFRESH_TIME = 5 * 1000;
type Props = { type PropsType = {
navigation: StackNavigationProp navigation: StackNavigationProp,
} };
type State = { type StateType = {
hasVoted: boolean, hasVoted: boolean,
mascotDialogVisible: boolean, mascotDialogVisible: boolean,
} };
/** /**
* Screen displaying vote information and controls * Screen displaying vote information and controls
*/ */
export default class VoteScreen extends React.Component<Props, State> { export default class VoteScreen extends React.Component<PropsType, StateType> {
teams: Array<VoteTeamType>;
state = { hasVoted: boolean;
hasVoted: false,
mascotDialogVisible: AsyncStorageManager.getBool(AsyncStorageManager.PREFERENCES.voteShowBanner.key), datesString: null | VoteDatesStringType;
dates: null | VoteDatesObjectType;
today: Date;
mainFlatListData: Array<{key: string}>;
lastRefresh: Date | null;
authRef: {current: null | AuthenticatedScreen};
constructor() {
super();
this.state = {
hasVoted: false,
mascotDialogVisible: AsyncStorageManager.getBool(
AsyncStorageManager.PREFERENCES.voteShowBanner.key,
),
}; };
this.hasVoted = false;
this.today = new Date();
this.authRef = React.createRef();
this.lastRefresh = null;
this.mainFlatListData = [{key: 'main'}, {key: 'info'}];
}
teams: Array<team>; /**
hasVoted: boolean; * Gets the string representation of the given date.
datesString: null | stringVoteDates; *
dates: null | objectVoteDates; * If the given date is the same day as today, only return the tile.
* Otherwise, return the full date.
*
* @param date The Date object representation of the wanted date
* @param dateString The string representation of the wanted date
* @returns {string}
*/
getDateString(date: Date, dateString: string): string {
if (this.today.getDate() === date.getDate()) {
const str = getTimeOnlyString(dateString);
return str != null ? str : '';
}
return dateString;
}
today: Date; getMainRenderItem = ({item}: {item: {key: string}}): React.Node => {
if (item.key === 'info')
return (
<View>
<Button
mode="contained"
icon="help-circle"
onPress={this.showMascotDialog}
style={{
marginLeft: 'auto',
marginRight: 'auto',
marginTop: 20,
}}>
{i18n.t('screens.vote.mascotDialog.title')}
</Button>
</View>
);
return this.getContent();
};
mainFlatListData: Array<{ key: string }>; getScreen = (data: Array<ApiGenericDataType | null>): React.Node => {
lastRefresh: Date | null; const {state} = this;
// data[0] = FAKE_TEAMS2;
// data[1] = FAKE_DATE;
this.lastRefresh = new Date();
authRef: { current: null | AuthenticatedScreen }; const teams: TeamResponseType | null = data[0];
const dateStrings: VoteDatesStringType | null = data[1];
constructor() { if (dateStrings != null && dateStrings.date_begin == null)
super(); this.datesString = null;
this.hasVoted = false; else this.datesString = dateStrings;
this.today = new Date();
this.authRef = React.createRef(); if (teams != null) {
this.lastRefresh = null; this.teams = teams.teams;
this.mainFlatListData = [ this.hasVoted = teams.has_voted;
{key: 'main'},
{key: 'info'},
]
} }
/** this.generateDateObject();
* Reloads vote data if last refresh delta is smaller than the minimum refresh time return (
*/ <CollapsibleFlatList
reloadData = () => { data={this.mainFlatListData}
let canRefresh; refreshControl={
const lastRefresh = this.lastRefresh; <RefreshControl refreshing={false} onRefresh={this.reloadData} />
if (lastRefresh != null)
canRefresh = (new Date().getTime() - lastRefresh.getTime()) > MIN_REFRESH_TIME;
else
canRefresh = true;
if (canRefresh && this.authRef.current != null)
this.authRef.current.reload()
};
/**
* Generates the objects containing string and Date representations of key vote dates
*/
generateDateObject() {
const strings = this.datesString;
if (strings != null) {
const dateBegin = stringToDate(strings.date_begin);
const dateEnd = stringToDate(strings.date_end);
const dateResultBegin = stringToDate(strings.date_result_begin);
const dateResultEnd = stringToDate(strings.date_result_end);
if (dateBegin != null && dateEnd != null && dateResultBegin != null && dateResultEnd != null) {
this.dates = {
date_begin: dateBegin,
date_end: dateEnd,
date_result_begin: dateResultBegin,
date_result_end: dateResultEnd,
};
} else
this.dates = null;
} else
this.dates = null;
}
/**
* Gets the string representation of the given date.
*
* If the given date is the same day as today, only return the tile.
* Otherwise, return the full date.
*
* @param date The Date object representation of the wanted date
* @param dateString The string representation of the wanted date
* @returns {string}
*/
getDateString(date: Date, dateString: string): string {
if (this.today.getDate() === date.getDate()) {
const str = getTimeOnlyString(dateString);
return str != null ? str : "";
} else
return dateString;
}
isVoteRunning() {
return this.dates != null && this.today > this.dates.date_begin && this.today < this.dates.date_end;
}
isVoteStarted() {
return this.dates != null && this.today > this.dates.date_begin;
}
isResultRunning() {
return this.dates != null && this.today > this.dates.date_result_begin && this.today < this.dates.date_result_end;
}
isResultStarted() {
return this.dates != null && this.today > this.dates.date_result_begin;
}
mainRenderItem = ({item}: { item: { key: string } }) => {
if (item.key === 'info')
return (
<View>
<Button
mode={"contained"}
icon={"help-circle"}
onPress={this.showMascotDialog}
style={{
marginLeft: "auto",
marginRight: "auto",
marginTop: 20
}}>
{i18n.t("screens.vote.mascotDialog.title")}
</Button>
</View>
);
else
return this.getContent();
};
getScreen = (data: Array<{ [key: string]: any } | null>) => {
// data[0] = FAKE_TEAMS2;
// data[1] = FAKE_DATE;
this.lastRefresh = new Date();
const teams: teamResponse | null = data[0];
const dateStrings: stringVoteDates | null = data[1];
if (dateStrings != null && dateStrings.date_begin == null)
this.datesString = null;
else
this.datesString = dateStrings;
if (teams != null) {
this.teams = teams.teams;
this.hasVoted = teams.has_voted;
} }
extraData={state.hasVoted.toString()}
renderItem={this.getMainRenderItem}
/>
);
};
this.generateDateObject(); getContent(): React.Node {
return ( const {state} = this;
<CollapsibleFlatList if (!this.isVoteStarted()) return this.getTeaseVoteCard();
data={this.mainFlatListData} if (this.isVoteRunning() && !this.hasVoted && !state.hasVoted)
refreshControl={ return this.getVoteCard();
<RefreshControl if (!this.isResultStarted()) return this.getWaitVoteCard();
refreshing={false} if (this.isResultRunning()) return this.getVoteResultCard();
onRefresh={this.reloadData} return <VoteNotAvailable />;
/> }
}
extraData={this.state.hasVoted.toString()}
renderItem={this.mainRenderItem}
/>
);
};
getContent() { onVoteSuccess = (): void => this.setState({hasVoted: true});
if (!this.isVoteStarted())
return this.getTeaseVoteCard();
else if (this.isVoteRunning() && (!this.hasVoted && !this.state.hasVoted))
return this.getVoteCard();
else if (!this.isResultStarted())
return this.getWaitVoteCard();
else if (this.isResultRunning())
return this.getVoteResultCard();
else
return <VoteNotAvailable/>;
}
onVoteSuccess = () => this.setState({hasVoted: true}); /**
* The user has not voted yet, and the votes are open
*/
getVoteCard(): React.Node {
return (
<VoteSelect
teams={this.teams}
onVoteSuccess={this.onVoteSuccess}
onVoteError={this.reloadData}
/>
);
}
/** /**
* The user has not voted yet, and the votes are open * Votes have ended, results can be displayed
*/ */
getVoteCard() { getVoteResultCard(): React.Node {
return <VoteSelect teams={this.teams} onVoteSuccess={this.onVoteSuccess} onVoteError={this.reloadData}/>; if (this.dates != null && this.datesString != null)
} return (
<VoteResults
teams={this.teams}
dateEnd={this.getDateString(
this.dates.date_result_end,
this.datesString.date_result_end,
)}
/>
);
return <VoteNotAvailable />;
}
/** /**
* Votes have ended, results can be displayed * Vote will open shortly
*/ */
getVoteResultCard() { getTeaseVoteCard(): React.Node {
if (this.dates != null && this.datesString != null) if (this.dates != null && this.datesString != null)
return <VoteResults return (
teams={this.teams} <VoteTease
dateEnd={this.getDateString( startDate={this.getDateString(
this.dates.date_result_end, this.dates.date_begin,
this.datesString.date_result_end)} this.datesString.date_begin,
/>; )}
else />
return <VoteNotAvailable/>; );
} return <VoteNotAvailable />;
}
/** /**
* Vote will open shortly * Votes have ended, or user has voted waiting for results
*/ */
getTeaseVoteCard() { getWaitVoteCard(): React.Node {
if (this.dates != null && this.datesString != null) const {state} = this;
return <VoteTease let startDate = null;
startDate={this.getDateString(this.dates.date_begin, this.datesString.date_begin)}/>; if (
else this.dates != null &&
return <VoteNotAvailable/>; this.datesString != null &&
} this.dates.date_result_begin != null
)
startDate = this.getDateString(
this.dates.date_result_begin,
this.datesString.date_result_begin,
);
return (
<VoteWait
startDate={startDate}
hasVoted={this.hasVoted || state.hasVoted}
justVoted={state.hasVoted}
isVoteRunning={this.isVoteRunning()}
/>
);
}
/** /**
* Votes have ended, or user has voted waiting for results * Reloads vote data if last refresh delta is smaller than the minimum refresh time
*/ */
getWaitVoteCard() { reloadData = () => {
let startDate = null; let canRefresh;
if (this.dates != null && this.datesString != null && this.dates.date_result_begin != null) const {lastRefresh} = this;
startDate = this.getDateString(this.dates.date_result_begin, this.datesString.date_result_begin); if (lastRefresh != null)
return <VoteWait startDate={startDate} hasVoted={this.hasVoted || this.state.hasVoted} canRefresh =
justVoted={this.state.hasVoted} new Date().getTime() - lastRefresh.getTime() > MIN_REFRESH_TIME;
isVoteRunning={this.isVoteRunning()}/>; else canRefresh = true;
} if (canRefresh && this.authRef.current != null)
this.authRef.current.reload();
};
showMascotDialog = () => { showMascotDialog = () => {
this.setState({mascotDialogVisible: true}) this.setState({mascotDialogVisible: true});
}; };
hideMascotDialog = () => { hideMascotDialog = () => {
AsyncStorageManager.set(AsyncStorageManager.PREFERENCES.voteShowBanner.key, false); AsyncStorageManager.set(
this.setState({mascotDialogVisible: false}) AsyncStorageManager.PREFERENCES.voteShowBanner.key,
}; false,
);
this.setState({mascotDialogVisible: false});
};
/** isVoteStarted(): boolean {
* Renders the authenticated screen. return this.dates != null && this.today > this.dates.date_begin;
* }
* Teams and dates are not mandatory to allow showing the information box even if api requests fail
* isResultRunning(): boolean {
* @returns {*} return (
*/ this.dates != null &&
render() { this.today > this.dates.date_result_begin &&
return ( this.today < this.dates.date_result_end
<View style={{flex: 1}}> );
<AuthenticatedScreen }
{...this.props}
ref={this.authRef} isResultStarted(): boolean {
requests={[ return this.dates != null && this.today > this.dates.date_result_begin;
{ }
link: 'elections/teams',
params: {}, isVoteRunning(): boolean {
mandatory: false, return (
}, this.dates != null &&
{ this.today > this.dates.date_begin &&
link: 'elections/dates', this.today < this.dates.date_end
params: {}, );
mandatory: false, }
},
]} /**
renderFunction={this.getScreen} * Generates the objects containing string and Date representations of key vote dates
/> */
<MascotPopup generateDateObject() {
visible={this.state.mascotDialogVisible} const strings = this.datesString;
title={i18n.t("screens.vote.mascotDialog.title")} if (strings != null) {
message={i18n.t("screens.vote.mascotDialog.message")} const dateBegin = stringToDate(strings.date_begin);
icon={"vote"} const dateEnd = stringToDate(strings.date_end);
buttons={{ const dateResultBegin = stringToDate(strings.date_result_begin);
action: null, const dateResultEnd = stringToDate(strings.date_result_end);
cancel: { if (
message: i18n.t("screens.vote.mascotDialog.button"), dateBegin != null &&
icon: "check", dateEnd != null &&
onPress: this.hideMascotDialog, dateResultBegin != null &&
} dateResultEnd != null
}} ) {
emotion={MASCOT_STYLE.CUTE} this.dates = {
/> date_begin: dateBegin,
</View> date_end: dateEnd,
); date_result_begin: dateResultBegin,
} date_result_end: dateResultEnd,
};
} else this.dates = null;
} else this.dates = null;
}
/**
* Renders the authenticated screen.
*
* Teams and dates are not mandatory to allow showing the information box even if api requests fail
*
* @returns {*}
*/
render(): React.Node {
const {props, state} = this;
return (
<View style={{flex: 1}}>
<AuthenticatedScreen
navigation={props.navigation}
ref={this.authRef}
requests={[
{
link: 'elections/teams',
params: {},
mandatory: false,
},
{
link: 'elections/dates',
params: {},
mandatory: false,
},
]}
renderFunction={this.getScreen}
/>
<MascotPopup
visible={state.mascotDialogVisible}
title={i18n.t('screens.vote.mascotDialog.title')}
message={i18n.t('screens.vote.mascotDialog.message')}
icon="vote"
buttons={{
action: null,
cancel: {
message: i18n.t('screens.vote.mascotDialog.button'),
icon: 'check',
onPress: this.hideMascotDialog,
},
}}
emotion={MASCOT_STYLE.CUTE}
/>
</View>
);
}
} }