Compare commits

..

No commits in common. "93d12b27f8c19020caa6a2d422977e5597dadf12" and "925bded69bba0af20237fb52d96a72c498718e0b" have entirely different histories.

30 changed files with 2884 additions and 3099 deletions

View file

@ -1,114 +1,101 @@
// @flow // @flow
import * as React from 'react'; import * as React from 'react';
import {View} from 'react-native'; import {View} from "react-native";
import {List, withTheme} from 'react-native-paper'; import {List, withTheme} from 'react-native-paper';
import Collapsible from 'react-native-collapsible'; import Collapsible from "react-native-collapsible";
import * as Animatable from 'react-native-animatable'; import * as Animatable from "react-native-animatable";
import type {CustomTheme} from '../../managers/ThemeManager'; import type {CustomTheme} from "../../managers/ThemeManager";
type PropsType = { type Props = {
theme: CustomTheme, theme: CustomTheme,
title: string, title: string,
subtitle?: string, subtitle?: string,
left?: () => React.Node, left?: (props: { [keys: string]: any }) => React.Node,
opened?: boolean, opened?: boolean,
unmountWhenCollapsed?: boolean, unmountWhenCollapsed: boolean,
children?: React.Node, children?: React.Node,
}; }
type StateType = { type State = {
expanded: boolean, expanded: boolean,
}; }
const AnimatedListIcon = Animatable.createAnimatableComponent(List.Icon); const AnimatedListIcon = Animatable.createAnimatableComponent(List.Icon);
class AnimatedAccordion extends React.Component<PropsType, StateType> { class AnimatedAccordion extends React.Component<Props, State> {
static defaultProps = {
subtitle: '',
left: null,
opened: null,
unmountWhenCollapsed: false,
children: null,
};
chevronRef: {current: null | AnimatedListIcon}; static defaultProps = {
unmountWhenCollapsed: false,
}
chevronRef: { current: null | AnimatedListIcon };
chevronIcon: string;
animStart: string;
animEnd: string;
chevronIcon: string; state = {
expanded: this.props.opened != null ? this.props.opened : false,
}
animStart: string; constructor(props) {
super(props);
this.chevronRef = React.createRef();
this.setupChevron();
}
animEnd: string; setupChevron() {
if (this.state.expanded) {
this.chevronIcon = "chevron-up";
this.animStart = "180deg";
this.animEnd = "0deg";
} else {
this.chevronIcon = "chevron-down";
this.animStart = "0deg";
this.animEnd = "180deg";
}
}
constructor(props: PropsType) { toggleAccordion = () => {
super(props); if (this.chevronRef.current != null) {
this.state = { this.chevronRef.current.transitionTo({rotate: this.state.expanded ? this.animStart : this.animEnd});
expanded: props.opened != null ? props.opened : false, this.setState({expanded: !this.state.expanded})
}
}; };
this.chevronRef = React.createRef();
this.setupChevron();
}
shouldComponentUpdate(nextProps: PropsType): boolean { shouldComponentUpdate(nextProps: Props, nextState: State): boolean {
const {state, props} = this; if (nextProps.opened != null && nextProps.opened !== this.props.opened)
if (nextProps.opened != null && nextProps.opened !== props.opened) this.state.expanded = nextProps.opened;
state.expanded = nextProps.opened; return true;
return true;
}
setupChevron() {
const {state} = this;
if (state.expanded) {
this.chevronIcon = 'chevron-up';
this.animStart = '180deg';
this.animEnd = '0deg';
} else {
this.chevronIcon = 'chevron-down';
this.animStart = '0deg';
this.animEnd = '180deg';
} }
}
toggleAccordion = () => { render() {
const {state} = this; const colors = this.props.theme.colors;
if (this.chevronRef.current != null) { return (
this.chevronRef.current.transitionTo({ <View>
rotate: state.expanded ? this.animStart : this.animEnd, <List.Item
}); {...this.props}
this.setState({expanded: !state.expanded}); title={this.props.title}
subtitle={this.props.subtitle}
titleStyle={this.state.expanded ? {color: colors.primary} : undefined}
onPress={this.toggleAccordion}
right={(props) => <AnimatedListIcon
ref={this.chevronRef}
{...props}
icon={this.chevronIcon}
color={this.state.expanded ? colors.primary : undefined}
useNativeDriver
/>}
left={this.props.left}
/>
<Collapsible collapsed={!this.state.expanded}>
{!this.props.unmountWhenCollapsed || (this.props.unmountWhenCollapsed && this.state.expanded)
? this.props.children
: null}
</Collapsible>
</View>
);
} }
};
render(): React.Node {
const {props, state} = this;
const {colors} = props.theme;
return (
<View>
<List.Item
title={props.title}
subtitle={props.subtitle}
titleStyle={state.expanded ? {color: colors.primary} : undefined}
onPress={this.toggleAccordion}
right={({size}: {size: number}): React.Node => (
<AnimatedListIcon
ref={this.chevronRef}
size={size}
icon={this.chevronIcon}
color={state.expanded ? colors.primary : undefined}
useNativeDriver
/>
)}
left={props.left}
/>
<Collapsible collapsed={!state.expanded}>
{!props.unmountWhenCollapsed ||
(props.unmountWhenCollapsed && state.expanded)
? props.children
: null}
</Collapsible>
</View>
);
}
} }
export default withTheme(AnimatedAccordion); export default withTheme(AnimatedAccordion);

View file

@ -1,178 +1,170 @@
// @flow // @flow
import * as React from 'react'; import * as React from 'react';
import {StyleSheet, View} from 'react-native'; import {StyleSheet, View} from "react-native";
import {FAB, IconButton, Surface, withTheme} from 'react-native-paper'; import {FAB, IconButton, Surface, withTheme} from "react-native-paper";
import AutoHideHandler from "../../utils/AutoHideHandler";
import * as Animatable from 'react-native-animatable'; import * as Animatable from 'react-native-animatable';
import {StackNavigationProp} from '@react-navigation/stack'; import CustomTabBar from "../Tabbar/CustomTabBar";
import AutoHideHandler from '../../utils/AutoHideHandler'; import {StackNavigationProp} from "@react-navigation/stack";
import CustomTabBar from '../Tabbar/CustomTabBar'; import type {CustomTheme} from "../../managers/ThemeManager";
import type {CustomTheme} from '../../managers/ThemeManager';
const AnimatedFAB = Animatable.createAnimatableComponent(FAB); const AnimatedFAB = Animatable.createAnimatableComponent(FAB);
type PropsType = { type Props = {
navigation: StackNavigationProp, navigation: StackNavigationProp,
theme: CustomTheme, theme: CustomTheme,
onPress: (action: string, data?: string) => void, onPress: (action: string, data: any) => void,
seekAttention: boolean, seekAttention: boolean,
};
type StateType = {
currentMode: string,
};
const DISPLAY_MODES = {
DAY: 'agendaDay',
WEEK: 'agendaWeek',
MONTH: 'month',
};
const styles = StyleSheet.create({
container: {
position: 'absolute',
left: '5%',
width: '90%',
},
surface: {
position: 'relative',
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
borderRadius: 50,
elevation: 2,
},
fabContainer: {
position: 'absolute',
left: 0,
right: 0,
alignItems: 'center',
width: '100%',
height: '100%',
},
fab: {
position: 'absolute',
alignSelf: 'center',
top: '-25%',
},
});
class AnimatedBottomBar extends React.Component<PropsType, StateType> {
ref: {current: null | Animatable.View};
hideHandler: AutoHideHandler;
displayModeIcons: {[key: string]: string};
constructor() {
super();
this.state = {
currentMode: DISPLAY_MODES.WEEK,
};
this.ref = React.createRef();
this.hideHandler = new AutoHideHandler(false);
this.hideHandler.addListener(this.onHideChange);
this.displayModeIcons = {};
this.displayModeIcons[DISPLAY_MODES.DAY] = 'calendar-text';
this.displayModeIcons[DISPLAY_MODES.WEEK] = 'calendar-week';
this.displayModeIcons[DISPLAY_MODES.MONTH] = 'calendar-range';
}
shouldComponentUpdate(nextProps: PropsType, nextState: StateType): boolean {
const {props, state} = this;
return (
nextProps.seekAttention !== props.seekAttention ||
nextState.currentMode !== state.currentMode
);
}
onHideChange = (shouldHide: boolean) => {
if (this.ref.current != null) {
if (shouldHide) this.ref.current.fadeOutDown(500);
else this.ref.current.fadeInUp(500);
}
};
onScroll = (event: SyntheticEvent<EventTarget>) => {
this.hideHandler.onScroll(event);
};
changeDisplayMode = () => {
const {props, state} = this;
let newMode;
switch (state.currentMode) {
case DISPLAY_MODES.DAY:
newMode = DISPLAY_MODES.WEEK;
break;
case DISPLAY_MODES.WEEK:
newMode = DISPLAY_MODES.MONTH;
break;
case DISPLAY_MODES.MONTH:
newMode = DISPLAY_MODES.DAY;
break;
default:
newMode = DISPLAY_MODES.WEEK;
break;
}
this.setState({currentMode: newMode});
props.onPress('changeView', newMode);
};
render(): React.Node {
const {props, state} = this;
const buttonColor = props.theme.colors.primary;
return (
<Animatable.View
ref={this.ref}
useNativeDriver
style={{
...styles.container,
bottom: 10 + CustomTabBar.TAB_BAR_HEIGHT,
}}>
<Surface style={styles.surface}>
<View style={styles.fabContainer}>
<AnimatedFAB
animation={props.seekAttention ? 'bounce' : undefined}
easing="ease-out"
iterationDelay={500}
iterationCount="infinite"
useNativeDriver
style={styles.fab}
icon="account-clock"
onPress={(): void => props.navigation.navigate('group-select')}
/>
</View>
<View style={{flexDirection: 'row'}}>
<IconButton
icon={this.displayModeIcons[state.currentMode]}
color={buttonColor}
onPress={this.changeDisplayMode}
/>
<IconButton
icon="clock-in"
color={buttonColor}
style={{marginLeft: 5}}
onPress={(): void => props.onPress('today')}
/>
</View>
<View style={{flexDirection: 'row'}}>
<IconButton
icon="chevron-left"
color={buttonColor}
onPress={(): void => props.onPress('prev')}
/>
<IconButton
icon="chevron-right"
color={buttonColor}
style={{marginLeft: 5}}
onPress={(): void => props.onPress('next')}
/>
</View>
</Surface>
</Animatable.View>
);
}
} }
type State = {
currentMode: string,
}
const DISPLAY_MODES = {
DAY: "agendaDay",
WEEK: "agendaWeek",
MONTH: "month",
}
class AnimatedBottomBar extends React.Component<Props, State> {
ref: { current: null | Animatable.View };
hideHandler: AutoHideHandler;
displayModeIcons: { [key: string]: string };
state = {
currentMode: DISPLAY_MODES.WEEK,
}
constructor() {
super();
this.ref = React.createRef();
this.hideHandler = new AutoHideHandler(false);
this.hideHandler.addListener(this.onHideChange);
this.displayModeIcons = {};
this.displayModeIcons[DISPLAY_MODES.DAY] = "calendar-text";
this.displayModeIcons[DISPLAY_MODES.WEEK] = "calendar-week";
this.displayModeIcons[DISPLAY_MODES.MONTH] = "calendar-range";
}
shouldComponentUpdate(nextProps: Props, nextState: State) {
return (nextProps.seekAttention !== this.props.seekAttention)
|| (nextState.currentMode !== this.state.currentMode);
}
onHideChange = (shouldHide: boolean) => {
if (this.ref.current != null) {
if (shouldHide)
this.ref.current.fadeOutDown(500);
else
this.ref.current.fadeInUp(500);
}
}
onScroll = (event: SyntheticEvent<EventTarget>) => {
this.hideHandler.onScroll(event);
};
changeDisplayMode = () => {
let newMode;
switch (this.state.currentMode) {
case DISPLAY_MODES.DAY:
newMode = DISPLAY_MODES.WEEK;
break;
case DISPLAY_MODES.WEEK:
newMode = DISPLAY_MODES.MONTH;
break;
case DISPLAY_MODES.MONTH:
newMode = DISPLAY_MODES.DAY;
break;
}
this.setState({currentMode: newMode});
this.props.onPress("changeView", newMode);
};
render() {
const buttonColor = this.props.theme.colors.primary;
return (
<Animatable.View
ref={this.ref}
useNativeDriver
style={{
...styles.container,
bottom: 10 + CustomTabBar.TAB_BAR_HEIGHT
}}>
<Surface style={styles.surface}>
<View style={styles.fabContainer}>
<AnimatedFAB
animation={this.props.seekAttention ? "bounce" : undefined}
easing="ease-out"
iterationDelay={500}
iterationCount="infinite"
useNativeDriver
style={styles.fab}
icon="account-clock"
onPress={() => this.props.navigation.navigate('group-select')}
/>
</View>
<View style={{flexDirection: 'row'}}>
<IconButton
icon={this.displayModeIcons[this.state.currentMode]}
color={buttonColor}
onPress={this.changeDisplayMode}/>
<IconButton
icon="clock-in"
color={buttonColor}
style={{marginLeft: 5}}
onPress={() => this.props.onPress('today', undefined)}/>
</View>
<View style={{flexDirection: 'row'}}>
<IconButton
icon="chevron-left"
color={buttonColor}
onPress={() => this.props.onPress('prev', undefined)}/>
<IconButton
icon="chevron-right"
color={buttonColor}
style={{marginLeft: 5}}
onPress={() => this.props.onPress('next', undefined)}/>
</View>
</Surface>
</Animatable.View>
);
}
}
const styles = StyleSheet.create({
container: {
position: 'absolute',
left: '5%',
width: '90%',
},
surface: {
position: 'relative',
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
borderRadius: 50,
elevation: 2,
},
fabContainer: {
position: "absolute",
left: 0,
right: 0,
alignItems: "center",
width: '100%',
height: '100%'
},
fab: {
position: 'absolute',
alignSelf: 'center',
top: '-25%',
}
});
export default withTheme(AnimatedBottomBar); export default withTheme(AnimatedBottomBar);

View file

@ -1,63 +1,66 @@
// @flow // @flow
import * as React from 'react'; import * as React from 'react';
import {StyleSheet} from 'react-native'; import {StyleSheet} from "react-native";
import {FAB} from 'react-native-paper'; import {FAB} from "react-native-paper";
import AutoHideHandler from "../../utils/AutoHideHandler";
import * as Animatable from 'react-native-animatable'; import * as Animatable from 'react-native-animatable';
import AutoHideHandler from '../../utils/AutoHideHandler'; import CustomTabBar from "../Tabbar/CustomTabBar";
import CustomTabBar from '../Tabbar/CustomTabBar'; import {StackNavigationProp} from "@react-navigation/stack";
type PropsType = { type Props = {
icon: string, navigation: StackNavigationProp,
onPress: () => void, icon: string,
}; onPress: () => void,
}
const AnimatedFab = Animatable.createAnimatableComponent(FAB); const AnimatedFab = Animatable.createAnimatableComponent(FAB);
const styles = StyleSheet.create({ export default class AnimatedFAB extends React.Component<Props> {
fab: {
position: 'absolute',
margin: 16,
right: 0,
},
});
export default class AnimatedFAB extends React.Component<PropsType> { ref: { current: null | Animatable.View };
ref: {current: null | Animatable.View}; hideHandler: AutoHideHandler;
hideHandler: AutoHideHandler; constructor() {
super();
constructor() { this.ref = React.createRef();
super(); this.hideHandler = new AutoHideHandler(false);
this.ref = React.createRef(); this.hideHandler.addListener(this.onHideChange);
this.hideHandler = new AutoHideHandler(false);
this.hideHandler.addListener(this.onHideChange);
}
onScroll = (event: SyntheticEvent<EventTarget>) => {
this.hideHandler.onScroll(event);
};
onHideChange = (shouldHide: boolean) => {
if (this.ref.current != null) {
if (shouldHide) this.ref.current.bounceOutDown(1000);
else this.ref.current.bounceInUp(1000);
} }
};
render(): React.Node { onScroll = (event: SyntheticEvent<EventTarget>) => {
const {props} = this; this.hideHandler.onScroll(event);
return ( };
<AnimatedFab
ref={this.ref} onHideChange = (shouldHide: boolean) => {
useNativeDriver if (this.ref.current != null) {
icon={props.icon} if (shouldHide)
onPress={props.onPress} this.ref.current.bounceOutDown(1000);
style={{ else
...styles.fab, this.ref.current.bounceInUp(1000);
bottom: CustomTabBar.TAB_BAR_HEIGHT, }
}} }
/>
); render() {
} return (
<AnimatedFab
ref={this.ref}
useNativeDriver
icon={this.props.icon}
onPress={this.props.onPress}
style={{
...styles.fab,
bottom: CustomTabBar.TAB_BAR_HEIGHT
}}
/>
);
}
} }
const styles = StyleSheet.create({
fab: {
position: 'absolute',
margin: 16,
right: 0,
},
});

View file

@ -1,59 +1,51 @@
// @flow // @flow
import * as React from 'react'; import * as React from 'react';
import {Collapsible} from 'react-navigation-collapsible'; import {withCollapsible} from "../../utils/withCollapsible";
import {withCollapsible} from '../../utils/withCollapsible'; import {Collapsible} from "react-navigation-collapsible";
import CustomTabBar from '../Tabbar/CustomTabBar'; import CustomTabBar from "../Tabbar/CustomTabBar";
export type CollapsibleComponentPropsType = { export type CollapsibleComponentProps = {
children?: React.Node, children?: React.Node,
hasTab?: boolean, hasTab?: boolean,
onScroll?: (event: SyntheticEvent<EventTarget>) => void, onScroll?: (event: SyntheticEvent<EventTarget>) => void,
}; };
type PropsType = { type Props = {
...CollapsibleComponentPropsType, ...CollapsibleComponentProps,
collapsibleStack: Collapsible, collapsibleStack: Collapsible,
// eslint-disable-next-line flowtype/no-weak-types component: any,
component: any, }
};
class CollapsibleComponent extends React.Component<PropsType> { class CollapsibleComponent extends React.Component<Props> {
static defaultProps = {
children: null,
hasTab: false,
onScroll: null,
};
onScroll = (event: SyntheticEvent<EventTarget>) => { static defaultProps = {
const {props} = this; hasTab: false,
if (props.onScroll) props.onScroll(event); }
};
render(): React.Node { onScroll = (event: SyntheticEvent<EventTarget>) => {
const {props} = this; if (this.props.onScroll)
const Comp = props.component; this.props.onScroll(event);
const { }
containerPaddingTop,
scrollIndicatorInsetTop,
onScrollWithListener,
} = props.collapsibleStack;
return ( render() {
<Comp const Comp = this.props.component;
// eslint-disable-next-line react/jsx-props-no-spreading const {containerPaddingTop, scrollIndicatorInsetTop, onScrollWithListener} = this.props.collapsibleStack;
{...props} return (
onScroll={onScrollWithListener(this.onScroll)} <Comp
contentContainerStyle={{ {...this.props}
paddingTop: containerPaddingTop, onScroll={onScrollWithListener(this.onScroll)}
paddingBottom: props.hasTab ? CustomTabBar.TAB_BAR_HEIGHT : 0, contentContainerStyle={{
minHeight: '100%', paddingTop: containerPaddingTop,
}} paddingBottom: this.props.hasTab ? CustomTabBar.TAB_BAR_HEIGHT : 0,
scrollIndicatorInsets={{top: scrollIndicatorInsetTop}}> minHeight: '100%'
{props.children} }}
</Comp> scrollIndicatorInsets={{top: scrollIndicatorInsetTop}}
); >
} {this.props.children}
</Comp>
);
}
} }
export default withCollapsible(CollapsibleComponent); export default withCollapsible(CollapsibleComponent);

View file

@ -1,26 +1,26 @@
// @flow // @flow
import * as React from 'react'; import * as React from 'react';
import {Animated} from 'react-native'; import {Animated} from "react-native";
import type {CollapsibleComponentPropsType} from './CollapsibleComponent'; import type {CollapsibleComponentProps} from "./CollapsibleComponent";
import CollapsibleComponent from './CollapsibleComponent'; import CollapsibleComponent from "./CollapsibleComponent";
type PropsType = { type Props = {
...CollapsibleComponentPropsType, ...CollapsibleComponentProps
}; }
// eslint-disable-next-line react/prefer-stateless-function class CollapsibleFlatList extends React.Component<Props> {
class CollapsibleFlatList extends React.Component<PropsType> {
render(): React.Node { render() {
const {props} = this; return (
return ( <CollapsibleComponent
<CollapsibleComponent // eslint-disable-next-line react/jsx-props-no-spreading {...this.props}
{...props} component={Animated.FlatList}
component={Animated.FlatList}> >
{props.children} {this.props.children}
</CollapsibleComponent> </CollapsibleComponent>
); );
} }
} }
export default CollapsibleFlatList; export default CollapsibleFlatList;

View file

@ -1,26 +1,26 @@
// @flow // @flow
import * as React from 'react'; import * as React from 'react';
import {Animated} from 'react-native'; import {Animated} from "react-native";
import type {CollapsibleComponentPropsType} from './CollapsibleComponent'; import type {CollapsibleComponentProps} from "./CollapsibleComponent";
import CollapsibleComponent from './CollapsibleComponent'; import CollapsibleComponent from "./CollapsibleComponent";
type PropsType = { type Props = {
...CollapsibleComponentPropsType, ...CollapsibleComponentProps
}; }
// eslint-disable-next-line react/prefer-stateless-function class CollapsibleScrollView extends React.Component<Props> {
class CollapsibleScrollView extends React.Component<PropsType> {
render(): React.Node { render() {
const {props} = this; return (
return ( <CollapsibleComponent
<CollapsibleComponent // eslint-disable-next-line react/jsx-props-no-spreading {...this.props}
{...props} component={Animated.ScrollView}
component={Animated.ScrollView}> >
{props.children} {this.props.children}
</CollapsibleComponent> </CollapsibleComponent>
); );
} }
} }
export default CollapsibleScrollView; export default CollapsibleScrollView;

View file

@ -1,26 +1,26 @@
// @flow // @flow
import * as React from 'react'; import * as React from 'react';
import {Animated} from 'react-native'; import {Animated} from "react-native";
import type {CollapsibleComponentPropsType} from './CollapsibleComponent'; import type {CollapsibleComponentProps} from "./CollapsibleComponent";
import CollapsibleComponent from './CollapsibleComponent'; import CollapsibleComponent from "./CollapsibleComponent";
type PropsType = { type Props = {
...CollapsibleComponentPropsType, ...CollapsibleComponentProps
}; }
// eslint-disable-next-line react/prefer-stateless-function class CollapsibleSectionList extends React.Component<Props> {
class CollapsibleSectionList extends React.Component<PropsType> {
render(): React.Node { render() {
const {props} = this; return (
return ( <CollapsibleComponent
<CollapsibleComponent // eslint-disable-next-line react/jsx-props-no-spreading {...this.props}
{...props} component={Animated.SectionList}
component={Animated.SectionList}> >
{props.children} {this.props.children}
</CollapsibleComponent> </CollapsibleComponent>
); );
} }
} }
export default CollapsibleSectionList; export default CollapsibleSectionList;

View file

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

View file

@ -1,96 +1,91 @@
// @flow // @flow
import * as React from 'react'; import * as React from 'react';
import { import {Avatar, Card, Text, TouchableRipple, withTheme} from 'react-native-paper';
Avatar, import {StyleSheet, View} from "react-native";
Card, import i18n from "i18n-js";
Text, import type {CustomTheme} from "../../managers/ThemeManager";
TouchableRipple,
withTheme,
} from 'react-native-paper';
import {StyleSheet, View} from 'react-native';
import i18n from 'i18n-js';
import type {CustomTheme} from '../../managers/ThemeManager';
type PropsType = { type Props = {
eventNumber: number, eventNumber: number;
clickAction: () => void, clickAction: () => void,
theme: CustomTheme, theme: CustomTheme,
children?: React.Node, children?: React.Node
}; }
const styles = StyleSheet.create({
card: {
width: 'auto',
marginLeft: 10,
marginRight: 10,
marginTop: 10,
overflow: 'hidden',
},
avatar: {
backgroundColor: 'transparent',
},
});
/** /**
* Component used to display a dashboard item containing a preview event * Component used to display a dashboard item containing a preview event
*/ */
class EventDashBoardItem extends React.Component<PropsType> { class EventDashBoardItem extends React.Component<Props> {
static defaultProps = {
children: null,
};
shouldComponentUpdate(nextProps: PropsType): boolean { shouldComponentUpdate(nextProps: Props) {
const {props} = this; return (nextProps.theme.dark !== this.props.theme.dark)
return ( || (nextProps.eventNumber !== this.props.eventNumber);
nextProps.theme.dark !== props.theme.dark || }
nextProps.eventNumber !== 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>
);
}
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>
);
}
} }
const styles = StyleSheet.create({
card: {
width: 'auto',
marginLeft: 10,
marginRight: 10,
marginTop: 10,
overflow: 'hidden',
},
avatar: {
backgroundColor: 'transparent'
}
});
export default withTheme(EventDashBoardItem); export default withTheme(EventDashBoardItem);

View file

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

View file

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

View file

@ -2,15 +2,15 @@
import * as React from 'react'; import * as React from 'react';
import {Badge, TouchableRipple, withTheme} from 'react-native-paper'; import {Badge, TouchableRipple, withTheme} from 'react-native-paper';
import {Dimensions, Image, View} from 'react-native'; import {Dimensions, Image, View} from "react-native";
import * as Animatable from 'react-native-animatable'; import type {CustomTheme} from "../../managers/ThemeManager";
import type {CustomTheme} from '../../managers/ThemeManager'; import * as Animatable from "react-native-animatable";
type PropsType = { type Props = {
image: string | null, image: string,
onPress: () => void | null, onPress: () => void,
badgeCount: number | null, badgeCount: number | null,
theme: CustomTheme, theme: CustomTheme,
}; };
const AnimatableBadge = Animatable.createAnimatableComponent(Badge); const AnimatableBadge = Animatable.createAnimatableComponent(Badge);
@ -18,68 +18,69 @@ const AnimatableBadge = Animatable.createAnimatableComponent(Badge);
/** /**
* Component used to render a small dashboard item * Component used to render a small dashboard item
*/ */
class SmallDashboardItem extends React.Component<PropsType> { class SmallDashboardItem extends React.Component<Props> {
itemSize: number;
constructor(props: PropsType) { itemSize: number;
super(props);
this.itemSize = Dimensions.get('window').width / 8;
}
shouldComponentUpdate(nextProps: PropsType): boolean { constructor(props: Props) {
const {props} = this; super(props);
return ( this.itemSize = Dimensions.get('window').width / 8;
nextProps.theme.dark !== props.theme.dark || }
nextProps.badgeCount !== props.badgeCount
); shouldComponentUpdate(nextProps: Props) {
} return (nextProps.theme.dark !== this.props.theme.dark)
|| (nextProps.badgeCount !== this.props.badgeCount);
}
render() {
const props = this.props;
return (
<TouchableRipple
onPress={this.props.onPress}
borderless={true}
style={{
marginLeft: this.itemSize / 6,
marginRight: this.itemSize / 6,
}}
>
<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",
}}
/>
{
props.badgeCount != null && props.badgeCount > 0 ?
<AnimatableBadge
animation={"zoomIn"}
duration={300}
useNativeDriver
style={{
position: 'absolute',
top: 0,
right: 0,
backgroundColor: props.theme.colors.primary,
borderColor: props.theme.colors.background,
borderWidth: 2,
}}>
{props.badgeCount}
</AnimatableBadge> : null
}
</View>
</TouchableRipple>
);
}
render(): React.Node {
const {props} = this;
return (
<TouchableRipple
onPress={props.onPress}
borderless
style={{
marginLeft: this.itemSize / 6,
marginRight: this.itemSize / 6,
}}>
<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',
}}
/>
{props.badgeCount != null && props.badgeCount > 0 ? (
<AnimatableBadge
animation="zoomIn"
duration={300}
useNativeDriver
style={{
position: 'absolute',
top: 0,
right: 0,
backgroundColor: props.theme.colors.primary,
borderColor: props.theme.colors.background,
borderWidth: 2,
}}>
{props.badgeCount}
</AnimatableBadge>
) : null}
</View>
</TouchableRipple>
);
}
} }
export default withTheme(SmallDashboardItem); export default withTheme(SmallDashboardItem);

View file

@ -1,73 +1,72 @@
// @flow // @flow
import * as React from 'react'; import * as React from 'react';
import {Animated, Dimensions} from 'react-native'; import {Animated, Dimensions} from "react-native";
import type {ViewStyle} from 'react-native/Libraries/StyleSheet/StyleSheet'; import ImageListItem from "./ImageListItem";
import ImageListItem from './ImageListItem'; import CardListItem from "./CardListItem";
import CardListItem from './CardListItem'; import type {ViewStyle} from "react-native/Libraries/StyleSheet/StyleSheet";
import type {ServiceItemType} from '../../../managers/ServicesManager';
type PropsType = { type Props = {
dataset: Array<ServiceItemType>, dataset: Array<cardItem>,
isHorizontal?: boolean, isHorizontal: boolean,
contentContainerStyle?: ViewStyle | null, contentContainerStyle?: ViewStyle,
}
export type cardItem = {
key: string,
title: string,
subtitle: string,
image: string | number,
onPress: () => void,
}; };
export default class CardList extends React.Component<PropsType> { export type cardList = Array<cardItem>;
static defaultProps = {
isHorizontal: false,
contentContainerStyle: null,
};
windowWidth: number;
horizontalItemSize: number; export default class CardList extends React.Component<Props> {
constructor(props: PropsType) { static defaultProps = {
super(props); isHorizontal: false,
this.windowWidth = Dimensions.get('window').width;
this.horizontalItemSize = this.windowWidth / 4; // So that we can fit 3 items and a part of the 4th => user knows he can scroll
}
getRenderItem = ({item}: {item: ServiceItemType}): React.Node => {
const {props} = this;
if (props.isHorizontal)
return (
<ImageListItem
item={item}
key={item.title}
width={this.horizontalItemSize}
/>
);
return <CardListItem item={item} key={item.title} />;
};
keyExtractor = (item: ServiceItemType): string => item.key;
render(): React.Node {
const {props} = this;
let containerStyle = {};
if (props.isHorizontal) {
containerStyle = {
height: this.horizontalItemSize + 50,
justifyContent: 'space-around',
};
} }
return (
<Animated.FlatList windowWidth: number;
data={props.dataset} horizontalItemSize: number;
renderItem={this.getRenderItem}
keyExtractor={this.keyExtractor} constructor(props: Props) {
numColumns={props.isHorizontal ? undefined : 2} super(props);
horizontal={props.isHorizontal} this.windowWidth = Dimensions.get('window').width;
contentContainerStyle={ this.horizontalItemSize = this.windowWidth/4; // So that we can fit 3 items and a part of the 4th => user knows he can scroll
props.isHorizontal ? containerStyle : props.contentContainerStyle }
renderItem = ({item}: { item: cardItem }) => {
if (this.props.isHorizontal)
return <ImageListItem item={item} key={item.title} width={this.horizontalItemSize}/>;
else
return <CardListItem item={item} key={item.title}/>;
};
keyExtractor = (item: cardItem) => item.key;
render() {
let containerStyle = {};
if (this.props.isHorizontal) {
containerStyle = {
height: this.horizontalItemSize + 50,
justifyContent: 'space-around',
};
} }
pagingEnabled={props.isHorizontal} return (
snapToInterval={ <Animated.FlatList
props.isHorizontal ? (this.horizontalItemSize + 5) * 3 : null {...this.props}
} data={this.props.dataset}
/> renderItem={this.renderItem}
); keyExtractor={this.keyExtractor}
} numColumns={this.props.isHorizontal ? undefined : 2}
horizontal={this.props.isHorizontal}
contentContainerStyle={this.props.isHorizontal ? containerStyle : this.props.contentContainerStyle}
pagingEnabled={this.props.isHorizontal}
snapToInterval={this.props.isHorizontal ? (this.horizontalItemSize+5)*3 : null}
/>
);
}
} }

View file

@ -2,41 +2,50 @@
import * as React from 'react'; import * as React from 'react';
import {Caption, Card, Paragraph, TouchableRipple} from 'react-native-paper'; import {Caption, Card, Paragraph, TouchableRipple} from 'react-native-paper';
import {View} from 'react-native'; import {View} from "react-native";
import type {ServiceItemType} from '../../../managers/ServicesManager'; import type {cardItem} from "./CardList";
type PropsType = { type Props = {
item: ServiceItemType, item: cardItem,
}; }
export default class CardListItem extends React.Component<PropsType> { export default class CardListItem extends React.Component<Props> {
shouldComponentUpdate(): boolean {
return false; shouldComponentUpdate() {
} return false;
}
render(): React.Node {
const {props} = this; render() {
const {item} = props; const props = this.props;
const source = const item = props.item;
typeof item.image === 'number' ? item.image : {uri: item.image}; const source = typeof item.image === "number"
return ( ? item.image
<Card : {uri: item.image};
style={{ return (
width: '40%', <Card
margin: 5, style={{
marginLeft: 'auto', width: '40%',
marginRight: 'auto', margin: 5,
}}> marginLeft: 'auto',
<TouchableRipple style={{flex: 1}} onPress={item.onPress}> marginRight: 'auto',
<View> }}
<Card.Cover style={{height: 80}} source={source} /> >
<Card.Content> <TouchableRipple
<Paragraph>{item.title}</Paragraph> style={{flex: 1}}
<Caption>{item.subtitle}</Caption> onPress={item.onPress}>
</Card.Content> <View>
</View> <Card.Cover
</TouchableRipple> style={{height: 80}}
</Card> source={source}
); />
} <Card.Content>
<Paragraph>{item.title}</Paragraph>
<Caption>{item.subtitle}</Caption>
</Card.Content>
</View>
</TouchableRipple>
</Card>
);
}
} }

View file

@ -3,52 +3,53 @@
import * as React from 'react'; import * as React from 'react';
import {Text, TouchableRipple} from 'react-native-paper'; import {Text, TouchableRipple} from 'react-native-paper';
import {Image, View} from 'react-native'; import {Image, View} from 'react-native';
import type {ServiceItemType} from '../../../managers/ServicesManager'; import type {cardItem} from "./CardList";
type PropsType = { type Props = {
item: ServiceItemType, item: cardItem,
width: number, width: number,
}; }
export default class ImageListItem extends React.Component<PropsType> { export default class ImageListItem extends React.Component<Props> {
shouldComponentUpdate(): boolean {
return false; shouldComponentUpdate() {
} return false;
}
render(): React.Node {
const {props} = this; render() {
const {item} = props; const item = this.props.item;
const source = const source = typeof item.image === "number"
typeof item.image === 'number' ? item.image : {uri: item.image}; ? item.image
return ( : {uri: item.image};
<TouchableRipple return (
style={{ <TouchableRipple
width: props.width, style={{
height: props.width + 40, width: this.props.width,
margin: 5, height: this.props.width + 40,
}} margin: 5,
onPress={item.onPress}> }}
<View> onPress={item.onPress}
<Image >
style={{ <View>
width: props.width - 20, <Image
height: props.width - 20, style={{
marginLeft: 'auto', width: this.props.width - 20,
marginRight: 'auto', height: this.props.width - 20,
}} marginLeft: 'auto',
source={source} marginRight: 'auto',
/> }}
<Text source={source}
style={{ />
marginTop: 5, <Text style={{
marginLeft: 'auto', marginTop: 5,
marginRight: 'auto', marginLeft: 'auto',
textAlign: 'center', marginRight: 'auto',
}}> textAlign: 'center'
{item.title} }}>
</Text> {item.title}
</View> </Text>
</TouchableRipple> </View>
); </TouchableRipple>
} );
}
} }

View file

@ -2,90 +2,82 @@
import * as React from 'react'; import * as React from 'react';
import {Card, Chip, List, Text} from 'react-native-paper'; import {Card, Chip, List, Text} from 'react-native-paper';
import {StyleSheet, View} from 'react-native'; import {StyleSheet, View} from "react-native";
import i18n from 'i18n-js'; import i18n from 'i18n-js';
import AnimatedAccordion from '../../Animations/AnimatedAccordion'; import AnimatedAccordion from "../../Animations/AnimatedAccordion";
import {isItemInCategoryFilter} from '../../../utils/Search'; import {isItemInCategoryFilter} from "../../../utils/Search";
import type {ClubCategoryType} from '../../../screens/Amicale/Clubs/ClubListScreen'; import type {category} from "../../../screens/Amicale/Clubs/ClubListScreen";
type PropsType = { type Props = {
categories: Array<ClubCategoryType>, categories: Array<category>,
onChipSelect: (id: number) => void, onChipSelect: (id: number) => void,
selectedCategories: Array<number>, selectedCategories: Array<number>,
};
const styles = StyleSheet.create({
card: {
margin: 5,
},
text: {
paddingLeft: 0,
marginTop: 5,
marginBottom: 10,
marginLeft: 'auto',
marginRight: 'auto',
},
chipContainer: {
justifyContent: 'space-around',
flexDirection: 'row',
flexWrap: 'wrap',
paddingLeft: 0,
marginBottom: 5,
},
});
class ClubListHeader extends React.Component<PropsType> {
shouldComponentUpdate(nextProps: PropsType): boolean {
const {props} = this;
return (
nextProps.selectedCategories.length !== props.selectedCategories.length
);
}
getChipRender = (category: ClubCategoryType, key: string): React.Node => {
const {props} = this;
const onPress = (): void => props.onChipSelect(category.id);
return (
<Chip
selected={isItemInCategoryFilter(props.selectedCategories, [
category.id,
null,
])}
mode="outlined"
onPress={onPress}
style={{marginRight: 5, marginLeft: 5, marginBottom: 5}}
key={key}>
{category.name}
</Chip>
);
};
getCategoriesRender(): React.Node {
const {props} = this;
const final = [];
props.categories.forEach((cat: ClubCategoryType) => {
final.push(this.getChipRender(cat, cat.id.toString()));
});
return final;
}
render(): React.Node {
return (
<Card style={styles.card}>
<AnimatedAccordion
title={i18n.t('screens.clubs.categories')}
left={({size}: {size: number}): React.Node => (
<List.Icon size={size} icon="star" />
)}
opened>
<Text style={styles.text}>
{i18n.t('screens.clubs.categoriesFilterMessage')}
</Text>
<View style={styles.chipContainer}>{this.getCategoriesRender()}</View>
</AnimatedAccordion>
</Card>
);
}
} }
class ClubListHeader extends React.Component<Props> {
shouldComponentUpdate(nextProps: Props) {
return nextProps.selectedCategories.length !== this.props.selectedCategories.length;
}
getChipRender = (category: category, key: string) => {
const onPress = () => this.props.onChipSelect(category.id);
return <Chip
selected={isItemInCategoryFilter(this.props.selectedCategories, [category.id])}
mode={'outlined'}
onPress={onPress}
style={{marginRight: 5, marginLeft: 5, marginBottom: 5}}
key={key}
>
{category.name}
</Chip>;
};
getCategoriesRender() {
let final = [];
for (let i = 0; i < this.props.categories.length; i++) {
final.push(this.getChipRender(this.props.categories[i], this.props.categories[i].id.toString()));
}
return final;
}
render() {
return (
<Card style={styles.card}>
<AnimatedAccordion
title={i18n.t("screens.clubs.categories")}
left={props => <List.Icon {...props} icon="star"/>}
opened={true}
>
<Text style={styles.text}>{i18n.t("screens.clubs.categoriesFilterMessage")}</Text>
<View style={styles.chipContainer}>
{this.getCategoriesRender()}
</View>
</AnimatedAccordion>
</Card>
);
}
}
const styles = StyleSheet.create({
card: {
margin: 5
},
text: {
paddingLeft: 0,
marginTop: 5,
marginBottom: 10,
marginLeft: 'auto',
marginRight: 'auto',
},
chipContainer: {
justifyContent: 'space-around',
flexDirection: 'row',
flexWrap: 'wrap',
paddingLeft: 0,
marginBottom: 5,
},
});
export default ClubListHeader; export default ClubListHeader;

View file

@ -2,93 +2,84 @@
import * as React from 'react'; import * as React from 'react';
import {Avatar, Chip, List, withTheme} from 'react-native-paper'; import {Avatar, Chip, List, withTheme} from 'react-native-paper';
import {View} from 'react-native'; import {View} from "react-native";
import type { import type {category, club} from "../../../screens/Amicale/Clubs/ClubListScreen";
ClubCategoryType, import type {CustomTheme} from "../../../managers/ThemeManager";
ClubType,
} from '../../../screens/Amicale/Clubs/ClubListScreen';
import type {CustomTheme} from '../../../managers/ThemeManager';
type PropsType = { type Props = {
onPress: () => void, onPress: () => void,
categoryTranslator: (id: number) => ClubCategoryType, categoryTranslator: (id: number) => category,
item: ClubType, item: club,
height: number, height: number,
theme: CustomTheme, theme: CustomTheme,
}; }
class ClubListItem extends React.Component<PropsType> { class ClubListItem extends React.Component<Props> {
hasManagers: boolean;
constructor(props: PropsType) { hasManagers: boolean;
super(props);
this.hasManagers = props.item.responsibles.length > 0;
}
shouldComponentUpdate(): boolean { constructor(props) {
return false; super(props);
} this.hasManagers = props.item.responsibles.length > 0;
}
getCategoriesRender(categories: Array<number | null>): React.Node { shouldComponentUpdate() {
const {props} = this; return false;
const final = []; }
categories.forEach((cat: number | null) => {
if (cat != null) {
const category: ClubCategoryType = props.categoryTranslator(cat);
final.push(
<Chip
style={{marginRight: 5, marginBottom: 5}}
key={`${props.item.id}:${category.id}`}>
{category.name}
</Chip>,
);
}
});
return <View style={{flexDirection: 'row'}}>{final}</View>;
}
render(): React.Node { getCategoriesRender(categories: Array<number | null>) {
const {props} = this; let final = [];
const categoriesRender = (): React.Node => for (let i = 0; i < categories.length; i++) {
this.getCategoriesRender(props.item.category); if (categories[i] !== null) {
const {colors} = props.theme; const category: category = this.props.categoryTranslator(categories[i]);
return ( final.push(
<List.Item <Chip
title={props.item.name} style={{marginRight: 5, marginBottom: 5}}
description={categoriesRender} key={this.props.item.id + ':' + category.id}
onPress={props.onPress} >
left={(): React.Node => ( {category.name}
<Avatar.Image </Chip>
style={{ );
backgroundColor: 'transparent',
marginLeft: 10,
marginRight: 10,
}}
size={64}
source={{uri: props.item.logo}}
/>
)}
right={(): React.Node => (
<Avatar.Icon
style={{
marginTop: 'auto',
marginBottom: 'auto',
backgroundColor: 'transparent',
}}
size={48}
icon={
this.hasManagers ? 'check-circle-outline' : 'alert-circle-outline'
} }
color={this.hasManagers ? colors.success : colors.primary} }
/> return <View style={{flexDirection: 'row'}}>{final}</View>;
)} }
style={{
height: props.height, render() {
justifyContent: 'center', const categoriesRender = this.getCategoriesRender.bind(this, this.props.item.category);
}} const colors = this.props.theme.colors;
/> return (
); <List.Item
} title={this.props.item.name}
description={categoriesRender}
onPress={this.props.onPress}
left={(props) => <Avatar.Image
{...props}
style={{
backgroundColor: 'transparent',
marginLeft: 10,
marginRight: 10,
}}
size={64}
source={{uri: this.props.item.logo}}/>}
right={(props) => <Avatar.Icon
{...props}
style={{
marginTop: 'auto',
marginBottom: 'auto',
backgroundColor: 'transparent',
}}
size={48}
icon={this.hasManagers ? "check-circle-outline" : "alert-circle-outline"}
color={this.hasManagers ? colors.success : colors.primary}
/>}
style={{
height: this.props.height,
justifyContent: 'center',
}}
/>
);
}
} }
export default withTheme(ClubListItem); export default withTheme(ClubListItem);

View file

@ -1,12 +1,12 @@
// @flow // @flow
import type {ServiceItemType} from './ServicesManager'; import type {ServiceItem} from './ServicesManager';
import ServicesManager from './ServicesManager'; import ServicesManager from './ServicesManager';
import {getSublistWithIds} from '../utils/Utils'; import {getSublistWithIds} from '../utils/Utils';
import AsyncStorageManager from './AsyncStorageManager'; import AsyncStorageManager from './AsyncStorageManager';
export default class DashboardManager extends ServicesManager { export default class DashboardManager extends ServicesManager {
getCurrentDashboard(): Array<ServiceItemType | null> { getCurrentDashboard(): Array<ServiceItem | null> {
const dashboardIdList = AsyncStorageManager.getObject( const dashboardIdList = AsyncStorageManager.getObject(
AsyncStorageManager.PREFERENCES.dashboardItems.key, AsyncStorageManager.PREFERENCES.dashboardItems.key,
); );

View file

@ -1,384 +1,378 @@
// @flow // @flow
import i18n from 'i18n-js'; import i18n from "i18n-js";
import {StackNavigationProp} from '@react-navigation/stack'; import AvailableWebsites from "../constants/AvailableWebsites";
import AvailableWebsites from '../constants/AvailableWebsites'; import {StackNavigationProp} from "@react-navigation/stack";
import ConnectionManager from './ConnectionManager'; import ConnectionManager from "./ConnectionManager";
import type {FullDashboardType} from '../screens/Home/HomeScreen'; import type {fullDashboard} from "../screens/Home/HomeScreen";
import getStrippedServicesList from '../utils/Services';
// AMICALE // AMICALE
const CLUBS_IMAGE = const CLUBS_IMAGE = "https://etud.insa-toulouse.fr/~amicale_app/images/Clubs.png";
'https://etud.insa-toulouse.fr/~amicale_app/images/Clubs.png'; const PROFILE_IMAGE = "https://etud.insa-toulouse.fr/~amicale_app/images/ProfilAmicaliste.png";
const PROFILE_IMAGE = const EQUIPMENT_IMAGE = "https://etud.insa-toulouse.fr/~amicale_app/images/Materiel.png";
'https://etud.insa-toulouse.fr/~amicale_app/images/ProfilAmicaliste.png'; const VOTE_IMAGE = "https://etud.insa-toulouse.fr/~amicale_app/images/Vote.png";
const EQUIPMENT_IMAGE = const AMICALE_IMAGE = "https://etud.insa-toulouse.fr/~amicale_app/images/WebsiteAmicale.png";
'https://etud.insa-toulouse.fr/~amicale_app/images/Materiel.png';
const VOTE_IMAGE = 'https://etud.insa-toulouse.fr/~amicale_app/images/Vote.png';
const AMICALE_IMAGE =
'https://etud.insa-toulouse.fr/~amicale_app/images/WebsiteAmicale.png';
// STUDENTS // STUDENTS
const PROXIMO_IMAGE = const PROXIMO_IMAGE = "https://etud.insa-toulouse.fr/~amicale_app/images/Proximo.png"
'https://etud.insa-toulouse.fr/~amicale_app/images/Proximo.png'; const WIKETUD_IMAGE = "https://etud.insa-toulouse.fr/~amicale_app/images/Wiketud.png";
const WIKETUD_IMAGE = const EE_IMAGE = "https://etud.insa-toulouse.fr/~amicale_app/images/EEC.png";
'https://etud.insa-toulouse.fr/~amicale_app/images/Wiketud.png'; const TUTORINSA_IMAGE = "https://etud.insa-toulouse.fr/~amicale_app/images/TutorINSA.png";
const EE_IMAGE = 'https://etud.insa-toulouse.fr/~amicale_app/images/EEC.png';
const TUTORINSA_IMAGE =
'https://etud.insa-toulouse.fr/~amicale_app/images/TutorINSA.png';
// INSA // INSA
const BIB_IMAGE = 'https://etud.insa-toulouse.fr/~amicale_app/images/Bib.png'; const BIB_IMAGE = "https://etud.insa-toulouse.fr/~amicale_app/images/Bib.png";
const RU_IMAGE = 'https://etud.insa-toulouse.fr/~amicale_app/images/RU.png'; const RU_IMAGE = "https://etud.insa-toulouse.fr/~amicale_app/images/RU.png";
const ROOM_IMAGE = const ROOM_IMAGE = "https://etud.insa-toulouse.fr/~amicale_app/images/Salles.png";
'https://etud.insa-toulouse.fr/~amicale_app/images/Salles.png'; const EMAIL_IMAGE = "https://etud.insa-toulouse.fr/~amicale_app/images/Bluemind.png";
const EMAIL_IMAGE = const ENT_IMAGE = "https://etud.insa-toulouse.fr/~amicale_app/images/ENT.png";
'https://etud.insa-toulouse.fr/~amicale_app/images/Bluemind.png'; const ACCOUNT_IMAGE = "https://etud.insa-toulouse.fr/~amicale_app/images/Account.png";
const ENT_IMAGE = 'https://etud.insa-toulouse.fr/~amicale_app/images/ENT.png';
const ACCOUNT_IMAGE =
'https://etud.insa-toulouse.fr/~amicale_app/images/Account.png';
// SPECIAL // SPECIAL
const WASHER_IMAGE = const WASHER_IMAGE = "https://etud.insa-toulouse.fr/~amicale_app/images/ProxiwashLaveLinge.png";
'https://etud.insa-toulouse.fr/~amicale_app/images/ProxiwashLaveLinge.png'; const DRYER_IMAGE = "https://etud.insa-toulouse.fr/~amicale_app/images/ProxiwashSecheLinge.png";
const DRYER_IMAGE =
'https://etud.insa-toulouse.fr/~amicale_app/images/ProxiwashSecheLinge.png';
const AMICALE_LOGO = require('../../assets/amicale.png'); const AMICALE_LOGO = require("../../assets/amicale.png");
export const SERVICES_KEY = { export const SERVICES_KEY = {
CLUBS: 'clubs', CLUBS: "clubs",
PROFILE: 'profile', PROFILE: "profile",
EQUIPMENT: 'equipment', EQUIPMENT: "equipment",
AMICALE_WEBSITE: 'amicale_website', AMICALE_WEBSITE: "amicale_website",
VOTE: 'vote', VOTE: "vote",
PROXIMO: 'proximo', PROXIMO: "proximo",
WIKETUD: 'wiketud', WIKETUD: "wiketud",
ELUS_ETUDIANTS: 'elus_etudiants', ELUS_ETUDIANTS: "elus_etudiants",
TUTOR_INSA: 'tutor_insa', TUTOR_INSA: "tutor_insa",
RU: 'ru', RU: "ru",
AVAILABLE_ROOMS: 'available_rooms', AVAILABLE_ROOMS: "available_rooms",
BIB: 'bib', BIB: "bib",
EMAIL: 'email', EMAIL: "email",
ENT: 'ent', ENT: "ent",
INSA_ACCOUNT: 'insa_account', INSA_ACCOUNT: "insa_account",
WASHERS: 'washers', WASHERS: "washers",
DRYERS: 'dryers', DRYERS: "dryers",
}; }
export const SERVICES_CATEGORIES_KEY = { export const SERVICES_CATEGORIES_KEY = {
AMICALE: 'amicale', AMICALE: "amicale",
STUDENTS: 'students', STUDENTS: "students",
INSA: 'insa', INSA: "insa",
SPECIAL: 'special', SPECIAL: "special",
}; }
export type ServiceItemType = {
key: string,
title: string,
subtitle: string,
image: string,
onPress: () => void,
badgeFunction?: (dashboard: FullDashboardType) => number,
};
export type ServiceCategoryType = { export type ServiceItem = {
key: string, key: string,
title: string, title: string,
subtitle: string, subtitle: string,
image: string | number, image: string,
content: Array<ServiceItemType>, onPress: () => void,
}; badgeFunction?: (dashboard: fullDashboard) => number,
}
export type ServiceCategory = {
key: string,
title: string,
subtitle: string,
image: string | number,
content: Array<ServiceItem>
}
export default class ServicesManager { export default class ServicesManager {
navigation: StackNavigationProp;
amicaleDataset: Array<ServiceItemType>; navigation: StackNavigationProp;
studentsDataset: Array<ServiceItemType>; amicaleDataset: Array<ServiceItem>;
studentsDataset: Array<ServiceItem>;
insaDataset: Array<ServiceItem>;
specialDataset: Array<ServiceItem>;
insaDataset: Array<ServiceItemType>; categoriesDataset: Array<ServiceCategory>;
specialDataset: Array<ServiceItemType>; constructor(nav: StackNavigationProp) {
this.navigation = nav;
this.amicaleDataset = [
{
key: SERVICES_KEY.CLUBS,
title: i18n.t('screens.clubs.title'),
subtitle: i18n.t('screens.services.descriptions.clubs'),
image: CLUBS_IMAGE,
onPress: () => this.onAmicaleServicePress("club-list"),
},
{
key: SERVICES_KEY.PROFILE,
title: i18n.t('screens.profile.title'),
subtitle: i18n.t('screens.services.descriptions.profile'),
image: PROFILE_IMAGE,
onPress: () => this.onAmicaleServicePress("profile"),
},
{
key: SERVICES_KEY.EQUIPMENT,
title: i18n.t('screens.equipment.title'),
subtitle: i18n.t('screens.services.descriptions.equipment'),
image: EQUIPMENT_IMAGE,
onPress: () => this.onAmicaleServicePress("equipment-list"),
},
{
key: SERVICES_KEY.AMICALE_WEBSITE,
title: i18n.t('screens.websites.amicale'),
subtitle: i18n.t('screens.services.descriptions.amicaleWebsite'),
image: AMICALE_IMAGE,
onPress: () => nav.navigate("website", {
host: AvailableWebsites.websites.AMICALE,
title: i18n.t('screens.websites.amicale')
}),
},
{
key: SERVICES_KEY.VOTE,
title: i18n.t('screens.vote.title'),
subtitle: i18n.t('screens.services.descriptions.vote'),
image: VOTE_IMAGE,
onPress: () => this.onAmicaleServicePress("vote"),
},
];
this.studentsDataset = [
{
key: SERVICES_KEY.PROXIMO,
title: i18n.t('screens.proximo.title'),
subtitle: i18n.t('screens.services.descriptions.proximo'),
image: PROXIMO_IMAGE,
onPress: () => nav.navigate("proximo"),
badgeFunction: (dashboard: fullDashboard) => dashboard.proximo_articles
},
{
key: SERVICES_KEY.WIKETUD,
title: "Wiketud",
subtitle: i18n.t('screens.services.descriptions.wiketud'),
image: WIKETUD_IMAGE,
onPress: () => nav.navigate("website", {host: AvailableWebsites.websites.WIKETUD, title: "Wiketud"}),
},
{
key: SERVICES_KEY.ELUS_ETUDIANTS,
title: "Élus Étudiants",
subtitle: i18n.t('screens.services.descriptions.elusEtudiants'),
image: EE_IMAGE,
onPress: () => nav.navigate("website", {
host: AvailableWebsites.websites.ELUS_ETUDIANTS,
title: "Élus Étudiants"
}),
},
{
key: SERVICES_KEY.TUTOR_INSA,
title: "Tutor'INSA",
subtitle: i18n.t('screens.services.descriptions.tutorInsa'),
image: TUTORINSA_IMAGE,
onPress: () => nav.navigate("website", {
host: AvailableWebsites.websites.TUTOR_INSA,
title: "Tutor'INSA"
}),
badgeFunction: (dashboard: fullDashboard) => dashboard.available_tutorials
},
];
this.insaDataset = [
{
key: SERVICES_KEY.RU,
title: i18n.t('screens.menu.title'),
subtitle: i18n.t('screens.services.descriptions.self'),
image: RU_IMAGE,
onPress: () => nav.navigate("self-menu"),
badgeFunction: (dashboard: fullDashboard) => dashboard.today_menu.length
},
{
key: SERVICES_KEY.AVAILABLE_ROOMS,
title: i18n.t('screens.websites.rooms'),
subtitle: i18n.t('screens.services.descriptions.availableRooms'),
image: ROOM_IMAGE,
onPress: () => nav.navigate("website", {
host: AvailableWebsites.websites.AVAILABLE_ROOMS,
title: i18n.t('screens.websites.rooms')
}),
},
{
key: SERVICES_KEY.BIB,
title: i18n.t('screens.websites.bib'),
subtitle: i18n.t('screens.services.descriptions.bib'),
image: BIB_IMAGE,
onPress: () => nav.navigate("website", {
host: AvailableWebsites.websites.BIB,
title: i18n.t('screens.websites.bib')
}),
},
{
key: SERVICES_KEY.EMAIL,
title: i18n.t('screens.websites.mails'),
subtitle: i18n.t('screens.services.descriptions.mails'),
image: EMAIL_IMAGE,
onPress: () => nav.navigate("website", {
host: AvailableWebsites.websites.BLUEMIND,
title: i18n.t('screens.websites.mails')
}),
},
{
key: SERVICES_KEY.ENT,
title: i18n.t('screens.websites.ent'),
subtitle: i18n.t('screens.services.descriptions.ent'),
image: ENT_IMAGE,
onPress: () => nav.navigate("website", {
host: AvailableWebsites.websites.ENT,
title: i18n.t('screens.websites.ent')
}),
},
{
key: SERVICES_KEY.INSA_ACCOUNT,
title: i18n.t('screens.insaAccount.title'),
subtitle: i18n.t('screens.services.descriptions.insaAccount'),
image: ACCOUNT_IMAGE,
onPress: () => nav.navigate("website", {
host: AvailableWebsites.websites.INSA_ACCOUNT,
title: i18n.t('screens.insaAccount.title')
}),
},
];
this.specialDataset = [
{
key: SERVICES_KEY.WASHERS,
title: i18n.t('screens.proxiwash.washers'),
subtitle: i18n.t('screens.services.descriptions.washers'),
image: WASHER_IMAGE,
onPress: () => nav.navigate("proxiwash"),
badgeFunction: (dashboard: fullDashboard) => dashboard.available_washers
},
{
key: SERVICES_KEY.DRYERS,
title: i18n.t('screens.proxiwash.dryers'),
subtitle: i18n.t('screens.services.descriptions.washers'),
image: DRYER_IMAGE,
onPress: () => nav.navigate("proxiwash"),
badgeFunction: (dashboard: fullDashboard) => dashboard.available_dryers
}
];
this.categoriesDataset = [
{
key: SERVICES_CATEGORIES_KEY.AMICALE,
title: i18n.t("screens.services.categories.amicale"),
subtitle: i18n.t("screens.services.more"),
image: AMICALE_LOGO,
content: this.amicaleDataset
},
{
key: SERVICES_CATEGORIES_KEY.STUDENTS,
title: i18n.t("screens.services.categories.students"),
subtitle: i18n.t("screens.services.more"),
image: 'account-group',
content: this.studentsDataset
},
{
key: SERVICES_CATEGORIES_KEY.INSA,
title: i18n.t("screens.services.categories.insa"),
subtitle: i18n.t("screens.services.more"),
image: 'school',
content: this.insaDataset
},
{
key: SERVICES_CATEGORIES_KEY.SPECIAL,
title: i18n.t("screens.services.categories.special"),
subtitle: i18n.t("screens.services.categories.special"),
image: 'star',
content: this.specialDataset
},
];
}
categoriesDataset: Array<ServiceCategoryType>; /**
* Redirects the user to the login screen if he is not logged in
*
* @param route
* @returns {null}
*/
onAmicaleServicePress(route: string) {
if (ConnectionManager.getInstance().isLoggedIn())
this.navigation.navigate(route);
else
this.navigation.navigate("login", {nextScreen: route});
}
constructor(nav: StackNavigationProp) { /**
this.navigation = nav; * Gets the given services list without items of the given ids
this.amicaleDataset = [ *
{ * @param idList The ids of items to remove
key: SERVICES_KEY.CLUBS, * @param sourceList The item list to use as source
title: i18n.t('screens.clubs.title'), * @returns {[]}
subtitle: i18n.t('screens.services.descriptions.clubs'), */
image: CLUBS_IMAGE, getStrippedList(idList: Array<string>, sourceList: Array<{key: string, [key: string]: any}>) {
onPress: (): void => this.onAmicaleServicePress('club-list'), let newArray = [];
}, for (let i = 0; i < sourceList.length; i++) {
{ const item = sourceList[i];
key: SERVICES_KEY.PROFILE, if (!(idList.includes(item.key)))
title: i18n.t('screens.profile.title'), newArray.push(item);
subtitle: i18n.t('screens.services.descriptions.profile'), }
image: PROFILE_IMAGE, return newArray;
onPress: (): void => this.onAmicaleServicePress('profile'), }
},
{
key: SERVICES_KEY.EQUIPMENT,
title: i18n.t('screens.equipment.title'),
subtitle: i18n.t('screens.services.descriptions.equipment'),
image: EQUIPMENT_IMAGE,
onPress: (): void => this.onAmicaleServicePress('equipment-list'),
},
{
key: SERVICES_KEY.AMICALE_WEBSITE,
title: i18n.t('screens.websites.amicale'),
subtitle: i18n.t('screens.services.descriptions.amicaleWebsite'),
image: AMICALE_IMAGE,
onPress: (): void =>
nav.navigate('website', {
host: AvailableWebsites.websites.AMICALE,
title: i18n.t('screens.websites.amicale'),
}),
},
{
key: SERVICES_KEY.VOTE,
title: i18n.t('screens.vote.title'),
subtitle: i18n.t('screens.services.descriptions.vote'),
image: VOTE_IMAGE,
onPress: (): void => this.onAmicaleServicePress('vote'),
},
];
this.studentsDataset = [
{
key: SERVICES_KEY.PROXIMO,
title: i18n.t('screens.proximo.title'),
subtitle: i18n.t('screens.services.descriptions.proximo'),
image: PROXIMO_IMAGE,
onPress: (): void => nav.navigate('proximo'),
badgeFunction: (dashboard: FullDashboardType): number =>
dashboard.proximo_articles,
},
{
key: SERVICES_KEY.WIKETUD,
title: 'Wiketud',
subtitle: i18n.t('screens.services.descriptions.wiketud'),
image: WIKETUD_IMAGE,
onPress: (): void =>
nav.navigate('website', {
host: AvailableWebsites.websites.WIKETUD,
title: 'Wiketud',
}),
},
{
key: SERVICES_KEY.ELUS_ETUDIANTS,
title: 'Élus Étudiants',
subtitle: i18n.t('screens.services.descriptions.elusEtudiants'),
image: EE_IMAGE,
onPress: (): void =>
nav.navigate('website', {
host: AvailableWebsites.websites.ELUS_ETUDIANTS,
title: 'Élus Étudiants',
}),
},
{
key: SERVICES_KEY.TUTOR_INSA,
title: "Tutor'INSA",
subtitle: i18n.t('screens.services.descriptions.tutorInsa'),
image: TUTORINSA_IMAGE,
onPress: (): void =>
nav.navigate('website', {
host: AvailableWebsites.websites.TUTOR_INSA,
title: "Tutor'INSA",
}),
badgeFunction: (dashboard: FullDashboardType): number =>
dashboard.available_tutorials,
},
];
this.insaDataset = [
{
key: SERVICES_KEY.RU,
title: i18n.t('screens.menu.title'),
subtitle: i18n.t('screens.services.descriptions.self'),
image: RU_IMAGE,
onPress: (): void => nav.navigate('self-menu'),
badgeFunction: (dashboard: FullDashboardType): number =>
dashboard.today_menu.length,
},
{
key: SERVICES_KEY.AVAILABLE_ROOMS,
title: i18n.t('screens.websites.rooms'),
subtitle: i18n.t('screens.services.descriptions.availableRooms'),
image: ROOM_IMAGE,
onPress: (): void =>
nav.navigate('website', {
host: AvailableWebsites.websites.AVAILABLE_ROOMS,
title: i18n.t('screens.websites.rooms'),
}),
},
{
key: SERVICES_KEY.BIB,
title: i18n.t('screens.websites.bib'),
subtitle: i18n.t('screens.services.descriptions.bib'),
image: BIB_IMAGE,
onPress: (): void =>
nav.navigate('website', {
host: AvailableWebsites.websites.BIB,
title: i18n.t('screens.websites.bib'),
}),
},
{
key: SERVICES_KEY.EMAIL,
title: i18n.t('screens.websites.mails'),
subtitle: i18n.t('screens.services.descriptions.mails'),
image: EMAIL_IMAGE,
onPress: (): void =>
nav.navigate('website', {
host: AvailableWebsites.websites.BLUEMIND,
title: i18n.t('screens.websites.mails'),
}),
},
{
key: SERVICES_KEY.ENT,
title: i18n.t('screens.websites.ent'),
subtitle: i18n.t('screens.services.descriptions.ent'),
image: ENT_IMAGE,
onPress: (): void =>
nav.navigate('website', {
host: AvailableWebsites.websites.ENT,
title: i18n.t('screens.websites.ent'),
}),
},
{
key: SERVICES_KEY.INSA_ACCOUNT,
title: i18n.t('screens.insaAccount.title'),
subtitle: i18n.t('screens.services.descriptions.insaAccount'),
image: ACCOUNT_IMAGE,
onPress: (): void =>
nav.navigate('website', {
host: AvailableWebsites.websites.INSA_ACCOUNT,
title: i18n.t('screens.insaAccount.title'),
}),
},
];
this.specialDataset = [
{
key: SERVICES_KEY.WASHERS,
title: i18n.t('screens.proxiwash.washers'),
subtitle: i18n.t('screens.services.descriptions.washers'),
image: WASHER_IMAGE,
onPress: (): void => nav.navigate('proxiwash'),
badgeFunction: (dashboard: FullDashboardType): number =>
dashboard.available_washers,
},
{
key: SERVICES_KEY.DRYERS,
title: i18n.t('screens.proxiwash.dryers'),
subtitle: i18n.t('screens.services.descriptions.washers'),
image: DRYER_IMAGE,
onPress: (): void => nav.navigate('proxiwash'),
badgeFunction: (dashboard: FullDashboardType): number =>
dashboard.available_dryers,
},
];
this.categoriesDataset = [
{
key: SERVICES_CATEGORIES_KEY.AMICALE,
title: i18n.t('screens.services.categories.amicale'),
subtitle: i18n.t('screens.services.more'),
image: AMICALE_LOGO,
content: this.amicaleDataset,
},
{
key: SERVICES_CATEGORIES_KEY.STUDENTS,
title: i18n.t('screens.services.categories.students'),
subtitle: i18n.t('screens.services.more'),
image: 'account-group',
content: this.studentsDataset,
},
{
key: SERVICES_CATEGORIES_KEY.INSA,
title: i18n.t('screens.services.categories.insa'),
subtitle: i18n.t('screens.services.more'),
image: 'school',
content: this.insaDataset,
},
{
key: SERVICES_CATEGORIES_KEY.SPECIAL,
title: i18n.t('screens.services.categories.special'),
subtitle: i18n.t('screens.services.categories.special'),
image: 'star',
content: this.specialDataset,
},
];
}
/** /**
* Redirects the user to the login screen if he is not logged in * Gets the list of amicale's services
* *
* @param route * @param excludedItems Ids of items to exclude from the returned list
* @returns {null} * @returns {Array<ServiceItem>}
*/ */
onAmicaleServicePress(route: string) { getAmicaleServices(excludedItems?: Array<string>) {
if (ConnectionManager.getInstance().isLoggedIn()) if (excludedItems != null)
this.navigation.navigate(route); return this.getStrippedList(excludedItems, this.amicaleDataset)
else this.navigation.navigate('login', {nextScreen: route}); else
} return this.amicaleDataset;
}
/** /**
* Gets the list of amicale's services * Gets the list of students' services
* *
* @param excludedItems Ids of items to exclude from the returned list * @param excludedItems Ids of items to exclude from the returned list
* @returns {Array<ServiceItemType>} * @returns {Array<ServiceItem>}
*/ */
getAmicaleServices(excludedItems?: Array<string>): Array<ServiceItemType> { getStudentServices(excludedItems?: Array<string>) {
if (excludedItems != null) if (excludedItems != null)
return getStrippedServicesList(excludedItems, this.amicaleDataset); return this.getStrippedList(excludedItems, this.studentsDataset)
return this.amicaleDataset; else
} return this.studentsDataset;
}
/** /**
* Gets the list of students' services * Gets the list of INSA's services
* *
* @param excludedItems Ids of items to exclude from the returned list * @param excludedItems Ids of items to exclude from the returned list
* @returns {Array<ServiceItemType>} * @returns {Array<ServiceItem>}
*/ */
getStudentServices(excludedItems?: Array<string>): Array<ServiceItemType> { getINSAServices(excludedItems?: Array<string>) {
if (excludedItems != null) if (excludedItems != null)
return getStrippedServicesList(excludedItems, this.studentsDataset); return this.getStrippedList(excludedItems, this.insaDataset)
return this.studentsDataset; else
} return this.insaDataset;
}
/** /**
* Gets the list of INSA's services * Gets the list of special services
* *
* @param excludedItems Ids of items to exclude from the returned list * @param excludedItems Ids of items to exclude from the returned list
* @returns {Array<ServiceItemType>} * @returns {Array<ServiceItem>}
*/ */
getINSAServices(excludedItems?: Array<string>): Array<ServiceItemType> { getSpecialServices(excludedItems?: Array<string>) {
if (excludedItems != null) if (excludedItems != null)
return getStrippedServicesList(excludedItems, this.insaDataset); return this.getStrippedList(excludedItems, this.specialDataset)
return this.insaDataset; else
} return this.specialDataset;
}
/** /**
* Gets the list of special services * Gets all services sorted by category
* *
* @param excludedItems Ids of items to exclude from the returned list * @param excludedItems Ids of categories to exclude from the returned list
* @returns {Array<ServiceItemType>} * @returns {Array<ServiceCategory>}
*/ */
getSpecialServices(excludedItems?: Array<string>): Array<ServiceItemType> { getCategories(excludedItems?: Array<string>) {
if (excludedItems != null) if (excludedItems != null)
return getStrippedServicesList(excludedItems, this.specialDataset); return this.getStrippedList(excludedItems, this.categoriesDataset)
return this.specialDataset; else
} return this.categoriesDataset;
}
/**
* Gets all services sorted by category
*
* @param excludedItems Ids of categories to exclude from the returned list
* @returns {Array<ServiceCategoryType>}
*/
getCategories(excludedItems?: Array<string>): Array<ServiceCategoryType> {
if (excludedItems != null)
return getStrippedServicesList(excludedItems, this.categoriesDataset);
return this.categoriesDataset;
}
} }

View file

@ -4,49 +4,49 @@ import * as React from 'react';
import {Image, View} from 'react-native'; import {Image, View} from 'react-native';
import {Card, List, Text, withTheme} from 'react-native-paper'; import {Card, List, Text, withTheme} from 'react-native-paper';
import i18n from 'i18n-js'; import i18n from 'i18n-js';
import Autolink from 'react-native-autolink'; import Autolink from "react-native-autolink";
import CollapsibleScrollView from '../../../components/Collapsible/CollapsibleScrollView'; import CollapsibleScrollView from "../../../components/Collapsible/CollapsibleScrollView";
import AMICALE_ICON from '../../../../assets/amicale.png';
type Props = {};
const CONTACT_LINK = 'clubs@amicale-insat.fr'; const CONTACT_LINK = 'clubs@amicale-insat.fr';
// eslint-disable-next-line react/prefer-stateless-function class ClubAboutScreen extends React.Component<Props> {
class ClubAboutScreen 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={require('../../../../assets/amicale.png')}
source={AMICALE_ICON} style={{flex: 1, resizeMode: "contain"}}
style={{flex: 1, resizeMode: 'contain'}} resizeMode="contain"/>
resizeMode="contain" </View>
/> <Text>{i18n.t("screens.clubs.about.text")}</Text>
</View> <Card style={{margin: 5}}>
<Text>{i18n.t('screens.clubs.about.text')}</Text> <Card.Title
<Card style={{margin: 5}}> title={i18n.t("screens.clubs.about.title")}
<Card.Title subtitle={i18n.t("screens.clubs.about.subtitle")}
title={i18n.t('screens.clubs.about.title')} left={props => <List.Icon {...props} icon={'information'}/>}
subtitle={i18n.t('screens.clubs.about.subtitle')} />
left={({size}: {size: number}): React.Node => ( <Card.Content>
<List.Icon size={size} icon="information" /> <Text>{i18n.t("screens.clubs.about.message")}</Text>
)} <Autolink
/> text={CONTACT_LINK}
<Card.Content> component={Text}
<Text>{i18n.t('screens.clubs.about.message')}</Text> />
<Autolink text={CONTACT_LINK} component={Text} /> </Card.Content>
</Card.Content> </Card>
</Card> </CollapsibleScrollView>
</CollapsibleScrollView> );
); }
}
} }
export default withTheme(ClubAboutScreen); export default withTheme(ClubAboutScreen);

View file

@ -2,276 +2,252 @@
import * as React from 'react'; import * as React from 'react';
import {Linking, View} from 'react-native'; import {Linking, View} from 'react-native';
import { import {Avatar, Button, Card, Chip, Paragraph, withTheme} from 'react-native-paper';
Avatar,
Button,
Card,
Chip,
Paragraph,
withTheme,
} from 'react-native-paper';
import ImageModal from 'react-native-image-modal'; import ImageModal from 'react-native-image-modal';
import i18n from 'i18n-js'; import i18n from "i18n-js";
import {StackNavigationProp} from '@react-navigation/stack'; import AuthenticatedScreen from "../../../components/Amicale/AuthenticatedScreen";
import AuthenticatedScreen from '../../../components/Amicale/AuthenticatedScreen'; import CustomHTML from "../../../components/Overrides/CustomHTML";
import CustomHTML from '../../../components/Overrides/CustomHTML'; import CustomTabBar from "../../../components/Tabbar/CustomTabBar";
import CustomTabBar from '../../../components/Tabbar/CustomTabBar'; import type {category, club} from "./ClubListScreen";
import type {ClubCategoryType, ClubType} from './ClubListScreen'; import type {CustomTheme} from "../../../managers/ThemeManager";
import type {CustomTheme} from '../../../managers/ThemeManager'; import {StackNavigationProp} from "@react-navigation/stack";
import {ERROR_TYPE} from '../../../utils/WebData'; import {ERROR_TYPE} from "../../../utils/WebData";
import CollapsibleScrollView from '../../../components/Collapsible/CollapsibleScrollView'; import CollapsibleScrollView from "../../../components/Collapsible/CollapsibleScrollView";
import type {ApiGenericDataType} from '../../../utils/WebData';
type PropsType = { type Props = {
navigation: StackNavigationProp, navigation: StackNavigationProp,
route: { route: {
params?: { params?: {
data?: ClubType, data?: club,
categories?: Array<ClubCategoryType>, categories?: Array<category>,
clubId?: number, clubId?: number,
}, ...
}, },
... theme: CustomTheme
},
theme: CustomTheme,
}; };
const AMICALE_MAIL = 'clubs@amicale-insat.fr'; type State = {
imageModalVisible: boolean,
};
const AMICALE_MAIL = "clubs@amicale-insat.fr";
/** /**
* Class defining a club event information page. * Class defining a club event information page.
* If called with data and categories navigation parameters, will use those to display the data. * If called with data and categories navigation parameters, will use those to display the data.
* If called with clubId parameter, will fetch the information on the server * If called with clubId parameter, will fetch the information on the server
*/ */
class ClubDisplayScreen extends React.Component<PropsType> { class ClubDisplayScreen extends React.Component<Props, State> {
displayData: ClubType | null;
categories: Array<ClubCategoryType> | null; displayData: club | null;
categories: Array<category> | null;
clubId: number;
clubId: number; shouldFetchData: boolean;
shouldFetchData: boolean; state = {
imageModalVisible: false,
};
constructor(props: PropsType) { constructor(props) {
super(props); super(props);
if (props.route.params != null) { if (this.props.route.params != null) {
if ( if (this.props.route.params.data != null && this.props.route.params.categories != null) {
props.route.params.data != null && this.displayData = this.props.route.params.data;
props.route.params.categories != null this.categories = this.props.route.params.categories;
) { this.clubId = this.props.route.params.data.id;
this.displayData = props.route.params.data; this.shouldFetchData = false;
this.categories = props.route.params.categories; } else if (this.props.route.params.clubId != null) {
this.clubId = props.route.params.data.id; this.displayData = null;
this.shouldFetchData = false; this.categories = null;
} else if (props.route.params.clubId != null) { this.clubId = this.props.route.params.clubId;
this.displayData = null; this.shouldFetchData = true;
this.categories = null; }
this.clubId = props.route.params.clubId; }
this.shouldFetchData = true;
}
} }
}
/** /**
* Gets the name of the category with the given ID * Gets the name of the category with the given ID
* *
* @param id The category's ID * @param id The category's ID
* @returns {string|*} * @returns {string|*}
*/ */
getCategoryName(id: number): string { getCategoryName(id: number) {
let categoryName = ''; if (this.categories !== null) {
if (this.categories !== null) { for (let i = 0; i < this.categories.length; i++) {
this.categories.forEach((item: ClubCategoryType) => { if (id === this.categories[i].id)
if (id === item.id) categoryName = item.name; return this.categories[i].name;
}); }
}
return "";
} }
return categoryName;
}
/** /**
* Gets the view for rendering categories * Gets the view for rendering categories
* *
* @param categories The categories to display (max 2) * @param categories The categories to display (max 2)
* @returns {null|*} * @returns {null|*}
*/ */
getCategoriesRender(categories: Array<number | null>): React.Node { getCategoriesRender(categories: [number, number]) {
if (this.categories == null) return null; if (this.categories === null)
return null;
const final = []; let final = [];
categories.forEach((cat: number | null) => { for (let i = 0; i < categories.length; i++) {
if (cat != null) { let cat = categories[i];
final.push( if (cat !== null) {
<Chip style={{marginRight: 5}} key={cat}> final.push(
{this.getCategoryName(cat)} <Chip
</Chip>, style={{marginRight: 5}}
key={i.toString()}>
{this.getCategoryName(cat)}
</Chip>
);
}
}
return <View style={{flexDirection: 'row', marginTop: 5}}>{final}</View>;
}
/**
* Gets the view for rendering club managers if any
*
* @param managers The list of manager names
* @param email The club contact email
* @returns {*}
*/
getManagersRender(managers: Array<string>, email: string | null) {
let managersListView = [];
for (let i = 0; i < managers.length; i++) {
managersListView.push(<Paragraph key={i.toString()}>{managers[i]}</Paragraph>)
}
const hasManagers = managers.length > 0;
return (
<Card style={{marginTop: 10, marginBottom: CustomTabBar.TAB_BAR_HEIGHT + 20}}>
<Card.Title
title={i18n.t('screens.clubs.managers')}
subtitle={hasManagers ? i18n.t('screens.clubs.managersSubtitle') : i18n.t('screens.clubs.managersUnavailable')}
left={(props) => <Avatar.Icon
{...props}
style={{backgroundColor: 'transparent'}}
color={hasManagers ? this.props.theme.colors.success : this.props.theme.colors.primary}
icon="account-tie"/>}
/>
<Card.Content>
{managersListView}
{this.getEmailButton(email, hasManagers)}
</Card.Content>
</Card>
); );
}
});
return <View style={{flexDirection: 'row', marginTop: 5}}>{final}</View>;
}
/**
* Gets the view for rendering club managers if any
*
* @param managers The list of manager names
* @param email The club contact email
* @returns {*}
*/
getManagersRender(managers: Array<string>, email: string | null): React.Node {
const {props} = this;
const managersListView = [];
managers.forEach((item: string) => {
managersListView.push(<Paragraph key={item}>{item}</Paragraph>);
});
const hasManagers = managers.length > 0;
return (
<Card
style={{marginTop: 10, marginBottom: CustomTabBar.TAB_BAR_HEIGHT + 20}}>
<Card.Title
title={i18n.t('screens.clubs.managers')}
subtitle={
hasManagers
? i18n.t('screens.clubs.managersSubtitle')
: i18n.t('screens.clubs.managersUnavailable')
}
left={({size}: {size: number}): React.Node => (
<Avatar.Icon
size={size}
style={{backgroundColor: 'transparent'}}
color={
hasManagers
? props.theme.colors.success
: props.theme.colors.primary
}
icon="account-tie"
/>
)}
/>
<Card.Content>
{managersListView}
{ClubDisplayScreen.getEmailButton(email, hasManagers)}
</Card.Content>
</Card>
);
}
/**
* Gets the email button to contact the club, or the amicale if the club does not have any managers
*
* @param email The club contact email
* @param hasManagers True if the club has managers
* @returns {*}
*/
static getEmailButton(
email: string | null,
hasManagers: boolean,
): React.Node {
const destinationEmail =
email != null && hasManagers ? email : AMICALE_MAIL;
const text =
email != null && hasManagers
? i18n.t('screens.clubs.clubContact')
: i18n.t('screens.clubs.amicaleContact');
return (
<Card.Actions>
<Button
icon="email"
mode="contained"
onPress={() => {
Linking.openURL(`mailto:${destinationEmail}`);
}}
style={{marginLeft: 'auto'}}>
{text}
</Button>
</Card.Actions>
);
}
getScreen = (response: Array<ApiGenericDataType | null>): React.Node => {
const {props} = this;
let data: ClubType | null = null;
if (response[0] != null) {
[data] = response;
this.updateHeaderTitle(data);
} }
if (data != null) {
return (
<CollapsibleScrollView style={{paddingLeft: 5, paddingRight: 5}} hasTab>
{this.getCategoriesRender(data.category)}
{data.logo !== null ? (
<View
style={{
marginLeft: 'auto',
marginRight: 'auto',
marginTop: 10,
marginBottom: 10,
}}>
<ImageModal
resizeMode="contain"
imageBackgroundColor={props.theme.colors.background}
style={{
width: 300,
height: 300,
}}
source={{
uri: data.logo,
}}
/>
</View>
) : (
<View />
)}
{data.description !== null ? ( /**
// Surround description with div to allow text styling if the description is not html * Gets the email button to contact the club, or the amicale if the club does not have any managers
<Card.Content> *
<CustomHTML html={data.description} /> * @param email The club contact email
</Card.Content> * @param hasManagers True if the club has managers
) : ( * @returns {*}
<View /> */
)} getEmailButton(email: string | null, hasManagers: boolean) {
{this.getManagersRender(data.responsibles, data.email)} const destinationEmail = email != null && hasManagers
</CollapsibleScrollView> ? email
); : AMICALE_MAIL;
const text = email != null && hasManagers
? i18n.t("screens.clubs.clubContact")
: i18n.t("screens.clubs.amicaleContact");
return (
<Card.Actions>
<Button
icon="email"
mode="contained"
onPress={() => Linking.openURL('mailto:' + destinationEmail)}
style={{marginLeft: 'auto'}}
>
{text}
</Button>
</Card.Actions>
);
} }
return null;
};
/** /**
* Updates the header title to match the given club * Updates the header title to match the given club
* *
* @param data The club data * @param data The club data
*/ */
updateHeaderTitle(data: ClubType) { updateHeaderTitle(data: club) {
const {props} = this; this.props.navigation.setOptions({title: data.name})
props.navigation.setOptions({title: data.name}); }
}
render(): React.Node { getScreen = (response: Array<{ [key: string]: any } | null>) => {
const {props} = this; let data: club | null = null;
if (this.shouldFetchData) if (response[0] != null) {
return ( data = response[0];
<AuthenticatedScreen this.updateHeaderTitle(data);
navigation={props.navigation} }
requests={[ if (data != null) {
{ return (
link: 'clubs/info', <CollapsibleScrollView
params: {id: this.clubId}, style={{paddingLeft: 5, paddingRight: 5}}
mandatory: true, hasTab={true}
}, >
]} {this.getCategoriesRender(data.category)}
renderFunction={this.getScreen} {data.logo !== null ?
errorViewOverride={[ <View style={{
{ marginLeft: 'auto',
errorCode: ERROR_TYPE.BAD_INPUT, marginRight: 'auto',
message: i18n.t('screens.clubs.invalidClub'), marginTop: 10,
icon: 'account-question', marginBottom: 10,
showRetryButton: false, }}>
}, <ImageModal
]} resizeMode="contain"
/> imageBackgroundColor={this.props.theme.colors.background}
); style={{
return this.getScreen([this.displayData]); width: 300,
} height: 300,
}}
source={{
uri: data.logo,
}}
/>
</View>
: <View/>}
{data.description !== null ?
// Surround description with div to allow text styling if the description is not html
<Card.Content>
<CustomHTML html={data.description}/>
</Card.Content>
: <View/>}
{this.getManagersRender(data.responsibles, data.email)}
</CollapsibleScrollView>
);
} else
return null;
};
render() {
if (this.shouldFetchData)
return <AuthenticatedScreen
{...this.props}
requests={[
{
link: 'clubs/info',
params: {'id': this.clubId},
mandatory: true
}
]}
renderFunction={this.getScreen}
errorViewOverride={[
{
errorCode: ERROR_TYPE.BAD_INPUT,
message: i18n.t("screens.clubs.invalidClub"),
icon: "account-question",
showRetryButton: false
}
]}
/>;
else
return this.getScreen([this.displayData]);
}
} }
export default withTheme(ClubDisplayScreen); export default withTheme(ClubDisplayScreen);

View file

@ -1,271 +1,237 @@
// @flow // @flow
import * as React from 'react'; import * as React from 'react';
import {Platform} from 'react-native'; import {Platform} from "react-native";
import {Searchbar} from 'react-native-paper'; import {Searchbar} from 'react-native-paper';
import i18n from 'i18n-js'; import AuthenticatedScreen from "../../../components/Amicale/AuthenticatedScreen";
import {StackNavigationProp} from '@react-navigation/stack'; import i18n from "i18n-js";
import AuthenticatedScreen from '../../../components/Amicale/AuthenticatedScreen'; import ClubListItem from "../../../components/Lists/Clubs/ClubListItem";
import ClubListItem from '../../../components/Lists/Clubs/ClubListItem'; import {isItemInCategoryFilter, stringMatchQuery} from "../../../utils/Search";
import {isItemInCategoryFilter, stringMatchQuery} from '../../../utils/Search'; import ClubListHeader from "../../../components/Lists/Clubs/ClubListHeader";
import ClubListHeader from '../../../components/Lists/Clubs/ClubListHeader'; import MaterialHeaderButtons, {Item} from "../../../components/Overrides/CustomHeaderButton";
import MaterialHeaderButtons, { import {StackNavigationProp} from "@react-navigation/stack";
Item, import type {CustomTheme} from "../../../managers/ThemeManager";
} from '../../../components/Overrides/CustomHeaderButton'; import CollapsibleFlatList from "../../../components/Collapsible/CollapsibleFlatList";
import CollapsibleFlatList from '../../../components/Collapsible/CollapsibleFlatList';
export type ClubCategoryType = { export type category = {
id: number, id: number,
name: string, name: string,
}; };
export type ClubType = { export type club = {
id: number, id: number,
name: string, name: string,
description: string, description: string,
logo: string, logo: string,
email: string | null, email: string | null,
category: Array<number | null>, category: [number, number],
responsibles: Array<string>, responsibles: Array<string>,
}; };
type PropsType = { type Props = {
navigation: StackNavigationProp, navigation: StackNavigationProp,
}; theme: CustomTheme,
}
type StateType = { type State = {
currentlySelectedCategories: Array<number>, currentlySelectedCategories: Array<number>,
currentSearchString: string, currentSearchString: string,
}; }
const LIST_ITEM_HEIGHT = 96; const LIST_ITEM_HEIGHT = 96;
class ClubListScreen extends React.Component<PropsType, StateType> { class ClubListScreen extends React.Component<Props, State> {
categories: Array<ClubCategoryType>;
constructor() { state = {
super(); currentlySelectedCategories: [],
this.state = { currentSearchString: '',
currentlySelectedCategories: [],
currentSearchString: '',
}; };
}
/** categories: Array<category>;
* Creates the header content
*/
componentDidMount() {
const {props} = this;
props.navigation.setOptions({
headerTitle: this.getSearchBar,
headerRight: this.getHeaderButtons,
headerBackTitleVisible: false,
headerTitleContainerStyle:
Platform.OS === 'ios'
? {marginHorizontal: 0, width: '70%'}
: {marginHorizontal: 0, right: 50, left: 50},
});
}
/** /**
* Callback used when clicking an article in the list. * Creates the header content
* It opens the modal to show detailed information about the article */
* componentDidMount() {
* @param item The article pressed this.props.navigation.setOptions({
*/ headerTitle: this.getSearchBar,
onListItemPress(item: ClubType) { headerRight: this.getHeaderButtons,
const {props} = this; headerBackTitleVisible: false,
props.navigation.navigate('club-information', { headerTitleContainerStyle: Platform.OS === 'ios' ?
data: item, {marginHorizontal: 0, width: '70%'} :
categories: this.categories, {marginHorizontal: 0, right: 50, left: 50},
}); });
} }
/** /**
* Callback used when the search changes * Gets the header search bar
* *
* @param str The new search string * @return {*}
*/ */
onSearchStringChange = (str: string) => { getSearchBar = () => {
this.updateFilteredData(str, null); return (
}; <Searchbar
placeholder={i18n.t('screens.proximo.search')}
/** onChangeText={this.onSearchStringChange}
* Gets the header search bar />
* );
* @return {*}
*/
getSearchBar = (): React.Node => {
return (
<Searchbar
placeholder={i18n.t('screens.proximo.search')}
onChangeText={this.onSearchStringChange}
/>
);
};
onChipSelect = (id: number) => {
this.updateFilteredData(null, id);
};
/**
* Gets the header button
* @return {*}
*/
getHeaderButtons = (): React.Node => {
const onPress = () => {
const {props} = this;
props.navigation.navigate('club-about');
}; };
return (
<MaterialHeaderButtons>
<Item title="main" iconName="information" onPress={onPress} />
</MaterialHeaderButtons>
);
};
getScreen = ( /**
data: Array<{ * Gets the header button
categories: Array<ClubCategoryType>, * @return {*}
clubs: Array<ClubType>, */
} | null>, getHeaderButtons = () => {
): React.Node => { const onPress = () => this.props.navigation.navigate("club-about");
let categoryList = []; return <MaterialHeaderButtons>
let clubList = []; <Item title="main" iconName="information" onPress={onPress}/>
if (data[0] != null) { </MaterialHeaderButtons>;
categoryList = data[0].categories;
clubList = data[0].clubs;
}
this.categories = categoryList;
return (
<CollapsibleFlatList
data={clubList}
keyExtractor={this.keyExtractor}
renderItem={this.getRenderItem}
ListHeaderComponent={this.getListHeader()}
// Performance props, see https://reactnative.dev/docs/optimizing-flatlist-configuration
removeClippedSubviews
getItemLayout={this.itemLayout}
/>
);
};
/**
* Gets the list header, with controls to change the categories filter
*
* @returns {*}
*/
getListHeader(): React.Node {
const {state} = this;
return (
<ClubListHeader
categories={this.categories}
selectedCategories={state.currentlySelectedCategories}
onChipSelect={this.onChipSelect}
/>
);
}
/**
* Gets the category object of the given ID
*
* @param id The ID of the category to find
* @returns {*}
*/
getCategoryOfId = (id: number): ClubCategoryType | null => {
let cat = null;
this.categories.forEach((item: ClubCategoryType) => {
if (id === item.id) cat = item;
});
return cat;
};
getRenderItem = ({item}: {item: ClubType}): React.Node => {
const onPress = () => {
this.onListItemPress(item);
}; };
if (this.shouldRenderItem(item)) {
return ( /**
<ClubListItem * Callback used when the search changes
categoryTranslator={this.getCategoryOfId} *
item={item} * @param str The new search string
onPress={onPress} */
height={LIST_ITEM_HEIGHT} onSearchStringChange = (str: string) => {
/> this.updateFilteredData(str, null);
); };
keyExtractor = (item: club) => item.id.toString();
itemLayout = (data, index) => ({length: LIST_ITEM_HEIGHT, offset: LIST_ITEM_HEIGHT * index, index});
getScreen = (data: Array<{ categories: Array<category>, clubs: Array<club> } | null>) => {
let categoryList = [];
let clubList = [];
if (data[0] != null) {
categoryList = data[0].categories;
clubList = data[0].clubs;
}
this.categories = categoryList;
return (
<CollapsibleFlatList
data={clubList}
keyExtractor={this.keyExtractor}
renderItem={this.getRenderItem}
ListHeaderComponent={this.getListHeader()}
// Performance props, see https://reactnative.dev/docs/optimizing-flatlist-configuration
removeClippedSubviews={true}
getItemLayout={this.itemLayout}
/>
)
};
onChipSelect = (id: number) => this.updateFilteredData(null, id);
/**
* Updates the search string and category filter, saving them to the State.
*
* If the given category is already in the filter, it removes it.
* Otherwise it adds it to the filter.
*
* @param filterStr The new filter string to use
* @param categoryId The category to add/remove from the filter
*/
updateFilteredData(filterStr: string | null, categoryId: number | null) {
let newCategoriesState = [...this.state.currentlySelectedCategories];
let newStrState = this.state.currentSearchString;
if (filterStr !== null)
newStrState = filterStr;
if (categoryId !== null) {
let index = newCategoriesState.indexOf(categoryId);
if (index === -1)
newCategoriesState.push(categoryId);
else
newCategoriesState.splice(index, 1);
}
if (filterStr !== null || categoryId !== null)
this.setState({
currentSearchString: newStrState,
currentlySelectedCategories: newCategoriesState,
})
} }
return null;
};
keyExtractor = (item: ClubType): string => item.id.toString(); /**
* Gets the list header, with controls to change the categories filter
itemLayout = ( *
data: {...}, * @returns {*}
index: number, */
): {length: number, offset: number, index: number} => ({ getListHeader() {
length: LIST_ITEM_HEIGHT, return <ClubListHeader
offset: LIST_ITEM_HEIGHT * index, categories={this.categories}
index, selectedCategories={this.state.currentlySelectedCategories}
}); onChipSelect={this.onChipSelect}
/>;
/**
* Updates the search string and category filter, saving them to the State.
*
* If the given category is already in the filter, it removes it.
* Otherwise it adds it to the filter.
*
* @param filterStr The new filter string to use
* @param categoryId The category to add/remove from the filter
*/
updateFilteredData(filterStr: string | null, categoryId: number | null) {
const {state} = this;
const newCategoriesState = [...state.currentlySelectedCategories];
let newStrState = state.currentSearchString;
if (filterStr !== null) newStrState = filterStr;
if (categoryId !== null) {
const index = newCategoriesState.indexOf(categoryId);
if (index === -1) newCategoriesState.push(categoryId);
else newCategoriesState.splice(index, 1);
} }
if (filterStr !== null || categoryId !== null)
this.setState({
currentSearchString: newStrState,
currentlySelectedCategories: newCategoriesState,
});
}
/** /**
* Checks if the given item should be rendered according to current name and category filters * Gets the category object of the given ID
* *
* @param item The club to check * @param id The ID of the category to find
* @returns {boolean} * @returns {*}
*/ */
shouldRenderItem(item: ClubType): boolean { getCategoryOfId = (id: number) => {
const {state} = this; for (let i = 0; i < this.categories.length; i++) {
let shouldRender = if (id === this.categories[i].id)
state.currentlySelectedCategories.length === 0 || return this.categories[i];
isItemInCategoryFilter(state.currentlySelectedCategories, item.category); }
if (shouldRender) };
shouldRender = stringMatchQuery(item.name, state.currentSearchString);
return shouldRender;
}
render(): React.Node { /**
const {props} = this; * Checks if the given item should be rendered according to current name and category filters
return ( *
<AuthenticatedScreen * @param item The club to check
navigation={props.navigation} * @returns {boolean}
requests={[ */
{ shouldRenderItem(item: club) {
link: 'clubs/list', let shouldRender = this.state.currentlySelectedCategories.length === 0
params: {}, || isItemInCategoryFilter(this.state.currentlySelectedCategories, item.category);
mandatory: true, if (shouldRender)
}, shouldRender = stringMatchQuery(item.name, this.state.currentSearchString);
]} return shouldRender;
renderFunction={this.getScreen} }
/>
); getRenderItem = ({item}: { item: club }) => {
} const onPress = this.onListItemPress.bind(this, item);
if (this.shouldRenderItem(item)) {
return (
<ClubListItem
categoryTranslator={this.getCategoryOfId}
item={item}
onPress={onPress}
height={LIST_ITEM_HEIGHT}
/>
);
} else
return null;
};
/**
* 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: club) {
this.props.navigation.navigate("club-information", {data: item, categories: this.categories});
}
render() {
return (
<AuthenticatedScreen
{...this.props}
requests={[
{
link: 'clubs/list',
params: {},
mandatory: true,
}
]}
renderFunction={this.getScreen}
/>
);
}
} }
export default ClubListScreen; export default ClubListScreen;

View file

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

File diff suppressed because it is too large Load diff

View file

@ -1,237 +1,238 @@
// @flow // @flow
import * as React from 'react'; 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 {Button, Text, withTheme} from 'react-native-paper';
import {RNCamera} from 'react-native-camera'; import {RNCamera} from 'react-native-camera';
import {BarcodeMask} from '@nartc/react-native-barcode-mask'; 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 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 {PERMISSIONS, request, RESULTS} from 'react-native-permissions';
import URLHandler from '../../utils/URLHandler'; import {MASCOT_STYLE} from "../../components/Mascot/Mascot";
import AlertDialog from '../../components/Dialogs/AlertDialog'; import MascotPopup from "../../components/Mascot/MascotPopup";
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 StateType = { type Props = {};
hasPermission: boolean, type State = {
scanned: boolean, hasPermission: boolean,
dialogVisible: boolean, scanned: boolean,
mascotDialogVisible: boolean, dialogVisible: boolean,
loading: boolean, mascotDialogVisible: boolean,
dialogTitle: string,
dialogMessage: string,
loading: boolean,
}; };
const styles = StyleSheet.create({ class ScannerScreen extends React.Component<Props, State> {
container: {
flex: 1,
justifyContent: 'center',
},
button: {
position: 'absolute',
bottom: 20,
width: '80%',
left: '10%',
},
});
class ScannerScreen extends React.Component<null, StateType> { state = {
constructor() { hasPermission: false,
super(); scanned: false,
this.state = { mascotDialogVisible: false,
hasPermission: false, dialogVisible: false,
scanned: false, dialogTitle: "",
mascotDialogVisible: false, dialogMessage: "",
dialogVisible: false, loading: false,
loading: false,
}; };
}
componentDidMount() { constructor() {
this.requestPermissions(); super();
}
/**
* Gets a view asking user for permission to use the camera
*
* @returns {*}
*/
getPermissionScreen(): React.Node {
return (
<View style={{marginLeft: 10, marginRight: 10}}>
<Text>{i18n.t('screens.scanner.permissions.error')}</Text>
<Button
icon="camera"
mode="contained"
onPress={this.requestPermissions}
style={{
marginTop: 10,
marginLeft: 'auto',
marginRight: 'auto',
}}>
{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,
});
}
/**
* Shows a dialog indicating how to use the scanner
*/
showHelpDialog = () => {
this.setState({
mascotDialogVisible: true,
scanned: true,
});
};
/**
* Shows a loading dialog
*/
showOpeningDialog = () => {
this.setState({
loading: true,
scanned: true,
});
};
/**
* Hide any dialog
*/
onDialogDismiss = () => {
this.setState({
dialogVisible: false,
scanned: false,
});
};
onMascotDialogDismiss = () => {
this.setState({
mascotDialogVisible: false,
scanned: false,
});
};
/**
* 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
*/
onCodeScanned = ({data}: {data: string}) => {
if (!URLHandler.isUrlValid(data)) this.showErrorDialog();
else {
this.showOpeningDialog();
Linking.openURL(data);
} }
};
render(): React.Node { componentDidMount() {
const {state} = this; this.requestPermissions();
return ( }
<View
style={{ /**
...styles.container, * Requests permission to use the camera
marginBottom: CustomTabBar.TAB_BAR_HEIGHT, */
}}> requestPermissions = () => {
{state.hasPermission ? this.getScanner() : this.getPermissionScreen()} if (Platform.OS === 'android')
<Button request(PERMISSIONS.ANDROID.CAMERA).then(this.updatePermissionStatus)
icon="information" else
mode="contained" request(PERMISSIONS.IOS.CAMERA).then(this.updatePermissionStatus)
onPress={this.showHelpDialog} };
style={styles.button}>
{i18n.t('screens.scanner.help.button')} /**
</Button> * Updates the state permission status
<MascotPopup *
visible={state.mascotDialogVisible} * @param result
title={i18n.t('screens.scanner.mascotDialog.title')} */
message={i18n.t('screens.scanner.mascotDialog.message')} updatePermissionStatus = (result) => this.setState({hasPermission: result === RESULTS.GRANTED});
icon="camera-iris"
buttons={{ /**
action: null, * Opens scanned link if it is a valid app link or shows and error dialog
cancel: { *
message: i18n.t('screens.scanner.mascotDialog.button'), * @param type The barcode type
icon: 'check', * @param data The scanned value
onPress: this.onMascotDialogDismiss, */
}, handleCodeScanned = ({type, data}) => {
}} if (!URLHandler.isUrlValid(data))
emotion={MASCOT_STYLE.NORMAL} this.showErrorDialog();
/> else {
<AlertDialog this.showOpeningDialog();
visible={state.dialogVisible} Linking.openURL(data);
onDismiss={this.onDialogDismiss} }
title={i18n.t('screens.scanner.error.title')} };
message={i18n.t('screens.scanner.error.message')}
/> /**
<LoadingConfirmDialog * Gets a view asking user for permission to use the camera
visible={state.loading} *
titleLoading={i18n.t('general.loading')} * @returns {*}
startLoading */
/> getPermissionScreen() {
</View> return <View style={{marginLeft: 10, marginRight: 10}}>
); <Text>{i18n.t("screens.scanner.permissions.error")}</Text>
} <Button
icon="camera"
mode="contained"
onPress={this.requestPermissions}
style={{
marginTop: 10,
marginLeft: 'auto',
marginRight: 'auto',
}}
>
{i18n.t("screens.scanner.permissions.button")}
</Button>
</View>
}
/**
* Shows a dialog indicating how to use the scanner
*/
showHelpDialog = () => {
this.setState({
mascotDialogVisible: true,
scanned: true,
});
};
/**
* Shows a loading dialog
*/
showOpeningDialog = () => {
this.setState({
loading: true,
scanned: true,
});
};
/**
* Shows a dialog indicating the user the scanned code was invalid
*/
showErrorDialog() {
this.setState({
dialogVisible: true,
scanned: true,
});
}
/**
* Hide any dialog
*/
onDialogDismiss = () => this.setState({
dialogVisible: false,
scanned: false,
});
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
*
* @returns {*}
*/
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>
);
}
render() {
return (
<View style={{
...styles.container,
marginBottom: CustomTabBar.TAB_BAR_HEIGHT
}}>
{this.state.hasPermission
? this.getScanner()
: this.getPermissionScreen()
}
<Button
icon="information"
mode="contained"
onPress={this.showHelpDialog}
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"}
buttons={{
action: null,
cancel: {
message: i18n.t("screens.scanner.mascotDialog.button"),
icon: "check",
onPress: this.onMascotDialogDismiss,
}
}}
emotion={MASCOT_STYLE.NORMAL}
/>
<AlertDialog
visible={this.state.dialogVisible}
onDismiss={this.onDialogDismiss}
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}
/>
</View>
);
}
} }
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
},
button: {
position: 'absolute',
bottom: 20,
width: '80%',
left: '10%'
},
});
export default withTheme(ScannerScreen); export default withTheme(ScannerScreen);

View file

@ -1,162 +1,149 @@
// @flow // @flow
import * as React from 'react'; import * as React from 'react';
import {Image, View} from 'react-native'; import type {cardList} from "../../components/Lists/CardList/CardList";
import { import CardList from "../../components/Lists/CardList/CardList";
Avatar, import {Image, View} from "react-native";
Card, import {Avatar, Card, Divider, List, TouchableRipple, withTheme} from "react-native-paper";
Divider, import type {CustomTheme} from "../../managers/ThemeManager";
List,
TouchableRipple,
withTheme,
} from 'react-native-paper';
import i18n from 'i18n-js'; import i18n from 'i18n-js';
import {StackNavigationProp} from '@react-navigation/stack'; import MaterialHeaderButtons, {Item} from "../../components/Overrides/CustomHeaderButton";
import CardList from '../../components/Lists/CardList/CardList'; import {StackNavigationProp} from "@react-navigation/stack";
import type {CustomTheme} from '../../managers/ThemeManager'; import {MASCOT_STYLE} from "../../components/Mascot/Mascot";
import MaterialHeaderButtons, { import MascotPopup from "../../components/Mascot/MascotPopup";
Item, import AsyncStorageManager from "../../managers/AsyncStorageManager";
} from '../../components/Overrides/CustomHeaderButton'; import ServicesManager, {SERVICES_CATEGORIES_KEY} from "../../managers/ServicesManager";
import {MASCOT_STYLE} from '../../components/Mascot/Mascot'; import CollapsibleFlatList from "../../components/Collapsible/CollapsibleFlatList";
import MascotPopup from '../../components/Mascot/MascotPopup';
import AsyncStorageManager from '../../managers/AsyncStorageManager';
import ServicesManager, {
SERVICES_CATEGORIES_KEY,
} from '../../managers/ServicesManager';
import CollapsibleFlatList from '../../components/Collapsible/CollapsibleFlatList';
import type {ServiceCategoryType} from '../../managers/ServicesManager';
type PropsType = { type Props = {
navigation: StackNavigationProp, navigation: StackNavigationProp,
theme: CustomTheme, theme: CustomTheme,
}; }
class ServicesScreen extends React.Component<PropsType> { export type listItem = {
finalDataset: Array<ServiceCategoryType>; title: string,
description: string,
image: string | number,
content: cardList,
}
constructor(props: PropsType) {
super(props);
const services = new ServicesManager(props.navigation);
this.finalDataset = services.getCategories([
SERVICES_CATEGORIES_KEY.SPECIAL,
]);
}
componentDidMount() { class ServicesScreen extends React.Component<Props> {
const {props} = this;
props.navigation.setOptions({
headerRight: this.getAboutButton,
});
}
getAboutButton = (): React.Node => ( finalDataset: Array<listItem>
<MaterialHeaderButtons>
<Item
title="information"
iconName="information"
onPress={this.onAboutPress}
/>
</MaterialHeaderButtons>
);
onAboutPress = () => { constructor(props) {
const {props} = this; super(props);
props.navigation.navigate('amicale-contact'); const services = new ServicesManager(props.navigation);
}; this.finalDataset = services.getCategories([SERVICES_CATEGORIES_KEY.SPECIAL])
}
/** componentDidMount() {
* Gets the list title image for the list. this.props.navigation.setOptions({
* headerRight: this.getAboutButton,
* If the source is a string, we are using an icon. });
* If the source is a number, we are using an internal image. }
*
* @param source The source image to display. Can be a string for icons or a number for local images
* @returns {*}
*/
getListTitleImage(source: string | number): React.Node {
const {props} = this;
if (typeof source === 'number')
return (
<Image
size={48}
source={source}
style={{
width: 48,
height: 48,
}}
/>
);
return (
<Avatar.Icon
size={48}
icon={source}
color={props.theme.colors.primary}
style={{backgroundColor: 'transparent'}}
/>
);
}
/** getAboutButton = () =>
* A list item showing a list of available services for the current category <MaterialHeaderButtons>
* <Item title="information" iconName="information" onPress={this.onAboutPress}/>
* @param item </MaterialHeaderButtons>;
* @returns {*}
*/
getRenderItem = ({item}: {item: ServiceCategoryType}): React.Node => {
const {props} = this;
return (
<TouchableRipple
style={{
margin: 5,
marginBottom: 20,
}}
onPress={() => {
props.navigation.navigate('services-section', {data: item});
}}>
<View>
<Card.Title
title={item.title}
subtitle={item.subtitle}
left={(): React.Node => this.getListTitleImage(item.image)}
right={({size}: {size: number}): React.Node => (
<List.Icon size={size} icon="chevron-right" />
)}
/>
<CardList dataset={item.content} isHorizontal />
</View>
</TouchableRipple>
);
};
keyExtractor = (item: ServiceCategoryType): string => item.title; onAboutPress = () => this.props.navigation.navigate('amicale-contact');
render(): React.Node { /**
return ( * Gets the list title image for the list.
<View> *
<CollapsibleFlatList * If the source is a string, we are using an icon.
data={this.finalDataset} * If the source is a number, we are using an internal image.
renderItem={this.getRenderItem} *
keyExtractor={this.keyExtractor} * @param props Props to pass to the component
ItemSeparatorComponent={(): React.Node => <Divider />} * @param source The source image to display. Can be a string for icons or a number for local images
hasTab * @returns {*}
/> */
<MascotPopup getListTitleImage(props, source: string | number) {
prefKey={AsyncStorageManager.PREFERENCES.servicesShowBanner.key} if (typeof source === "number")
title={i18n.t('screens.services.mascotDialog.title')} return <Image
message={i18n.t('screens.services.mascotDialog.message')} size={48}
icon="cloud-question" source={source}
buttons={{ style={{
action: null, width: 48,
cancel: { height: 48,
message: i18n.t('screens.services.mascotDialog.button'), }}/>
icon: 'check', else
}, return <Avatar.Icon
}} {...props}
emotion={MASCOT_STYLE.WINK} size={48}
/> icon={source}
</View> color={this.props.theme.colors.primary}
); style={{backgroundColor: 'transparent'}}
} />
}
/**
* A list item showing a list of available services for the current category
*
* @param item
* @returns {*}
*/
renderItem = ({item}: { item: listItem }) => {
return (
<TouchableRipple
style={{
margin: 5,
marginBottom: 20,
}}
onPress={() => this.props.navigation.navigate("services-section", {data: item})}
>
<View>
<Card.Title
title={item.title}
subtitle={item.description}
left={(props) => this.getListTitleImage(props, item.image)}
right={(props) => <List.Icon {...props} icon="chevron-right"/>}
/>
<CardList
dataset={item.content}
isHorizontal={true}
/>
</View>
</TouchableRipple>
);
};
keyExtractor = (item: listItem) => {
return item.title;
}
render() {
return (
<View>
<CollapsibleFlatList
data={this.finalDataset}
renderItem={this.renderItem}
keyExtractor={this.keyExtractor}
ItemSeparatorComponent={() => <Divider/>}
hasTab={true}
/>
<MascotPopup
prefKey={AsyncStorageManager.PREFERENCES.servicesShowBanner.key}
title={i18n.t("screens.services.mascotDialog.title")}
message={i18n.t("screens.services.mascotDialog.message")}
icon={"cloud-question"}
buttons={{
action: null,
cancel: {
message: i18n.t("screens.services.mascotDialog.button"),
icon: "check",
onPress: this.onHideMascotDialog,
}
}}
emotion={MASCOT_STYLE.WINK}
/>
</View>
);
}
} }
export default withTheme(ServicesScreen); export default withTheme(ServicesScreen);

View file

@ -1,65 +1,58 @@
// @flow // @flow
import * as React from 'react'; import * as React from 'react';
import {Collapsible} from 'react-navigation-collapsible'; import CardList from "../../components/Lists/CardList/CardList";
import {CommonActions} from '@react-navigation/native'; import CustomTabBar from "../../components/Tabbar/CustomTabBar";
import {StackNavigationProp} from '@react-navigation/stack'; import {withCollapsible} from "../../utils/withCollapsible";
import CardList from '../../components/Lists/CardList/CardList'; import {Collapsible} from "react-navigation-collapsible";
import CustomTabBar from '../../components/Tabbar/CustomTabBar'; import {CommonActions} from "@react-navigation/native";
import {withCollapsible} from '../../utils/withCollapsible'; import type {listItem} from "./ServicesScreen";
import type {ServiceCategoryType} from '../../managers/ServicesManager'; import {StackNavigationProp} from "@react-navigation/stack";
type PropsType = { type Props = {
navigation: StackNavigationProp, navigation: StackNavigationProp,
route: {params: {data: ServiceCategoryType | null}}, route: { params: { data: listItem | null } },
collapsibleStack: Collapsible, collapsibleStack: Collapsible,
}; }
class ServicesSectionScreen extends React.Component<PropsType> { class ServicesSectionScreen extends React.Component<Props> {
finalDataset: ServiceCategoryType;
constructor(props: PropsType) { finalDataset: listItem;
super(props);
this.handleNavigationParams();
}
/** constructor(props) {
* Recover the list to display from navigation parameters super(props);
*/ this.handleNavigationParams();
handleNavigationParams() {
const {props} = this;
if (props.route.params != null) {
if (props.route.params.data != null) {
this.finalDataset = props.route.params.data;
// reset params to prevent infinite loop
props.navigation.dispatch(CommonActions.setParams({data: null}));
props.navigation.setOptions({
headerTitle: this.finalDataset.title,
});
}
} }
}
render(): React.Node { /**
const {props} = this; * Recover the list to display from navigation parameters
const { */
containerPaddingTop, handleNavigationParams() {
scrollIndicatorInsetTop, if (this.props.route.params != null) {
onScroll, if (this.props.route.params.data != null) {
} = props.collapsibleStack; this.finalDataset = this.props.route.params.data;
return ( // reset params to prevent infinite loop
<CardList this.props.navigation.dispatch(CommonActions.setParams({data: null}));
dataset={this.finalDataset.content} this.props.navigation.setOptions({
isHorizontal={false} headerTitle: this.finalDataset.title,
onScroll={onScroll} });
contentContainerStyle={{ }
paddingTop: containerPaddingTop, }
paddingBottom: CustomTabBar.TAB_BAR_HEIGHT + 20, }
}}
scrollIndicatorInsets={{top: scrollIndicatorInsetTop}} render() {
/> const {containerPaddingTop, scrollIndicatorInsetTop, onScroll} = this.props.collapsibleStack;
); return <CardList
} dataset={this.finalDataset.content}
isHorizontal={false}
onScroll={onScroll}
contentContainerStyle={{
paddingTop: containerPaddingTop,
paddingBottom: CustomTabBar.TAB_BAR_HEIGHT + 20
}}
scrollIndicatorInsets={{top: scrollIndicatorInsetTop}}
/>
}
} }
export default withCollapsible(ServicesSectionScreen); export default withCollapsible(ServicesSectionScreen);

View file

@ -1,123 +0,0 @@
// @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;
}

View file

@ -1,5 +1,6 @@
// @flow // @flow
/** /**
* Sanitizes the given string to improve search performance. * Sanitizes the given string to improve search performance.
* *
@ -9,12 +10,11 @@
* @return {string} The sanitized string * @return {string} The sanitized string
*/ */
export function sanitizeString(str: string): string { export function sanitizeString(str: string): string {
return str return str.toLowerCase()
.toLowerCase() .normalize("NFD")
.normalize('NFD') .replace(/[\u0300-\u036f]/g, "")
.replace(/[\u0300-\u036f]/g, '') .replace(/ /g, "")
.replace(/ /g, '') .replace(/_/g, "");
.replace(/_/g, '');
} }
/** /**
@ -24,8 +24,8 @@ export function sanitizeString(str: string): string {
* @param query The query string used to find a match * @param query The query string used to find a match
* @returns {boolean} * @returns {boolean}
*/ */
export function stringMatchQuery(str: string, query: string): boolean { export function stringMatchQuery(str: string, query: string) {
return sanitizeString(str).includes(sanitizeString(query)); return sanitizeString(str).includes(sanitizeString(query));
} }
/** /**
@ -35,13 +35,10 @@ export function stringMatchQuery(str: string, query: string): boolean {
* @param categories The item's categories tuple * @param categories The item's categories tuple
* @returns {boolean} True if at least one entry is in both arrays * @returns {boolean} True if at least one entry is in both arrays
*/ */
export function isItemInCategoryFilter( export function isItemInCategoryFilter(filter: Array<number>, categories: [number, number]) {
filter: Array<number>, for (const category of categories) {
categories: Array<number | null>, if (filter.indexOf(category) !== -1)
): boolean { return true;
let itemFound = false; }
categories.forEach((cat: number | null) => { return false;
if (cat != null && filter.indexOf(cat) !== -1) itemFound = true;
});
return itemFound;
} }

View file

@ -1,19 +0,0 @@
// @flow
/**
* Gets the given services list without items of the given ids
*
* @param idList The ids of items to remove
* @param sourceList The item list to use as source
* @returns {[]}
*/
export default function getStrippedServicesList<T>(
idList: Array<string>,
sourceList: Array<{key: string, ...T}>,
): Array<{key: string, ...T}> {
const newArray = [];
sourceList.forEach((item: {key: string, ...T}) => {
if (!idList.includes(item.key)) newArray.push(item);
});
return newArray;
}