Compare commits
45 commits
05ef28f3b5
...
b378473591
| Author | SHA1 | Date | |
|---|---|---|---|
| b378473591 | |||
| 327488a470 | |||
| eef6f75414 | |||
| 5166e0b879 | |||
| 98770611ff | |||
| ee9e225dae | |||
| 05f769fe79 | |||
| 1be913c5aa | |||
| c86281cbd2 | |||
| 4cc9c61d72 | |||
| 1e81b2cd7b | |||
| cbe3777957 | |||
| 569e659779 | |||
| fcbc70956b | |||
| 3ce23726c2 | |||
| a3299c19f7 | |||
| 0a64f5fcd7 | |||
| 483970c9a8 | |||
| 3e4f2f4ac1 | |||
| 7107a8eadf | |||
| 7ac62b99f4 | |||
| aa992d20b2 | |||
| 0117b25cd8 | |||
| 4db4516296 | |||
| 7b94afadcc | |||
| 1cc0802c12 | |||
| 547af66977 | |||
| ab86c1c85c | |||
| 11b5f2ac71 | |||
| 70365136ac | |||
| 93d12b27f8 | |||
| 33d98b024b | |||
| 6b12b4cde2 | |||
| 34ccf9c4c9 | |||
| 9d92a88627 | |||
| 925bded69b | |||
| 3629c5730a | |||
| 3d9bfdea4c | |||
| 142b861ccb | |||
| 0a9e0eb0ca | |||
| 9fc02baf6d | |||
| 22eabf28d5 | |||
| c0777511a6 | |||
| be1f61b671 | |||
| b596f68abe |
145 changed files with 18112 additions and 16502 deletions
|
|
@ -13,6 +13,8 @@ module.exports = {
|
|||
jest: true,
|
||||
},
|
||||
rules: {
|
||||
'react/jsx-filename-extension': [1, {extensions: ['.js', '.jsx']}],
|
||||
'react/static-property-placement': [2, 'static public field'],
|
||||
'flowtype/define-flow-type': 1,
|
||||
'flowtype/no-mixed': 2,
|
||||
'flowtype/no-primitive-constructor-types': 2,
|
||||
|
|
@ -37,4 +39,8 @@ module.exports = {
|
|||
onlyFilesWithFlowAnnotation: false,
|
||||
},
|
||||
},
|
||||
globals: {
|
||||
fetch: false,
|
||||
Headers: false,
|
||||
},
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,16 +0,0 @@
|
|||
<component name="ProjectRunConfigurationManager">
|
||||
<configuration default="false" name="Expo" type="ReactNative" factoryName="React Native">
|
||||
<node-interpreter value="project" />
|
||||
<react-native value="$USER_HOME$/.nvm/versions/node/v12.4.0/lib/node_modules/react-native-cli" />
|
||||
<platform value="ANDROID" />
|
||||
<envs />
|
||||
<only-packager />
|
||||
<build-and-launch value="false" />
|
||||
<browser value="98ca6316-2f89-46d9-a9e5-fa9e2b0625b3" />
|
||||
<debug-host value="127.0.0.1" />
|
||||
<debug-port value="19001" />
|
||||
<method v="2">
|
||||
<option name="ReactNativePackager" enabled="true" />
|
||||
</method>
|
||||
</configuration>
|
||||
</component>
|
||||
369
App.js
369
App.js
|
|
@ -1,210 +1,211 @@
|
|||
// @flow
|
||||
|
||||
import * as React from 'react';
|
||||
import {LogBox, Platform, SafeAreaView, StatusBar, View} from 'react-native';
|
||||
import LocaleManager from './src/managers/LocaleManager';
|
||||
import AsyncStorageManager from "./src/managers/AsyncStorageManager";
|
||||
import CustomIntroSlider from "./src/components/Overrides/CustomIntroSlider";
|
||||
import type {CustomTheme} from "./src/managers/ThemeManager";
|
||||
import ThemeManager from './src/managers/ThemeManager';
|
||||
import {LogBox, Platform, SafeAreaView, View} from 'react-native';
|
||||
import {NavigationContainer} from '@react-navigation/native';
|
||||
import MainNavigator from './src/navigation/MainNavigator';
|
||||
import {Provider as PaperProvider} from 'react-native-paper';
|
||||
import AprilFoolsManager from "./src/managers/AprilFoolsManager";
|
||||
import Update from "./src/constants/Update";
|
||||
import ConnectionManager from "./src/managers/ConnectionManager";
|
||||
import URLHandler from "./src/utils/URLHandler";
|
||||
import {setSafeBounceHeight} from "react-navigation-collapsible";
|
||||
import SplashScreen from 'react-native-splash-screen'
|
||||
import {OverflowMenuProvider} from "react-navigation-header-buttons";
|
||||
import {setSafeBounceHeight} from 'react-navigation-collapsible';
|
||||
import SplashScreen from 'react-native-splash-screen';
|
||||
import {OverflowMenuProvider} from 'react-navigation-header-buttons';
|
||||
import LocaleManager from './src/managers/LocaleManager';
|
||||
import AsyncStorageManager from './src/managers/AsyncStorageManager';
|
||||
import CustomIntroSlider from './src/components/Overrides/CustomIntroSlider';
|
||||
import type {CustomThemeType} from './src/managers/ThemeManager';
|
||||
import ThemeManager from './src/managers/ThemeManager';
|
||||
import MainNavigator from './src/navigation/MainNavigator';
|
||||
import AprilFoolsManager from './src/managers/AprilFoolsManager';
|
||||
import Update from './src/constants/Update';
|
||||
import ConnectionManager from './src/managers/ConnectionManager';
|
||||
import type {ParsedUrlDataType} from './src/utils/URLHandler';
|
||||
import URLHandler from './src/utils/URLHandler';
|
||||
import {setupStatusBar} from './src/utils/Utils';
|
||||
|
||||
// Native optimizations https://reactnavigation.org/docs/react-native-screens
|
||||
// Crashes app when navigating away from webview on android 9+
|
||||
// enableScreens(true);
|
||||
|
||||
|
||||
LogBox.ignoreLogs([ // collapsible headers cause this warning, just ignore as it is not an issue
|
||||
'Non-serializable values were found in the navigation state',
|
||||
'Cannot update a component from inside the function body of a different component',
|
||||
LogBox.ignoreLogs([
|
||||
// collapsible headers cause this warning, just ignore as it is not an issue
|
||||
'Non-serializable values were found in the navigation state',
|
||||
'Cannot update a component from inside the function body of a different component',
|
||||
]);
|
||||
|
||||
type Props = {};
|
||||
|
||||
type State = {
|
||||
isLoading: boolean,
|
||||
showIntro: boolean,
|
||||
showUpdate: boolean,
|
||||
showAprilFools: boolean,
|
||||
currentTheme: CustomTheme | null,
|
||||
type StateType = {
|
||||
isLoading: boolean,
|
||||
showIntro: boolean,
|
||||
showUpdate: boolean,
|
||||
showAprilFools: boolean,
|
||||
currentTheme: CustomThemeType | null,
|
||||
};
|
||||
|
||||
export default class App extends React.Component<Props, State> {
|
||||
export default class App extends React.Component<null, StateType> {
|
||||
navigatorRef: {current: null | NavigationContainer};
|
||||
|
||||
state = {
|
||||
isLoading: true,
|
||||
showIntro: true,
|
||||
showUpdate: true,
|
||||
showAprilFools: false,
|
||||
currentTheme: null,
|
||||
defaultHomeRoute: string | null;
|
||||
|
||||
defaultHomeData: {[key: string]: string};
|
||||
|
||||
urlHandler: URLHandler;
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
this.state = {
|
||||
isLoading: true,
|
||||
showIntro: true,
|
||||
showUpdate: true,
|
||||
showAprilFools: false,
|
||||
currentTheme: null,
|
||||
};
|
||||
LocaleManager.initTranslations();
|
||||
this.navigatorRef = React.createRef();
|
||||
this.defaultHomeRoute = null;
|
||||
this.defaultHomeData = {};
|
||||
this.urlHandler = new URLHandler(this.onInitialURLParsed, this.onDetectURL);
|
||||
this.urlHandler.listen();
|
||||
setSafeBounceHeight(Platform.OS === 'ios' ? 100 : 20);
|
||||
this.loadAssetsAsync().finally(() => {
|
||||
this.onLoadFinished();
|
||||
});
|
||||
}
|
||||
|
||||
navigatorRef: { current: null | NavigationContainer };
|
||||
/**
|
||||
* The app has been started by an url, and it has been parsed.
|
||||
* Set a new default start route based on the data parsed.
|
||||
*
|
||||
* @param parsedData The data parsed from the url
|
||||
*/
|
||||
onInitialURLParsed = (parsedData: ParsedUrlDataType) => {
|
||||
this.defaultHomeRoute = parsedData.route;
|
||||
this.defaultHomeData = parsedData.data;
|
||||
};
|
||||
|
||||
defaultHomeRoute: string | null;
|
||||
defaultHomeData: { [key: string]: any }
|
||||
|
||||
createDrawerNavigator: () => React.Node;
|
||||
|
||||
urlHandler: URLHandler;
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
LocaleManager.initTranslations();
|
||||
this.navigatorRef = React.createRef();
|
||||
this.defaultHomeRoute = null;
|
||||
this.defaultHomeData = {};
|
||||
this.urlHandler = new URLHandler(this.onInitialURLParsed, this.onDetectURL);
|
||||
this.urlHandler.listen();
|
||||
setSafeBounceHeight(Platform.OS === 'ios' ? 100 : 20);
|
||||
this.loadAssetsAsync().then(() => {
|
||||
this.onLoadFinished();
|
||||
});
|
||||
/**
|
||||
* An url has been opened and parsed while the app was active.
|
||||
* Redirect the user to the screen according to parsed data.
|
||||
*
|
||||
* @param parsedData The data parsed from the url
|
||||
*/
|
||||
onDetectURL = (parsedData: ParsedUrlDataType) => {
|
||||
// Navigate to nested navigator and pass data to the index screen
|
||||
const nav = this.navigatorRef.current;
|
||||
if (nav != null) {
|
||||
nav.navigate('home', {
|
||||
screen: 'index',
|
||||
params: {nextScreen: parsedData.route, data: parsedData.data},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* The app has been started by an url, and it has been parsed.
|
||||
* Set a new default start route based on the data parsed.
|
||||
*
|
||||
* @param parsedData The data parsed from the url
|
||||
*/
|
||||
onInitialURLParsed = (parsedData: { route: string, data: { [key: string]: any } }) => {
|
||||
this.defaultHomeRoute = parsedData.route;
|
||||
this.defaultHomeData = parsedData.data;
|
||||
};
|
||||
/**
|
||||
* Updates the current theme
|
||||
*/
|
||||
onUpdateTheme = () => {
|
||||
this.setState({
|
||||
currentTheme: ThemeManager.getCurrentTheme(),
|
||||
});
|
||||
setupStatusBar();
|
||||
};
|
||||
|
||||
/**
|
||||
* An url has been opened and parsed while the app was active.
|
||||
* Redirect the user to the screen according to parsed data.
|
||||
*
|
||||
* @param parsedData The data parsed from the url
|
||||
*/
|
||||
onDetectURL = (parsedData: { route: string, data: { [key: string]: any } }) => {
|
||||
// Navigate to nested navigator and pass data to the index screen
|
||||
if (this.navigatorRef.current != null) {
|
||||
this.navigatorRef.current.navigate('home', {
|
||||
screen: 'index',
|
||||
params: {nextScreen: parsedData.route, data: parsedData.data}
|
||||
});
|
||||
}
|
||||
};
|
||||
/**
|
||||
* Callback when user ends the intro. Save in preferences to avoid showing back the introSlides
|
||||
*/
|
||||
onIntroDone = () => {
|
||||
this.setState({
|
||||
showIntro: false,
|
||||
showUpdate: false,
|
||||
showAprilFools: false,
|
||||
});
|
||||
AsyncStorageManager.set(
|
||||
AsyncStorageManager.PREFERENCES.showIntro.key,
|
||||
false,
|
||||
);
|
||||
AsyncStorageManager.set(
|
||||
AsyncStorageManager.PREFERENCES.updateNumber.key,
|
||||
Update.number,
|
||||
);
|
||||
AsyncStorageManager.set(
|
||||
AsyncStorageManager.PREFERENCES.showAprilFoolsStart.key,
|
||||
false,
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Updates the current theme
|
||||
*/
|
||||
onUpdateTheme = () => {
|
||||
this.setState({
|
||||
currentTheme: ThemeManager.getCurrentTheme()
|
||||
});
|
||||
this.setupStatusBar();
|
||||
};
|
||||
/**
|
||||
* Async loading is done, finish processing startup data
|
||||
*/
|
||||
onLoadFinished() {
|
||||
// Only show intro if this is the first time starting the app
|
||||
ThemeManager.getInstance().setUpdateThemeCallback(this.onUpdateTheme);
|
||||
// Status bar goes dark if set too fast on ios
|
||||
if (Platform.OS === 'ios') setTimeout(setupStatusBar, 1000);
|
||||
else setupStatusBar();
|
||||
|
||||
/**
|
||||
* Updates status bar content color if on iOS only,
|
||||
* as the android status bar is always set to black.
|
||||
*/
|
||||
setupStatusBar() {
|
||||
if (ThemeManager.getNightMode()) {
|
||||
StatusBar.setBarStyle('light-content', true);
|
||||
} else {
|
||||
StatusBar.setBarStyle('dark-content', true);
|
||||
}
|
||||
if (Platform.OS === "android")
|
||||
StatusBar.setBackgroundColor(ThemeManager.getCurrentTheme().colors.surface, true);
|
||||
this.setState({
|
||||
isLoading: false,
|
||||
currentTheme: ThemeManager.getCurrentTheme(),
|
||||
showIntro: AsyncStorageManager.getBool(
|
||||
AsyncStorageManager.PREFERENCES.showIntro.key,
|
||||
),
|
||||
showUpdate:
|
||||
AsyncStorageManager.getNumber(
|
||||
AsyncStorageManager.PREFERENCES.updateNumber.key,
|
||||
) !== Update.number,
|
||||
showAprilFools:
|
||||
AprilFoolsManager.getInstance().isAprilFoolsEnabled() &&
|
||||
AsyncStorageManager.getBool(
|
||||
AsyncStorageManager.PREFERENCES.showAprilFoolsStart.key,
|
||||
),
|
||||
});
|
||||
SplashScreen.hide();
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads every async data
|
||||
*
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
loadAssetsAsync = async () => {
|
||||
await AsyncStorageManager.getInstance().loadPreferences();
|
||||
await ConnectionManager.getInstance().recoverLogin();
|
||||
};
|
||||
|
||||
/**
|
||||
* Renders the app based on loading state
|
||||
*/
|
||||
render(): React.Node {
|
||||
const {state} = this;
|
||||
if (state.isLoading) {
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Callback when user ends the intro. Save in preferences to avoid showing back the introSlides
|
||||
*/
|
||||
onIntroDone = () => {
|
||||
this.setState({
|
||||
showIntro: false,
|
||||
showUpdate: false,
|
||||
showAprilFools: false,
|
||||
});
|
||||
AsyncStorageManager.set(AsyncStorageManager.PREFERENCES.showIntro.key, false);
|
||||
AsyncStorageManager.set(AsyncStorageManager.PREFERENCES.updateNumber.key, Update.number);
|
||||
AsyncStorageManager.set(AsyncStorageManager.PREFERENCES.showAprilFoolsStart.key, false);
|
||||
};
|
||||
|
||||
/**
|
||||
* Loads every async data
|
||||
*
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
loadAssetsAsync = async () => {
|
||||
await AsyncStorageManager.getInstance().loadPreferences();
|
||||
try {
|
||||
await ConnectionManager.getInstance().recoverLogin();
|
||||
} catch (e) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Async loading is done, finish processing startup data
|
||||
*/
|
||||
onLoadFinished() {
|
||||
// Only show intro if this is the first time starting the app
|
||||
this.createDrawerNavigator = () => <MainNavigator
|
||||
defaultHomeRoute={this.defaultHomeRoute}
|
||||
defaultHomeData={this.defaultHomeData}
|
||||
/>;
|
||||
ThemeManager.getInstance().setUpdateThemeCallback(this.onUpdateTheme);
|
||||
// Status bar goes dark if set too fast on ios
|
||||
if (Platform.OS === 'ios')
|
||||
setTimeout(this.setupStatusBar, 1000);
|
||||
else
|
||||
this.setupStatusBar();
|
||||
this.setState({
|
||||
isLoading: false,
|
||||
currentTheme: ThemeManager.getCurrentTheme(),
|
||||
showIntro: AsyncStorageManager.getBool(AsyncStorageManager.PREFERENCES.showIntro.key),
|
||||
showUpdate: AsyncStorageManager.getNumber(AsyncStorageManager.PREFERENCES.updateNumber.key)
|
||||
!== Update.number,
|
||||
showAprilFools: AprilFoolsManager.getInstance().isAprilFoolsEnabled()
|
||||
&& AsyncStorageManager.getBool(AsyncStorageManager.PREFERENCES.showAprilFoolsStart.key),
|
||||
});
|
||||
SplashScreen.hide();
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the app based on loading state
|
||||
*/
|
||||
render() {
|
||||
if (this.state.isLoading) {
|
||||
return null;
|
||||
} else if (this.state.showIntro || this.state.showUpdate || this.state.showAprilFools) {
|
||||
return <CustomIntroSlider
|
||||
onDone={this.onIntroDone}
|
||||
isUpdate={this.state.showUpdate && !this.state.showIntro}
|
||||
isAprilFools={this.state.showAprilFools && !this.state.showIntro}
|
||||
/>;
|
||||
} else {
|
||||
return (
|
||||
<PaperProvider theme={this.state.currentTheme}>
|
||||
<OverflowMenuProvider>
|
||||
<View style={{backgroundColor: ThemeManager.getCurrentTheme().colors.background, flex: 1}}>
|
||||
<SafeAreaView style={{flex: 1}}>
|
||||
<NavigationContainer theme={this.state.currentTheme} ref={this.navigatorRef}>
|
||||
<MainNavigator
|
||||
defaultHomeRoute={this.defaultHomeRoute}
|
||||
defaultHomeData={this.defaultHomeData}
|
||||
/>
|
||||
</NavigationContainer>
|
||||
</SafeAreaView>
|
||||
</View>
|
||||
</OverflowMenuProvider>
|
||||
</PaperProvider>
|
||||
);
|
||||
}
|
||||
if (state.showIntro || state.showUpdate || state.showAprilFools) {
|
||||
return (
|
||||
<CustomIntroSlider
|
||||
onDone={this.onIntroDone}
|
||||
isUpdate={state.showUpdate && !state.showIntro}
|
||||
isAprilFools={state.showAprilFools && !state.showIntro}
|
||||
/>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<PaperProvider theme={state.currentTheme}>
|
||||
<OverflowMenuProvider>
|
||||
<View
|
||||
style={{
|
||||
backgroundColor: ThemeManager.getCurrentTheme().colors.background,
|
||||
flex: 1,
|
||||
}}>
|
||||
<SafeAreaView style={{flex: 1}}>
|
||||
<NavigationContainer
|
||||
theme={state.currentTheme}
|
||||
ref={this.navigatorRef}>
|
||||
<MainNavigator
|
||||
defaultHomeRoute={this.defaultHomeRoute}
|
||||
defaultHomeData={this.defaultHomeData}
|
||||
/>
|
||||
</NavigationContainer>
|
||||
</SafeAreaView>
|
||||
</View>
|
||||
</OverflowMenuProvider>
|
||||
</PaperProvider>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,210 +1,217 @@
|
|||
jest.mock('react-native-keychain');
|
||||
/* eslint-disable */
|
||||
|
||||
import React from 'react';
|
||||
import ConnectionManager from "../../src/managers/ConnectionManager";
|
||||
import {ERROR_TYPE} from "../../src/utils/WebData";
|
||||
import ConnectionManager from '../../src/managers/ConnectionManager';
|
||||
import {ERROR_TYPE} from '../../src/utils/WebData';
|
||||
|
||||
let fetch = require('isomorphic-fetch'); // fetch is not implemented in nodeJS but in react-native
|
||||
jest.mock('react-native-keychain');
|
||||
|
||||
const fetch = require('isomorphic-fetch'); // fetch is not implemented in nodeJS but in react-native
|
||||
|
||||
const c = ConnectionManager.getInstance();
|
||||
|
||||
afterEach(() => {
|
||||
jest.restoreAllMocks();
|
||||
jest.restoreAllMocks();
|
||||
});
|
||||
|
||||
test('isLoggedIn yes', () => {
|
||||
jest.spyOn(ConnectionManager.prototype, 'getToken').mockImplementationOnce(() => {
|
||||
return 'token';
|
||||
jest
|
||||
.spyOn(ConnectionManager.prototype, 'getToken')
|
||||
.mockImplementationOnce(() => {
|
||||
return 'token';
|
||||
});
|
||||
return expect(c.isLoggedIn()).toBe(true);
|
||||
return expect(c.isLoggedIn()).toBe(true);
|
||||
});
|
||||
|
||||
test('isLoggedIn no', () => {
|
||||
jest.spyOn(ConnectionManager.prototype, 'getToken').mockImplementationOnce(() => {
|
||||
return null;
|
||||
jest
|
||||
.spyOn(ConnectionManager.prototype, 'getToken')
|
||||
.mockImplementationOnce(() => {
|
||||
return null;
|
||||
});
|
||||
return expect(c.isLoggedIn()).toBe(false);
|
||||
return expect(c.isLoggedIn()).toBe(false);
|
||||
});
|
||||
|
||||
test("isConnectionResponseValid", () => {
|
||||
let json = {
|
||||
error: 0,
|
||||
data: {token: 'token'}
|
||||
};
|
||||
expect(c.isConnectionResponseValid(json)).toBeTrue();
|
||||
json = {
|
||||
error: 2,
|
||||
data: {}
|
||||
};
|
||||
expect(c.isConnectionResponseValid(json)).toBeTrue();
|
||||
json = {
|
||||
error: 0,
|
||||
data: {token: ''}
|
||||
};
|
||||
expect(c.isConnectionResponseValid(json)).toBeFalse();
|
||||
json = {
|
||||
error: 'prout',
|
||||
data: {token: ''}
|
||||
};
|
||||
expect(c.isConnectionResponseValid(json)).toBeFalse();
|
||||
test('connect bad credentials', () => {
|
||||
jest.spyOn(global, 'fetch').mockImplementationOnce(() => {
|
||||
return Promise.resolve({
|
||||
json: () => {
|
||||
return {
|
||||
error: ERROR_TYPE.BAD_CREDENTIALS,
|
||||
data: {},
|
||||
};
|
||||
},
|
||||
});
|
||||
});
|
||||
return expect(c.connect('email', 'password')).rejects.toBe(
|
||||
ERROR_TYPE.BAD_CREDENTIALS,
|
||||
);
|
||||
});
|
||||
|
||||
test("connect bad credentials", () => {
|
||||
jest.spyOn(global, 'fetch').mockImplementationOnce(() => {
|
||||
return Promise.resolve({
|
||||
json: () => {
|
||||
return {
|
||||
error: ERROR_TYPE.BAD_CREDENTIALS,
|
||||
data: {}
|
||||
};
|
||||
},
|
||||
})
|
||||
test('connect good credentials', () => {
|
||||
jest.spyOn(global, 'fetch').mockImplementationOnce(() => {
|
||||
return Promise.resolve({
|
||||
json: () => {
|
||||
return {
|
||||
error: ERROR_TYPE.SUCCESS,
|
||||
data: {token: 'token'},
|
||||
};
|
||||
},
|
||||
});
|
||||
return expect(c.connect('email', 'password'))
|
||||
.rejects.toBe(ERROR_TYPE.BAD_CREDENTIALS);
|
||||
});
|
||||
jest
|
||||
.spyOn(ConnectionManager.prototype, 'saveLogin')
|
||||
.mockImplementationOnce(() => {
|
||||
return Promise.resolve(true);
|
||||
});
|
||||
return expect(c.connect('email', 'password')).resolves.toBe(undefined);
|
||||
});
|
||||
|
||||
test("connect good credentials", () => {
|
||||
jest.spyOn(global, 'fetch').mockImplementationOnce(() => {
|
||||
return Promise.resolve({
|
||||
json: () => {
|
||||
return {
|
||||
error: ERROR_TYPE.SUCCESS,
|
||||
data: {token: 'token'}
|
||||
};
|
||||
},
|
||||
})
|
||||
test('connect good credentials no consent', () => {
|
||||
jest.spyOn(global, 'fetch').mockImplementationOnce(() => {
|
||||
return Promise.resolve({
|
||||
json: () => {
|
||||
return {
|
||||
error: ERROR_TYPE.NO_CONSENT,
|
||||
data: {},
|
||||
};
|
||||
},
|
||||
});
|
||||
jest.spyOn(ConnectionManager.prototype, 'saveLogin').mockImplementationOnce(() => {
|
||||
return Promise.resolve(true);
|
||||
});
|
||||
return expect(c.connect('email', 'password')).resolves.toBeTruthy();
|
||||
});
|
||||
return expect(c.connect('email', 'password')).rejects.toBe(
|
||||
ERROR_TYPE.NO_CONSENT,
|
||||
);
|
||||
});
|
||||
|
||||
test("connect good credentials no consent", () => {
|
||||
jest.spyOn(global, 'fetch').mockImplementationOnce(() => {
|
||||
return Promise.resolve({
|
||||
json: () => {
|
||||
return {
|
||||
error: ERROR_TYPE.NO_CONSENT,
|
||||
data: {}
|
||||
};
|
||||
},
|
||||
})
|
||||
test('connect good credentials, fail save token', () => {
|
||||
jest.spyOn(global, 'fetch').mockImplementationOnce(() => {
|
||||
return Promise.resolve({
|
||||
json: () => {
|
||||
return {
|
||||
error: ERROR_TYPE.SUCCESS,
|
||||
data: {token: 'token'},
|
||||
};
|
||||
},
|
||||
});
|
||||
return expect(c.connect('email', 'password'))
|
||||
.rejects.toBe(ERROR_TYPE.NO_CONSENT);
|
||||
});
|
||||
jest
|
||||
.spyOn(ConnectionManager.prototype, 'saveLogin')
|
||||
.mockImplementationOnce(() => {
|
||||
return Promise.reject(false);
|
||||
});
|
||||
return expect(c.connect('email', 'password')).rejects.toBe(
|
||||
ERROR_TYPE.TOKEN_SAVE,
|
||||
);
|
||||
});
|
||||
|
||||
test("connect good credentials, fail save token", () => {
|
||||
jest.spyOn(global, 'fetch').mockImplementationOnce(() => {
|
||||
return Promise.resolve({
|
||||
json: () => {
|
||||
return {
|
||||
error: ERROR_TYPE.SUCCESS,
|
||||
data: {token: 'token'}
|
||||
};
|
||||
},
|
||||
})
|
||||
});
|
||||
jest.spyOn(ConnectionManager.prototype, 'saveLogin').mockImplementationOnce(() => {
|
||||
return Promise.reject(false);
|
||||
});
|
||||
return expect(c.connect('email', 'password')).rejects.toBe(ERROR_TYPE.UNKNOWN);
|
||||
test('connect connection error', () => {
|
||||
jest.spyOn(global, 'fetch').mockImplementationOnce(() => {
|
||||
return Promise.reject();
|
||||
});
|
||||
return expect(c.connect('email', 'password')).rejects.toBe(
|
||||
ERROR_TYPE.CONNECTION_ERROR,
|
||||
);
|
||||
});
|
||||
|
||||
test("connect connection error", () => {
|
||||
jest.spyOn(global, 'fetch').mockImplementationOnce(() => {
|
||||
return Promise.reject();
|
||||
test('connect bogus response 1', () => {
|
||||
jest.spyOn(global, 'fetch').mockImplementationOnce(() => {
|
||||
return Promise.resolve({
|
||||
json: () => {
|
||||
return {
|
||||
thing: true,
|
||||
wrong: '',
|
||||
};
|
||||
},
|
||||
});
|
||||
return expect(c.connect('email', 'password'))
|
||||
.rejects.toBe(ERROR_TYPE.CONNECTION_ERROR);
|
||||
});
|
||||
return expect(c.connect('email', 'password')).rejects.toBe(
|
||||
ERROR_TYPE.SERVER_ERROR,
|
||||
);
|
||||
});
|
||||
|
||||
test("connect bogus response 1", () => {
|
||||
jest.spyOn(global, 'fetch').mockImplementationOnce(() => {
|
||||
return Promise.resolve({
|
||||
json: () => {
|
||||
return {
|
||||
thing: true,
|
||||
wrong: '',
|
||||
}
|
||||
},
|
||||
})
|
||||
test('authenticatedRequest success', () => {
|
||||
jest
|
||||
.spyOn(ConnectionManager.prototype, 'getToken')
|
||||
.mockImplementationOnce(() => {
|
||||
return 'token';
|
||||
});
|
||||
return expect(c.connect('email', 'password'))
|
||||
.rejects.toBe(ERROR_TYPE.CONNECTION_ERROR);
|
||||
jest.spyOn(global, 'fetch').mockImplementationOnce(() => {
|
||||
return Promise.resolve({
|
||||
json: () => {
|
||||
return {
|
||||
error: ERROR_TYPE.SUCCESS,
|
||||
data: {coucou: 'toi'},
|
||||
};
|
||||
},
|
||||
});
|
||||
});
|
||||
return expect(
|
||||
c.authenticatedRequest('https://www.amicale-insat.fr/api/token/check'),
|
||||
).resolves.toStrictEqual({coucou: 'toi'});
|
||||
});
|
||||
|
||||
|
||||
test("authenticatedRequest success", () => {
|
||||
jest.spyOn(ConnectionManager.prototype, 'getToken').mockImplementationOnce(() => {
|
||||
return 'token';
|
||||
test('authenticatedRequest error wrong token', () => {
|
||||
jest
|
||||
.spyOn(ConnectionManager.prototype, 'getToken')
|
||||
.mockImplementationOnce(() => {
|
||||
return 'token';
|
||||
});
|
||||
jest.spyOn(global, 'fetch').mockImplementationOnce(() => {
|
||||
return Promise.resolve({
|
||||
json: () => {
|
||||
return {
|
||||
error: ERROR_TYPE.SUCCESS,
|
||||
data: {coucou: 'toi'}
|
||||
};
|
||||
},
|
||||
})
|
||||
jest.spyOn(global, 'fetch').mockImplementationOnce(() => {
|
||||
return Promise.resolve({
|
||||
json: () => {
|
||||
return {
|
||||
error: ERROR_TYPE.BAD_TOKEN,
|
||||
data: {},
|
||||
};
|
||||
},
|
||||
});
|
||||
return expect(c.authenticatedRequest('https://www.amicale-insat.fr/api/token/check'))
|
||||
.resolves.toStrictEqual({coucou: 'toi'});
|
||||
});
|
||||
return expect(
|
||||
c.authenticatedRequest('https://www.amicale-insat.fr/api/token/check'),
|
||||
).rejects.toBe(ERROR_TYPE.BAD_TOKEN);
|
||||
});
|
||||
|
||||
test("authenticatedRequest error wrong token", () => {
|
||||
jest.spyOn(ConnectionManager.prototype, 'getToken').mockImplementationOnce(() => {
|
||||
return 'token';
|
||||
test('authenticatedRequest error bogus response', () => {
|
||||
jest
|
||||
.spyOn(ConnectionManager.prototype, 'getToken')
|
||||
.mockImplementationOnce(() => {
|
||||
return 'token';
|
||||
});
|
||||
jest.spyOn(global, 'fetch').mockImplementationOnce(() => {
|
||||
return Promise.resolve({
|
||||
json: () => {
|
||||
return {
|
||||
error: ERROR_TYPE.BAD_TOKEN,
|
||||
data: {}
|
||||
};
|
||||
},
|
||||
})
|
||||
jest.spyOn(global, 'fetch').mockImplementationOnce(() => {
|
||||
return Promise.resolve({
|
||||
json: () => {
|
||||
return {
|
||||
error: ERROR_TYPE.SUCCESS,
|
||||
};
|
||||
},
|
||||
});
|
||||
return expect(c.authenticatedRequest('https://www.amicale-insat.fr/api/token/check'))
|
||||
.rejects.toBe(ERROR_TYPE.BAD_TOKEN);
|
||||
});
|
||||
return expect(
|
||||
c.authenticatedRequest('https://www.amicale-insat.fr/api/token/check'),
|
||||
).rejects.toBe(ERROR_TYPE.SERVER_ERROR);
|
||||
});
|
||||
|
||||
test("authenticatedRequest error bogus response", () => {
|
||||
jest.spyOn(ConnectionManager.prototype, 'getToken').mockImplementationOnce(() => {
|
||||
return 'token';
|
||||
test('authenticatedRequest connection error', () => {
|
||||
jest
|
||||
.spyOn(ConnectionManager.prototype, 'getToken')
|
||||
.mockImplementationOnce(() => {
|
||||
return 'token';
|
||||
});
|
||||
jest.spyOn(global, 'fetch').mockImplementationOnce(() => {
|
||||
return Promise.resolve({
|
||||
json: () => {
|
||||
return {
|
||||
error: ERROR_TYPE.SUCCESS,
|
||||
};
|
||||
},
|
||||
})
|
||||
});
|
||||
return expect(c.authenticatedRequest('https://www.amicale-insat.fr/api/token/check'))
|
||||
.rejects.toBe(ERROR_TYPE.CONNECTION_ERROR);
|
||||
jest.spyOn(global, 'fetch').mockImplementationOnce(() => {
|
||||
return Promise.reject();
|
||||
});
|
||||
return expect(
|
||||
c.authenticatedRequest('https://www.amicale-insat.fr/api/token/check'),
|
||||
).rejects.toBe(ERROR_TYPE.CONNECTION_ERROR);
|
||||
});
|
||||
|
||||
test("authenticatedRequest connection error", () => {
|
||||
jest.spyOn(ConnectionManager.prototype, 'getToken').mockImplementationOnce(() => {
|
||||
return 'token';
|
||||
test('authenticatedRequest error no token', () => {
|
||||
jest
|
||||
.spyOn(ConnectionManager.prototype, 'getToken')
|
||||
.mockImplementationOnce(() => {
|
||||
return null;
|
||||
});
|
||||
jest.spyOn(global, 'fetch').mockImplementationOnce(() => {
|
||||
return Promise.reject()
|
||||
});
|
||||
return expect(c.authenticatedRequest('https://www.amicale-insat.fr/api/token/check'))
|
||||
.rejects.toBe(ERROR_TYPE.CONNECTION_ERROR);
|
||||
});
|
||||
|
||||
test("authenticatedRequest error no token", () => {
|
||||
jest.spyOn(ConnectionManager.prototype, 'getToken').mockImplementationOnce(() => {
|
||||
return null;
|
||||
});
|
||||
return expect(c.authenticatedRequest('https://www.amicale-insat.fr/api/token/check'))
|
||||
.rejects.toBe(ERROR_TYPE.UNKNOWN);
|
||||
return expect(
|
||||
c.authenticatedRequest('https://www.amicale-insat.fr/api/token/check'),
|
||||
).rejects.toBe(ERROR_TYPE.TOKEN_RETRIEVE);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,319 +1,345 @@
|
|||
/* eslint-disable */
|
||||
|
||||
import React from 'react';
|
||||
import * as EquipmentBooking from "../../src/utils/EquipmentBooking";
|
||||
import i18n from "i18n-js";
|
||||
import * as EquipmentBooking from '../../src/utils/EquipmentBooking';
|
||||
import i18n from 'i18n-js';
|
||||
|
||||
test('getISODate', () => {
|
||||
let date = new Date("2020-03-05 12:00");
|
||||
expect(EquipmentBooking.getISODate(date)).toBe("2020-03-05");
|
||||
date = new Date("2020-03-05");
|
||||
expect(EquipmentBooking.getISODate(date)).toBe("2020-03-05");
|
||||
date = new Date("2020-03-05 00:00"); // Treated as local time
|
||||
expect(EquipmentBooking.getISODate(date)).toBe("2020-03-04"); // Treated as UTC
|
||||
let date = new Date('2020-03-05 12:00');
|
||||
expect(EquipmentBooking.getISODate(date)).toBe('2020-03-05');
|
||||
date = new Date('2020-03-05');
|
||||
expect(EquipmentBooking.getISODate(date)).toBe('2020-03-05');
|
||||
date = new Date('2020-03-05 00:00'); // Treated as local time
|
||||
expect(EquipmentBooking.getISODate(date)).toBe('2020-03-04'); // Treated as UTC
|
||||
});
|
||||
|
||||
test('getCurrentDay', () => {
|
||||
jest.spyOn(Date, 'now')
|
||||
.mockImplementation(() =>
|
||||
new Date('2020-01-14 14:50:35').getTime()
|
||||
);
|
||||
expect(EquipmentBooking.getCurrentDay().getTime()).toBe(new Date("2020-01-14").getTime());
|
||||
jest
|
||||
.spyOn(Date, 'now')
|
||||
.mockImplementation(() => new Date('2020-01-14 14:50:35').getTime());
|
||||
expect(EquipmentBooking.getCurrentDay().getTime()).toBe(
|
||||
new Date('2020-01-14').getTime(),
|
||||
);
|
||||
});
|
||||
|
||||
test('isEquipmentAvailable', () => {
|
||||
jest.spyOn(Date, 'now')
|
||||
.mockImplementation(() =>
|
||||
new Date('2020-07-09').getTime()
|
||||
);
|
||||
let testDevice = {
|
||||
id: 1,
|
||||
name: "Petit barbecue",
|
||||
caution: 100,
|
||||
booked_at: [{begin: "2020-07-07", end: "2020-07-10"}]
|
||||
};
|
||||
expect(EquipmentBooking.isEquipmentAvailable(testDevice)).toBeFalse();
|
||||
jest
|
||||
.spyOn(Date, 'now')
|
||||
.mockImplementation(() => new Date('2020-07-09').getTime());
|
||||
let testDevice = {
|
||||
id: 1,
|
||||
name: 'Petit barbecue',
|
||||
caution: 100,
|
||||
booked_at: [{begin: '2020-07-07', end: '2020-07-10'}],
|
||||
};
|
||||
expect(EquipmentBooking.isEquipmentAvailable(testDevice)).toBeFalse();
|
||||
|
||||
testDevice.booked_at = [{begin: "2020-07-07", end: "2020-07-09"}];
|
||||
expect(EquipmentBooking.isEquipmentAvailable(testDevice)).toBeFalse();
|
||||
testDevice.booked_at = [{begin: '2020-07-07', end: '2020-07-09'}];
|
||||
expect(EquipmentBooking.isEquipmentAvailable(testDevice)).toBeFalse();
|
||||
|
||||
testDevice.booked_at = [{begin: "2020-07-09", end: "2020-07-10"}];
|
||||
expect(EquipmentBooking.isEquipmentAvailable(testDevice)).toBeFalse();
|
||||
testDevice.booked_at = [{begin: '2020-07-09', end: '2020-07-10'}];
|
||||
expect(EquipmentBooking.isEquipmentAvailable(testDevice)).toBeFalse();
|
||||
|
||||
testDevice.booked_at = [
|
||||
{begin: "2020-07-07", end: "2020-07-8"},
|
||||
{begin: "2020-07-10", end: "2020-07-12"},
|
||||
];
|
||||
expect(EquipmentBooking.isEquipmentAvailable(testDevice)).toBeTrue();
|
||||
testDevice.booked_at = [
|
||||
{begin: '2020-07-07', end: '2020-07-8'},
|
||||
{begin: '2020-07-10', end: '2020-07-12'},
|
||||
];
|
||||
expect(EquipmentBooking.isEquipmentAvailable(testDevice)).toBeTrue();
|
||||
});
|
||||
|
||||
test('getFirstEquipmentAvailability', () => {
|
||||
jest.spyOn(Date, 'now')
|
||||
.mockImplementation(() =>
|
||||
new Date('2020-07-09').getTime()
|
||||
);
|
||||
let testDevice = {
|
||||
id: 1,
|
||||
name: "Petit barbecue",
|
||||
caution: 100,
|
||||
booked_at: [{begin: "2020-07-07", end: "2020-07-10"}]
|
||||
};
|
||||
expect(EquipmentBooking.getFirstEquipmentAvailability(testDevice).getTime()).toBe(new Date("2020-07-11").getTime());
|
||||
testDevice.booked_at = [{begin: "2020-07-07", end: "2020-07-09"}];
|
||||
expect(EquipmentBooking.getFirstEquipmentAvailability(testDevice).getTime()).toBe(new Date("2020-07-10").getTime());
|
||||
testDevice.booked_at = [
|
||||
{begin: "2020-07-07", end: "2020-07-09"},
|
||||
{begin: "2020-07-10", end: "2020-07-16"},
|
||||
];
|
||||
expect(EquipmentBooking.getFirstEquipmentAvailability(testDevice).getTime()).toBe(new Date("2020-07-17").getTime());
|
||||
testDevice.booked_at = [
|
||||
{begin: "2020-07-07", end: "2020-07-09"},
|
||||
{begin: "2020-07-10", end: "2020-07-12"},
|
||||
{begin: "2020-07-14", end: "2020-07-16"},
|
||||
];
|
||||
expect(EquipmentBooking.getFirstEquipmentAvailability(testDevice).getTime()).toBe(new Date("2020-07-13").getTime());
|
||||
jest
|
||||
.spyOn(Date, 'now')
|
||||
.mockImplementation(() => new Date('2020-07-09').getTime());
|
||||
let testDevice = {
|
||||
id: 1,
|
||||
name: 'Petit barbecue',
|
||||
caution: 100,
|
||||
booked_at: [{begin: '2020-07-07', end: '2020-07-10'}],
|
||||
};
|
||||
expect(
|
||||
EquipmentBooking.getFirstEquipmentAvailability(testDevice).getTime(),
|
||||
).toBe(new Date('2020-07-11').getTime());
|
||||
testDevice.booked_at = [{begin: '2020-07-07', end: '2020-07-09'}];
|
||||
expect(
|
||||
EquipmentBooking.getFirstEquipmentAvailability(testDevice).getTime(),
|
||||
).toBe(new Date('2020-07-10').getTime());
|
||||
testDevice.booked_at = [
|
||||
{begin: '2020-07-07', end: '2020-07-09'},
|
||||
{begin: '2020-07-10', end: '2020-07-16'},
|
||||
];
|
||||
expect(
|
||||
EquipmentBooking.getFirstEquipmentAvailability(testDevice).getTime(),
|
||||
).toBe(new Date('2020-07-17').getTime());
|
||||
testDevice.booked_at = [
|
||||
{begin: '2020-07-07', end: '2020-07-09'},
|
||||
{begin: '2020-07-10', end: '2020-07-12'},
|
||||
{begin: '2020-07-14', end: '2020-07-16'},
|
||||
];
|
||||
expect(
|
||||
EquipmentBooking.getFirstEquipmentAvailability(testDevice).getTime(),
|
||||
).toBe(new Date('2020-07-13').getTime());
|
||||
});
|
||||
|
||||
test('getRelativeDateString', () => {
|
||||
jest.spyOn(Date, 'now')
|
||||
.mockImplementation(() =>
|
||||
new Date('2020-07-09').getTime()
|
||||
);
|
||||
jest.spyOn(i18n, 't')
|
||||
.mockImplementation((translationString: string) => {
|
||||
const prefix = "screens.equipment.";
|
||||
if (translationString === prefix + "otherYear")
|
||||
return "0";
|
||||
else if (translationString === prefix + "otherMonth")
|
||||
return "1";
|
||||
else if (translationString === prefix + "thisMonth")
|
||||
return "2";
|
||||
else if (translationString === prefix + "tomorrow")
|
||||
return "3";
|
||||
else if (translationString === prefix + "today")
|
||||
return "4";
|
||||
else
|
||||
return null;
|
||||
}
|
||||
);
|
||||
expect(EquipmentBooking.getRelativeDateString(new Date("2020-07-09"))).toBe("4");
|
||||
expect(EquipmentBooking.getRelativeDateString(new Date("2020-07-10"))).toBe("3");
|
||||
expect(EquipmentBooking.getRelativeDateString(new Date("2020-07-11"))).toBe("2");
|
||||
expect(EquipmentBooking.getRelativeDateString(new Date("2020-07-30"))).toBe("2");
|
||||
expect(EquipmentBooking.getRelativeDateString(new Date("2020-08-30"))).toBe("1");
|
||||
expect(EquipmentBooking.getRelativeDateString(new Date("2020-11-10"))).toBe("1");
|
||||
expect(EquipmentBooking.getRelativeDateString(new Date("2021-11-10"))).toBe("0");
|
||||
jest
|
||||
.spyOn(Date, 'now')
|
||||
.mockImplementation(() => new Date('2020-07-09').getTime());
|
||||
jest.spyOn(i18n, 't').mockImplementation((translationString: string) => {
|
||||
const prefix = 'screens.equipment.';
|
||||
if (translationString === prefix + 'otherYear') return '0';
|
||||
else if (translationString === prefix + 'otherMonth') return '1';
|
||||
else if (translationString === prefix + 'thisMonth') return '2';
|
||||
else if (translationString === prefix + 'tomorrow') return '3';
|
||||
else if (translationString === prefix + 'today') return '4';
|
||||
else return null;
|
||||
});
|
||||
expect(EquipmentBooking.getRelativeDateString(new Date('2020-07-09'))).toBe(
|
||||
'4',
|
||||
);
|
||||
expect(EquipmentBooking.getRelativeDateString(new Date('2020-07-10'))).toBe(
|
||||
'3',
|
||||
);
|
||||
expect(EquipmentBooking.getRelativeDateString(new Date('2020-07-11'))).toBe(
|
||||
'2',
|
||||
);
|
||||
expect(EquipmentBooking.getRelativeDateString(new Date('2020-07-30'))).toBe(
|
||||
'2',
|
||||
);
|
||||
expect(EquipmentBooking.getRelativeDateString(new Date('2020-08-30'))).toBe(
|
||||
'1',
|
||||
);
|
||||
expect(EquipmentBooking.getRelativeDateString(new Date('2020-11-10'))).toBe(
|
||||
'1',
|
||||
);
|
||||
expect(EquipmentBooking.getRelativeDateString(new Date('2021-11-10'))).toBe(
|
||||
'0',
|
||||
);
|
||||
});
|
||||
|
||||
test('getValidRange', () => {
|
||||
let testDevice = {
|
||||
id: 1,
|
||||
name: "Petit barbecue",
|
||||
caution: 100,
|
||||
booked_at: [{begin: "2020-07-07", end: "2020-07-10"}]
|
||||
};
|
||||
let start = new Date("2020-07-11");
|
||||
let end = new Date("2020-07-15");
|
||||
let result = [
|
||||
"2020-07-11",
|
||||
"2020-07-12",
|
||||
"2020-07-13",
|
||||
"2020-07-14",
|
||||
"2020-07-15",
|
||||
];
|
||||
expect(EquipmentBooking.getValidRange(start, end, testDevice)).toStrictEqual(result);
|
||||
testDevice.booked_at = [
|
||||
{begin: "2020-07-07", end: "2020-07-10"},
|
||||
{begin: "2020-07-13", end: "2020-07-15"},
|
||||
];
|
||||
result = [
|
||||
"2020-07-11",
|
||||
"2020-07-12",
|
||||
];
|
||||
expect(EquipmentBooking.getValidRange(start, end, testDevice)).toStrictEqual(result);
|
||||
let testDevice = {
|
||||
id: 1,
|
||||
name: 'Petit barbecue',
|
||||
caution: 100,
|
||||
booked_at: [{begin: '2020-07-07', end: '2020-07-10'}],
|
||||
};
|
||||
let start = new Date('2020-07-11');
|
||||
let end = new Date('2020-07-15');
|
||||
let result = [
|
||||
'2020-07-11',
|
||||
'2020-07-12',
|
||||
'2020-07-13',
|
||||
'2020-07-14',
|
||||
'2020-07-15',
|
||||
];
|
||||
expect(EquipmentBooking.getValidRange(start, end, testDevice)).toStrictEqual(
|
||||
result,
|
||||
);
|
||||
testDevice.booked_at = [
|
||||
{begin: '2020-07-07', end: '2020-07-10'},
|
||||
{begin: '2020-07-13', end: '2020-07-15'},
|
||||
];
|
||||
result = ['2020-07-11', '2020-07-12'];
|
||||
expect(EquipmentBooking.getValidRange(start, end, testDevice)).toStrictEqual(
|
||||
result,
|
||||
);
|
||||
|
||||
testDevice.booked_at = [{begin: "2020-07-12", end: "2020-07-13"}];
|
||||
result = ["2020-07-11"];
|
||||
expect(EquipmentBooking.getValidRange(start, end, testDevice)).toStrictEqual(result);
|
||||
testDevice.booked_at = [{begin: "2020-07-07", end: "2020-07-12"},];
|
||||
result = [
|
||||
"2020-07-13",
|
||||
"2020-07-14",
|
||||
"2020-07-15",
|
||||
];
|
||||
expect(EquipmentBooking.getValidRange(end, start, testDevice)).toStrictEqual(result);
|
||||
start = new Date("2020-07-14");
|
||||
end = new Date("2020-07-14");
|
||||
result = [
|
||||
"2020-07-14",
|
||||
];
|
||||
expect(EquipmentBooking.getValidRange(start, start, testDevice)).toStrictEqual(result);
|
||||
expect(EquipmentBooking.getValidRange(end, start, testDevice)).toStrictEqual(result);
|
||||
expect(EquipmentBooking.getValidRange(start, end, null)).toStrictEqual(result);
|
||||
testDevice.booked_at = [{begin: '2020-07-12', end: '2020-07-13'}];
|
||||
result = ['2020-07-11'];
|
||||
expect(EquipmentBooking.getValidRange(start, end, testDevice)).toStrictEqual(
|
||||
result,
|
||||
);
|
||||
testDevice.booked_at = [{begin: '2020-07-07', end: '2020-07-12'}];
|
||||
result = ['2020-07-13', '2020-07-14', '2020-07-15'];
|
||||
expect(EquipmentBooking.getValidRange(end, start, testDevice)).toStrictEqual(
|
||||
result,
|
||||
);
|
||||
start = new Date('2020-07-14');
|
||||
end = new Date('2020-07-14');
|
||||
result = ['2020-07-14'];
|
||||
expect(
|
||||
EquipmentBooking.getValidRange(start, start, testDevice),
|
||||
).toStrictEqual(result);
|
||||
expect(EquipmentBooking.getValidRange(end, start, testDevice)).toStrictEqual(
|
||||
result,
|
||||
);
|
||||
expect(EquipmentBooking.getValidRange(start, end, null)).toStrictEqual(
|
||||
result,
|
||||
);
|
||||
|
||||
start = new Date("2020-07-14");
|
||||
end = new Date("2020-07-17");
|
||||
result = [
|
||||
"2020-07-14",
|
||||
"2020-07-15",
|
||||
"2020-07-16",
|
||||
"2020-07-17",
|
||||
];
|
||||
expect(EquipmentBooking.getValidRange(start, end, null)).toStrictEqual(result);
|
||||
start = new Date('2020-07-14');
|
||||
end = new Date('2020-07-17');
|
||||
result = ['2020-07-14', '2020-07-15', '2020-07-16', '2020-07-17'];
|
||||
expect(EquipmentBooking.getValidRange(start, end, null)).toStrictEqual(
|
||||
result,
|
||||
);
|
||||
|
||||
testDevice.booked_at = [{begin: "2020-07-17", end: "2020-07-17"}];
|
||||
result = [
|
||||
"2020-07-14",
|
||||
"2020-07-15",
|
||||
"2020-07-16",
|
||||
];
|
||||
expect(EquipmentBooking.getValidRange(start, end, testDevice)).toStrictEqual(result);
|
||||
testDevice.booked_at = [{begin: '2020-07-17', end: '2020-07-17'}];
|
||||
result = ['2020-07-14', '2020-07-15', '2020-07-16'];
|
||||
expect(EquipmentBooking.getValidRange(start, end, testDevice)).toStrictEqual(
|
||||
result,
|
||||
);
|
||||
|
||||
testDevice.booked_at = [
|
||||
{begin: "2020-07-12", end: "2020-07-13"},
|
||||
{begin: "2020-07-15", end: "2020-07-20"},
|
||||
];
|
||||
start = new Date("2020-07-11");
|
||||
end = new Date("2020-07-23");
|
||||
result = [
|
||||
"2020-07-21",
|
||||
"2020-07-22",
|
||||
"2020-07-23",
|
||||
];
|
||||
expect(EquipmentBooking.getValidRange(end, start, testDevice)).toStrictEqual(result);
|
||||
testDevice.booked_at = [
|
||||
{begin: '2020-07-12', end: '2020-07-13'},
|
||||
{begin: '2020-07-15', end: '2020-07-20'},
|
||||
];
|
||||
start = new Date('2020-07-11');
|
||||
end = new Date('2020-07-23');
|
||||
result = ['2020-07-21', '2020-07-22', '2020-07-23'];
|
||||
expect(EquipmentBooking.getValidRange(end, start, testDevice)).toStrictEqual(
|
||||
result,
|
||||
);
|
||||
});
|
||||
|
||||
test('generateMarkedDates', () => {
|
||||
let theme = {
|
||||
colors: {
|
||||
primary: "primary",
|
||||
danger: "primary",
|
||||
textDisabled: "primary",
|
||||
}
|
||||
}
|
||||
let testDevice = {
|
||||
id: 1,
|
||||
name: "Petit barbecue",
|
||||
caution: 100,
|
||||
booked_at: [{begin: "2020-07-07", end: "2020-07-10"}]
|
||||
};
|
||||
let start = new Date("2020-07-11");
|
||||
let end = new Date("2020-07-13");
|
||||
let range = EquipmentBooking.getValidRange(start, end, testDevice);
|
||||
let result = {
|
||||
"2020-07-11": {
|
||||
startingDay: true,
|
||||
endingDay: false,
|
||||
color: theme.colors.primary
|
||||
},
|
||||
"2020-07-12": {
|
||||
startingDay: false,
|
||||
endingDay: false,
|
||||
color: theme.colors.danger
|
||||
},
|
||||
"2020-07-13": {
|
||||
startingDay: false,
|
||||
endingDay: true,
|
||||
color: theme.colors.primary
|
||||
},
|
||||
};
|
||||
expect(EquipmentBooking.generateMarkedDates(true, theme, range)).toStrictEqual(result);
|
||||
result = {
|
||||
"2020-07-11": {
|
||||
startingDay: true,
|
||||
endingDay: false,
|
||||
color: theme.colors.textDisabled
|
||||
},
|
||||
"2020-07-12": {
|
||||
startingDay: false,
|
||||
endingDay: false,
|
||||
color: theme.colors.textDisabled
|
||||
},
|
||||
"2020-07-13": {
|
||||
startingDay: false,
|
||||
endingDay: true,
|
||||
color: theme.colors.textDisabled
|
||||
},
|
||||
};
|
||||
expect(EquipmentBooking.generateMarkedDates(false, theme, range)).toStrictEqual(result);
|
||||
result = {
|
||||
"2020-07-11": {
|
||||
startingDay: true,
|
||||
endingDay: false,
|
||||
color: theme.colors.textDisabled
|
||||
},
|
||||
"2020-07-12": {
|
||||
startingDay: false,
|
||||
endingDay: false,
|
||||
color: theme.colors.textDisabled
|
||||
},
|
||||
"2020-07-13": {
|
||||
startingDay: false,
|
||||
endingDay: true,
|
||||
color: theme.colors.textDisabled
|
||||
},
|
||||
};
|
||||
range = EquipmentBooking.getValidRange(end, start, testDevice);
|
||||
expect(EquipmentBooking.generateMarkedDates(false, theme, range)).toStrictEqual(result);
|
||||
let theme = {
|
||||
colors: {
|
||||
primary: 'primary',
|
||||
danger: 'primary',
|
||||
textDisabled: 'primary',
|
||||
},
|
||||
};
|
||||
let testDevice = {
|
||||
id: 1,
|
||||
name: 'Petit barbecue',
|
||||
caution: 100,
|
||||
booked_at: [{begin: '2020-07-07', end: '2020-07-10'}],
|
||||
};
|
||||
let start = new Date('2020-07-11');
|
||||
let end = new Date('2020-07-13');
|
||||
let range = EquipmentBooking.getValidRange(start, end, testDevice);
|
||||
let result = {
|
||||
'2020-07-11': {
|
||||
startingDay: true,
|
||||
endingDay: false,
|
||||
color: theme.colors.primary,
|
||||
},
|
||||
'2020-07-12': {
|
||||
startingDay: false,
|
||||
endingDay: false,
|
||||
color: theme.colors.danger,
|
||||
},
|
||||
'2020-07-13': {
|
||||
startingDay: false,
|
||||
endingDay: true,
|
||||
color: theme.colors.primary,
|
||||
},
|
||||
};
|
||||
expect(
|
||||
EquipmentBooking.generateMarkedDates(true, theme, range),
|
||||
).toStrictEqual(result);
|
||||
result = {
|
||||
'2020-07-11': {
|
||||
startingDay: true,
|
||||
endingDay: false,
|
||||
color: theme.colors.textDisabled,
|
||||
},
|
||||
'2020-07-12': {
|
||||
startingDay: false,
|
||||
endingDay: false,
|
||||
color: theme.colors.textDisabled,
|
||||
},
|
||||
'2020-07-13': {
|
||||
startingDay: false,
|
||||
endingDay: true,
|
||||
color: theme.colors.textDisabled,
|
||||
},
|
||||
};
|
||||
expect(
|
||||
EquipmentBooking.generateMarkedDates(false, theme, range),
|
||||
).toStrictEqual(result);
|
||||
result = {
|
||||
'2020-07-11': {
|
||||
startingDay: true,
|
||||
endingDay: false,
|
||||
color: theme.colors.textDisabled,
|
||||
},
|
||||
'2020-07-12': {
|
||||
startingDay: false,
|
||||
endingDay: false,
|
||||
color: theme.colors.textDisabled,
|
||||
},
|
||||
'2020-07-13': {
|
||||
startingDay: false,
|
||||
endingDay: true,
|
||||
color: theme.colors.textDisabled,
|
||||
},
|
||||
};
|
||||
range = EquipmentBooking.getValidRange(end, start, testDevice);
|
||||
expect(
|
||||
EquipmentBooking.generateMarkedDates(false, theme, range),
|
||||
).toStrictEqual(result);
|
||||
|
||||
testDevice.booked_at = [{begin: "2020-07-13", end: "2020-07-15"},];
|
||||
result = {
|
||||
"2020-07-11": {
|
||||
startingDay: true,
|
||||
endingDay: false,
|
||||
color: theme.colors.primary
|
||||
},
|
||||
"2020-07-12": {
|
||||
startingDay: false,
|
||||
endingDay: true,
|
||||
color: theme.colors.primary
|
||||
},
|
||||
};
|
||||
range = EquipmentBooking.getValidRange(start, end, testDevice);
|
||||
expect(EquipmentBooking.generateMarkedDates(true, theme, range)).toStrictEqual(result);
|
||||
testDevice.booked_at = [{begin: '2020-07-13', end: '2020-07-15'}];
|
||||
result = {
|
||||
'2020-07-11': {
|
||||
startingDay: true,
|
||||
endingDay: false,
|
||||
color: theme.colors.primary,
|
||||
},
|
||||
'2020-07-12': {
|
||||
startingDay: false,
|
||||
endingDay: true,
|
||||
color: theme.colors.primary,
|
||||
},
|
||||
};
|
||||
range = EquipmentBooking.getValidRange(start, end, testDevice);
|
||||
expect(
|
||||
EquipmentBooking.generateMarkedDates(true, theme, range),
|
||||
).toStrictEqual(result);
|
||||
|
||||
testDevice.booked_at = [{begin: "2020-07-12", end: "2020-07-13"},];
|
||||
result = {
|
||||
"2020-07-11": {
|
||||
startingDay: true,
|
||||
endingDay: true,
|
||||
color: theme.colors.primary
|
||||
},
|
||||
};
|
||||
range = EquipmentBooking.getValidRange(start, end, testDevice);
|
||||
expect(EquipmentBooking.generateMarkedDates(true, theme, range)).toStrictEqual(result);
|
||||
testDevice.booked_at = [{begin: '2020-07-12', end: '2020-07-13'}];
|
||||
result = {
|
||||
'2020-07-11': {
|
||||
startingDay: true,
|
||||
endingDay: true,
|
||||
color: theme.colors.primary,
|
||||
},
|
||||
};
|
||||
range = EquipmentBooking.getValidRange(start, end, testDevice);
|
||||
expect(
|
||||
EquipmentBooking.generateMarkedDates(true, theme, range),
|
||||
).toStrictEqual(result);
|
||||
|
||||
testDevice.booked_at = [
|
||||
{begin: "2020-07-12", end: "2020-07-13"},
|
||||
{begin: "2020-07-15", end: "2020-07-20"},
|
||||
];
|
||||
start = new Date("2020-07-11");
|
||||
end = new Date("2020-07-23");
|
||||
result = {
|
||||
"2020-07-11": {
|
||||
startingDay: true,
|
||||
endingDay: true,
|
||||
color: theme.colors.primary
|
||||
},
|
||||
};
|
||||
range = EquipmentBooking.getValidRange(start, end, testDevice);
|
||||
expect(EquipmentBooking.generateMarkedDates(true, theme, range)).toStrictEqual(result);
|
||||
testDevice.booked_at = [
|
||||
{begin: '2020-07-12', end: '2020-07-13'},
|
||||
{begin: '2020-07-15', end: '2020-07-20'},
|
||||
];
|
||||
start = new Date('2020-07-11');
|
||||
end = new Date('2020-07-23');
|
||||
result = {
|
||||
'2020-07-11': {
|
||||
startingDay: true,
|
||||
endingDay: true,
|
||||
color: theme.colors.primary,
|
||||
},
|
||||
};
|
||||
range = EquipmentBooking.getValidRange(start, end, testDevice);
|
||||
expect(
|
||||
EquipmentBooking.generateMarkedDates(true, theme, range),
|
||||
).toStrictEqual(result);
|
||||
|
||||
result = {
|
||||
"2020-07-21": {
|
||||
startingDay: true,
|
||||
endingDay: false,
|
||||
color: theme.colors.primary
|
||||
},
|
||||
"2020-07-22": {
|
||||
startingDay: false,
|
||||
endingDay: false,
|
||||
color: theme.colors.danger
|
||||
},
|
||||
"2020-07-23": {
|
||||
startingDay: false,
|
||||
endingDay: true,
|
||||
color: theme.colors.primary
|
||||
},
|
||||
};
|
||||
range = EquipmentBooking.getValidRange(end, start, testDevice);
|
||||
expect(EquipmentBooking.generateMarkedDates(true, theme, range)).toStrictEqual(result);
|
||||
result = {
|
||||
'2020-07-21': {
|
||||
startingDay: true,
|
||||
endingDay: false,
|
||||
color: theme.colors.primary,
|
||||
},
|
||||
'2020-07-22': {
|
||||
startingDay: false,
|
||||
endingDay: false,
|
||||
color: theme.colors.danger,
|
||||
},
|
||||
'2020-07-23': {
|
||||
startingDay: false,
|
||||
endingDay: true,
|
||||
color: theme.colors.primary,
|
||||
},
|
||||
};
|
||||
range = EquipmentBooking.getValidRange(end, start, testDevice);
|
||||
expect(
|
||||
EquipmentBooking.generateMarkedDates(true, theme, range),
|
||||
).toStrictEqual(result);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,210 +1,222 @@
|
|||
/* eslint-disable */
|
||||
|
||||
import React from 'react';
|
||||
import * as Planning from "../../src/utils/Planning";
|
||||
import * as Planning from '../../src/utils/Planning';
|
||||
|
||||
test('isDescriptionEmpty', () => {
|
||||
expect(Planning.isDescriptionEmpty("")).toBeTrue();
|
||||
expect(Planning.isDescriptionEmpty(" ")).toBeTrue();
|
||||
// noinspection CheckTagEmptyBody
|
||||
expect(Planning.isDescriptionEmpty("<p></p>")).toBeTrue();
|
||||
expect(Planning.isDescriptionEmpty("<p> </p>")).toBeTrue();
|
||||
expect(Planning.isDescriptionEmpty("<p><br></p>")).toBeTrue();
|
||||
expect(Planning.isDescriptionEmpty("<p><br></p><p><br></p>")).toBeTrue();
|
||||
expect(Planning.isDescriptionEmpty("<p><br><br><br></p>")).toBeTrue();
|
||||
expect(Planning.isDescriptionEmpty("<p><br>")).toBeTrue();
|
||||
expect(Planning.isDescriptionEmpty(null)).toBeTrue();
|
||||
expect(Planning.isDescriptionEmpty(undefined)).toBeTrue();
|
||||
expect(Planning.isDescriptionEmpty("coucou")).toBeFalse();
|
||||
expect(Planning.isDescriptionEmpty("<p>coucou</p>")).toBeFalse();
|
||||
expect(Planning.isDescriptionEmpty('')).toBeTrue();
|
||||
expect(Planning.isDescriptionEmpty(' ')).toBeTrue();
|
||||
// noinspection CheckTagEmptyBody
|
||||
expect(Planning.isDescriptionEmpty('<p></p>')).toBeTrue();
|
||||
expect(Planning.isDescriptionEmpty('<p> </p>')).toBeTrue();
|
||||
expect(Planning.isDescriptionEmpty('<p><br></p>')).toBeTrue();
|
||||
expect(Planning.isDescriptionEmpty('<p><br></p><p><br></p>')).toBeTrue();
|
||||
expect(Planning.isDescriptionEmpty('<p><br><br><br></p>')).toBeTrue();
|
||||
expect(Planning.isDescriptionEmpty('<p><br>')).toBeTrue();
|
||||
expect(Planning.isDescriptionEmpty(null)).toBeTrue();
|
||||
expect(Planning.isDescriptionEmpty(undefined)).toBeTrue();
|
||||
expect(Planning.isDescriptionEmpty('coucou')).toBeFalse();
|
||||
expect(Planning.isDescriptionEmpty('<p>coucou</p>')).toBeFalse();
|
||||
});
|
||||
|
||||
test('isEventDateStringFormatValid', () => {
|
||||
expect(Planning.isEventDateStringFormatValid("2020-03-21 09:00")).toBeTrue();
|
||||
expect(Planning.isEventDateStringFormatValid("3214-64-12 01:16")).toBeTrue();
|
||||
expect(Planning.isEventDateStringFormatValid('2020-03-21 09:00')).toBeTrue();
|
||||
expect(Planning.isEventDateStringFormatValid('3214-64-12 01:16')).toBeTrue();
|
||||
|
||||
expect(Planning.isEventDateStringFormatValid("3214-64-12 01:16:00")).toBeFalse();
|
||||
expect(Planning.isEventDateStringFormatValid("3214-64-12 1:16")).toBeFalse();
|
||||
expect(Planning.isEventDateStringFormatValid("3214-f4-12 01:16")).toBeFalse();
|
||||
expect(Planning.isEventDateStringFormatValid("sqdd 09:00")).toBeFalse();
|
||||
expect(Planning.isEventDateStringFormatValid("2020-03-21")).toBeFalse();
|
||||
expect(Planning.isEventDateStringFormatValid("2020-03-21 truc")).toBeFalse();
|
||||
expect(Planning.isEventDateStringFormatValid("3214-64-12 1:16:65")).toBeFalse();
|
||||
expect(Planning.isEventDateStringFormatValid("garbage")).toBeFalse();
|
||||
expect(Planning.isEventDateStringFormatValid("")).toBeFalse();
|
||||
expect(Planning.isEventDateStringFormatValid(undefined)).toBeFalse();
|
||||
expect(Planning.isEventDateStringFormatValid(null)).toBeFalse();
|
||||
expect(
|
||||
Planning.isEventDateStringFormatValid('3214-64-12 01:16:00'),
|
||||
).toBeFalse();
|
||||
expect(Planning.isEventDateStringFormatValid('3214-64-12 1:16')).toBeFalse();
|
||||
expect(Planning.isEventDateStringFormatValid('3214-f4-12 01:16')).toBeFalse();
|
||||
expect(Planning.isEventDateStringFormatValid('sqdd 09:00')).toBeFalse();
|
||||
expect(Planning.isEventDateStringFormatValid('2020-03-21')).toBeFalse();
|
||||
expect(Planning.isEventDateStringFormatValid('2020-03-21 truc')).toBeFalse();
|
||||
expect(
|
||||
Planning.isEventDateStringFormatValid('3214-64-12 1:16:65'),
|
||||
).toBeFalse();
|
||||
expect(Planning.isEventDateStringFormatValid('garbage')).toBeFalse();
|
||||
expect(Planning.isEventDateStringFormatValid('')).toBeFalse();
|
||||
expect(Planning.isEventDateStringFormatValid(undefined)).toBeFalse();
|
||||
expect(Planning.isEventDateStringFormatValid(null)).toBeFalse();
|
||||
});
|
||||
|
||||
test('stringToDate', () => {
|
||||
let testDate = new Date();
|
||||
expect(Planning.stringToDate(undefined)).toBeNull();
|
||||
expect(Planning.stringToDate("")).toBeNull();
|
||||
expect(Planning.stringToDate("garbage")).toBeNull();
|
||||
expect(Planning.stringToDate("2020-03-21")).toBeNull();
|
||||
expect(Planning.stringToDate("09:00:00")).toBeNull();
|
||||
expect(Planning.stringToDate("2020-03-21 09:g0")).toBeNull();
|
||||
expect(Planning.stringToDate("2020-03-21 09:g0:")).toBeNull();
|
||||
testDate.setFullYear(2020, 2, 21);
|
||||
testDate.setHours(9, 0, 0, 0);
|
||||
expect(Planning.stringToDate("2020-03-21 09:00")).toEqual(testDate);
|
||||
testDate.setFullYear(2020, 0, 31);
|
||||
testDate.setHours(18, 30, 0, 0);
|
||||
expect(Planning.stringToDate("2020-01-31 18:30")).toEqual(testDate);
|
||||
testDate.setFullYear(2020, 50, 50);
|
||||
testDate.setHours(65, 65, 0, 0);
|
||||
expect(Planning.stringToDate("2020-51-50 65:65")).toEqual(testDate);
|
||||
let testDate = new Date();
|
||||
expect(Planning.stringToDate(undefined)).toBeNull();
|
||||
expect(Planning.stringToDate('')).toBeNull();
|
||||
expect(Planning.stringToDate('garbage')).toBeNull();
|
||||
expect(Planning.stringToDate('2020-03-21')).toBeNull();
|
||||
expect(Planning.stringToDate('09:00:00')).toBeNull();
|
||||
expect(Planning.stringToDate('2020-03-21 09:g0')).toBeNull();
|
||||
expect(Planning.stringToDate('2020-03-21 09:g0:')).toBeNull();
|
||||
testDate.setFullYear(2020, 2, 21);
|
||||
testDate.setHours(9, 0, 0, 0);
|
||||
expect(Planning.stringToDate('2020-03-21 09:00')).toEqual(testDate);
|
||||
testDate.setFullYear(2020, 0, 31);
|
||||
testDate.setHours(18, 30, 0, 0);
|
||||
expect(Planning.stringToDate('2020-01-31 18:30')).toEqual(testDate);
|
||||
testDate.setFullYear(2020, 50, 50);
|
||||
testDate.setHours(65, 65, 0, 0);
|
||||
expect(Planning.stringToDate('2020-51-50 65:65')).toEqual(testDate);
|
||||
});
|
||||
|
||||
test('getFormattedEventTime', () => {
|
||||
expect(Planning.getFormattedEventTime(null, null))
|
||||
.toBe('/ - /');
|
||||
expect(Planning.getFormattedEventTime(undefined, undefined))
|
||||
.toBe('/ - /');
|
||||
expect(Planning.getFormattedEventTime("20:30", "23:00"))
|
||||
.toBe('/ - /');
|
||||
expect(Planning.getFormattedEventTime("2020-03-30", "2020-03-31"))
|
||||
.toBe('/ - /');
|
||||
expect(Planning.getFormattedEventTime(null, null)).toBe('/ - /');
|
||||
expect(Planning.getFormattedEventTime(undefined, undefined)).toBe('/ - /');
|
||||
expect(Planning.getFormattedEventTime('20:30', '23:00')).toBe('/ - /');
|
||||
expect(Planning.getFormattedEventTime('2020-03-30', '2020-03-31')).toBe(
|
||||
'/ - /',
|
||||
);
|
||||
|
||||
|
||||
expect(Planning.getFormattedEventTime("2020-03-21 09:00", "2020-03-21 09:00"))
|
||||
.toBe('09:00');
|
||||
expect(Planning.getFormattedEventTime("2020-03-21 09:00", "2020-03-22 17:00"))
|
||||
.toBe('09:00 - 23:59');
|
||||
expect(Planning.getFormattedEventTime("2020-03-30 20:30", "2020-03-30 23:00"))
|
||||
.toBe('20:30 - 23:00');
|
||||
expect(
|
||||
Planning.getFormattedEventTime('2020-03-21 09:00', '2020-03-21 09:00'),
|
||||
).toBe('09:00');
|
||||
expect(
|
||||
Planning.getFormattedEventTime('2020-03-21 09:00', '2020-03-22 17:00'),
|
||||
).toBe('09:00 - 23:59');
|
||||
expect(
|
||||
Planning.getFormattedEventTime('2020-03-30 20:30', '2020-03-30 23:00'),
|
||||
).toBe('20:30 - 23:00');
|
||||
});
|
||||
|
||||
test('getDateOnlyString', () => {
|
||||
expect(Planning.getDateOnlyString("2020-03-21 09:00")).toBe("2020-03-21");
|
||||
expect(Planning.getDateOnlyString("2021-12-15 09:00")).toBe("2021-12-15");
|
||||
expect(Planning.getDateOnlyString("2021-12-o5 09:00")).toBeNull();
|
||||
expect(Planning.getDateOnlyString("2021-12-15 09:")).toBeNull();
|
||||
expect(Planning.getDateOnlyString("2021-12-15")).toBeNull();
|
||||
expect(Planning.getDateOnlyString("garbage")).toBeNull();
|
||||
expect(Planning.getDateOnlyString('2020-03-21 09:00')).toBe('2020-03-21');
|
||||
expect(Planning.getDateOnlyString('2021-12-15 09:00')).toBe('2021-12-15');
|
||||
expect(Planning.getDateOnlyString('2021-12-o5 09:00')).toBeNull();
|
||||
expect(Planning.getDateOnlyString('2021-12-15 09:')).toBeNull();
|
||||
expect(Planning.getDateOnlyString('2021-12-15')).toBeNull();
|
||||
expect(Planning.getDateOnlyString('garbage')).toBeNull();
|
||||
});
|
||||
|
||||
test('isEventBefore', () => {
|
||||
expect(Planning.isEventBefore(
|
||||
"2020-03-21 09:00", "2020-03-21 10:00")).toBeTrue();
|
||||
expect(Planning.isEventBefore(
|
||||
"2020-03-21 10:00", "2020-03-21 10:15")).toBeTrue();
|
||||
expect(Planning.isEventBefore(
|
||||
"2020-03-21 10:15", "2021-03-21 10:15")).toBeTrue();
|
||||
expect(Planning.isEventBefore(
|
||||
"2020-03-21 10:15", "2020-05-21 10:15")).toBeTrue();
|
||||
expect(Planning.isEventBefore(
|
||||
"2020-03-21 10:15", "2020-03-30 10:15")).toBeTrue();
|
||||
expect(
|
||||
Planning.isEventBefore('2020-03-21 09:00', '2020-03-21 10:00'),
|
||||
).toBeTrue();
|
||||
expect(
|
||||
Planning.isEventBefore('2020-03-21 10:00', '2020-03-21 10:15'),
|
||||
).toBeTrue();
|
||||
expect(
|
||||
Planning.isEventBefore('2020-03-21 10:15', '2021-03-21 10:15'),
|
||||
).toBeTrue();
|
||||
expect(
|
||||
Planning.isEventBefore('2020-03-21 10:15', '2020-05-21 10:15'),
|
||||
).toBeTrue();
|
||||
expect(
|
||||
Planning.isEventBefore('2020-03-21 10:15', '2020-03-30 10:15'),
|
||||
).toBeTrue();
|
||||
|
||||
expect(Planning.isEventBefore(
|
||||
"2020-03-21 10:00", "2020-03-21 10:00")).toBeFalse();
|
||||
expect(Planning.isEventBefore(
|
||||
"2020-03-21 10:00", "2020-03-21 09:00")).toBeFalse();
|
||||
expect(Planning.isEventBefore(
|
||||
"2020-03-21 10:15", "2020-03-21 10:00")).toBeFalse();
|
||||
expect(Planning.isEventBefore(
|
||||
"2021-03-21 10:15", "2020-03-21 10:15")).toBeFalse();
|
||||
expect(Planning.isEventBefore(
|
||||
"2020-05-21 10:15", "2020-03-21 10:15")).toBeFalse();
|
||||
expect(Planning.isEventBefore(
|
||||
"2020-03-30 10:15", "2020-03-21 10:15")).toBeFalse();
|
||||
expect(
|
||||
Planning.isEventBefore('2020-03-21 10:00', '2020-03-21 10:00'),
|
||||
).toBeFalse();
|
||||
expect(
|
||||
Planning.isEventBefore('2020-03-21 10:00', '2020-03-21 09:00'),
|
||||
).toBeFalse();
|
||||
expect(
|
||||
Planning.isEventBefore('2020-03-21 10:15', '2020-03-21 10:00'),
|
||||
).toBeFalse();
|
||||
expect(
|
||||
Planning.isEventBefore('2021-03-21 10:15', '2020-03-21 10:15'),
|
||||
).toBeFalse();
|
||||
expect(
|
||||
Planning.isEventBefore('2020-05-21 10:15', '2020-03-21 10:15'),
|
||||
).toBeFalse();
|
||||
expect(
|
||||
Planning.isEventBefore('2020-03-30 10:15', '2020-03-21 10:15'),
|
||||
).toBeFalse();
|
||||
|
||||
expect(Planning.isEventBefore(
|
||||
"garbage", "2020-03-21 10:15")).toBeFalse();
|
||||
expect(Planning.isEventBefore(
|
||||
undefined, undefined)).toBeFalse();
|
||||
expect(Planning.isEventBefore('garbage', '2020-03-21 10:15')).toBeFalse();
|
||||
expect(Planning.isEventBefore(undefined, undefined)).toBeFalse();
|
||||
});
|
||||
|
||||
test('dateToString', () => {
|
||||
let testDate = new Date();
|
||||
testDate.setFullYear(2020, 2, 21);
|
||||
testDate.setHours(9, 0, 0, 0);
|
||||
expect(Planning.dateToString(testDate)).toBe("2020-03-21 09:00");
|
||||
testDate.setFullYear(2021, 0, 12);
|
||||
testDate.setHours(9, 10, 0, 0);
|
||||
expect(Planning.dateToString(testDate)).toBe("2021-01-12 09:10");
|
||||
testDate.setFullYear(2022, 11, 31);
|
||||
testDate.setHours(9, 10, 15, 0);
|
||||
expect(Planning.dateToString(testDate)).toBe("2022-12-31 09:10");
|
||||
let testDate = new Date();
|
||||
testDate.setFullYear(2020, 2, 21);
|
||||
testDate.setHours(9, 0, 0, 0);
|
||||
expect(Planning.dateToString(testDate)).toBe('2020-03-21 09:00');
|
||||
testDate.setFullYear(2021, 0, 12);
|
||||
testDate.setHours(9, 10, 0, 0);
|
||||
expect(Planning.dateToString(testDate)).toBe('2021-01-12 09:10');
|
||||
testDate.setFullYear(2022, 11, 31);
|
||||
testDate.setHours(9, 10, 15, 0);
|
||||
expect(Planning.dateToString(testDate)).toBe('2022-12-31 09:10');
|
||||
});
|
||||
|
||||
test('generateEmptyCalendar', () => {
|
||||
jest.spyOn(Date, 'now')
|
||||
.mockImplementation(() =>
|
||||
new Date('2020-01-14T00:00:00.000Z').getTime()
|
||||
);
|
||||
let calendar = Planning.generateEmptyCalendar(1);
|
||||
expect(calendar).toHaveProperty("2020-01-14");
|
||||
expect(calendar).toHaveProperty("2020-01-20");
|
||||
expect(calendar).toHaveProperty("2020-02-10");
|
||||
expect(Object.keys(calendar).length).toBe(32);
|
||||
calendar = Planning.generateEmptyCalendar(3);
|
||||
expect(calendar).toHaveProperty("2020-01-14");
|
||||
expect(calendar).toHaveProperty("2020-01-20");
|
||||
expect(calendar).toHaveProperty("2020-02-10");
|
||||
expect(calendar).toHaveProperty("2020-02-14");
|
||||
expect(calendar).toHaveProperty("2020-03-20");
|
||||
expect(calendar).toHaveProperty("2020-04-12");
|
||||
expect(Object.keys(calendar).length).toBe(92);
|
||||
jest
|
||||
.spyOn(Date, 'now')
|
||||
.mockImplementation(() => new Date('2020-01-14T00:00:00.000Z').getTime());
|
||||
let calendar = Planning.generateEmptyCalendar(1);
|
||||
expect(calendar).toHaveProperty('2020-01-14');
|
||||
expect(calendar).toHaveProperty('2020-01-20');
|
||||
expect(calendar).toHaveProperty('2020-02-10');
|
||||
expect(Object.keys(calendar).length).toBe(32);
|
||||
calendar = Planning.generateEmptyCalendar(3);
|
||||
expect(calendar).toHaveProperty('2020-01-14');
|
||||
expect(calendar).toHaveProperty('2020-01-20');
|
||||
expect(calendar).toHaveProperty('2020-02-10');
|
||||
expect(calendar).toHaveProperty('2020-02-14');
|
||||
expect(calendar).toHaveProperty('2020-03-20');
|
||||
expect(calendar).toHaveProperty('2020-04-12');
|
||||
expect(Object.keys(calendar).length).toBe(92);
|
||||
});
|
||||
|
||||
test('pushEventInOrder', () => {
|
||||
let eventArray = [];
|
||||
let event1 = {date_begin: "2020-01-14 09:15"};
|
||||
Planning.pushEventInOrder(eventArray, event1);
|
||||
expect(eventArray.length).toBe(1);
|
||||
expect(eventArray[0]).toBe(event1);
|
||||
let eventArray = [];
|
||||
let event1 = {date_begin: '2020-01-14 09:15'};
|
||||
Planning.pushEventInOrder(eventArray, event1);
|
||||
expect(eventArray.length).toBe(1);
|
||||
expect(eventArray[0]).toBe(event1);
|
||||
|
||||
let event2 = {date_begin: "2020-01-14 10:15"};
|
||||
Planning.pushEventInOrder(eventArray, event2);
|
||||
expect(eventArray.length).toBe(2);
|
||||
expect(eventArray[0]).toBe(event1);
|
||||
expect(eventArray[1]).toBe(event2);
|
||||
let event2 = {date_begin: '2020-01-14 10:15'};
|
||||
Planning.pushEventInOrder(eventArray, event2);
|
||||
expect(eventArray.length).toBe(2);
|
||||
expect(eventArray[0]).toBe(event1);
|
||||
expect(eventArray[1]).toBe(event2);
|
||||
|
||||
let event3 = {date_begin: "2020-01-14 10:15", title: "garbage"};
|
||||
Planning.pushEventInOrder(eventArray, event3);
|
||||
expect(eventArray.length).toBe(3);
|
||||
expect(eventArray[0]).toBe(event1);
|
||||
expect(eventArray[1]).toBe(event2);
|
||||
expect(eventArray[2]).toBe(event3);
|
||||
let event3 = {date_begin: '2020-01-14 10:15', title: 'garbage'};
|
||||
Planning.pushEventInOrder(eventArray, event3);
|
||||
expect(eventArray.length).toBe(3);
|
||||
expect(eventArray[0]).toBe(event1);
|
||||
expect(eventArray[1]).toBe(event2);
|
||||
expect(eventArray[2]).toBe(event3);
|
||||
|
||||
let event4 = {date_begin: "2020-01-13 09:00"};
|
||||
Planning.pushEventInOrder(eventArray, event4);
|
||||
expect(eventArray.length).toBe(4);
|
||||
expect(eventArray[0]).toBe(event4);
|
||||
expect(eventArray[1]).toBe(event1);
|
||||
expect(eventArray[2]).toBe(event2);
|
||||
expect(eventArray[3]).toBe(event3);
|
||||
let event4 = {date_begin: '2020-01-13 09:00'};
|
||||
Planning.pushEventInOrder(eventArray, event4);
|
||||
expect(eventArray.length).toBe(4);
|
||||
expect(eventArray[0]).toBe(event4);
|
||||
expect(eventArray[1]).toBe(event1);
|
||||
expect(eventArray[2]).toBe(event2);
|
||||
expect(eventArray[3]).toBe(event3);
|
||||
});
|
||||
|
||||
test('generateEventAgenda', () => {
|
||||
jest.spyOn(Date, 'now')
|
||||
.mockImplementation(() =>
|
||||
new Date('2020-01-14T00:00:00.000Z').getTime()
|
||||
);
|
||||
let eventList = [
|
||||
{date_begin: "2020-01-14 09:15"},
|
||||
{date_begin: "2020-02-01 09:15"},
|
||||
{date_begin: "2020-01-15 09:15"},
|
||||
{date_begin: "2020-02-01 09:30"},
|
||||
{date_begin: "2020-02-01 08:30"},
|
||||
];
|
||||
const calendar = Planning.generateEventAgenda(eventList, 2);
|
||||
expect(calendar["2020-01-14"].length).toBe(1);
|
||||
expect(calendar["2020-01-14"][0]).toBe(eventList[0]);
|
||||
expect(calendar["2020-01-15"].length).toBe(1);
|
||||
expect(calendar["2020-01-15"][0]).toBe(eventList[2]);
|
||||
expect(calendar["2020-02-01"].length).toBe(3);
|
||||
expect(calendar["2020-02-01"][0]).toBe(eventList[4]);
|
||||
expect(calendar["2020-02-01"][1]).toBe(eventList[1]);
|
||||
expect(calendar["2020-02-01"][2]).toBe(eventList[3]);
|
||||
jest
|
||||
.spyOn(Date, 'now')
|
||||
.mockImplementation(() => new Date('2020-01-14T00:00:00.000Z').getTime());
|
||||
let eventList = [
|
||||
{date_begin: '2020-01-14 09:15'},
|
||||
{date_begin: '2020-02-01 09:15'},
|
||||
{date_begin: '2020-01-15 09:15'},
|
||||
{date_begin: '2020-02-01 09:30'},
|
||||
{date_begin: '2020-02-01 08:30'},
|
||||
];
|
||||
const calendar = Planning.generateEventAgenda(eventList, 2);
|
||||
expect(calendar['2020-01-14'].length).toBe(1);
|
||||
expect(calendar['2020-01-14'][0]).toBe(eventList[0]);
|
||||
expect(calendar['2020-01-15'].length).toBe(1);
|
||||
expect(calendar['2020-01-15'][0]).toBe(eventList[2]);
|
||||
expect(calendar['2020-02-01'].length).toBe(3);
|
||||
expect(calendar['2020-02-01'][0]).toBe(eventList[4]);
|
||||
expect(calendar['2020-02-01'][1]).toBe(eventList[1]);
|
||||
expect(calendar['2020-02-01'][2]).toBe(eventList[3]);
|
||||
});
|
||||
|
||||
test('getCurrentDateString', () => {
|
||||
jest.spyOn(Date, 'now')
|
||||
.mockImplementation(() => {
|
||||
let date = new Date();
|
||||
date.setFullYear(2020, 0, 14);
|
||||
date.setHours(15, 30, 54, 65);
|
||||
return date.getTime();
|
||||
});
|
||||
expect(Planning.getCurrentDateString()).toBe('2020-01-14 15:30');
|
||||
jest.spyOn(Date, 'now').mockImplementation(() => {
|
||||
let date = new Date();
|
||||
date.setFullYear(2020, 0, 14);
|
||||
date.setHours(15, 30, 54, 65);
|
||||
return date.getTime();
|
||||
});
|
||||
expect(Planning.getCurrentDateString()).toBe('2020-01-14 15:30');
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,142 +1,167 @@
|
|||
/* eslint-disable */
|
||||
|
||||
import React from 'react';
|
||||
import {getCleanedMachineWatched, getMachineEndDate, getMachineOfId, isMachineWatched} from "../../src/utils/Proxiwash";
|
||||
import {
|
||||
getCleanedMachineWatched,
|
||||
getMachineEndDate,
|
||||
getMachineOfId,
|
||||
isMachineWatched,
|
||||
} from '../../src/utils/Proxiwash';
|
||||
|
||||
test('getMachineEndDate', () => {
|
||||
jest.spyOn(Date, 'now')
|
||||
.mockImplementation(() =>
|
||||
new Date('2020-01-14T15:00:00.000Z').getTime()
|
||||
);
|
||||
let expectDate = new Date('2020-01-14T15:00:00.000Z');
|
||||
expectDate.setHours(23);
|
||||
expectDate.setMinutes(10);
|
||||
expect(getMachineEndDate({endTime: "23:10"}).getTime()).toBe(expectDate.getTime());
|
||||
jest
|
||||
.spyOn(Date, 'now')
|
||||
.mockImplementation(() => new Date('2020-01-14T15:00:00.000Z').getTime());
|
||||
let expectDate = new Date('2020-01-14T15:00:00.000Z');
|
||||
expectDate.setHours(23);
|
||||
expectDate.setMinutes(10);
|
||||
expect(getMachineEndDate({endTime: '23:10'}).getTime()).toBe(
|
||||
expectDate.getTime(),
|
||||
);
|
||||
|
||||
expectDate.setHours(16);
|
||||
expectDate.setMinutes(30);
|
||||
expect(getMachineEndDate({endTime: "16:30"}).getTime()).toBe(expectDate.getTime());
|
||||
expectDate.setHours(16);
|
||||
expectDate.setMinutes(30);
|
||||
expect(getMachineEndDate({endTime: '16:30'}).getTime()).toBe(
|
||||
expectDate.getTime(),
|
||||
);
|
||||
|
||||
expect(getMachineEndDate({endTime: "15:30"})).toBeNull();
|
||||
expect(getMachineEndDate({endTime: '15:30'})).toBeNull();
|
||||
|
||||
expect(getMachineEndDate({endTime: "13:10"})).toBeNull();
|
||||
expect(getMachineEndDate({endTime: '13:10'})).toBeNull();
|
||||
|
||||
jest.spyOn(Date, 'now')
|
||||
.mockImplementation(() =>
|
||||
new Date('2020-01-14T23:00:00.000Z').getTime()
|
||||
);
|
||||
expectDate = new Date('2020-01-14T23:00:00.000Z');
|
||||
expectDate.setHours(0);
|
||||
expectDate.setMinutes(30);
|
||||
expect(getMachineEndDate({endTime: "00:30"}).getTime()).toBe(expectDate.getTime());
|
||||
jest
|
||||
.spyOn(Date, 'now')
|
||||
.mockImplementation(() => new Date('2020-01-14T23:00:00.000Z').getTime());
|
||||
expectDate = new Date('2020-01-14T23:00:00.000Z');
|
||||
expectDate.setHours(0);
|
||||
expectDate.setMinutes(30);
|
||||
expect(getMachineEndDate({endTime: '00:30'}).getTime()).toBe(
|
||||
expectDate.getTime(),
|
||||
);
|
||||
});
|
||||
|
||||
test('isMachineWatched', () => {
|
||||
let machineList = [
|
||||
{
|
||||
number: "0",
|
||||
endTime: "23:30",
|
||||
},
|
||||
{
|
||||
number: "1",
|
||||
endTime: "20:30",
|
||||
},
|
||||
];
|
||||
expect(isMachineWatched({number: "0", endTime: "23:30"}, machineList)).toBeTrue();
|
||||
expect(isMachineWatched({number: "1", endTime: "20:30"}, machineList)).toBeTrue();
|
||||
expect(isMachineWatched({number: "3", endTime: "20:30"}, machineList)).toBeFalse();
|
||||
expect(isMachineWatched({number: "1", endTime: "23:30"}, machineList)).toBeFalse();
|
||||
let machineList = [
|
||||
{
|
||||
number: '0',
|
||||
endTime: '23:30',
|
||||
},
|
||||
{
|
||||
number: '1',
|
||||
endTime: '20:30',
|
||||
},
|
||||
];
|
||||
expect(
|
||||
isMachineWatched({number: '0', endTime: '23:30'}, machineList),
|
||||
).toBeTrue();
|
||||
expect(
|
||||
isMachineWatched({number: '1', endTime: '20:30'}, machineList),
|
||||
).toBeTrue();
|
||||
expect(
|
||||
isMachineWatched({number: '3', endTime: '20:30'}, machineList),
|
||||
).toBeFalse();
|
||||
expect(
|
||||
isMachineWatched({number: '1', endTime: '23:30'}, machineList),
|
||||
).toBeFalse();
|
||||
});
|
||||
|
||||
test('getMachineOfId', () => {
|
||||
let machineList = [
|
||||
{
|
||||
number: "0",
|
||||
},
|
||||
{
|
||||
number: "1",
|
||||
},
|
||||
];
|
||||
expect(getMachineOfId("0", machineList)).toStrictEqual({number: "0"});
|
||||
expect(getMachineOfId("1", machineList)).toStrictEqual({number: "1"});
|
||||
expect(getMachineOfId("3", machineList)).toBeNull();
|
||||
let machineList = [
|
||||
{
|
||||
number: '0',
|
||||
},
|
||||
{
|
||||
number: '1',
|
||||
},
|
||||
];
|
||||
expect(getMachineOfId('0', machineList)).toStrictEqual({number: '0'});
|
||||
expect(getMachineOfId('1', machineList)).toStrictEqual({number: '1'});
|
||||
expect(getMachineOfId('3', machineList)).toBeNull();
|
||||
});
|
||||
|
||||
test('getCleanedMachineWatched', () => {
|
||||
let machineList = [
|
||||
{
|
||||
number: "0",
|
||||
endTime: "23:30",
|
||||
},
|
||||
{
|
||||
number: "1",
|
||||
endTime: "20:30",
|
||||
},
|
||||
{
|
||||
number: "2",
|
||||
endTime: "",
|
||||
},
|
||||
];
|
||||
let watchList = [
|
||||
{
|
||||
number: "0",
|
||||
endTime: "23:30",
|
||||
},
|
||||
{
|
||||
number: "1",
|
||||
endTime: "20:30",
|
||||
},
|
||||
{
|
||||
number: "2",
|
||||
endTime: "",
|
||||
},
|
||||
];
|
||||
let cleanedList = watchList;
|
||||
expect(getCleanedMachineWatched(watchList, machineList)).toStrictEqual(cleanedList);
|
||||
let machineList = [
|
||||
{
|
||||
number: '0',
|
||||
endTime: '23:30',
|
||||
},
|
||||
{
|
||||
number: '1',
|
||||
endTime: '20:30',
|
||||
},
|
||||
{
|
||||
number: '2',
|
||||
endTime: '',
|
||||
},
|
||||
];
|
||||
let watchList = [
|
||||
{
|
||||
number: '0',
|
||||
endTime: '23:30',
|
||||
},
|
||||
{
|
||||
number: '1',
|
||||
endTime: '20:30',
|
||||
},
|
||||
{
|
||||
number: '2',
|
||||
endTime: '',
|
||||
},
|
||||
];
|
||||
let cleanedList = watchList;
|
||||
expect(getCleanedMachineWatched(watchList, machineList)).toStrictEqual(
|
||||
cleanedList,
|
||||
);
|
||||
|
||||
watchList = [
|
||||
{
|
||||
number: "0",
|
||||
endTime: "23:30",
|
||||
},
|
||||
{
|
||||
number: "1",
|
||||
endTime: "20:30",
|
||||
},
|
||||
{
|
||||
number: "2",
|
||||
endTime: "15:30",
|
||||
},
|
||||
];
|
||||
cleanedList = [
|
||||
{
|
||||
number: "0",
|
||||
endTime: "23:30",
|
||||
},
|
||||
{
|
||||
number: "1",
|
||||
endTime: "20:30",
|
||||
},
|
||||
];
|
||||
expect(getCleanedMachineWatched(watchList, machineList)).toStrictEqual(cleanedList);
|
||||
watchList = [
|
||||
{
|
||||
number: '0',
|
||||
endTime: '23:30',
|
||||
},
|
||||
{
|
||||
number: '1',
|
||||
endTime: '20:30',
|
||||
},
|
||||
{
|
||||
number: '2',
|
||||
endTime: '15:30',
|
||||
},
|
||||
];
|
||||
cleanedList = [
|
||||
{
|
||||
number: '0',
|
||||
endTime: '23:30',
|
||||
},
|
||||
{
|
||||
number: '1',
|
||||
endTime: '20:30',
|
||||
},
|
||||
];
|
||||
expect(getCleanedMachineWatched(watchList, machineList)).toStrictEqual(
|
||||
cleanedList,
|
||||
);
|
||||
|
||||
watchList = [
|
||||
{
|
||||
number: "0",
|
||||
endTime: "23:30",
|
||||
},
|
||||
{
|
||||
number: "1",
|
||||
endTime: "20:31",
|
||||
},
|
||||
{
|
||||
number: "3",
|
||||
endTime: "15:30",
|
||||
},
|
||||
];
|
||||
cleanedList = [
|
||||
{
|
||||
number: "0",
|
||||
endTime: "23:30",
|
||||
},
|
||||
];
|
||||
expect(getCleanedMachineWatched(watchList, machineList)).toStrictEqual(cleanedList);
|
||||
});
|
||||
watchList = [
|
||||
{
|
||||
number: '0',
|
||||
endTime: '23:30',
|
||||
},
|
||||
{
|
||||
number: '1',
|
||||
endTime: '20:31',
|
||||
},
|
||||
{
|
||||
number: '3',
|
||||
endTime: '15:30',
|
||||
},
|
||||
];
|
||||
cleanedList = [
|
||||
{
|
||||
number: '0',
|
||||
endTime: '23:30',
|
||||
},
|
||||
];
|
||||
expect(getCleanedMachineWatched(watchList, machineList)).toStrictEqual(
|
||||
cleanedList,
|
||||
);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,45 +0,0 @@
|
|||
import React from 'react';
|
||||
import {isResponseValid} from "../../src/utils/WebData";
|
||||
|
||||
let fetch = require('isomorphic-fetch'); // fetch is not implemented in nodeJS but in react-native
|
||||
|
||||
test('isRequestResponseValid', () => {
|
||||
let json = {
|
||||
error: 0,
|
||||
data: {}
|
||||
};
|
||||
expect(isResponseValid(json)).toBeTrue();
|
||||
json = {
|
||||
error: 1,
|
||||
data: {}
|
||||
};
|
||||
expect(isResponseValid(json)).toBeTrue();
|
||||
json = {
|
||||
error: 50,
|
||||
data: {}
|
||||
};
|
||||
expect(isResponseValid(json)).toBeTrue();
|
||||
json = {
|
||||
error: 50,
|
||||
data: {truc: 'machin'}
|
||||
};
|
||||
expect(isResponseValid(json)).toBeTrue();
|
||||
json = {
|
||||
message: 'coucou'
|
||||
};
|
||||
expect(isResponseValid(json)).toBeFalse();
|
||||
json = {
|
||||
error: 'coucou',
|
||||
data: {truc: 'machin'}
|
||||
};
|
||||
expect(isResponseValid(json)).toBeFalse();
|
||||
json = {
|
||||
error: 0,
|
||||
data: 'coucou'
|
||||
};
|
||||
expect(isResponseValid(json)).toBeFalse();
|
||||
json = {
|
||||
error: 0,
|
||||
};
|
||||
expect(isResponseValid(json)).toBeFalse();
|
||||
});
|
||||
47
__tests__/utils/WebData.test.js
Normal file
47
__tests__/utils/WebData.test.js
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
/* eslint-disable */
|
||||
|
||||
import React from 'react';
|
||||
import {isApiResponseValid} from '../../src/utils/WebData';
|
||||
|
||||
const fetch = require('isomorphic-fetch'); // fetch is not implemented in nodeJS but in react-native
|
||||
|
||||
test('isRequestResponseValid', () => {
|
||||
let json = {
|
||||
error: 0,
|
||||
data: {},
|
||||
};
|
||||
expect(isApiResponseValid(json)).toBeTrue();
|
||||
json = {
|
||||
error: 1,
|
||||
data: {},
|
||||
};
|
||||
expect(isApiResponseValid(json)).toBeTrue();
|
||||
json = {
|
||||
error: 50,
|
||||
data: {},
|
||||
};
|
||||
expect(isApiResponseValid(json)).toBeTrue();
|
||||
json = {
|
||||
error: 50,
|
||||
data: {truc: 'machin'},
|
||||
};
|
||||
expect(isApiResponseValid(json)).toBeTrue();
|
||||
json = {
|
||||
message: 'coucou',
|
||||
};
|
||||
expect(isApiResponseValid(json)).toBeFalse();
|
||||
json = {
|
||||
error: 'coucou',
|
||||
data: {truc: 'machin'},
|
||||
};
|
||||
expect(isApiResponseValid(json)).toBeFalse();
|
||||
json = {
|
||||
error: 0,
|
||||
data: 'coucou',
|
||||
};
|
||||
expect(isApiResponseValid(json)).toBeFalse();
|
||||
json = {
|
||||
error: 0,
|
||||
};
|
||||
expect(isApiResponseValid(json)).toBeFalse();
|
||||
});
|
||||
|
|
@ -136,8 +136,8 @@ android {
|
|||
applicationId 'fr.amicaleinsat.application'
|
||||
minSdkVersion rootProject.ext.minSdkVersion
|
||||
targetSdkVersion rootProject.ext.targetSdkVersion
|
||||
versionCode 32
|
||||
versionName "3.1.4"
|
||||
versionCode 34
|
||||
versionName "4.0.1"
|
||||
missingDimensionStrategy 'react-native-camera', 'general'
|
||||
}
|
||||
splits {
|
||||
|
|
|
|||
|
|
@ -1,3 +1,3 @@
|
|||
module.exports = {
|
||||
presets: ['module:metro-react-native-babel-preset'],
|
||||
presets: ['module:metro-react-native-babel-preset', '@babel/preset-flow'],
|
||||
};
|
||||
|
|
|
|||
1
index.js
1
index.js
|
|
@ -6,4 +6,5 @@ import {AppRegistry} from 'react-native';
|
|||
import App from './App';
|
||||
import {name as appName} from './app.json';
|
||||
|
||||
// eslint-disable-next-line flowtype/require-return-type
|
||||
AppRegistry.registerComponent(appName, () => App);
|
||||
|
|
|
|||
|
|
@ -6,12 +6,13 @@
|
|||
*/
|
||||
|
||||
module.exports = {
|
||||
transformer: {
|
||||
getTransformOptions: async () => ({
|
||||
transform: {
|
||||
experimentalImportSupport: false,
|
||||
inlineRequires: false,
|
||||
},
|
||||
}),
|
||||
},
|
||||
transformer: {
|
||||
// eslint-disable-next-line flowtype/require-return-type
|
||||
getTransformOptions: async () => ({
|
||||
transform: {
|
||||
experimentalImportSupport: false,
|
||||
inlineRequires: false,
|
||||
},
|
||||
}),
|
||||
},
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,219 +1,205 @@
|
|||
// @flow
|
||||
|
||||
import * as React from 'react';
|
||||
import ConnectionManager from "../../managers/ConnectionManager";
|
||||
import {ERROR_TYPE} from "../../utils/WebData";
|
||||
import ErrorView from "../Screens/ErrorView";
|
||||
import BasicLoadingScreen from "../Screens/BasicLoadingScreen";
|
||||
import {StackNavigationProp} from "@react-navigation/stack";
|
||||
import {StackNavigationProp} from '@react-navigation/stack';
|
||||
import ConnectionManager from '../../managers/ConnectionManager';
|
||||
import type {ApiGenericDataType} from '../../utils/WebData';
|
||||
import {ERROR_TYPE} from '../../utils/WebData';
|
||||
import ErrorView from '../Screens/ErrorView';
|
||||
import BasicLoadingScreen from '../Screens/BasicLoadingScreen';
|
||||
|
||||
type Props = {
|
||||
navigation: StackNavigationProp,
|
||||
requests: Array<{
|
||||
link: string,
|
||||
params: Object,
|
||||
mandatory: boolean
|
||||
}>,
|
||||
renderFunction: (Array<{ [key: string]: any } | null>) => React.Node,
|
||||
errorViewOverride?: Array<{
|
||||
errorCode: number,
|
||||
message: string,
|
||||
icon: string,
|
||||
showRetryButton: boolean
|
||||
}>,
|
||||
}
|
||||
type PropsType = {
|
||||
navigation: StackNavigationProp,
|
||||
requests: Array<{
|
||||
link: string,
|
||||
params: {...},
|
||||
mandatory: boolean,
|
||||
}>,
|
||||
renderFunction: (Array<ApiGenericDataType | null>) => React.Node,
|
||||
errorViewOverride?: Array<{
|
||||
errorCode: number,
|
||||
message: string,
|
||||
icon: string,
|
||||
showRetryButton: boolean,
|
||||
}> | null,
|
||||
};
|
||||
|
||||
type State = {
|
||||
loading: boolean,
|
||||
}
|
||||
type StateType = {
|
||||
loading: boolean,
|
||||
};
|
||||
|
||||
class AuthenticatedScreen extends React.Component<Props, State> {
|
||||
class AuthenticatedScreen extends React.Component<PropsType, StateType> {
|
||||
static defaultProps = {
|
||||
errorViewOverride: null,
|
||||
};
|
||||
|
||||
state = {
|
||||
loading: true,
|
||||
currentUserToken: string | null;
|
||||
|
||||
connectionManager: ConnectionManager;
|
||||
|
||||
errors: Array<number>;
|
||||
|
||||
fetchedData: Array<ApiGenericDataType | null>;
|
||||
|
||||
constructor(props: PropsType) {
|
||||
super(props);
|
||||
this.state = {
|
||||
loading: true,
|
||||
};
|
||||
this.connectionManager = ConnectionManager.getInstance();
|
||||
props.navigation.addListener('focus', this.onScreenFocus);
|
||||
this.fetchedData = new Array(props.requests.length);
|
||||
this.errors = new Array(props.requests.length);
|
||||
}
|
||||
|
||||
currentUserToken: string | null;
|
||||
connectionManager: ConnectionManager;
|
||||
errors: Array<number>;
|
||||
fetchedData: Array<{ [key: string]: any } | null>;
|
||||
/**
|
||||
* Refreshes screen if user changed
|
||||
*/
|
||||
onScreenFocus = () => {
|
||||
if (this.currentUserToken !== this.connectionManager.getToken()) {
|
||||
this.currentUserToken = this.connectionManager.getToken();
|
||||
this.fetchData();
|
||||
}
|
||||
};
|
||||
|
||||
constructor(props: Object) {
|
||||
super(props);
|
||||
this.connectionManager = ConnectionManager.getInstance();
|
||||
this.props.navigation.addListener('focus', this.onScreenFocus);
|
||||
this.fetchedData = new Array(this.props.requests.length);
|
||||
this.errors = new Array(this.props.requests.length);
|
||||
/**
|
||||
* Callback used when a request finishes, successfully or not.
|
||||
* Saves data and error code.
|
||||
* If the token is invalid, logout the user and open the login screen.
|
||||
* If the last request was received, stop the loading screen.
|
||||
*
|
||||
* @param data The data fetched from the server
|
||||
* @param index The index for the data
|
||||
* @param error The error code received
|
||||
*/
|
||||
onRequestFinished(
|
||||
data: ApiGenericDataType | null,
|
||||
index: number,
|
||||
error?: number,
|
||||
) {
|
||||
const {props} = this;
|
||||
if (index >= 0 && index < props.requests.length) {
|
||||
this.fetchedData[index] = data;
|
||||
this.errors[index] = error != null ? error : ERROR_TYPE.SUCCESS;
|
||||
}
|
||||
// Token expired, logout user
|
||||
if (error === ERROR_TYPE.BAD_TOKEN) this.connectionManager.disconnect();
|
||||
|
||||
if (this.allRequestsFinished()) this.setState({loading: false});
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the error to render.
|
||||
* Non-mandatory requests are ignored.
|
||||
*
|
||||
*
|
||||
* @return {number} The error code or ERROR_TYPE.SUCCESS if no error was found
|
||||
*/
|
||||
getError(): number {
|
||||
const {props} = this;
|
||||
for (let i = 0; i < this.errors.length; i += 1) {
|
||||
if (
|
||||
this.errors[i] !== ERROR_TYPE.SUCCESS &&
|
||||
props.requests[i].mandatory
|
||||
) {
|
||||
return this.errors[i];
|
||||
}
|
||||
}
|
||||
return ERROR_TYPE.SUCCESS;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the error view to display in case of error
|
||||
*
|
||||
* @return {*}
|
||||
*/
|
||||
getErrorRender(): React.Node {
|
||||
const {props} = this;
|
||||
const errorCode = this.getError();
|
||||
let shouldOverride = false;
|
||||
let override = null;
|
||||
const overrideList = props.errorViewOverride;
|
||||
if (overrideList != null) {
|
||||
for (let i = 0; i < overrideList.length; i += 1) {
|
||||
if (overrideList[i].errorCode === errorCode) {
|
||||
shouldOverride = true;
|
||||
override = overrideList[i];
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Refreshes screen if user changed
|
||||
*/
|
||||
onScreenFocus = () => {
|
||||
if (this.currentUserToken !== this.connectionManager.getToken()) {
|
||||
this.currentUserToken = this.connectionManager.getToken();
|
||||
this.fetchData();
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Fetches the data from the server.
|
||||
*
|
||||
* If the user is not logged in errorCode is set to BAD_TOKEN and all requests fail.
|
||||
*
|
||||
* If the user is logged in, send all requests.
|
||||
*/
|
||||
fetchData = () => {
|
||||
if (!this.state.loading)
|
||||
this.setState({loading: true});
|
||||
if (this.connectionManager.isLoggedIn()) {
|
||||
for (let i = 0; i < this.props.requests.length; i++) {
|
||||
this.connectionManager.authenticatedRequest(
|
||||
this.props.requests[i].link,
|
||||
this.props.requests[i].params)
|
||||
.then((data) => {
|
||||
this.onRequestFinished(data, i, -1);
|
||||
})
|
||||
.catch((error) => {
|
||||
this.onRequestFinished(null, i, error);
|
||||
});
|
||||
}
|
||||
} else {
|
||||
for (let i = 0; i < this.props.requests.length; i++) {
|
||||
this.onRequestFinished(null, i, ERROR_TYPE.BAD_TOKEN);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Callback used when a request finishes, successfully or not.
|
||||
* Saves data and error code.
|
||||
* If the token is invalid, logout the user and open the login screen.
|
||||
* If the last request was received, stop the loading screen.
|
||||
*
|
||||
* @param data The data fetched from the server
|
||||
* @param index The index for the data
|
||||
* @param error The error code received
|
||||
*/
|
||||
onRequestFinished(data: { [key: string]: any } | null, index: number, error: number) {
|
||||
if (index >= 0 && index < this.props.requests.length) {
|
||||
this.fetchedData[index] = data;
|
||||
this.errors[index] = error;
|
||||
}
|
||||
|
||||
if (error === ERROR_TYPE.BAD_TOKEN) // Token expired, logout user
|
||||
this.connectionManager.disconnect();
|
||||
|
||||
if (this.allRequestsFinished())
|
||||
this.setState({loading: false});
|
||||
if (shouldOverride && override != null) {
|
||||
return (
|
||||
<ErrorView
|
||||
icon={override.icon}
|
||||
message={override.message}
|
||||
showRetryButton={override.showRetryButton}
|
||||
/>
|
||||
);
|
||||
}
|
||||
return <ErrorView errorCode={errorCode} onRefresh={this.fetchData} />;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if all requests finished processing
|
||||
*
|
||||
* @return {boolean} True if all finished
|
||||
*/
|
||||
allRequestsFinished() {
|
||||
let finished = true;
|
||||
for (let i = 0; i < this.fetchedData.length; i++) {
|
||||
if (this.fetchedData[i] === undefined) {
|
||||
finished = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return finished;
|
||||
/**
|
||||
* Fetches the data from the server.
|
||||
*
|
||||
* If the user is not logged in errorCode is set to BAD_TOKEN and all requests fail.
|
||||
*
|
||||
* If the user is logged in, send all requests.
|
||||
*/
|
||||
fetchData = () => {
|
||||
const {state, props} = this;
|
||||
if (!state.loading) this.setState({loading: true});
|
||||
|
||||
if (this.connectionManager.isLoggedIn()) {
|
||||
for (let i = 0; i < props.requests.length; i += 1) {
|
||||
this.connectionManager
|
||||
.authenticatedRequest(
|
||||
props.requests[i].link,
|
||||
props.requests[i].params,
|
||||
)
|
||||
.then((response: ApiGenericDataType): void =>
|
||||
this.onRequestFinished(response, i),
|
||||
)
|
||||
.catch((error: number): void =>
|
||||
this.onRequestFinished(null, i, error),
|
||||
);
|
||||
}
|
||||
} else {
|
||||
for (let i = 0; i < props.requests.length; i += 1) {
|
||||
this.onRequestFinished(null, i, ERROR_TYPE.BAD_TOKEN);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Checks if all requests have finished successfully.
|
||||
* This will return false only if a mandatory request failed.
|
||||
* All non-mandatory requests can fail without impacting the return value.
|
||||
*
|
||||
* @return {boolean} True if all finished successfully
|
||||
*/
|
||||
allRequestsValid() {
|
||||
let valid = true;
|
||||
for (let i = 0; i < this.fetchedData.length; i++) {
|
||||
if (this.fetchedData[i] === null && this.props.requests[i].mandatory) {
|
||||
valid = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return valid;
|
||||
}
|
||||
/**
|
||||
* Checks if all requests finished processing
|
||||
*
|
||||
* @return {boolean} True if all finished
|
||||
*/
|
||||
allRequestsFinished(): boolean {
|
||||
let finished = true;
|
||||
this.errors.forEach((error: number | null) => {
|
||||
if (error == null) finished = false;
|
||||
});
|
||||
return finished;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the error to render.
|
||||
* Non-mandatory requests are ignored.
|
||||
*
|
||||
*
|
||||
* @return {number} The error code or ERROR_TYPE.SUCCESS if no error was found
|
||||
*/
|
||||
getError() {
|
||||
for (let i = 0; i < this.errors.length; i++) {
|
||||
if (this.errors[i] !== 0 && this.props.requests[i].mandatory) {
|
||||
return this.errors[i];
|
||||
}
|
||||
}
|
||||
return ERROR_TYPE.SUCCESS;
|
||||
}
|
||||
/**
|
||||
* Reloads the data, to be called using ref by parent components
|
||||
*/
|
||||
reload() {
|
||||
this.fetchData();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the error view to display in case of error
|
||||
*
|
||||
* @return {*}
|
||||
*/
|
||||
getErrorRender() {
|
||||
const errorCode = this.getError();
|
||||
let shouldOverride = false;
|
||||
let override = null;
|
||||
const overrideList = this.props.errorViewOverride;
|
||||
if (overrideList != null) {
|
||||
for (let i = 0; i < overrideList.length; i++) {
|
||||
if (overrideList[i].errorCode === errorCode) {
|
||||
shouldOverride = true;
|
||||
override = overrideList[i];
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (shouldOverride && override != null) {
|
||||
return (
|
||||
<ErrorView
|
||||
{...this.props}
|
||||
icon={override.icon}
|
||||
message={override.message}
|
||||
showRetryButton={override.showRetryButton}
|
||||
/>
|
||||
);
|
||||
} else {
|
||||
return (
|
||||
<ErrorView
|
||||
{...this.props}
|
||||
errorCode={errorCode}
|
||||
onRefresh={this.fetchData}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Reloads the data, to be called using ref by parent components
|
||||
*/
|
||||
reload() {
|
||||
this.fetchData();
|
||||
}
|
||||
|
||||
render() {
|
||||
return (
|
||||
this.state.loading
|
||||
? <BasicLoadingScreen/>
|
||||
: (this.allRequestsValid()
|
||||
? this.props.renderFunction(this.fetchedData)
|
||||
: this.getErrorRender())
|
||||
);
|
||||
}
|
||||
render(): React.Node {
|
||||
const {state, props} = this;
|
||||
if (state.loading) return <BasicLoadingScreen />;
|
||||
if (this.getError() === ERROR_TYPE.SUCCESS)
|
||||
return props.renderFunction(this.fetchedData);
|
||||
return this.getErrorRender();
|
||||
}
|
||||
}
|
||||
|
||||
export default AuthenticatedScreen;
|
||||
|
|
|
|||
|
|
@ -2,45 +2,46 @@
|
|||
|
||||
import * as React from 'react';
|
||||
import i18n from 'i18n-js';
|
||||
import LoadingConfirmDialog from "../Dialogs/LoadingConfirmDialog";
|
||||
import ConnectionManager from "../../managers/ConnectionManager";
|
||||
import {StackNavigationProp} from "@react-navigation/stack";
|
||||
import {StackNavigationProp} from '@react-navigation/stack';
|
||||
import LoadingConfirmDialog from '../Dialogs/LoadingConfirmDialog';
|
||||
import ConnectionManager from '../../managers/ConnectionManager';
|
||||
|
||||
type Props = {
|
||||
navigation: StackNavigationProp,
|
||||
visible: boolean,
|
||||
onDismiss: () => void,
|
||||
}
|
||||
type PropsType = {
|
||||
navigation: StackNavigationProp,
|
||||
visible: boolean,
|
||||
onDismiss: () => void,
|
||||
};
|
||||
|
||||
class LogoutDialog extends React.PureComponent<Props> {
|
||||
|
||||
onClickAccept = async () => {
|
||||
return new Promise((resolve) => {
|
||||
ConnectionManager.getInstance().disconnect()
|
||||
.then(() => {
|
||||
this.props.navigation.reset({
|
||||
index: 0,
|
||||
routes: [{name: 'main'}],
|
||||
});
|
||||
this.props.onDismiss();
|
||||
resolve();
|
||||
});
|
||||
class LogoutDialog extends React.PureComponent<PropsType> {
|
||||
onClickAccept = async (): Promise<void> => {
|
||||
const {props} = this;
|
||||
return new Promise((resolve: () => void) => {
|
||||
ConnectionManager.getInstance()
|
||||
.disconnect()
|
||||
.then(() => {
|
||||
props.navigation.reset({
|
||||
index: 0,
|
||||
routes: [{name: 'main'}],
|
||||
});
|
||||
props.onDismiss();
|
||||
resolve();
|
||||
});
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
render() {
|
||||
return (
|
||||
<LoadingConfirmDialog
|
||||
{...this.props}
|
||||
visible={this.props.visible}
|
||||
onDismiss={this.props.onDismiss}
|
||||
onAccept={this.onClickAccept}
|
||||
title={i18n.t("dialog.disconnect.title")}
|
||||
titleLoading={i18n.t("dialog.disconnect.titleLoading")}
|
||||
message={i18n.t("dialog.disconnect.message")}
|
||||
/>
|
||||
);
|
||||
}
|
||||
render(): React.Node {
|
||||
const {props} = this;
|
||||
return (
|
||||
<LoadingConfirmDialog
|
||||
visible={props.visible}
|
||||
onDismiss={props.onDismiss}
|
||||
onAccept={this.onClickAccept}
|
||||
title={i18n.t('dialog.disconnect.title')}
|
||||
titleLoading={i18n.t('dialog.disconnect.titleLoading')}
|
||||
message={i18n.t('dialog.disconnect.message')}
|
||||
/>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default LogoutDialog;
|
||||
|
|
|
|||
|
|
@ -2,36 +2,38 @@
|
|||
|
||||
import * as React from 'react';
|
||||
import {View} from 'react-native';
|
||||
import {Headline, withTheme} from "react-native-paper";
|
||||
import {Headline, withTheme} from 'react-native-paper';
|
||||
import i18n from 'i18n-js';
|
||||
import type {CustomTheme} from "../../../managers/ThemeManager";
|
||||
import type {CustomThemeType} from '../../../managers/ThemeManager';
|
||||
|
||||
type Props = {
|
||||
theme: CustomTheme
|
||||
}
|
||||
type PropsType = {
|
||||
theme: CustomThemeType,
|
||||
};
|
||||
|
||||
class VoteNotAvailable extends React.Component<Props> {
|
||||
class VoteNotAvailable extends React.Component<PropsType> {
|
||||
shouldComponentUpdate(): boolean {
|
||||
return false;
|
||||
}
|
||||
|
||||
shouldComponentUpdate() {
|
||||
return false;
|
||||
}
|
||||
|
||||
render() {
|
||||
return (
|
||||
<View style={{
|
||||
width: "100%",
|
||||
marginTop: 10,
|
||||
marginBottom: 10,
|
||||
}}>
|
||||
<Headline
|
||||
style={{
|
||||
color: this.props.theme.colors.textDisabled,
|
||||
textAlign: "center",
|
||||
}}
|
||||
>{i18n.t("screens.vote.noVote")}</Headline>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
render(): React.Node {
|
||||
const {props} = this;
|
||||
return (
|
||||
<View
|
||||
style={{
|
||||
width: '100%',
|
||||
marginTop: 10,
|
||||
marginBottom: 10,
|
||||
}}>
|
||||
<Headline
|
||||
style={{
|
||||
color: props.theme.colors.textDisabled,
|
||||
textAlign: 'center',
|
||||
}}>
|
||||
{i18n.t('screens.vote.noVote')}
|
||||
</Headline>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default withTheme(VoteNotAvailable);
|
||||
|
|
|
|||
|
|
@ -1,116 +1,134 @@
|
|||
// @flow
|
||||
|
||||
import * as React from 'react';
|
||||
import {Avatar, Card, List, ProgressBar, Subheading, withTheme} from "react-native-paper";
|
||||
import {FlatList, StyleSheet} from "react-native";
|
||||
import {
|
||||
Avatar,
|
||||
Card,
|
||||
List,
|
||||
ProgressBar,
|
||||
Subheading,
|
||||
withTheme,
|
||||
} from 'react-native-paper';
|
||||
import {FlatList, StyleSheet} from 'react-native';
|
||||
import i18n from 'i18n-js';
|
||||
import type {team} from "../../../screens/Amicale/VoteScreen";
|
||||
import type {CustomTheme} from "../../../managers/ThemeManager";
|
||||
import type {VoteTeamType} from '../../../screens/Amicale/VoteScreen';
|
||||
import type {CustomThemeType} from '../../../managers/ThemeManager';
|
||||
|
||||
|
||||
type Props = {
|
||||
teams: Array<team>,
|
||||
dateEnd: string,
|
||||
theme: CustomTheme,
|
||||
}
|
||||
|
||||
class VoteResults extends React.Component<Props> {
|
||||
|
||||
totalVotes: number;
|
||||
winnerIds: Array<number>;
|
||||
|
||||
constructor(props) {
|
||||
super();
|
||||
props.teams.sort(this.sortByVotes);
|
||||
this.getTotalVotes(props.teams);
|
||||
this.getWinnerIds(props.teams);
|
||||
}
|
||||
|
||||
shouldComponentUpdate() {
|
||||
return false;
|
||||
}
|
||||
|
||||
sortByVotes = (a: team, b: team) => b.votes - a.votes;
|
||||
|
||||
getTotalVotes(teams: Array<team>) {
|
||||
this.totalVotes = 0;
|
||||
for (let i = 0; i < teams.length; i++) {
|
||||
this.totalVotes += teams[i].votes;
|
||||
}
|
||||
}
|
||||
|
||||
getWinnerIds(teams: Array<team>) {
|
||||
let max = teams[0].votes;
|
||||
this.winnerIds = [];
|
||||
for (let i = 0; i < teams.length; i++) {
|
||||
if (teams[i].votes === max)
|
||||
this.winnerIds.push(teams[i].id);
|
||||
else
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
voteKeyExtractor = (item: team) => item.id.toString();
|
||||
|
||||
resultRenderItem = ({item}: { item: team }) => {
|
||||
const isWinner = this.winnerIds.indexOf(item.id) !== -1;
|
||||
const isDraw = this.winnerIds.length > 1;
|
||||
const colors = this.props.theme.colors;
|
||||
return (
|
||||
<Card style={{
|
||||
marginTop: 10,
|
||||
elevation: isWinner ? 5 : 3,
|
||||
}}>
|
||||
<List.Item
|
||||
title={item.name}
|
||||
description={item.votes + ' ' + i18n.t('screens.vote.results.votes')}
|
||||
left={props => isWinner
|
||||
? <List.Icon {...props} icon={isDraw ? "trophy-outline" : "trophy"} color={colors.primary}/>
|
||||
: null}
|
||||
titleStyle={{
|
||||
color: isWinner
|
||||
? colors.primary
|
||||
: colors.text
|
||||
}}
|
||||
style={{padding: 0}}
|
||||
/>
|
||||
<ProgressBar progress={item.votes / this.totalVotes} color={colors.primary}/>
|
||||
</Card>
|
||||
);
|
||||
};
|
||||
|
||||
render() {
|
||||
return (
|
||||
<Card style={styles.card}>
|
||||
<Card.Title
|
||||
title={i18n.t('screens.vote.results.title')}
|
||||
subtitle={i18n.t('screens.vote.results.subtitle') + ' ' + this.props.dateEnd}
|
||||
left={(props) => <Avatar.Icon
|
||||
{...props}
|
||||
icon={"podium-gold"}
|
||||
/>}
|
||||
/>
|
||||
<Card.Content>
|
||||
<Subheading>{i18n.t('screens.vote.results.totalVotes') + ' ' + this.totalVotes}</Subheading>
|
||||
{/*$FlowFixMe*/}
|
||||
<FlatList
|
||||
data={this.props.teams}
|
||||
keyExtractor={this.voteKeyExtractor}
|
||||
renderItem={this.resultRenderItem}
|
||||
/>
|
||||
</Card.Content>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
}
|
||||
type PropsType = {
|
||||
teams: Array<VoteTeamType>,
|
||||
dateEnd: string,
|
||||
theme: CustomThemeType,
|
||||
};
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
card: {
|
||||
margin: 10,
|
||||
},
|
||||
icon: {
|
||||
backgroundColor: 'transparent'
|
||||
},
|
||||
card: {
|
||||
margin: 10,
|
||||
},
|
||||
icon: {
|
||||
backgroundColor: 'transparent',
|
||||
},
|
||||
});
|
||||
|
||||
class VoteResults extends React.Component<PropsType> {
|
||||
totalVotes: number;
|
||||
|
||||
winnerIds: Array<number>;
|
||||
|
||||
constructor(props: PropsType) {
|
||||
super();
|
||||
props.teams.sort(this.sortByVotes);
|
||||
this.getTotalVotes(props.teams);
|
||||
this.getWinnerIds(props.teams);
|
||||
}
|
||||
|
||||
shouldComponentUpdate(): boolean {
|
||||
return false;
|
||||
}
|
||||
|
||||
getTotalVotes(teams: Array<VoteTeamType>) {
|
||||
this.totalVotes = 0;
|
||||
for (let i = 0; i < teams.length; i += 1) {
|
||||
this.totalVotes += teams[i].votes;
|
||||
}
|
||||
}
|
||||
|
||||
getWinnerIds(teams: Array<VoteTeamType>) {
|
||||
const max = teams[0].votes;
|
||||
this.winnerIds = [];
|
||||
for (let i = 0; i < teams.length; i += 1) {
|
||||
if (teams[i].votes === max) this.winnerIds.push(teams[i].id);
|
||||
else break;
|
||||
}
|
||||
}
|
||||
|
||||
sortByVotes = (a: VoteTeamType, b: VoteTeamType): number => b.votes - a.votes;
|
||||
|
||||
voteKeyExtractor = (item: VoteTeamType): string => item.id.toString();
|
||||
|
||||
resultRenderItem = ({item}: {item: VoteTeamType}): React.Node => {
|
||||
const isWinner = this.winnerIds.indexOf(item.id) !== -1;
|
||||
const isDraw = this.winnerIds.length > 1;
|
||||
const {props} = this;
|
||||
return (
|
||||
<Card
|
||||
style={{
|
||||
marginTop: 10,
|
||||
elevation: isWinner ? 5 : 3,
|
||||
}}>
|
||||
<List.Item
|
||||
title={item.name}
|
||||
description={`${item.votes} ${i18n.t('screens.vote.results.votes')}`}
|
||||
left={({size}: {size: number}): React.Node =>
|
||||
isWinner ? (
|
||||
<List.Icon
|
||||
size={size}
|
||||
icon={isDraw ? 'trophy-outline' : 'trophy'}
|
||||
color={props.theme.colors.primary}
|
||||
/>
|
||||
) : null
|
||||
}
|
||||
titleStyle={{
|
||||
color: isWinner
|
||||
? props.theme.colors.primary
|
||||
: props.theme.colors.text,
|
||||
}}
|
||||
style={{padding: 0}}
|
||||
/>
|
||||
<ProgressBar
|
||||
progress={item.votes / this.totalVotes}
|
||||
color={props.theme.colors.primary}
|
||||
/>
|
||||
</Card>
|
||||
);
|
||||
};
|
||||
|
||||
render(): React.Node {
|
||||
const {props} = this;
|
||||
return (
|
||||
<Card style={styles.card}>
|
||||
<Card.Title
|
||||
title={i18n.t('screens.vote.results.title')}
|
||||
subtitle={`${i18n.t('screens.vote.results.subtitle')} ${
|
||||
props.dateEnd
|
||||
}`}
|
||||
left={({size}: {size: number}): React.Node => (
|
||||
<Avatar.Icon size={size} icon="podium-gold" />
|
||||
)}
|
||||
/>
|
||||
<Card.Content>
|
||||
<Subheading>{`${i18n.t('screens.vote.results.totalVotes')} ${
|
||||
this.totalVotes
|
||||
}`}</Subheading>
|
||||
{/* $FlowFixMe */}
|
||||
<FlatList
|
||||
data={props.teams}
|
||||
keyExtractor={this.voteKeyExtractor}
|
||||
renderItem={this.resultRenderItem}
|
||||
/>
|
||||
</Card.Content>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default withTheme(VoteResults);
|
||||
|
|
|
|||
|
|
@ -1,137 +1,146 @@
|
|||
// @flow
|
||||
|
||||
import * as React from 'react';
|
||||
import {Avatar, Button, Card, RadioButton} from "react-native-paper";
|
||||
import {FlatList, StyleSheet, View} from "react-native";
|
||||
import ConnectionManager from "../../../managers/ConnectionManager";
|
||||
import LoadingConfirmDialog from "../../Dialogs/LoadingConfirmDialog";
|
||||
import ErrorDialog from "../../Dialogs/ErrorDialog";
|
||||
import {Avatar, Button, Card, RadioButton} from 'react-native-paper';
|
||||
import {FlatList, StyleSheet, View} from 'react-native';
|
||||
import i18n from 'i18n-js';
|
||||
import type {team} from "../../../screens/Amicale/VoteScreen";
|
||||
import ConnectionManager from '../../../managers/ConnectionManager';
|
||||
import LoadingConfirmDialog from '../../Dialogs/LoadingConfirmDialog';
|
||||
import ErrorDialog from '../../Dialogs/ErrorDialog';
|
||||
import type {VoteTeamType} from '../../../screens/Amicale/VoteScreen';
|
||||
|
||||
type Props = {
|
||||
teams: Array<team>,
|
||||
onVoteSuccess: () => void,
|
||||
onVoteError: () => void,
|
||||
}
|
||||
type PropsType = {
|
||||
teams: Array<VoteTeamType>,
|
||||
onVoteSuccess: () => void,
|
||||
onVoteError: () => void,
|
||||
};
|
||||
|
||||
type State = {
|
||||
selectedTeam: string,
|
||||
voteDialogVisible: boolean,
|
||||
errorDialogVisible: boolean,
|
||||
currentError: number,
|
||||
}
|
||||
|
||||
|
||||
export default class VoteSelect extends React.PureComponent<Props, State> {
|
||||
|
||||
state = {
|
||||
selectedTeam: "none",
|
||||
voteDialogVisible: false,
|
||||
errorDialogVisible: false,
|
||||
currentError: 0,
|
||||
};
|
||||
|
||||
onVoteSelectionChange = (team: string) => this.setState({selectedTeam: team});
|
||||
|
||||
voteKeyExtractor = (item: team) => item.id.toString();
|
||||
|
||||
voteRenderItem = ({item}: { item: team }) => <RadioButton.Item label={item.name} value={item.id.toString()}/>;
|
||||
|
||||
showVoteDialog = () => this.setState({voteDialogVisible: true});
|
||||
|
||||
onVoteDialogDismiss = () => this.setState({voteDialogVisible: false,});
|
||||
|
||||
onVoteDialogAccept = async () => {
|
||||
return new Promise((resolve) => {
|
||||
ConnectionManager.getInstance().authenticatedRequest(
|
||||
"elections/vote",
|
||||
{"team": parseInt(this.state.selectedTeam)})
|
||||
.then(() => {
|
||||
this.onVoteDialogDismiss();
|
||||
this.props.onVoteSuccess();
|
||||
resolve();
|
||||
})
|
||||
.catch((error: number) => {
|
||||
this.onVoteDialogDismiss();
|
||||
this.showErrorDialog(error);
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
showErrorDialog = (error: number) => this.setState({
|
||||
errorDialogVisible: true,
|
||||
currentError: error,
|
||||
});
|
||||
|
||||
onErrorDialogDismiss = () => {
|
||||
this.setState({errorDialogVisible: false});
|
||||
this.props.onVoteError();
|
||||
};
|
||||
|
||||
render() {
|
||||
return (
|
||||
<View>
|
||||
<Card style={styles.card}>
|
||||
<Card.Title
|
||||
title={i18n.t('screens.vote.select.title')}
|
||||
subtitle={i18n.t('screens.vote.select.subtitle')}
|
||||
left={(props) =>
|
||||
<Avatar.Icon
|
||||
{...props}
|
||||
icon={"alert-decagram"}
|
||||
/>}
|
||||
/>
|
||||
<Card.Content>
|
||||
<RadioButton.Group
|
||||
onValueChange={this.onVoteSelectionChange}
|
||||
value={this.state.selectedTeam}
|
||||
>
|
||||
{/*$FlowFixMe*/}
|
||||
<FlatList
|
||||
data={this.props.teams}
|
||||
keyExtractor={this.voteKeyExtractor}
|
||||
extraData={this.state.selectedTeam}
|
||||
renderItem={this.voteRenderItem}
|
||||
/>
|
||||
</RadioButton.Group>
|
||||
</Card.Content>
|
||||
<Card.Actions>
|
||||
<Button
|
||||
icon="send"
|
||||
mode="contained"
|
||||
onPress={this.showVoteDialog}
|
||||
style={{marginLeft: 'auto'}}
|
||||
disabled={this.state.selectedTeam === "none"}
|
||||
>
|
||||
{i18n.t('screens.vote.select.sendButton')}
|
||||
</Button>
|
||||
</Card.Actions>
|
||||
</Card>
|
||||
<LoadingConfirmDialog
|
||||
visible={this.state.voteDialogVisible}
|
||||
onDismiss={this.onVoteDialogDismiss}
|
||||
onAccept={this.onVoteDialogAccept}
|
||||
title={i18n.t('screens.vote.select.dialogTitle')}
|
||||
titleLoading={i18n.t('screens.vote.select.dialogTitleLoading')}
|
||||
message={i18n.t('screens.vote.select.dialogMessage')}
|
||||
/>
|
||||
<ErrorDialog
|
||||
visible={this.state.errorDialogVisible}
|
||||
onDismiss={this.onErrorDialogDismiss}
|
||||
errorCode={this.state.currentError}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
}
|
||||
type StateType = {
|
||||
selectedTeam: string,
|
||||
voteDialogVisible: boolean,
|
||||
errorDialogVisible: boolean,
|
||||
currentError: number,
|
||||
};
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
card: {
|
||||
margin: 10,
|
||||
},
|
||||
icon: {
|
||||
backgroundColor: 'transparent'
|
||||
},
|
||||
card: {
|
||||
margin: 10,
|
||||
},
|
||||
icon: {
|
||||
backgroundColor: 'transparent',
|
||||
},
|
||||
});
|
||||
|
||||
export default class VoteSelect extends React.PureComponent<
|
||||
PropsType,
|
||||
StateType,
|
||||
> {
|
||||
constructor() {
|
||||
super();
|
||||
this.state = {
|
||||
selectedTeam: 'none',
|
||||
voteDialogVisible: false,
|
||||
errorDialogVisible: false,
|
||||
currentError: 0,
|
||||
};
|
||||
}
|
||||
|
||||
onVoteSelectionChange = (teamName: string): void =>
|
||||
this.setState({selectedTeam: teamName});
|
||||
|
||||
voteKeyExtractor = (item: VoteTeamType): string => item.id.toString();
|
||||
|
||||
voteRenderItem = ({item}: {item: VoteTeamType}): React.Node => (
|
||||
<RadioButton.Item label={item.name} value={item.id.toString()} />
|
||||
);
|
||||
|
||||
showVoteDialog = (): void => this.setState({voteDialogVisible: true});
|
||||
|
||||
onVoteDialogDismiss = (): void => this.setState({voteDialogVisible: false});
|
||||
|
||||
onVoteDialogAccept = async (): Promise<void> => {
|
||||
return new Promise((resolve: () => void) => {
|
||||
const {state} = this;
|
||||
ConnectionManager.getInstance()
|
||||
.authenticatedRequest('elections/vote', {
|
||||
team: parseInt(state.selectedTeam, 10),
|
||||
})
|
||||
.then(() => {
|
||||
this.onVoteDialogDismiss();
|
||||
const {props} = this;
|
||||
props.onVoteSuccess();
|
||||
resolve();
|
||||
})
|
||||
.catch((error: number) => {
|
||||
this.onVoteDialogDismiss();
|
||||
this.showErrorDialog(error);
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
showErrorDialog = (error: number): void =>
|
||||
this.setState({
|
||||
errorDialogVisible: true,
|
||||
currentError: error,
|
||||
});
|
||||
|
||||
onErrorDialogDismiss = () => {
|
||||
this.setState({errorDialogVisible: false});
|
||||
const {props} = this;
|
||||
props.onVoteError();
|
||||
};
|
||||
|
||||
render(): React.Node {
|
||||
const {state, props} = this;
|
||||
return (
|
||||
<View>
|
||||
<Card style={styles.card}>
|
||||
<Card.Title
|
||||
title={i18n.t('screens.vote.select.title')}
|
||||
subtitle={i18n.t('screens.vote.select.subtitle')}
|
||||
left={({size}: {size: number}): React.Node => (
|
||||
<Avatar.Icon size={size} icon="alert-decagram" />
|
||||
)}
|
||||
/>
|
||||
<Card.Content>
|
||||
<RadioButton.Group
|
||||
onValueChange={this.onVoteSelectionChange}
|
||||
value={state.selectedTeam}>
|
||||
{/* $FlowFixMe */}
|
||||
<FlatList
|
||||
data={props.teams}
|
||||
keyExtractor={this.voteKeyExtractor}
|
||||
extraData={state.selectedTeam}
|
||||
renderItem={this.voteRenderItem}
|
||||
/>
|
||||
</RadioButton.Group>
|
||||
</Card.Content>
|
||||
<Card.Actions>
|
||||
<Button
|
||||
icon="send"
|
||||
mode="contained"
|
||||
onPress={this.showVoteDialog}
|
||||
style={{marginLeft: 'auto'}}
|
||||
disabled={state.selectedTeam === 'none'}>
|
||||
{i18n.t('screens.vote.select.sendButton')}
|
||||
</Button>
|
||||
</Card.Actions>
|
||||
</Card>
|
||||
<LoadingConfirmDialog
|
||||
visible={state.voteDialogVisible}
|
||||
onDismiss={this.onVoteDialogDismiss}
|
||||
onAccept={this.onVoteDialogAccept}
|
||||
title={i18n.t('screens.vote.select.dialogTitle')}
|
||||
titleLoading={i18n.t('screens.vote.select.dialogTitleLoading')}
|
||||
message={i18n.t('screens.vote.select.dialogMessage')}
|
||||
/>
|
||||
<ErrorDialog
|
||||
visible={state.errorDialogVisible}
|
||||
onDismiss={this.onErrorDialogDismiss}
|
||||
errorCode={state.currentError}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,45 +1,45 @@
|
|||
// @flow
|
||||
|
||||
import * as React from 'react';
|
||||
import {Avatar, Card, Paragraph} from "react-native-paper";
|
||||
import {StyleSheet} from "react-native";
|
||||
import {Avatar, Card, Paragraph} from 'react-native-paper';
|
||||
import {StyleSheet} from 'react-native';
|
||||
import i18n from 'i18n-js';
|
||||
|
||||
type Props = {
|
||||
startDate: string,
|
||||
}
|
||||
|
||||
export default class VoteTease extends React.Component<Props> {
|
||||
|
||||
shouldComponentUpdate() {
|
||||
return false;
|
||||
}
|
||||
|
||||
render() {
|
||||
return (
|
||||
<Card style={styles.card}>
|
||||
<Card.Title
|
||||
title={i18n.t('screens.vote.tease.title')}
|
||||
subtitle={i18n.t('screens.vote.tease.subtitle')}
|
||||
left={props => <Avatar.Icon
|
||||
{...props}
|
||||
icon="vote"/>}
|
||||
/>
|
||||
<Card.Content>
|
||||
<Paragraph>
|
||||
{i18n.t('screens.vote.tease.message') + ' ' + this.props.startDate}
|
||||
</Paragraph>
|
||||
</Card.Content>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
}
|
||||
type PropsType = {
|
||||
startDate: string,
|
||||
};
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
card: {
|
||||
margin: 10,
|
||||
},
|
||||
icon: {
|
||||
backgroundColor: 'transparent'
|
||||
},
|
||||
card: {
|
||||
margin: 10,
|
||||
},
|
||||
icon: {
|
||||
backgroundColor: 'transparent',
|
||||
},
|
||||
});
|
||||
|
||||
export default class VoteTease extends React.Component<PropsType> {
|
||||
shouldComponentUpdate(): boolean {
|
||||
return false;
|
||||
}
|
||||
|
||||
render(): React.Node {
|
||||
const {props} = this;
|
||||
return (
|
||||
<Card style={styles.card}>
|
||||
<Card.Title
|
||||
title={i18n.t('screens.vote.tease.title')}
|
||||
subtitle={i18n.t('screens.vote.tease.subtitle')}
|
||||
left={({size}: {size: number}): React.Node => (
|
||||
<Avatar.Icon size={size} icon="vote" />
|
||||
)}
|
||||
/>
|
||||
<Card.Content>
|
||||
<Paragraph>
|
||||
{`${i18n.t('screens.vote.tease.message')} ${props.startDate}`}
|
||||
</Paragraph>
|
||||
</Card.Content>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,72 +1,78 @@
|
|||
// @flow
|
||||
|
||||
import * as React from 'react';
|
||||
import {ActivityIndicator, Card, Paragraph, withTheme} from "react-native-paper";
|
||||
import {StyleSheet} from "react-native";
|
||||
import {
|
||||
ActivityIndicator,
|
||||
Card,
|
||||
Paragraph,
|
||||
withTheme,
|
||||
} from 'react-native-paper';
|
||||
import {StyleSheet} from 'react-native';
|
||||
import i18n from 'i18n-js';
|
||||
import type {CustomTheme} from "../../../managers/ThemeManager";
|
||||
import type {CustomThemeType} from '../../../managers/ThemeManager';
|
||||
|
||||
type Props = {
|
||||
startDate: string | null,
|
||||
justVoted: boolean,
|
||||
hasVoted: boolean,
|
||||
isVoteRunning: boolean,
|
||||
theme: CustomTheme,
|
||||
}
|
||||
|
||||
class VoteWait extends React.Component<Props> {
|
||||
|
||||
shouldComponentUpdate() {
|
||||
return false;
|
||||
}
|
||||
|
||||
render() {
|
||||
const colors = this.props.theme.colors;
|
||||
const startDate = this.props.startDate;
|
||||
return (
|
||||
<Card style={styles.card}>
|
||||
<Card.Title
|
||||
title={this.props.isVoteRunning
|
||||
? i18n.t('screens.vote.wait.titleSubmitted')
|
||||
: i18n.t('screens.vote.wait.titleEnded')}
|
||||
subtitle={i18n.t('screens.vote.wait.subtitle')}
|
||||
left={(props) => <ActivityIndicator {...props}/>}
|
||||
/>
|
||||
<Card.Content>
|
||||
{
|
||||
this.props.justVoted
|
||||
? <Paragraph style={{color: colors.success}}>
|
||||
{i18n.t('screens.vote.wait.messageSubmitted')}
|
||||
</Paragraph>
|
||||
: null
|
||||
}
|
||||
{
|
||||
this.props.hasVoted
|
||||
? <Paragraph style={{color: colors.success}}>
|
||||
{i18n.t('screens.vote.wait.messageVoted')}
|
||||
</Paragraph>
|
||||
: null
|
||||
}
|
||||
{
|
||||
startDate != null
|
||||
? <Paragraph>
|
||||
{i18n.t('screens.vote.wait.messageDate') + ' ' + startDate}
|
||||
</Paragraph>
|
||||
: <Paragraph>{i18n.t('screens.vote.wait.messageDateUndefined')}</Paragraph>
|
||||
}
|
||||
</Card.Content>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
}
|
||||
type PropsType = {
|
||||
startDate: string | null,
|
||||
justVoted: boolean,
|
||||
hasVoted: boolean,
|
||||
isVoteRunning: boolean,
|
||||
theme: CustomThemeType,
|
||||
};
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
card: {
|
||||
margin: 10,
|
||||
},
|
||||
icon: {
|
||||
backgroundColor: 'transparent'
|
||||
},
|
||||
card: {
|
||||
margin: 10,
|
||||
},
|
||||
icon: {
|
||||
backgroundColor: 'transparent',
|
||||
},
|
||||
});
|
||||
|
||||
class VoteWait extends React.Component<PropsType> {
|
||||
shouldComponentUpdate(): boolean {
|
||||
return false;
|
||||
}
|
||||
|
||||
render(): React.Node {
|
||||
const {props} = this;
|
||||
const {startDate} = props;
|
||||
return (
|
||||
<Card style={styles.card}>
|
||||
<Card.Title
|
||||
title={
|
||||
props.isVoteRunning
|
||||
? i18n.t('screens.vote.wait.titleSubmitted')
|
||||
: i18n.t('screens.vote.wait.titleEnded')
|
||||
}
|
||||
subtitle={i18n.t('screens.vote.wait.subtitle')}
|
||||
left={({size}: {size: number}): React.Node => (
|
||||
<ActivityIndicator size={size} />
|
||||
)}
|
||||
/>
|
||||
<Card.Content>
|
||||
{props.justVoted ? (
|
||||
<Paragraph style={{color: props.theme.colors.success}}>
|
||||
{i18n.t('screens.vote.wait.messageSubmitted')}
|
||||
</Paragraph>
|
||||
) : null}
|
||||
{props.hasVoted ? (
|
||||
<Paragraph style={{color: props.theme.colors.success}}>
|
||||
{i18n.t('screens.vote.wait.messageVoted')}
|
||||
</Paragraph>
|
||||
) : null}
|
||||
{startDate != null ? (
|
||||
<Paragraph>
|
||||
{`${i18n.t('screens.vote.wait.messageDate')} ${startDate}`}
|
||||
</Paragraph>
|
||||
) : (
|
||||
<Paragraph>
|
||||
{i18n.t('screens.vote.wait.messageDateUndefined')}
|
||||
</Paragraph>
|
||||
)}
|
||||
</Card.Content>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default withTheme(VoteWait);
|
||||
|
|
|
|||
|
|
@ -1,101 +1,117 @@
|
|||
// @flow
|
||||
|
||||
import * as React from 'react';
|
||||
import {View} from "react-native";
|
||||
import {View} from 'react-native';
|
||||
import {List, withTheme} from 'react-native-paper';
|
||||
import Collapsible from "react-native-collapsible";
|
||||
import * as Animatable from "react-native-animatable";
|
||||
import type {CustomTheme} from "../../managers/ThemeManager";
|
||||
import Collapsible from 'react-native-collapsible';
|
||||
import * as Animatable from 'react-native-animatable';
|
||||
import type {CustomThemeType} from '../../managers/ThemeManager';
|
||||
|
||||
type Props = {
|
||||
theme: CustomTheme,
|
||||
title: string,
|
||||
subtitle?: string,
|
||||
left?: (props: { [keys: string]: any }) => React.Node,
|
||||
opened?: boolean,
|
||||
unmountWhenCollapsed: boolean,
|
||||
children?: React.Node,
|
||||
}
|
||||
type PropsType = {
|
||||
theme: CustomThemeType,
|
||||
title: string,
|
||||
subtitle?: string,
|
||||
left?: () => React.Node,
|
||||
opened?: boolean,
|
||||
unmountWhenCollapsed?: boolean,
|
||||
children?: React.Node,
|
||||
};
|
||||
|
||||
type State = {
|
||||
expanded: boolean,
|
||||
}
|
||||
type StateType = {
|
||||
expanded: boolean,
|
||||
};
|
||||
|
||||
const AnimatedListIcon = Animatable.createAnimatableComponent(List.Icon);
|
||||
|
||||
class AnimatedAccordion extends React.Component<Props, State> {
|
||||
class AnimatedAccordion extends React.Component<PropsType, StateType> {
|
||||
static defaultProps = {
|
||||
subtitle: '',
|
||||
left: null,
|
||||
opened: null,
|
||||
unmountWhenCollapsed: false,
|
||||
children: null,
|
||||
};
|
||||
|
||||
static defaultProps = {
|
||||
unmountWhenCollapsed: false,
|
||||
}
|
||||
chevronRef: { current: null | AnimatedListIcon };
|
||||
chevronIcon: string;
|
||||
animStart: string;
|
||||
animEnd: string;
|
||||
chevronRef: {current: null | AnimatedListIcon};
|
||||
|
||||
state = {
|
||||
expanded: this.props.opened != null ? this.props.opened : false,
|
||||
}
|
||||
chevronIcon: string;
|
||||
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.chevronRef = React.createRef();
|
||||
this.setupChevron();
|
||||
}
|
||||
animStart: 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";
|
||||
}
|
||||
}
|
||||
animEnd: string;
|
||||
|
||||
toggleAccordion = () => {
|
||||
if (this.chevronRef.current != null) {
|
||||
this.chevronRef.current.transitionTo({rotate: this.state.expanded ? this.animStart : this.animEnd});
|
||||
this.setState({expanded: !this.state.expanded})
|
||||
}
|
||||
constructor(props: PropsType) {
|
||||
super(props);
|
||||
this.state = {
|
||||
expanded: props.opened != null ? props.opened : false,
|
||||
};
|
||||
this.chevronRef = React.createRef();
|
||||
this.setupChevron();
|
||||
}
|
||||
|
||||
shouldComponentUpdate(nextProps: Props, nextState: State): boolean {
|
||||
if (nextProps.opened != null && nextProps.opened !== this.props.opened)
|
||||
this.state.expanded = nextProps.opened;
|
||||
return true;
|
||||
shouldComponentUpdate(nextProps: PropsType): boolean {
|
||||
const {state, props} = this;
|
||||
if (nextProps.opened != null && nextProps.opened !== props.opened)
|
||||
state.expanded = nextProps.opened;
|
||||
return true;
|
||||
}
|
||||
|
||||
setupChevron() {
|
||||
const {expanded} = this.state;
|
||||
if (expanded) {
|
||||
this.chevronIcon = 'chevron-up';
|
||||
this.animStart = '180deg';
|
||||
this.animEnd = '0deg';
|
||||
} else {
|
||||
this.chevronIcon = 'chevron-down';
|
||||
this.animStart = '0deg';
|
||||
this.animEnd = '180deg';
|
||||
}
|
||||
}
|
||||
|
||||
render() {
|
||||
const colors = this.props.theme.colors;
|
||||
return (
|
||||
<View>
|
||||
<List.Item
|
||||
{...this.props}
|
||||
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>
|
||||
);
|
||||
toggleAccordion = () => {
|
||||
const {expanded} = this.state;
|
||||
if (this.chevronRef.current != null) {
|
||||
this.chevronRef.current.transitionTo({
|
||||
rotate: expanded ? this.animStart : this.animEnd,
|
||||
});
|
||||
this.setState((prevState: StateType): {expanded: boolean} => ({
|
||||
expanded: !prevState.expanded,
|
||||
}));
|
||||
}
|
||||
};
|
||||
|
||||
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} : null}
|
||||
onPress={this.toggleAccordion}
|
||||
right={({size}: {size: number}): React.Node => (
|
||||
<AnimatedListIcon
|
||||
ref={this.chevronRef}
|
||||
size={size}
|
||||
icon={this.chevronIcon}
|
||||
color={state.expanded ? colors.primary : null}
|
||||
useNativeDriver
|
||||
style={{rotate: '0deg'}}
|
||||
/>
|
||||
)}
|
||||
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);
|
||||
|
|
|
|||
|
|
@ -1,170 +1,179 @@
|
|||
// @flow
|
||||
|
||||
import * as React from 'react';
|
||||
import {StyleSheet, View} from "react-native";
|
||||
import {FAB, IconButton, Surface, withTheme} from "react-native-paper";
|
||||
import AutoHideHandler from "../../utils/AutoHideHandler";
|
||||
import {StyleSheet, View} from 'react-native';
|
||||
import {FAB, IconButton, Surface, withTheme} from 'react-native-paper';
|
||||
import * as Animatable from 'react-native-animatable';
|
||||
import CustomTabBar from "../Tabbar/CustomTabBar";
|
||||
import {StackNavigationProp} from "@react-navigation/stack";
|
||||
import type {CustomTheme} from "../../managers/ThemeManager";
|
||||
import {StackNavigationProp} from '@react-navigation/stack';
|
||||
import AutoHideHandler from '../../utils/AutoHideHandler';
|
||||
import CustomTabBar from '../Tabbar/CustomTabBar';
|
||||
import type {CustomThemeType} from '../../managers/ThemeManager';
|
||||
import type {OnScrollType} from '../../utils/AutoHideHandler';
|
||||
|
||||
const AnimatedFAB = Animatable.createAnimatableComponent(FAB);
|
||||
|
||||
type Props = {
|
||||
navigation: StackNavigationProp,
|
||||
theme: CustomTheme,
|
||||
onPress: (action: string, data: any) => void,
|
||||
seekAttention: boolean,
|
||||
}
|
||||
type PropsType = {
|
||||
navigation: StackNavigationProp,
|
||||
theme: CustomThemeType,
|
||||
onPress: (action: string, data?: string) => void,
|
||||
seekAttention: boolean,
|
||||
};
|
||||
|
||||
type State = {
|
||||
currentMode: string,
|
||||
}
|
||||
type StateType = {
|
||||
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>
|
||||
);
|
||||
}
|
||||
}
|
||||
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%',
|
||||
}
|
||||
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: OnScrollType) => {
|
||||
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>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default withTheme(AnimatedBottomBar);
|
||||
|
|
|
|||
|
|
@ -1,66 +1,63 @@
|
|||
// @flow
|
||||
|
||||
import * as React from 'react';
|
||||
import {StyleSheet} from "react-native";
|
||||
import {FAB} from "react-native-paper";
|
||||
import AutoHideHandler from "../../utils/AutoHideHandler";
|
||||
import {StyleSheet} from 'react-native';
|
||||
import {FAB} from 'react-native-paper';
|
||||
import * as Animatable from 'react-native-animatable';
|
||||
import CustomTabBar from "../Tabbar/CustomTabBar";
|
||||
import {StackNavigationProp} from "@react-navigation/stack";
|
||||
import AutoHideHandler from '../../utils/AutoHideHandler';
|
||||
import CustomTabBar from '../Tabbar/CustomTabBar';
|
||||
|
||||
type Props = {
|
||||
navigation: StackNavigationProp,
|
||||
icon: string,
|
||||
onPress: () => void,
|
||||
}
|
||||
type PropsType = {
|
||||
icon: string,
|
||||
onPress: () => void,
|
||||
};
|
||||
|
||||
const AnimatedFab = Animatable.createAnimatableComponent(FAB);
|
||||
|
||||
export default class AnimatedFAB extends React.Component<Props> {
|
||||
|
||||
ref: { current: null | Animatable.View };
|
||||
hideHandler: AutoHideHandler;
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
this.ref = React.createRef();
|
||||
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() {
|
||||
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,
|
||||
},
|
||||
fab: {
|
||||
position: 'absolute',
|
||||
margin: 16,
|
||||
right: 0,
|
||||
},
|
||||
});
|
||||
|
||||
export default class AnimatedFAB extends React.Component<PropsType> {
|
||||
ref: {current: null | Animatable.View};
|
||||
|
||||
hideHandler: AutoHideHandler;
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
this.ref = React.createRef();
|
||||
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 {
|
||||
const {props} = this;
|
||||
return (
|
||||
<AnimatedFab
|
||||
ref={this.ref}
|
||||
useNativeDriver
|
||||
icon={props.icon}
|
||||
onPress={props.onPress}
|
||||
style={{
|
||||
...styles.fab,
|
||||
bottom: CustomTabBar.TAB_BAR_HEIGHT,
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,51 +1,59 @@
|
|||
// @flow
|
||||
|
||||
import * as React from 'react';
|
||||
import {withCollapsible} from "../../utils/withCollapsible";
|
||||
import {Collapsible} from "react-navigation-collapsible";
|
||||
import CustomTabBar from "../Tabbar/CustomTabBar";
|
||||
import {Collapsible} from 'react-navigation-collapsible';
|
||||
import withCollapsible from '../../utils/withCollapsible';
|
||||
import CustomTabBar from '../Tabbar/CustomTabBar';
|
||||
|
||||
export type CollapsibleComponentProps = {
|
||||
children?: React.Node,
|
||||
hasTab?: boolean,
|
||||
onScroll?: (event: SyntheticEvent<EventTarget>) => void,
|
||||
export type CollapsibleComponentPropsType = {
|
||||
children?: React.Node,
|
||||
hasTab?: boolean,
|
||||
onScroll?: (event: SyntheticEvent<EventTarget>) => void,
|
||||
};
|
||||
|
||||
type Props = {
|
||||
...CollapsibleComponentProps,
|
||||
collapsibleStack: Collapsible,
|
||||
component: any,
|
||||
}
|
||||
type PropsType = {
|
||||
...CollapsibleComponentPropsType,
|
||||
collapsibleStack: Collapsible,
|
||||
// eslint-disable-next-line flowtype/no-weak-types
|
||||
component: any,
|
||||
};
|
||||
|
||||
class CollapsibleComponent extends React.Component<Props> {
|
||||
class CollapsibleComponent extends React.Component<PropsType> {
|
||||
static defaultProps = {
|
||||
children: null,
|
||||
hasTab: false,
|
||||
onScroll: null,
|
||||
};
|
||||
|
||||
static defaultProps = {
|
||||
hasTab: false,
|
||||
}
|
||||
onScroll = (event: SyntheticEvent<EventTarget>) => {
|
||||
const {props} = this;
|
||||
if (props.onScroll) props.onScroll(event);
|
||||
};
|
||||
|
||||
onScroll = (event: SyntheticEvent<EventTarget>) => {
|
||||
if (this.props.onScroll)
|
||||
this.props.onScroll(event);
|
||||
}
|
||||
render(): React.Node {
|
||||
const {props} = this;
|
||||
const Comp = props.component;
|
||||
const {
|
||||
containerPaddingTop,
|
||||
scrollIndicatorInsetTop,
|
||||
onScrollWithListener,
|
||||
} = props.collapsibleStack;
|
||||
|
||||
render() {
|
||||
const Comp = this.props.component;
|
||||
const {containerPaddingTop, scrollIndicatorInsetTop, onScrollWithListener} = this.props.collapsibleStack;
|
||||
return (
|
||||
<Comp
|
||||
{...this.props}
|
||||
onScroll={onScrollWithListener(this.onScroll)}
|
||||
contentContainerStyle={{
|
||||
paddingTop: containerPaddingTop,
|
||||
paddingBottom: this.props.hasTab ? CustomTabBar.TAB_BAR_HEIGHT : 0,
|
||||
minHeight: '100%'
|
||||
}}
|
||||
scrollIndicatorInsets={{top: scrollIndicatorInsetTop}}
|
||||
>
|
||||
{this.props.children}
|
||||
</Comp>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<Comp
|
||||
// eslint-disable-next-line react/jsx-props-no-spreading
|
||||
{...props}
|
||||
onScroll={onScrollWithListener(this.onScroll)}
|
||||
contentContainerStyle={{
|
||||
paddingTop: containerPaddingTop,
|
||||
paddingBottom: props.hasTab ? CustomTabBar.TAB_BAR_HEIGHT : 0,
|
||||
minHeight: '100%',
|
||||
}}
|
||||
scrollIndicatorInsets={{top: scrollIndicatorInsetTop}}>
|
||||
{props.children}
|
||||
</Comp>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default withCollapsible(CollapsibleComponent);
|
||||
|
|
|
|||
|
|
@ -1,26 +1,26 @@
|
|||
// @flow
|
||||
|
||||
import * as React from 'react';
|
||||
import {Animated} from "react-native";
|
||||
import type {CollapsibleComponentProps} from "./CollapsibleComponent";
|
||||
import CollapsibleComponent from "./CollapsibleComponent";
|
||||
import {Animated} from 'react-native';
|
||||
import type {CollapsibleComponentPropsType} from './CollapsibleComponent';
|
||||
import CollapsibleComponent from './CollapsibleComponent';
|
||||
|
||||
type Props = {
|
||||
...CollapsibleComponentProps
|
||||
}
|
||||
type PropsType = {
|
||||
...CollapsibleComponentPropsType,
|
||||
};
|
||||
|
||||
class CollapsibleFlatList extends React.Component<Props> {
|
||||
|
||||
render() {
|
||||
return (
|
||||
<CollapsibleComponent
|
||||
{...this.props}
|
||||
component={Animated.FlatList}
|
||||
>
|
||||
{this.props.children}
|
||||
</CollapsibleComponent>
|
||||
);
|
||||
}
|
||||
// eslint-disable-next-line react/prefer-stateless-function
|
||||
class CollapsibleFlatList extends React.Component<PropsType> {
|
||||
render(): React.Node {
|
||||
const {props} = this;
|
||||
return (
|
||||
<CollapsibleComponent // eslint-disable-next-line react/jsx-props-no-spreading
|
||||
{...props}
|
||||
component={Animated.FlatList}>
|
||||
{props.children}
|
||||
</CollapsibleComponent>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default CollapsibleFlatList;
|
||||
|
|
|
|||
|
|
@ -1,26 +1,26 @@
|
|||
// @flow
|
||||
|
||||
import * as React from 'react';
|
||||
import {Animated} from "react-native";
|
||||
import type {CollapsibleComponentProps} from "./CollapsibleComponent";
|
||||
import CollapsibleComponent from "./CollapsibleComponent";
|
||||
import {Animated} from 'react-native';
|
||||
import type {CollapsibleComponentPropsType} from './CollapsibleComponent';
|
||||
import CollapsibleComponent from './CollapsibleComponent';
|
||||
|
||||
type Props = {
|
||||
...CollapsibleComponentProps
|
||||
}
|
||||
type PropsType = {
|
||||
...CollapsibleComponentPropsType,
|
||||
};
|
||||
|
||||
class CollapsibleScrollView extends React.Component<Props> {
|
||||
|
||||
render() {
|
||||
return (
|
||||
<CollapsibleComponent
|
||||
{...this.props}
|
||||
component={Animated.ScrollView}
|
||||
>
|
||||
{this.props.children}
|
||||
</CollapsibleComponent>
|
||||
);
|
||||
}
|
||||
// eslint-disable-next-line react/prefer-stateless-function
|
||||
class CollapsibleScrollView extends React.Component<PropsType> {
|
||||
render(): React.Node {
|
||||
const {props} = this;
|
||||
return (
|
||||
<CollapsibleComponent // eslint-disable-next-line react/jsx-props-no-spreading
|
||||
{...props}
|
||||
component={Animated.ScrollView}>
|
||||
{props.children}
|
||||
</CollapsibleComponent>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default CollapsibleScrollView;
|
||||
|
|
|
|||
|
|
@ -1,26 +1,26 @@
|
|||
// @flow
|
||||
|
||||
import * as React from 'react';
|
||||
import {Animated} from "react-native";
|
||||
import type {CollapsibleComponentProps} from "./CollapsibleComponent";
|
||||
import CollapsibleComponent from "./CollapsibleComponent";
|
||||
import {Animated} from 'react-native';
|
||||
import type {CollapsibleComponentPropsType} from './CollapsibleComponent';
|
||||
import CollapsibleComponent from './CollapsibleComponent';
|
||||
|
||||
type Props = {
|
||||
...CollapsibleComponentProps
|
||||
}
|
||||
type PropsType = {
|
||||
...CollapsibleComponentPropsType,
|
||||
};
|
||||
|
||||
class CollapsibleSectionList extends React.Component<Props> {
|
||||
|
||||
render() {
|
||||
return (
|
||||
<CollapsibleComponent
|
||||
{...this.props}
|
||||
component={Animated.SectionList}
|
||||
>
|
||||
{this.props.children}
|
||||
</CollapsibleComponent>
|
||||
);
|
||||
}
|
||||
// eslint-disable-next-line react/prefer-stateless-function
|
||||
class CollapsibleSectionList extends React.Component<PropsType> {
|
||||
render(): React.Node {
|
||||
const {props} = this;
|
||||
return (
|
||||
<CollapsibleComponent // eslint-disable-next-line react/jsx-props-no-spreading
|
||||
{...props}
|
||||
component={Animated.SectionList}>
|
||||
{props.children}
|
||||
</CollapsibleComponent>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default CollapsibleSectionList;
|
||||
|
|
|
|||
|
|
@ -2,34 +2,32 @@
|
|||
|
||||
import * as React from 'react';
|
||||
import {Button, Dialog, Paragraph, Portal} from 'react-native-paper';
|
||||
import i18n from "i18n-js";
|
||||
import i18n from 'i18n-js';
|
||||
|
||||
type Props = {
|
||||
visible: boolean,
|
||||
onDismiss: () => void,
|
||||
title: string,
|
||||
message: string,
|
||||
}
|
||||
type PropsType = {
|
||||
visible: boolean,
|
||||
onDismiss: () => void,
|
||||
title: string,
|
||||
message: string,
|
||||
};
|
||||
|
||||
class AlertDialog extends React.PureComponent<Props> {
|
||||
|
||||
render() {
|
||||
return (
|
||||
<Portal>
|
||||
<Dialog
|
||||
visible={this.props.visible}
|
||||
onDismiss={this.props.onDismiss}>
|
||||
<Dialog.Title>{this.props.title}</Dialog.Title>
|
||||
<Dialog.Content>
|
||||
<Paragraph>{this.props.message}</Paragraph>
|
||||
</Dialog.Content>
|
||||
<Dialog.Actions>
|
||||
<Button onPress={this.props.onDismiss}>{i18n.t("dialog.ok")}</Button>
|
||||
</Dialog.Actions>
|
||||
</Dialog>
|
||||
</Portal>
|
||||
);
|
||||
}
|
||||
class AlertDialog extends React.PureComponent<PropsType> {
|
||||
render(): React.Node {
|
||||
const {props} = this;
|
||||
return (
|
||||
<Portal>
|
||||
<Dialog visible={props.visible} onDismiss={props.onDismiss}>
|
||||
<Dialog.Title>{props.title}</Dialog.Title>
|
||||
<Dialog.Content>
|
||||
<Paragraph>{props.message}</Paragraph>
|
||||
</Dialog.Content>
|
||||
<Dialog.Actions>
|
||||
<Button onPress={props.onDismiss}>{i18n.t('dialog.ok')}</Button>
|
||||
</Dialog.Actions>
|
||||
</Dialog>
|
||||
</Portal>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default AlertDialog;
|
||||
|
|
|
|||
|
|
@ -1,64 +1,71 @@
|
|||
// @flow
|
||||
|
||||
import * as React from 'react';
|
||||
import i18n from "i18n-js";
|
||||
import {ERROR_TYPE} from "../../utils/WebData";
|
||||
import AlertDialog from "./AlertDialog";
|
||||
import i18n from 'i18n-js';
|
||||
import {ERROR_TYPE} from '../../utils/WebData';
|
||||
import AlertDialog from './AlertDialog';
|
||||
|
||||
type Props = {
|
||||
visible: boolean,
|
||||
onDismiss: () => void,
|
||||
errorCode: number,
|
||||
}
|
||||
type PropsType = {
|
||||
visible: boolean,
|
||||
onDismiss: () => void,
|
||||
errorCode: number,
|
||||
};
|
||||
|
||||
class ErrorDialog extends React.PureComponent<Props> {
|
||||
class ErrorDialog extends React.PureComponent<PropsType> {
|
||||
title: string;
|
||||
|
||||
title: string;
|
||||
message: string;
|
||||
message: string;
|
||||
|
||||
generateMessage() {
|
||||
this.title = i18n.t("errors.title");
|
||||
switch (this.props.errorCode) {
|
||||
case ERROR_TYPE.BAD_CREDENTIALS:
|
||||
this.message = i18n.t("errors.badCredentials");
|
||||
break;
|
||||
case ERROR_TYPE.BAD_TOKEN:
|
||||
this.message = i18n.t("errors.badToken");
|
||||
break;
|
||||
case ERROR_TYPE.NO_CONSENT:
|
||||
this.message = i18n.t("errors.noConsent");
|
||||
break;
|
||||
case ERROR_TYPE.TOKEN_SAVE:
|
||||
this.message = i18n.t("errors.tokenSave");
|
||||
break;
|
||||
case ERROR_TYPE.TOKEN_RETRIEVE:
|
||||
this.message = i18n.t("errors.unknown");
|
||||
break;
|
||||
case ERROR_TYPE.BAD_INPUT:
|
||||
this.message = i18n.t("errors.badInput");
|
||||
break;
|
||||
case ERROR_TYPE.FORBIDDEN:
|
||||
this.message = i18n.t("errors.forbidden");
|
||||
break;
|
||||
case ERROR_TYPE.CONNECTION_ERROR:
|
||||
this.message = i18n.t("errors.connectionError");
|
||||
break;
|
||||
case ERROR_TYPE.SERVER_ERROR:
|
||||
this.message = i18n.t("errors.serverError");
|
||||
break;
|
||||
default:
|
||||
this.message = i18n.t("errors.unknown");
|
||||
break;
|
||||
}
|
||||
this.message += "\n\nCode " + this.props.errorCode;
|
||||
generateMessage() {
|
||||
const {props} = this;
|
||||
this.title = i18n.t('errors.title');
|
||||
switch (props.errorCode) {
|
||||
case ERROR_TYPE.BAD_CREDENTIALS:
|
||||
this.message = i18n.t('errors.badCredentials');
|
||||
break;
|
||||
case ERROR_TYPE.BAD_TOKEN:
|
||||
this.message = i18n.t('errors.badToken');
|
||||
break;
|
||||
case ERROR_TYPE.NO_CONSENT:
|
||||
this.message = i18n.t('errors.noConsent');
|
||||
break;
|
||||
case ERROR_TYPE.TOKEN_SAVE:
|
||||
this.message = i18n.t('errors.tokenSave');
|
||||
break;
|
||||
case ERROR_TYPE.TOKEN_RETRIEVE:
|
||||
this.message = i18n.t('errors.unknown');
|
||||
break;
|
||||
case ERROR_TYPE.BAD_INPUT:
|
||||
this.message = i18n.t('errors.badInput');
|
||||
break;
|
||||
case ERROR_TYPE.FORBIDDEN:
|
||||
this.message = i18n.t('errors.forbidden');
|
||||
break;
|
||||
case ERROR_TYPE.CONNECTION_ERROR:
|
||||
this.message = i18n.t('errors.connectionError');
|
||||
break;
|
||||
case ERROR_TYPE.SERVER_ERROR:
|
||||
this.message = i18n.t('errors.serverError');
|
||||
break;
|
||||
default:
|
||||
this.message = i18n.t('errors.unknown');
|
||||
break;
|
||||
}
|
||||
this.message += `\n\nCode ${props.errorCode}`;
|
||||
}
|
||||
|
||||
render() {
|
||||
this.generateMessage();
|
||||
return (
|
||||
<AlertDialog {...this.props} title={this.title} message={this.message}/>
|
||||
);
|
||||
}
|
||||
render(): React.Node {
|
||||
this.generateMessage();
|
||||
const {props} = this;
|
||||
return (
|
||||
<AlertDialog
|
||||
visible={props.visible}
|
||||
onDismiss={props.onDismiss}
|
||||
title={this.title}
|
||||
message={this.message}
|
||||
/>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default ErrorDialog;
|
||||
|
|
|
|||
|
|
@ -1,92 +1,106 @@
|
|||
// @flow
|
||||
|
||||
import * as React from 'react';
|
||||
import {ActivityIndicator, Button, Dialog, Paragraph, Portal} from 'react-native-paper';
|
||||
import i18n from "i18n-js";
|
||||
import {
|
||||
ActivityIndicator,
|
||||
Button,
|
||||
Dialog,
|
||||
Paragraph,
|
||||
Portal,
|
||||
} from 'react-native-paper';
|
||||
import i18n from 'i18n-js';
|
||||
|
||||
type Props = {
|
||||
visible: boolean,
|
||||
onDismiss: () => void,
|
||||
onAccept: () => Promise<void>, // async function to be executed
|
||||
title: string,
|
||||
titleLoading: string,
|
||||
message: string,
|
||||
startLoading: boolean,
|
||||
}
|
||||
type PropsType = {
|
||||
visible: boolean,
|
||||
onDismiss?: () => void,
|
||||
onAccept?: () => Promise<void>, // async function to be executed
|
||||
title?: string,
|
||||
titleLoading?: string,
|
||||
message?: string,
|
||||
startLoading?: boolean,
|
||||
};
|
||||
|
||||
type State = {
|
||||
loading: boolean,
|
||||
}
|
||||
type StateType = {
|
||||
loading: boolean,
|
||||
};
|
||||
|
||||
class LoadingConfirmDialog extends React.PureComponent<Props, State> {
|
||||
class LoadingConfirmDialog extends React.PureComponent<PropsType, StateType> {
|
||||
static defaultProps = {
|
||||
onDismiss: () => {},
|
||||
onAccept: (): Promise<void> => {
|
||||
return Promise.resolve();
|
||||
},
|
||||
title: '',
|
||||
titleLoading: '',
|
||||
message: '',
|
||||
startLoading: false,
|
||||
};
|
||||
|
||||
static defaultProps = {
|
||||
title: '',
|
||||
message: '',
|
||||
onDismiss: () => {},
|
||||
onAccept: () => {return Promise.resolve()},
|
||||
startLoading: false,
|
||||
}
|
||||
|
||||
state = {
|
||||
loading: this.props.startLoading,
|
||||
constructor(props: PropsType) {
|
||||
super(props);
|
||||
this.state = {
|
||||
loading:
|
||||
props.startLoading != null
|
||||
? props.startLoading
|
||||
: LoadingConfirmDialog.defaultProps.startLoading,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the dialog into loading state and closes it when operation finishes
|
||||
*/
|
||||
onClickAccept = () => {
|
||||
this.setState({loading: true});
|
||||
this.props.onAccept().then(this.hideLoading);
|
||||
};
|
||||
/**
|
||||
* Set the dialog into loading state and closes it when operation finishes
|
||||
*/
|
||||
onClickAccept = () => {
|
||||
const {props} = this;
|
||||
this.setState({loading: true});
|
||||
if (props.onAccept != null) props.onAccept().then(this.hideLoading);
|
||||
};
|
||||
|
||||
/**
|
||||
* Waits for fade out animations to finish before hiding loading
|
||||
* @returns {TimeoutID}
|
||||
*/
|
||||
hideLoading = () => setTimeout(() => {
|
||||
this.setState({loading: false})
|
||||
/**
|
||||
* Waits for fade out animations to finish before hiding loading
|
||||
* @returns {TimeoutID}
|
||||
*/
|
||||
hideLoading = (): TimeoutID =>
|
||||
setTimeout(() => {
|
||||
this.setState({loading: false});
|
||||
}, 200);
|
||||
|
||||
/**
|
||||
* Hide the dialog if it is not loading
|
||||
*/
|
||||
onDismiss = () => {
|
||||
if (!this.state.loading)
|
||||
this.props.onDismiss();
|
||||
};
|
||||
/**
|
||||
* Hide the dialog if it is not loading
|
||||
*/
|
||||
onDismiss = () => {
|
||||
const {state, props} = this;
|
||||
if (!state.loading && props.onDismiss != null) props.onDismiss();
|
||||
};
|
||||
|
||||
render() {
|
||||
return (
|
||||
<Portal>
|
||||
<Dialog
|
||||
visible={this.props.visible}
|
||||
onDismiss={this.onDismiss}>
|
||||
<Dialog.Title>
|
||||
{this.state.loading
|
||||
? this.props.titleLoading
|
||||
: this.props.title}
|
||||
</Dialog.Title>
|
||||
<Dialog.Content>
|
||||
{this.state.loading
|
||||
? <ActivityIndicator
|
||||
animating={true}
|
||||
size={'large'}/>
|
||||
: <Paragraph>{this.props.message}</Paragraph>
|
||||
}
|
||||
</Dialog.Content>
|
||||
{this.state.loading
|
||||
? null
|
||||
: <Dialog.Actions>
|
||||
<Button onPress={this.onDismiss}
|
||||
style={{marginRight: 10}}>{i18n.t("dialog.cancel")}</Button>
|
||||
<Button onPress={this.onClickAccept}>{i18n.t("dialog.yes")}</Button>
|
||||
</Dialog.Actions>
|
||||
}
|
||||
</Dialog>
|
||||
</Portal>
|
||||
);
|
||||
}
|
||||
render(): React.Node {
|
||||
const {state, props} = this;
|
||||
return (
|
||||
<Portal>
|
||||
<Dialog visible={props.visible} onDismiss={this.onDismiss}>
|
||||
<Dialog.Title>
|
||||
{state.loading ? props.titleLoading : props.title}
|
||||
</Dialog.Title>
|
||||
<Dialog.Content>
|
||||
{state.loading ? (
|
||||
<ActivityIndicator animating size="large" />
|
||||
) : (
|
||||
<Paragraph>{props.message}</Paragraph>
|
||||
)}
|
||||
</Dialog.Content>
|
||||
{state.loading ? null : (
|
||||
<Dialog.Actions>
|
||||
<Button onPress={this.onDismiss} style={{marginRight: 10}}>
|
||||
{i18n.t('dialog.cancel')}
|
||||
</Button>
|
||||
<Button onPress={this.onClickAccept}>
|
||||
{i18n.t('dialog.yes')}
|
||||
</Button>
|
||||
</Dialog.Actions>
|
||||
)}
|
||||
</Dialog>
|
||||
</Portal>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default LoadingConfirmDialog;
|
||||
|
|
|
|||
|
|
@ -2,55 +2,50 @@
|
|||
|
||||
import * as React from 'react';
|
||||
import {Button, Dialog, Paragraph, Portal} from 'react-native-paper';
|
||||
import {FlatList} from "react-native";
|
||||
import {FlatList} from 'react-native';
|
||||
|
||||
export type OptionsDialogButton = {
|
||||
title: string,
|
||||
onPress: () => void,
|
||||
}
|
||||
export type OptionsDialogButtonType = {
|
||||
title: string,
|
||||
onPress: () => void,
|
||||
};
|
||||
|
||||
type Props = {
|
||||
visible: boolean,
|
||||
title: string,
|
||||
message: string,
|
||||
buttons: Array<OptionsDialogButton>,
|
||||
onDismiss: () => void,
|
||||
}
|
||||
type PropsType = {
|
||||
visible: boolean,
|
||||
title: string,
|
||||
message: string,
|
||||
buttons: Array<OptionsDialogButtonType>,
|
||||
onDismiss: () => void,
|
||||
};
|
||||
|
||||
class OptionsDialog extends React.PureComponent<Props> {
|
||||
class OptionsDialog extends React.PureComponent<PropsType> {
|
||||
getButtonRender = ({item}: {item: OptionsDialogButtonType}): React.Node => {
|
||||
return <Button onPress={item.onPress}>{item.title}</Button>;
|
||||
};
|
||||
|
||||
getButtonRender = ({item}: { item: OptionsDialogButton }) => {
|
||||
return <Button
|
||||
onPress={item.onPress}>
|
||||
{item.title}
|
||||
</Button>;
|
||||
}
|
||||
keyExtractor = (item: OptionsDialogButtonType): string => item.title;
|
||||
|
||||
keyExtractor = (item: OptionsDialogButton) => item.title;
|
||||
|
||||
render() {
|
||||
return (
|
||||
<Portal>
|
||||
<Dialog
|
||||
visible={this.props.visible}
|
||||
onDismiss={this.props.onDismiss}>
|
||||
<Dialog.Title>{this.props.title}</Dialog.Title>
|
||||
<Dialog.Content>
|
||||
<Paragraph>{this.props.message}</Paragraph>
|
||||
</Dialog.Content>
|
||||
<Dialog.Actions>
|
||||
<FlatList
|
||||
data={this.props.buttons}
|
||||
renderItem={this.getButtonRender}
|
||||
keyExtractor={this.keyExtractor}
|
||||
horizontal={true}
|
||||
inverted={true}
|
||||
/>
|
||||
</Dialog.Actions>
|
||||
</Dialog>
|
||||
</Portal>
|
||||
);
|
||||
}
|
||||
render(): React.Node {
|
||||
const {props} = this;
|
||||
return (
|
||||
<Portal>
|
||||
<Dialog visible={props.visible} onDismiss={props.onDismiss}>
|
||||
<Dialog.Title>{props.title}</Dialog.Title>
|
||||
<Dialog.Content>
|
||||
<Paragraph>{props.message}</Paragraph>
|
||||
</Dialog.Content>
|
||||
<Dialog.Actions>
|
||||
<FlatList
|
||||
data={props.buttons}
|
||||
renderItem={this.getButtonRender}
|
||||
keyExtractor={this.keyExtractor}
|
||||
horizontal
|
||||
inverted
|
||||
/>
|
||||
</Dialog.Actions>
|
||||
</Dialog>
|
||||
</Portal>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default OptionsDialog;
|
||||
|
|
|
|||
|
|
@ -2,37 +2,46 @@
|
|||
|
||||
import * as React from 'react';
|
||||
import {List, withTheme} from 'react-native-paper';
|
||||
import {View} from "react-native";
|
||||
import type {CustomTheme} from "../../managers/ThemeManager";
|
||||
import {View} from 'react-native';
|
||||
import i18n from 'i18n-js';
|
||||
import {StackNavigationProp} from "@react-navigation/stack";
|
||||
import {StackNavigationProp} from '@react-navigation/stack';
|
||||
import type {CustomThemeType} from '../../managers/ThemeManager';
|
||||
|
||||
type Props = {
|
||||
navigation: StackNavigationProp,
|
||||
theme: CustomTheme,
|
||||
}
|
||||
type PropsType = {
|
||||
navigation: StackNavigationProp,
|
||||
theme: CustomThemeType,
|
||||
};
|
||||
|
||||
class ActionsDashBoardItem extends React.Component<Props> {
|
||||
class ActionsDashBoardItem extends React.Component<PropsType> {
|
||||
shouldComponentUpdate(nextProps: PropsType): boolean {
|
||||
const {props} = this;
|
||||
return nextProps.theme.dark !== props.theme.dark;
|
||||
}
|
||||
|
||||
shouldComponentUpdate(nextProps: Props): boolean {
|
||||
return (nextProps.theme.dark !== this.props.theme.dark);
|
||||
}
|
||||
|
||||
render() {
|
||||
return (
|
||||
<View>
|
||||
<List.Item
|
||||
title={i18n.t("screens.feedback.homeButtonTitle")}
|
||||
description={i18n.t("screens.feedback.homeButtonSubtitle")}
|
||||
left={props => <List.Icon {...props} icon={"comment-quote"}/>}
|
||||
right={props => <List.Icon {...props} icon={"chevron-right"}/>}
|
||||
onPress={() => this.props.navigation.navigate("feedback")}
|
||||
style={{paddingTop: 0, paddingBottom: 0, marginLeft: 10, marginRight: 10}}
|
||||
/>
|
||||
</View>
|
||||
|
||||
);
|
||||
}
|
||||
render(): React.Node {
|
||||
const {props} = this;
|
||||
return (
|
||||
<View>
|
||||
<List.Item
|
||||
title={i18n.t('screens.feedback.homeButtonTitle')}
|
||||
description={i18n.t('screens.feedback.homeButtonSubtitle')}
|
||||
left={({size}: {size: number}): React.Node => (
|
||||
<List.Icon size={size} icon="comment-quote" />
|
||||
)}
|
||||
right={({size}: {size: number}): React.Node => (
|
||||
<List.Icon size={size} icon="chevron-right" />
|
||||
)}
|
||||
onPress={(): void => props.navigation.navigate('feedback')}
|
||||
style={{
|
||||
paddingTop: 0,
|
||||
paddingBottom: 0,
|
||||
marginLeft: 10,
|
||||
marginRight: 10,
|
||||
}}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default withTheme(ActionsDashBoardItem);
|
||||
|
|
|
|||
|
|
@ -1,91 +1,96 @@
|
|||
// @flow
|
||||
|
||||
import * as React from 'react';
|
||||
import {Avatar, Card, Text, TouchableRipple, withTheme} from 'react-native-paper';
|
||||
import {StyleSheet, View} from "react-native";
|
||||
import i18n from "i18n-js";
|
||||
import type {CustomTheme} from "../../managers/ThemeManager";
|
||||
import {
|
||||
Avatar,
|
||||
Card,
|
||||
Text,
|
||||
TouchableRipple,
|
||||
withTheme,
|
||||
} from 'react-native-paper';
|
||||
import {StyleSheet, View} from 'react-native';
|
||||
import i18n from 'i18n-js';
|
||||
import type {CustomThemeType} from '../../managers/ThemeManager';
|
||||
|
||||
type Props = {
|
||||
eventNumber: number;
|
||||
clickAction: () => void,
|
||||
theme: CustomTheme,
|
||||
children?: React.Node
|
||||
}
|
||||
type PropsType = {
|
||||
eventNumber: number,
|
||||
clickAction: () => void,
|
||||
theme: CustomThemeType,
|
||||
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
|
||||
*/
|
||||
class EventDashBoardItem extends React.Component<Props> {
|
||||
class EventDashBoardItem extends React.Component<PropsType> {
|
||||
static defaultProps = {
|
||||
children: null,
|
||||
};
|
||||
|
||||
shouldComponentUpdate(nextProps: Props) {
|
||||
return (nextProps.theme.dark !== this.props.theme.dark)
|
||||
|| (nextProps.eventNumber !== this.props.eventNumber);
|
||||
}
|
||||
|
||||
render() {
|
||||
const props = this.props;
|
||||
const colors = props.theme.colors;
|
||||
const isAvailable = props.eventNumber > 0;
|
||||
const iconColor = isAvailable ?
|
||||
colors.planningColor :
|
||||
colors.textDisabled;
|
||||
const textColor = isAvailable ?
|
||||
colors.text :
|
||||
colors.textDisabled;
|
||||
let subtitle;
|
||||
if (isAvailable) {
|
||||
subtitle =
|
||||
<Text>
|
||||
<Text style={{fontWeight: "bold"}}>{props.eventNumber}</Text>
|
||||
<Text>
|
||||
{props.eventNumber > 1
|
||||
? i18n.t('screens.home.dashboard.todayEventsSubtitlePlural')
|
||||
: i18n.t('screens.home.dashboard.todayEventsSubtitle')}
|
||||
</Text>
|
||||
</Text>;
|
||||
} else
|
||||
subtitle = i18n.t('screens.home.dashboard.todayEventsSubtitleNA');
|
||||
return (
|
||||
<Card style={styles.card}>
|
||||
<TouchableRipple
|
||||
style={{flex: 1}}
|
||||
onPress={props.clickAction}>
|
||||
<View>
|
||||
<Card.Title
|
||||
title={i18n.t('screens.home.dashboard.todayEventsTitle')}
|
||||
titleStyle={{color: textColor}}
|
||||
subtitle={subtitle}
|
||||
subtitleStyle={{color: textColor}}
|
||||
left={() =>
|
||||
<Avatar.Icon
|
||||
icon={'calendar-range'}
|
||||
color={iconColor}
|
||||
size={60}
|
||||
style={styles.avatar}/>}
|
||||
/>
|
||||
<Card.Content>
|
||||
{props.children}
|
||||
</Card.Content>
|
||||
</View>
|
||||
</TouchableRipple>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
shouldComponentUpdate(nextProps: PropsType): boolean {
|
||||
const {props} = this;
|
||||
return (
|
||||
nextProps.theme.dark !== props.theme.dark ||
|
||||
nextProps.eventNumber !== props.eventNumber
|
||||
);
|
||||
}
|
||||
|
||||
render(): React.Node {
|
||||
const {props} = this;
|
||||
const {colors} = props.theme;
|
||||
const isAvailable = props.eventNumber > 0;
|
||||
const iconColor = isAvailable ? colors.planningColor : colors.textDisabled;
|
||||
const textColor = isAvailable ? colors.text : colors.textDisabled;
|
||||
let subtitle;
|
||||
if (isAvailable) {
|
||||
subtitle = (
|
||||
<Text>
|
||||
<Text style={{fontWeight: 'bold'}}>{props.eventNumber}</Text>
|
||||
<Text>
|
||||
{props.eventNumber > 1
|
||||
? i18n.t('screens.home.dashboard.todayEventsSubtitlePlural')
|
||||
: i18n.t('screens.home.dashboard.todayEventsSubtitle')}
|
||||
</Text>
|
||||
</Text>
|
||||
);
|
||||
} else subtitle = i18n.t('screens.home.dashboard.todayEventsSubtitleNA');
|
||||
return (
|
||||
<Card style={styles.card}>
|
||||
<TouchableRipple style={{flex: 1}} onPress={props.clickAction}>
|
||||
<View>
|
||||
<Card.Title
|
||||
title={i18n.t('screens.home.dashboard.todayEventsTitle')}
|
||||
titleStyle={{color: textColor}}
|
||||
subtitle={subtitle}
|
||||
subtitleStyle={{color: textColor}}
|
||||
left={(): React.Node => (
|
||||
<Avatar.Icon
|
||||
icon="calendar-range"
|
||||
color={iconColor}
|
||||
size={60}
|
||||
style={styles.avatar}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
<Card.Content>{props.children}</Card.Content>
|
||||
</View>
|
||||
</TouchableRipple>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
card: {
|
||||
width: 'auto',
|
||||
marginLeft: 10,
|
||||
marginRight: 10,
|
||||
marginTop: 10,
|
||||
overflow: 'hidden',
|
||||
},
|
||||
avatar: {
|
||||
backgroundColor: 'transparent'
|
||||
}
|
||||
});
|
||||
|
||||
export default withTheme(EventDashBoardItem);
|
||||
|
|
|
|||
|
|
@ -2,126 +2,114 @@
|
|||
|
||||
import * as React from 'react';
|
||||
import {Button, Card, Text, TouchableRipple} from 'react-native-paper';
|
||||
import {Image, View} from "react-native";
|
||||
import Autolink from "react-native-autolink";
|
||||
import i18n from "i18n-js";
|
||||
import {Image, View} from 'react-native';
|
||||
import Autolink from 'react-native-autolink';
|
||||
import i18n from 'i18n-js';
|
||||
import ImageModal from 'react-native-image-modal';
|
||||
import {StackNavigationProp} from "@react-navigation/stack";
|
||||
import type {CustomTheme} from "../../managers/ThemeManager";
|
||||
import type {feedItem} from "../../screens/Home/HomeScreen";
|
||||
import {StackNavigationProp} from '@react-navigation/stack';
|
||||
import type {FeedItemType} from '../../screens/Home/HomeScreen';
|
||||
|
||||
const ICON_AMICALE = require('../../../assets/amicale.png');
|
||||
|
||||
type Props = {
|
||||
navigation: StackNavigationProp,
|
||||
theme: CustomTheme,
|
||||
item: feedItem,
|
||||
title: string,
|
||||
subtitle: string,
|
||||
height: number,
|
||||
}
|
||||
|
||||
type PropsType = {
|
||||
navigation: StackNavigationProp,
|
||||
item: FeedItemType,
|
||||
title: string,
|
||||
subtitle: string,
|
||||
height: number,
|
||||
};
|
||||
|
||||
/**
|
||||
* Component used to display a feed item
|
||||
*/
|
||||
class FeedItem extends React.Component<Props> {
|
||||
class FeedItem extends React.Component<PropsType> {
|
||||
shouldComponentUpdate(): boolean {
|
||||
return false;
|
||||
}
|
||||
|
||||
shouldComponentUpdate() {
|
||||
return false;
|
||||
}
|
||||
onPress = () => {
|
||||
const {props} = this;
|
||||
props.navigation.navigate('feed-information', {
|
||||
data: props.item,
|
||||
date: props.subtitle,
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Gets the amicale INSAT logo
|
||||
*
|
||||
* @return {*}
|
||||
*/
|
||||
getAvatar() {
|
||||
return (
|
||||
<Image
|
||||
size={48}
|
||||
source={ICON_AMICALE}
|
||||
style={{
|
||||
render(): React.Node {
|
||||
const {props} = this;
|
||||
const {item} = props;
|
||||
const hasImage =
|
||||
item.full_picture !== '' && item.full_picture !== undefined;
|
||||
|
||||
const cardMargin = 10;
|
||||
const cardHeight = props.height - 2 * cardMargin;
|
||||
const imageSize = 250;
|
||||
const titleHeight = 80;
|
||||
const actionsHeight = 60;
|
||||
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,
|
||||
height: 48,
|
||||
}}/>
|
||||
);
|
||||
}
|
||||
|
||||
onPress = () => {
|
||||
this.props.navigation.navigate(
|
||||
'feed-information',
|
||||
{
|
||||
data: this.props.item,
|
||||
date: this.props.subtitle
|
||||
});
|
||||
};
|
||||
|
||||
render() {
|
||||
const item = this.props.item;
|
||||
const hasImage = item.full_picture !== '' && item.full_picture !== undefined;
|
||||
|
||||
const cardMargin = 10;
|
||||
const cardHeight = this.props.height - 2 * cardMargin;
|
||||
const imageSize = 250;
|
||||
const titleHeight = 80;
|
||||
const actionsHeight = 60;
|
||||
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={this.props.title}
|
||||
subtitle={this.props.subtitle}
|
||||
left={this.getAvatar}
|
||||
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>
|
||||
);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
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;
|
||||
|
|
|
|||
|
|
@ -1,94 +1,100 @@
|
|||
// @flow
|
||||
|
||||
import * as React from 'react';
|
||||
import {StyleSheet, View} from "react-native";
|
||||
import i18n from "i18n-js";
|
||||
import {StyleSheet, View} from 'react-native';
|
||||
import i18n from 'i18n-js';
|
||||
import {Avatar, Button, Card, TouchableRipple} from 'react-native-paper';
|
||||
import {getFormattedEventTime, isDescriptionEmpty} from "../../utils/Planning";
|
||||
import CustomHTML from "../Overrides/CustomHTML";
|
||||
import type {CustomTheme} from "../../managers/ThemeManager";
|
||||
import type {event} from "../../screens/Home/HomeScreen";
|
||||
import {getFormattedEventTime, isDescriptionEmpty} from '../../utils/Planning';
|
||||
import CustomHTML from '../Overrides/CustomHTML';
|
||||
import type {EventType} from '../../screens/Home/HomeScreen';
|
||||
|
||||
type Props = {
|
||||
event?: event,
|
||||
clickAction: () => void,
|
||||
theme?: CustomTheme,
|
||||
}
|
||||
type PropsType = {
|
||||
event?: EventType | null,
|
||||
clickAction: () => void,
|
||||
};
|
||||
|
||||
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
|
||||
*/
|
||||
class PreviewEventDashboardItem extends React.Component<Props> {
|
||||
// eslint-disable-next-line react/prefer-stateless-function
|
||||
class PreviewEventDashboardItem extends React.Component<PropsType> {
|
||||
static defaultProps = {
|
||||
event: null,
|
||||
};
|
||||
|
||||
render() {
|
||||
const props = this.props;
|
||||
const isEmpty = props.event == null
|
||||
? true
|
||||
: isDescriptionEmpty(props.event.description);
|
||||
render(): React.Node {
|
||||
const {props} = this;
|
||||
const {event} = props;
|
||||
const isEmpty =
|
||||
event == null ? true : isDescriptionEmpty(event.description);
|
||||
|
||||
if (props.event != null) {
|
||||
const event = props.event;
|
||||
const hasImage = event.logo !== '' && event.logo != null;
|
||||
const getImage = () => <Avatar.Image
|
||||
source={{uri: event.logo}}
|
||||
size={50}
|
||||
style={styles.avatar}/>;
|
||||
return (
|
||||
<Card
|
||||
style={styles.card}
|
||||
elevation={3}
|
||||
>
|
||||
<TouchableRipple
|
||||
style={{flex: 1}}
|
||||
onPress={props.clickAction}>
|
||||
<View>
|
||||
{hasImage ?
|
||||
<Card.Title
|
||||
title={event.title}
|
||||
subtitle={getFormattedEventTime(event.date_begin, event.date_end)}
|
||||
left={getImage}
|
||||
/> :
|
||||
<Card.Title
|
||||
title={event.title}
|
||||
subtitle={getFormattedEventTime(event.date_begin, event.date_end)}
|
||||
/>}
|
||||
{!isEmpty ?
|
||||
<Card.Content style={styles.content}>
|
||||
<CustomHTML html={event.description}/>
|
||||
</Card.Content> : null}
|
||||
if (event != null) {
|
||||
const hasImage = event.logo !== '' && event.logo != null;
|
||||
const getImage = (): React.Node => (
|
||||
<Avatar.Image
|
||||
source={{uri: event.logo}}
|
||||
size={50}
|
||||
style={styles.avatar}
|
||||
/>
|
||||
);
|
||||
return (
|
||||
<Card style={styles.card} elevation={3}>
|
||||
<TouchableRipple style={{flex: 1}} onPress={props.clickAction}>
|
||||
<View>
|
||||
{hasImage ? (
|
||||
<Card.Title
|
||||
title={event.title}
|
||||
subtitle={getFormattedEventTime(
|
||||
event.date_begin,
|
||||
event.date_end,
|
||||
)}
|
||||
left={getImage}
|
||||
/>
|
||||
) : (
|
||||
<Card.Title
|
||||
title={event.title}
|
||||
subtitle={getFormattedEventTime(
|
||||
event.date_begin,
|
||||
event.date_end,
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
{!isEmpty ? (
|
||||
<Card.Content style={styles.content}>
|
||||
<CustomHTML html={event.description} />
|
||||
</Card.Content>
|
||||
) : null}
|
||||
|
||||
<Card.Actions style={styles.actions}>
|
||||
<Button
|
||||
icon={'chevron-right'}
|
||||
>
|
||||
{i18n.t("screens.home.dashboard.seeMore")}
|
||||
</Button>
|
||||
</Card.Actions>
|
||||
</View>
|
||||
</TouchableRipple>
|
||||
</Card>
|
||||
);
|
||||
} else
|
||||
return null;
|
||||
<Card.Actions style={styles.actions}>
|
||||
<Button icon="chevron-right">
|
||||
{i18n.t('screens.home.dashboard.seeMore')}
|
||||
</Button>
|
||||
</Card.Actions>
|
||||
</View>
|
||||
</TouchableRipple>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
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;
|
||||
|
|
|
|||
|
|
@ -2,15 +2,15 @@
|
|||
|
||||
import * as React from 'react';
|
||||
import {Badge, TouchableRipple, withTheme} from 'react-native-paper';
|
||||
import {Dimensions, Image, View} from "react-native";
|
||||
import type {CustomTheme} from "../../managers/ThemeManager";
|
||||
import * as Animatable from "react-native-animatable";
|
||||
import {Dimensions, Image, View} from 'react-native';
|
||||
import * as Animatable from 'react-native-animatable';
|
||||
import type {CustomThemeType} from '../../managers/ThemeManager';
|
||||
|
||||
type Props = {
|
||||
image: string,
|
||||
onPress: () => void,
|
||||
badgeCount: number | null,
|
||||
theme: CustomTheme,
|
||||
type PropsType = {
|
||||
image: string | null,
|
||||
onPress: () => void | null,
|
||||
badgeCount: number | null,
|
||||
theme: CustomThemeType,
|
||||
};
|
||||
|
||||
const AnimatableBadge = Animatable.createAnimatableComponent(Badge);
|
||||
|
|
@ -18,69 +18,68 @@ const AnimatableBadge = Animatable.createAnimatableComponent(Badge);
|
|||
/**
|
||||
* Component used to render a small dashboard item
|
||||
*/
|
||||
class SmallDashboardItem extends React.Component<Props> {
|
||||
class SmallDashboardItem extends React.Component<PropsType> {
|
||||
itemSize: number;
|
||||
|
||||
itemSize: number;
|
||||
constructor(props: PropsType) {
|
||||
super(props);
|
||||
this.itemSize = Dimensions.get('window').width / 8;
|
||||
}
|
||||
|
||||
constructor(props: Props) {
|
||||
super(props);
|
||||
this.itemSize = Dimensions.get('window').width / 8;
|
||||
}
|
||||
|
||||
shouldComponentUpdate(nextProps: Props) {
|
||||
return (nextProps.theme.dark !== this.props.theme.dark)
|
||||
|| (nextProps.badgeCount !== this.props.badgeCount);
|
||||
}
|
||||
|
||||
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>
|
||||
|
||||
);
|
||||
}
|
||||
shouldComponentUpdate(nextProps: PropsType): boolean {
|
||||
const {props} = this;
|
||||
return (
|
||||
nextProps.theme.dark !== props.theme.dark ||
|
||||
nextProps.badgeCount !== props.badgeCount
|
||||
);
|
||||
}
|
||||
|
||||
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);
|
||||
|
|
|
|||
|
|
@ -1,72 +1,73 @@
|
|||
// @flow
|
||||
|
||||
import * as React from 'react';
|
||||
import {Animated, Dimensions} from "react-native";
|
||||
import ImageListItem from "./ImageListItem";
|
||||
import CardListItem from "./CardListItem";
|
||||
import type {ViewStyle} from "react-native/Libraries/StyleSheet/StyleSheet";
|
||||
import {Animated, Dimensions} from 'react-native';
|
||||
import type {ViewStyle} from 'react-native/Libraries/StyleSheet/StyleSheet';
|
||||
import ImageListItem from './ImageListItem';
|
||||
import CardListItem from './CardListItem';
|
||||
import type {ServiceItemType} from '../../../managers/ServicesManager';
|
||||
|
||||
type Props = {
|
||||
dataset: Array<cardItem>,
|
||||
isHorizontal: boolean,
|
||||
contentContainerStyle?: ViewStyle,
|
||||
}
|
||||
|
||||
export type cardItem = {
|
||||
key: string,
|
||||
title: string,
|
||||
subtitle: string,
|
||||
image: string | number,
|
||||
onPress: () => void,
|
||||
type PropsType = {
|
||||
dataset: Array<ServiceItemType>,
|
||||
isHorizontal?: boolean,
|
||||
contentContainerStyle?: ViewStyle | null,
|
||||
};
|
||||
|
||||
export type cardList = Array<cardItem>;
|
||||
export default class CardList extends React.Component<PropsType> {
|
||||
static defaultProps = {
|
||||
isHorizontal: false,
|
||||
contentContainerStyle: null,
|
||||
};
|
||||
|
||||
windowWidth: number;
|
||||
|
||||
export default class CardList extends React.Component<Props> {
|
||||
horizontalItemSize: number;
|
||||
|
||||
static defaultProps = {
|
||||
isHorizontal: false,
|
||||
constructor(props: PropsType) {
|
||||
super(props);
|
||||
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',
|
||||
};
|
||||
}
|
||||
|
||||
windowWidth: number;
|
||||
horizontalItemSize: number;
|
||||
|
||||
constructor(props: Props) {
|
||||
super(props);
|
||||
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
|
||||
}
|
||||
|
||||
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',
|
||||
};
|
||||
return (
|
||||
<Animated.FlatList
|
||||
data={props.dataset}
|
||||
renderItem={this.getRenderItem}
|
||||
keyExtractor={this.keyExtractor}
|
||||
numColumns={props.isHorizontal ? undefined : 2}
|
||||
horizontal={props.isHorizontal}
|
||||
contentContainerStyle={
|
||||
props.isHorizontal ? containerStyle : props.contentContainerStyle
|
||||
}
|
||||
return (
|
||||
<Animated.FlatList
|
||||
{...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}
|
||||
/>
|
||||
);
|
||||
}
|
||||
pagingEnabled={props.isHorizontal}
|
||||
snapToInterval={
|
||||
props.isHorizontal ? (this.horizontalItemSize + 5) * 3 : null
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,50 +2,41 @@
|
|||
|
||||
import * as React from 'react';
|
||||
import {Caption, Card, Paragraph, TouchableRipple} from 'react-native-paper';
|
||||
import {View} from "react-native";
|
||||
import type {cardItem} from "./CardList";
|
||||
import {View} from 'react-native';
|
||||
import type {ServiceItemType} from '../../../managers/ServicesManager';
|
||||
|
||||
type Props = {
|
||||
item: cardItem,
|
||||
}
|
||||
|
||||
export default class CardListItem extends React.Component<Props> {
|
||||
|
||||
shouldComponentUpdate() {
|
||||
return false;
|
||||
}
|
||||
|
||||
render() {
|
||||
const props = this.props;
|
||||
const item = props.item;
|
||||
const source = typeof item.image === "number"
|
||||
? item.image
|
||||
: {uri: item.image};
|
||||
return (
|
||||
<Card
|
||||
style={{
|
||||
width: '40%',
|
||||
margin: 5,
|
||||
marginLeft: 'auto',
|
||||
marginRight: 'auto',
|
||||
}}
|
||||
>
|
||||
<TouchableRipple
|
||||
style={{flex: 1}}
|
||||
onPress={item.onPress}>
|
||||
<View>
|
||||
<Card.Cover
|
||||
style={{height: 80}}
|
||||
source={source}
|
||||
/>
|
||||
<Card.Content>
|
||||
<Paragraph>{item.title}</Paragraph>
|
||||
<Caption>{item.subtitle}</Caption>
|
||||
</Card.Content>
|
||||
</View>
|
||||
</TouchableRipple>
|
||||
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
type PropsType = {
|
||||
item: ServiceItemType,
|
||||
};
|
||||
|
||||
export default class CardListItem extends React.Component<PropsType> {
|
||||
shouldComponentUpdate(): boolean {
|
||||
return false;
|
||||
}
|
||||
|
||||
render(): React.Node {
|
||||
const {props} = this;
|
||||
const {item} = props;
|
||||
const source =
|
||||
typeof item.image === 'number' ? item.image : {uri: item.image};
|
||||
return (
|
||||
<Card
|
||||
style={{
|
||||
width: '40%',
|
||||
margin: 5,
|
||||
marginLeft: 'auto',
|
||||
marginRight: 'auto',
|
||||
}}>
|
||||
<TouchableRipple style={{flex: 1}} onPress={item.onPress}>
|
||||
<View>
|
||||
<Card.Cover style={{height: 80}} source={source} />
|
||||
<Card.Content>
|
||||
<Paragraph>{item.title}</Paragraph>
|
||||
<Caption>{item.subtitle}</Caption>
|
||||
</Card.Content>
|
||||
</View>
|
||||
</TouchableRipple>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,53 +3,52 @@
|
|||
import * as React from 'react';
|
||||
import {Text, TouchableRipple} from 'react-native-paper';
|
||||
import {Image, View} from 'react-native';
|
||||
import type {cardItem} from "./CardList";
|
||||
import type {ServiceItemType} from '../../../managers/ServicesManager';
|
||||
|
||||
type Props = {
|
||||
item: cardItem,
|
||||
width: number,
|
||||
}
|
||||
|
||||
export default class ImageListItem extends React.Component<Props> {
|
||||
|
||||
shouldComponentUpdate() {
|
||||
return false;
|
||||
}
|
||||
|
||||
render() {
|
||||
const item = this.props.item;
|
||||
const source = typeof item.image === "number"
|
||||
? item.image
|
||||
: {uri: item.image};
|
||||
return (
|
||||
<TouchableRipple
|
||||
style={{
|
||||
width: this.props.width,
|
||||
height: this.props.width + 40,
|
||||
margin: 5,
|
||||
}}
|
||||
onPress={item.onPress}
|
||||
>
|
||||
<View>
|
||||
<Image
|
||||
style={{
|
||||
width: this.props.width - 20,
|
||||
height: this.props.width - 20,
|
||||
marginLeft: 'auto',
|
||||
marginRight: 'auto',
|
||||
}}
|
||||
source={source}
|
||||
/>
|
||||
<Text style={{
|
||||
marginTop: 5,
|
||||
marginLeft: 'auto',
|
||||
marginRight: 'auto',
|
||||
textAlign: 'center'
|
||||
}}>
|
||||
{item.title}
|
||||
</Text>
|
||||
</View>
|
||||
</TouchableRipple>
|
||||
);
|
||||
}
|
||||
type PropsType = {
|
||||
item: ServiceItemType,
|
||||
width: number,
|
||||
};
|
||||
|
||||
export default class ImageListItem extends React.Component<PropsType> {
|
||||
shouldComponentUpdate(): boolean {
|
||||
return false;
|
||||
}
|
||||
|
||||
render(): React.Node {
|
||||
const {props} = this;
|
||||
const {item} = props;
|
||||
const source =
|
||||
typeof item.image === 'number' ? item.image : {uri: item.image};
|
||||
return (
|
||||
<TouchableRipple
|
||||
style={{
|
||||
width: props.width,
|
||||
height: props.width + 40,
|
||||
margin: 5,
|
||||
}}
|
||||
onPress={item.onPress}>
|
||||
<View>
|
||||
<Image
|
||||
style={{
|
||||
width: props.width - 20,
|
||||
height: props.width - 20,
|
||||
marginLeft: 'auto',
|
||||
marginRight: 'auto',
|
||||
}}
|
||||
source={source}
|
||||
/>
|
||||
<Text
|
||||
style={{
|
||||
marginTop: 5,
|
||||
marginLeft: 'auto',
|
||||
marginRight: 'auto',
|
||||
textAlign: 'center',
|
||||
}}>
|
||||
{item.title}
|
||||
</Text>
|
||||
</View>
|
||||
</TouchableRipple>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,82 +2,90 @@
|
|||
|
||||
import * as React from 'react';
|
||||
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 AnimatedAccordion from "../../Animations/AnimatedAccordion";
|
||||
import {isItemInCategoryFilter} from "../../../utils/Search";
|
||||
import type {category} from "../../../screens/Amicale/Clubs/ClubListScreen";
|
||||
import AnimatedAccordion from '../../Animations/AnimatedAccordion';
|
||||
import {isItemInCategoryFilter} from '../../../utils/Search';
|
||||
import type {ClubCategoryType} from '../../../screens/Amicale/Clubs/ClubListScreen';
|
||||
|
||||
type Props = {
|
||||
categories: Array<category>,
|
||||
onChipSelect: (id: number) => void,
|
||||
selectedCategories: Array<number>,
|
||||
}
|
||||
|
||||
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>
|
||||
);
|
||||
}
|
||||
}
|
||||
type PropsType = {
|
||||
categories: Array<ClubCategoryType>,
|
||||
onChipSelect: (id: number) => void,
|
||||
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,
|
||||
},
|
||||
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>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default ClubListHeader;
|
||||
|
|
|
|||
|
|
@ -2,84 +2,93 @@
|
|||
|
||||
import * as React from 'react';
|
||||
import {Avatar, Chip, List, withTheme} from 'react-native-paper';
|
||||
import {View} from "react-native";
|
||||
import type {category, club} from "../../../screens/Amicale/Clubs/ClubListScreen";
|
||||
import type {CustomTheme} from "../../../managers/ThemeManager";
|
||||
import {View} from 'react-native';
|
||||
import type {
|
||||
ClubCategoryType,
|
||||
ClubType,
|
||||
} from '../../../screens/Amicale/Clubs/ClubListScreen';
|
||||
import type {CustomThemeType} from '../../../managers/ThemeManager';
|
||||
|
||||
type Props = {
|
||||
onPress: () => void,
|
||||
categoryTranslator: (id: number) => category,
|
||||
item: club,
|
||||
height: number,
|
||||
theme: CustomTheme,
|
||||
}
|
||||
type PropsType = {
|
||||
onPress: () => void,
|
||||
categoryTranslator: (id: number) => ClubCategoryType,
|
||||
item: ClubType,
|
||||
height: number,
|
||||
theme: CustomThemeType,
|
||||
};
|
||||
|
||||
class ClubListItem extends React.Component<Props> {
|
||||
class ClubListItem extends React.Component<PropsType> {
|
||||
hasManagers: boolean;
|
||||
|
||||
hasManagers: boolean;
|
||||
constructor(props: PropsType) {
|
||||
super(props);
|
||||
this.hasManagers = props.item.responsibles.length > 0;
|
||||
}
|
||||
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.hasManagers = props.item.responsibles.length > 0;
|
||||
}
|
||||
shouldComponentUpdate(): boolean {
|
||||
return false;
|
||||
}
|
||||
|
||||
shouldComponentUpdate() {
|
||||
return false;
|
||||
}
|
||||
|
||||
getCategoriesRender(categories: Array<number | null>) {
|
||||
let final = [];
|
||||
for (let i = 0; i < categories.length; i++) {
|
||||
if (categories[i] !== null) {
|
||||
const category: category = this.props.categoryTranslator(categories[i]);
|
||||
final.push(
|
||||
<Chip
|
||||
style={{marginRight: 5, marginBottom: 5}}
|
||||
key={this.props.item.id + ':' + category.id}
|
||||
>
|
||||
{category.name}
|
||||
</Chip>
|
||||
);
|
||||
}
|
||||
}
|
||||
return <View style={{flexDirection: 'row'}}>{final}</View>;
|
||||
}
|
||||
|
||||
render() {
|
||||
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',
|
||||
}}
|
||||
/>
|
||||
getCategoriesRender(categories: Array<number | null>): React.Node {
|
||||
const {props} = this;
|
||||
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 {
|
||||
const {props} = this;
|
||||
const categoriesRender = (): React.Node =>
|
||||
this.getCategoriesRender(props.item.category);
|
||||
const {colors} = props.theme;
|
||||
return (
|
||||
<List.Item
|
||||
title={props.item.name}
|
||||
description={categoriesRender}
|
||||
onPress={props.onPress}
|
||||
left={(): React.Node => (
|
||||
<Avatar.Image
|
||||
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}
|
||||
/>
|
||||
)}
|
||||
style={{
|
||||
height: props.height,
|
||||
justifyContent: 'center',
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default withTheme(ClubListItem);
|
||||
|
|
|
|||
|
|
@ -2,71 +2,88 @@
|
|||
|
||||
import * as React from 'react';
|
||||
import {withTheme} from 'react-native-paper';
|
||||
import {FlatList, Image, View} from "react-native";
|
||||
import DashboardEditItem from "./DashboardEditItem";
|
||||
import AnimatedAccordion from "../../Animations/AnimatedAccordion";
|
||||
import type {ServiceCategory, ServiceItem} from "../../../managers/ServicesManager";
|
||||
import MaterialCommunityIcons from "react-native-vector-icons/MaterialCommunityIcons";
|
||||
import type {CustomTheme} from "../../../managers/ThemeManager";
|
||||
import {FlatList, Image, View} from 'react-native';
|
||||
import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons';
|
||||
import DashboardEditItem from './DashboardEditItem';
|
||||
import AnimatedAccordion from '../../Animations/AnimatedAccordion';
|
||||
import type {
|
||||
ServiceCategoryType,
|
||||
ServiceItemType,
|
||||
} from '../../../managers/ServicesManager';
|
||||
import type {CustomThemeType} from '../../../managers/ThemeManager';
|
||||
|
||||
type Props = {
|
||||
item: ServiceCategory,
|
||||
activeDashboard: Array<string>,
|
||||
onPress: (service: ServiceItem) => void,
|
||||
theme: CustomTheme,
|
||||
}
|
||||
type PropsType = {
|
||||
item: ServiceCategoryType,
|
||||
activeDashboard: Array<string>,
|
||||
onPress: (service: ServiceItemType) => void,
|
||||
theme: CustomThemeType,
|
||||
};
|
||||
|
||||
const LIST_ITEM_HEIGHT = 64;
|
||||
|
||||
class DashboardEditAccordion extends React.Component<Props> {
|
||||
class DashboardEditAccordion extends React.Component<PropsType> {
|
||||
getRenderItem = ({item}: {item: ServiceItemType}): React.Node => {
|
||||
const {props} = this;
|
||||
return (
|
||||
<DashboardEditItem
|
||||
height={LIST_ITEM_HEIGHT}
|
||||
item={item}
|
||||
isActive={props.activeDashboard.includes(item.key)}
|
||||
onPress={() => {
|
||||
props.onPress(item);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
renderItem = ({item}: { item: ServiceItem }) => {
|
||||
return (
|
||||
<DashboardEditItem
|
||||
height={LIST_ITEM_HEIGHT}
|
||||
item={item}
|
||||
isActive={this.props.activeDashboard.includes(item.key)}
|
||||
onPress={() => this.props.onPress(item)}/>
|
||||
);
|
||||
}
|
||||
getItemLayout = (
|
||||
data: ?Array<ServiceItemType>,
|
||||
index: number,
|
||||
): {length: number, offset: number, index: number} => ({
|
||||
length: LIST_ITEM_HEIGHT,
|
||||
offset: LIST_ITEM_HEIGHT * index,
|
||||
index,
|
||||
});
|
||||
|
||||
itemLayout = (data, index) => ({length: LIST_ITEM_HEIGHT, offset: LIST_ITEM_HEIGHT * index, index});
|
||||
|
||||
render() {
|
||||
const item = this.props.item;
|
||||
return (
|
||||
<View>
|
||||
<AnimatedAccordion
|
||||
title={item.title}
|
||||
left={props => typeof item.image === "number"
|
||||
? <Image
|
||||
{...props}
|
||||
source={item.image}
|
||||
style={{
|
||||
width: 40,
|
||||
height: 40
|
||||
}}
|
||||
/>
|
||||
: <MaterialCommunityIcons
|
||||
//$FlowFixMe
|
||||
name={item.image}
|
||||
color={this.props.theme.colors.primary}
|
||||
size={40}/>}
|
||||
>
|
||||
{/*$FlowFixMe*/}
|
||||
<FlatList
|
||||
data={item.content}
|
||||
extraData={this.props.activeDashboard.toString()}
|
||||
renderItem={this.renderItem}
|
||||
listKey={item.key}
|
||||
// Performance props, see https://reactnative.dev/docs/optimizing-flatlist-configuration
|
||||
getItemLayout={this.itemLayout}
|
||||
removeClippedSubviews={true}
|
||||
/>
|
||||
</AnimatedAccordion>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
render(): React.Node {
|
||||
const {props} = this;
|
||||
const {item} = props;
|
||||
return (
|
||||
<View>
|
||||
<AnimatedAccordion
|
||||
title={item.title}
|
||||
left={(): React.Node =>
|
||||
typeof item.image === 'number' ? (
|
||||
<Image
|
||||
source={item.image}
|
||||
style={{
|
||||
width: 40,
|
||||
height: 40,
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<MaterialCommunityIcons
|
||||
// $FlowFixMe
|
||||
name={item.image}
|
||||
color={props.theme.colors.primary}
|
||||
size={40}
|
||||
/>
|
||||
)
|
||||
}>
|
||||
{/* $FlowFixMe */}
|
||||
<FlatList
|
||||
data={item.content}
|
||||
extraData={props.activeDashboard.toString()}
|
||||
renderItem={this.getRenderItem}
|
||||
listKey={item.key}
|
||||
// Performance props, see https://reactnative.dev/docs/optimizing-flatlist-configuration
|
||||
getItemLayout={this.getItemLayout}
|
||||
removeClippedSubviews
|
||||
/>
|
||||
</AnimatedAccordion>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default withTheme(DashboardEditAccordion)
|
||||
export default withTheme(DashboardEditAccordion);
|
||||
|
|
|
|||
|
|
@ -1,55 +1,61 @@
|
|||
// @flow
|
||||
|
||||
import * as React from 'react';
|
||||
import {Image} from "react-native";
|
||||
import {Image} from 'react-native';
|
||||
import {List, withTheme} from 'react-native-paper';
|
||||
import type {CustomTheme} from "../../../managers/ThemeManager";
|
||||
import type {ServiceItem} from "../../../managers/ServicesManager";
|
||||
import type {CustomThemeType} from '../../../managers/ThemeManager';
|
||||
import type {ServiceItemType} from '../../../managers/ServicesManager';
|
||||
|
||||
type Props = {
|
||||
item: ServiceItem,
|
||||
isActive: boolean,
|
||||
height: number,
|
||||
onPress: () => void,
|
||||
theme: CustomTheme,
|
||||
}
|
||||
type PropsType = {
|
||||
item: ServiceItemType,
|
||||
isActive: boolean,
|
||||
height: number,
|
||||
onPress: () => void,
|
||||
theme: CustomThemeType,
|
||||
};
|
||||
|
||||
class DashboardEditItem extends React.Component<Props> {
|
||||
class DashboardEditItem extends React.Component<PropsType> {
|
||||
shouldComponentUpdate(nextProps: PropsType): boolean {
|
||||
const {isActive} = this.props;
|
||||
return nextProps.isActive !== isActive;
|
||||
}
|
||||
|
||||
shouldComponentUpdate(nextProps: Props) {
|
||||
return (nextProps.isActive !== this.props.isActive);
|
||||
}
|
||||
|
||||
render() {
|
||||
return (
|
||||
<List.Item
|
||||
title={this.props.item.title}
|
||||
description={this.props.item.subtitle}
|
||||
onPress={this.props.isActive ? null : this.props.onPress}
|
||||
left={props =>
|
||||
<Image
|
||||
{...props}
|
||||
source={{uri: this.props.item.image}}
|
||||
style={{
|
||||
width: 40,
|
||||
height: 40
|
||||
}}
|
||||
/>}
|
||||
right={props => this.props.isActive
|
||||
? <List.Icon
|
||||
{...props}
|
||||
icon={"check"}
|
||||
color={this.props.theme.colors.success}
|
||||
/> : null}
|
||||
style={{
|
||||
height: this.props.height,
|
||||
justifyContent: 'center',
|
||||
paddingLeft: 30,
|
||||
backgroundColor: this.props.isActive ? this.props.theme.colors.proxiwashFinishedColor : "transparent"
|
||||
}}
|
||||
render(): React.Node {
|
||||
const {props} = this;
|
||||
return (
|
||||
<List.Item
|
||||
title={props.item.title}
|
||||
description={props.item.subtitle}
|
||||
onPress={props.isActive ? null : props.onPress}
|
||||
left={(): React.Node => (
|
||||
<Image
|
||||
source={{uri: props.item.image}}
|
||||
style={{
|
||||
width: 40,
|
||||
height: 40,
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
right={({size}: {size: number}): React.Node =>
|
||||
props.isActive ? (
|
||||
<List.Icon
|
||||
size={size}
|
||||
icon="check"
|
||||
color={props.theme.colors.success}
|
||||
/>
|
||||
);
|
||||
}
|
||||
) : null
|
||||
}
|
||||
style={{
|
||||
height: props.height,
|
||||
justifyContent: 'center',
|
||||
paddingLeft: 30,
|
||||
backgroundColor: props.isActive
|
||||
? props.theme.colors.proxiwashFinishedColor
|
||||
: 'transparent',
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default withTheme(DashboardEditItem);
|
||||
|
|
|
|||
|
|
@ -2,57 +2,57 @@
|
|||
|
||||
import * as React from 'react';
|
||||
import {TouchableRipple, withTheme} from 'react-native-paper';
|
||||
import {Dimensions, Image, View} from "react-native";
|
||||
import type {CustomTheme} from "../../../managers/ThemeManager";
|
||||
import {Dimensions, Image, View} from 'react-native';
|
||||
import type {CustomThemeType} from '../../../managers/ThemeManager';
|
||||
|
||||
type Props = {
|
||||
image: string,
|
||||
isActive: boolean,
|
||||
onPress: () => void,
|
||||
theme: CustomTheme,
|
||||
type PropsType = {
|
||||
image: string,
|
||||
isActive: boolean,
|
||||
onPress: () => void,
|
||||
theme: CustomThemeType,
|
||||
};
|
||||
|
||||
/**
|
||||
* Component used to render a small dashboard item
|
||||
*/
|
||||
class DashboardEditPreviewItem extends React.Component<Props> {
|
||||
class DashboardEditPreviewItem extends React.Component<PropsType> {
|
||||
itemSize: number;
|
||||
|
||||
itemSize: number;
|
||||
|
||||
constructor(props: Props) {
|
||||
super(props);
|
||||
this.itemSize = Dimensions.get('window').width / 8;
|
||||
}
|
||||
|
||||
render() {
|
||||
const props = this.props;
|
||||
return (
|
||||
<TouchableRipple
|
||||
onPress={this.props.onPress}
|
||||
borderless={true}
|
||||
style={{
|
||||
marginLeft: 5,
|
||||
marginRight: 5,
|
||||
backgroundColor: this.props.isActive ? this.props.theme.colors.textDisabled : "transparent",
|
||||
borderRadius: 5
|
||||
}}
|
||||
>
|
||||
<View style={{
|
||||
width: this.itemSize,
|
||||
height: this.itemSize,
|
||||
}}>
|
||||
<Image
|
||||
source={{uri: props.image}}
|
||||
style={{
|
||||
width: "100%",
|
||||
height: "100%",
|
||||
}}
|
||||
/>
|
||||
</View>
|
||||
</TouchableRipple>
|
||||
);
|
||||
}
|
||||
constructor(props: PropsType) {
|
||||
super(props);
|
||||
this.itemSize = Dimensions.get('window').width / 8;
|
||||
}
|
||||
|
||||
render(): React.Node {
|
||||
const {props} = this;
|
||||
return (
|
||||
<TouchableRipple
|
||||
onPress={props.onPress}
|
||||
borderless
|
||||
style={{
|
||||
marginLeft: 5,
|
||||
marginRight: 5,
|
||||
backgroundColor: props.isActive
|
||||
? props.theme.colors.textDisabled
|
||||
: 'transparent',
|
||||
borderRadius: 5,
|
||||
}}>
|
||||
<View
|
||||
style={{
|
||||
width: this.itemSize,
|
||||
height: this.itemSize,
|
||||
}}>
|
||||
<Image
|
||||
source={{uri: props.image}}
|
||||
style={{
|
||||
width: '100%',
|
||||
height: '100%',
|
||||
}}
|
||||
/>
|
||||
</View>
|
||||
</TouchableRipple>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default withTheme(DashboardEditPreviewItem)
|
||||
export default withTheme(DashboardEditPreviewItem);
|
||||
|
|
|
|||
|
|
@ -2,111 +2,112 @@
|
|||
|
||||
import * as React from 'react';
|
||||
import {Avatar, List, withTheme} from 'react-native-paper';
|
||||
import type {CustomTheme} from "../../../managers/ThemeManager";
|
||||
import type {Device} from "../../../screens/Amicale/Equipment/EquipmentListScreen";
|
||||
import i18n from "i18n-js";
|
||||
import i18n from 'i18n-js';
|
||||
import {StackNavigationProp} from '@react-navigation/stack';
|
||||
import type {CustomThemeType} from '../../../managers/ThemeManager';
|
||||
import type {DeviceType} from '../../../screens/Amicale/Equipment/EquipmentListScreen';
|
||||
import {
|
||||
getFirstEquipmentAvailability,
|
||||
getRelativeDateString,
|
||||
isEquipmentAvailable
|
||||
} from "../../../utils/EquipmentBooking";
|
||||
import {StackNavigationProp} from "@react-navigation/stack";
|
||||
getFirstEquipmentAvailability,
|
||||
getRelativeDateString,
|
||||
isEquipmentAvailable,
|
||||
} from '../../../utils/EquipmentBooking';
|
||||
|
||||
type Props = {
|
||||
navigation: StackNavigationProp,
|
||||
userDeviceRentDates: [string, string],
|
||||
item: Device,
|
||||
height: number,
|
||||
theme: CustomTheme,
|
||||
}
|
||||
type PropsType = {
|
||||
navigation: StackNavigationProp,
|
||||
userDeviceRentDates: [string, string],
|
||||
item: DeviceType,
|
||||
height: number,
|
||||
theme: CustomThemeType,
|
||||
};
|
||||
|
||||
class EquipmentListItem extends React.Component<Props> {
|
||||
class EquipmentListItem extends React.Component<PropsType> {
|
||||
shouldComponentUpdate(nextProps: PropsType): boolean {
|
||||
const {userDeviceRentDates} = this.props;
|
||||
return nextProps.userDeviceRentDates !== userDeviceRentDates;
|
||||
}
|
||||
|
||||
shouldComponentUpdate(nextProps: Props): boolean {
|
||||
return nextProps.userDeviceRentDates !== this.props.userDeviceRentDates;
|
||||
}
|
||||
render(): React.Node {
|
||||
const {item, userDeviceRentDates, navigation, height, theme} = this.props;
|
||||
const isRented = userDeviceRentDates != null;
|
||||
const isAvailable = isEquipmentAvailable(item);
|
||||
const firstAvailability = getFirstEquipmentAvailability(item);
|
||||
|
||||
render() {
|
||||
const colors = this.props.theme.colors;
|
||||
const item = this.props.item;
|
||||
const userDeviceRentDates = this.props.userDeviceRentDates;
|
||||
const isRented = userDeviceRentDates != null;
|
||||
const isAvailable = isEquipmentAvailable(item);
|
||||
const firstAvailability = getFirstEquipmentAvailability(item);
|
||||
let onPress;
|
||||
if (isRented)
|
||||
onPress = () => {
|
||||
navigation.navigate('equipment-confirm', {
|
||||
item,
|
||||
dates: userDeviceRentDates,
|
||||
});
|
||||
};
|
||||
else
|
||||
onPress = () => {
|
||||
navigation.navigate('equipment-rent', {item});
|
||||
};
|
||||
|
||||
let onPress;
|
||||
if (isRented)
|
||||
onPress = () => this.props.navigation.navigate("equipment-confirm", {
|
||||
item: item,
|
||||
dates: userDeviceRentDates
|
||||
});
|
||||
else
|
||||
onPress = () => this.props.navigation.navigate("equipment-rent", {item: item});
|
||||
let description;
|
||||
if (isRented) {
|
||||
const start = new Date(userDeviceRentDates[0]);
|
||||
const end = new Date(userDeviceRentDates[1]);
|
||||
if (start.getTime() !== end.getTime())
|
||||
description = i18n.t('screens.equipment.bookingPeriod', {
|
||||
begin: getRelativeDateString(start),
|
||||
end: getRelativeDateString(end),
|
||||
});
|
||||
else
|
||||
description = i18n.t('screens.equipment.bookingDay', {
|
||||
date: getRelativeDateString(start),
|
||||
});
|
||||
} else if (isAvailable)
|
||||
description = i18n.t('screens.equipment.bail', {cost: item.caution});
|
||||
else
|
||||
description = i18n.t('screens.equipment.available', {
|
||||
date: getRelativeDateString(firstAvailability),
|
||||
});
|
||||
|
||||
let description;
|
||||
if (isRented) {
|
||||
const start = new Date(userDeviceRentDates[0]);
|
||||
const end = new Date(userDeviceRentDates[1]);
|
||||
if (start.getTime() !== end.getTime())
|
||||
description = i18n.t('screens.equipment.bookingPeriod', {
|
||||
begin: getRelativeDateString(start),
|
||||
end: getRelativeDateString(end)
|
||||
});
|
||||
else
|
||||
description = i18n.t('screens.equipment.bookingDay', {
|
||||
date: getRelativeDateString(start)
|
||||
});
|
||||
} else if (isAvailable)
|
||||
description = i18n.t('screens.equipment.bail', {cost: item.caution});
|
||||
else
|
||||
description = i18n.t('screens.equipment.available', {date: getRelativeDateString(firstAvailability)});
|
||||
let icon;
|
||||
if (isRented) icon = 'bookmark-check';
|
||||
else if (isAvailable) icon = 'check-circle-outline';
|
||||
else icon = 'update';
|
||||
|
||||
let icon;
|
||||
if (isRented)
|
||||
icon = "bookmark-check";
|
||||
else if (isAvailable)
|
||||
icon = "check-circle-outline";
|
||||
else
|
||||
icon = "update";
|
||||
let color;
|
||||
if (isRented) color = theme.colors.warning;
|
||||
else if (isAvailable) color = theme.colors.success;
|
||||
else color = theme.colors.primary;
|
||||
|
||||
let color;
|
||||
if (isRented)
|
||||
color = colors.warning;
|
||||
else if (isAvailable)
|
||||
color = colors.success;
|
||||
else
|
||||
color = colors.primary;
|
||||
|
||||
return (
|
||||
<List.Item
|
||||
title={item.name}
|
||||
description={description}
|
||||
onPress={onPress}
|
||||
left={(props) => <Avatar.Icon
|
||||
{...props}
|
||||
style={{
|
||||
backgroundColor: 'transparent',
|
||||
}}
|
||||
icon={icon}
|
||||
color={color}
|
||||
/>}
|
||||
right={(props) => <Avatar.Icon
|
||||
{...props}
|
||||
style={{
|
||||
marginTop: 'auto',
|
||||
marginBottom: 'auto',
|
||||
backgroundColor: 'transparent',
|
||||
}}
|
||||
size={48}
|
||||
icon={"chevron-right"}
|
||||
/>}
|
||||
style={{
|
||||
height: this.props.height,
|
||||
justifyContent: 'center',
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<List.Item
|
||||
title={item.name}
|
||||
description={description}
|
||||
onPress={onPress}
|
||||
left={({size}: {size: number}): React.Node => (
|
||||
<Avatar.Icon
|
||||
size={size}
|
||||
style={{
|
||||
backgroundColor: 'transparent',
|
||||
}}
|
||||
icon={icon}
|
||||
color={color}
|
||||
/>
|
||||
)}
|
||||
right={(): React.Node => (
|
||||
<Avatar.Icon
|
||||
style={{
|
||||
marginTop: 'auto',
|
||||
marginBottom: 'auto',
|
||||
backgroundColor: 'transparent',
|
||||
}}
|
||||
size={48}
|
||||
icon="chevron-right"
|
||||
/>
|
||||
)}
|
||||
style={{
|
||||
height,
|
||||
justifyContent: 'center',
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default withTheme(EquipmentListItem);
|
||||
|
|
|
|||
|
|
@ -2,96 +2,116 @@
|
|||
|
||||
import * as React from 'react';
|
||||
import {List, withTheme} from 'react-native-paper';
|
||||
import {FlatList, View} from "react-native";
|
||||
import {stringMatchQuery} from "../../../utils/Search";
|
||||
import GroupListItem from "./GroupListItem";
|
||||
import AnimatedAccordion from "../../Animations/AnimatedAccordion";
|
||||
import type {group, groupCategory} from "../../../screens/Planex/GroupSelectionScreen";
|
||||
import type {CustomTheme} from "../../../managers/ThemeManager";
|
||||
import {FlatList, View} from 'react-native';
|
||||
import {stringMatchQuery} from '../../../utils/Search';
|
||||
import GroupListItem from './GroupListItem';
|
||||
import AnimatedAccordion from '../../Animations/AnimatedAccordion';
|
||||
import type {
|
||||
PlanexGroupType,
|
||||
PlanexGroupCategoryType,
|
||||
} from '../../../screens/Planex/GroupSelectionScreen';
|
||||
import type {CustomThemeType} from '../../../managers/ThemeManager';
|
||||
|
||||
type Props = {
|
||||
item: groupCategory,
|
||||
onGroupPress: (group) => void,
|
||||
onFavoritePress: (group) => void,
|
||||
currentSearchString: string,
|
||||
favoriteNumber: number,
|
||||
height: number,
|
||||
theme: CustomTheme,
|
||||
}
|
||||
type PropsType = {
|
||||
item: PlanexGroupCategoryType,
|
||||
favorites: Array<PlanexGroupType>,
|
||||
onGroupPress: (PlanexGroupType) => void,
|
||||
onFavoritePress: (PlanexGroupType) => void,
|
||||
currentSearchString: string,
|
||||
height: number,
|
||||
theme: CustomThemeType,
|
||||
};
|
||||
|
||||
const LIST_ITEM_HEIGHT = 64;
|
||||
const REPLACE_REGEX = /_/g;
|
||||
|
||||
class GroupListAccordion extends React.Component<Props> {
|
||||
class GroupListAccordion extends React.Component<PropsType> {
|
||||
shouldComponentUpdate(nextProps: PropsType): boolean {
|
||||
const {props} = this;
|
||||
return (
|
||||
nextProps.currentSearchString !== props.currentSearchString ||
|
||||
nextProps.favorites.length !== props.favorites.length ||
|
||||
nextProps.item.content.length !== props.item.content.length
|
||||
);
|
||||
}
|
||||
|
||||
shouldComponentUpdate(nextProps: Props) {
|
||||
return (nextProps.currentSearchString !== this.props.currentSearchString)
|
||||
|| (nextProps.favoriteNumber !== this.props.favoriteNumber)
|
||||
|| (nextProps.item.content.length !== this.props.item.content.length);
|
||||
}
|
||||
getRenderItem = ({item}: {item: PlanexGroupType}): React.Node => {
|
||||
const {props} = this;
|
||||
const onPress = () => {
|
||||
props.onGroupPress(item);
|
||||
};
|
||||
const onStarPress = () => {
|
||||
props.onFavoritePress(item);
|
||||
};
|
||||
return (
|
||||
<GroupListItem
|
||||
height={LIST_ITEM_HEIGHT}
|
||||
item={item}
|
||||
favorites={props.favorites}
|
||||
onPress={onPress}
|
||||
onStarPress={onStarPress}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
keyExtractor = (item: group) => item.id.toString();
|
||||
getData(): Array<PlanexGroupType> {
|
||||
const {props} = this;
|
||||
const originalData = props.item.content;
|
||||
const displayData = [];
|
||||
originalData.forEach((data: PlanexGroupType) => {
|
||||
if (stringMatchQuery(data.name, props.currentSearchString))
|
||||
displayData.push(data);
|
||||
});
|
||||
return displayData;
|
||||
}
|
||||
|
||||
renderItem = ({item}: { item: group }) => {
|
||||
const onPress = () => this.props.onGroupPress(item);
|
||||
const onStarPress = () => this.props.onFavoritePress(item);
|
||||
return (
|
||||
<GroupListItem
|
||||
height={LIST_ITEM_HEIGHT}
|
||||
item={item}
|
||||
onPress={onPress}
|
||||
onStarPress={onStarPress}/>
|
||||
);
|
||||
}
|
||||
itemLayout = (
|
||||
data: ?Array<PlanexGroupType>,
|
||||
index: number,
|
||||
): {length: number, offset: number, index: number} => ({
|
||||
length: LIST_ITEM_HEIGHT,
|
||||
offset: LIST_ITEM_HEIGHT * index,
|
||||
index,
|
||||
});
|
||||
|
||||
getData() {
|
||||
const originalData = this.props.item.content;
|
||||
let displayData = [];
|
||||
for (let i = 0; i < originalData.length; i++) {
|
||||
if (stringMatchQuery(originalData[i].name, this.props.currentSearchString))
|
||||
displayData.push(originalData[i]);
|
||||
}
|
||||
return displayData;
|
||||
}
|
||||
keyExtractor = (item: PlanexGroupType): string => item.id.toString();
|
||||
|
||||
itemLayout = (data, index) => ({length: LIST_ITEM_HEIGHT, offset: LIST_ITEM_HEIGHT * index, index});
|
||||
|
||||
|
||||
render() {
|
||||
const item = this.props.item;
|
||||
return (
|
||||
<View>
|
||||
<AnimatedAccordion
|
||||
title={item.name}
|
||||
style={{
|
||||
height: this.props.height,
|
||||
justifyContent: 'center',
|
||||
}}
|
||||
left={props =>
|
||||
item.id === 0
|
||||
? <List.Icon
|
||||
{...props}
|
||||
icon={"star"}
|
||||
color={this.props.theme.colors.tetrisScore}
|
||||
/>
|
||||
: null}
|
||||
unmountWhenCollapsed={true}// Only render list if expanded for increased performance
|
||||
opened={this.props.item.id === 0 || this.props.currentSearchString.length > 0}
|
||||
>
|
||||
{/*$FlowFixMe*/}
|
||||
<FlatList
|
||||
data={this.getData()}
|
||||
extraData={this.props.currentSearchString}
|
||||
renderItem={this.renderItem}
|
||||
keyExtractor={this.keyExtractor}
|
||||
listKey={item.id.toString()}
|
||||
// Performance props, see https://reactnative.dev/docs/optimizing-flatlist-configuration
|
||||
getItemLayout={this.itemLayout}
|
||||
removeClippedSubviews={true}
|
||||
/>
|
||||
</AnimatedAccordion>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
render(): React.Node {
|
||||
const {props} = this;
|
||||
const {item} = this.props;
|
||||
return (
|
||||
<View>
|
||||
<AnimatedAccordion
|
||||
title={item.name.replace(REPLACE_REGEX, ' ')}
|
||||
style={{
|
||||
height: props.height,
|
||||
justifyContent: 'center',
|
||||
}}
|
||||
left={({size}: {size: number}): React.Node =>
|
||||
item.id === 0 ? (
|
||||
<List.Icon
|
||||
size={size}
|
||||
icon="star"
|
||||
color={props.theme.colors.tetrisScore}
|
||||
/>
|
||||
) : null
|
||||
}
|
||||
unmountWhenCollapsed={item.id !== 0} // Only render list if expanded for increased performance
|
||||
opened={props.currentSearchString.length > 0}>
|
||||
<FlatList
|
||||
data={this.getData()}
|
||||
extraData={props.currentSearchString + props.favorites.length}
|
||||
renderItem={this.getRenderItem}
|
||||
keyExtractor={this.keyExtractor}
|
||||
listKey={item.id.toString()}
|
||||
// Performance props, see https://reactnative.dev/docs/optimizing-flatlist-configuration
|
||||
getItemLayout={this.itemLayout}
|
||||
removeClippedSubviews
|
||||
/>
|
||||
</AnimatedAccordion>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default withTheme(GroupListAccordion)
|
||||
export default withTheme(GroupListAccordion);
|
||||
|
|
|
|||
|
|
@ -2,65 +2,85 @@
|
|||
|
||||
import * as React from 'react';
|
||||
import {IconButton, List, withTheme} from 'react-native-paper';
|
||||
import type {CustomTheme} from "../../../managers/ThemeManager";
|
||||
import type {group} from "../../../screens/Planex/GroupSelectionScreen";
|
||||
import * as Animatable from 'react-native-animatable';
|
||||
import type {CustomThemeType} from '../../../managers/ThemeManager';
|
||||
import type {PlanexGroupType} from '../../../screens/Planex/GroupSelectionScreen';
|
||||
|
||||
type Props = {
|
||||
theme: CustomTheme,
|
||||
onPress: () => void,
|
||||
onStarPress: () => void,
|
||||
item: group,
|
||||
height: number,
|
||||
}
|
||||
type PropsType = {
|
||||
theme: CustomThemeType,
|
||||
onPress: () => void,
|
||||
onStarPress: () => void,
|
||||
item: PlanexGroupType,
|
||||
favorites: Array<PlanexGroupType>,
|
||||
height: number,
|
||||
};
|
||||
|
||||
type State = {
|
||||
isFav: boolean,
|
||||
}
|
||||
const REPLACE_REGEX = /_/g;
|
||||
|
||||
class GroupListItem extends React.Component<Props, State> {
|
||||
class GroupListItem extends React.Component<PropsType> {
|
||||
isFav: boolean;
|
||||
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.state = {
|
||||
isFav: (props.item.isFav !== undefined && props.item.isFav),
|
||||
}
|
||||
starRef = {current: null | IconButton};
|
||||
|
||||
constructor(props: PropsType) {
|
||||
super(props);
|
||||
this.isFav = this.isGroupInFavorites(props.favorites);
|
||||
}
|
||||
|
||||
shouldComponentUpdate(nextProps: PropsType): boolean {
|
||||
const {favorites} = this.props;
|
||||
const favChanged = favorites.length !== nextProps.favorites.length;
|
||||
let newFavState = this.isFav;
|
||||
if (favChanged) newFavState = this.isGroupInFavorites(nextProps.favorites);
|
||||
const shouldUpdate = this.isFav !== newFavState;
|
||||
this.isFav = newFavState;
|
||||
return shouldUpdate;
|
||||
}
|
||||
|
||||
isGroupInFavorites(favorites: Array<PlanexGroupType>): boolean {
|
||||
const {item} = this.props;
|
||||
for (let i = 0; i < favorites.length; i += 1) {
|
||||
if (favorites[i].id === item.id) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
shouldComponentUpdate(prevProps: Props, prevState: State) {
|
||||
return (prevState.isFav !== this.state.isFav);
|
||||
onStarPress = () => {
|
||||
const {props} = this;
|
||||
if (this.starRef.current != null) {
|
||||
if (this.isFav) this.starRef.current.rubberBand();
|
||||
else this.starRef.current.swing();
|
||||
}
|
||||
props.onStarPress();
|
||||
};
|
||||
|
||||
onStarPress = () => {
|
||||
this.setState({isFav: !this.state.isFav});
|
||||
this.props.onStarPress();
|
||||
}
|
||||
|
||||
render() {
|
||||
const colors = this.props.theme.colors;
|
||||
return (
|
||||
<List.Item
|
||||
title={this.props.item.name}
|
||||
onPress={this.props.onPress}
|
||||
left={props =>
|
||||
<List.Icon
|
||||
{...props}
|
||||
icon={"chevron-right"}/>}
|
||||
right={props =>
|
||||
<IconButton
|
||||
{...props}
|
||||
icon={"star"}
|
||||
onPress={this.onStarPress}
|
||||
color={this.state.isFav
|
||||
? colors.tetrisScore
|
||||
: props.color}
|
||||
/>}
|
||||
style={{
|
||||
height: this.props.height,
|
||||
justifyContent: 'center',
|
||||
}}
|
||||
render(): React.Node {
|
||||
const {props} = this;
|
||||
const {colors} = props.theme;
|
||||
return (
|
||||
<List.Item
|
||||
title={props.item.name.replace(REPLACE_REGEX, ' ')}
|
||||
onPress={props.onPress}
|
||||
left={({size}: {size: number}): React.Node => (
|
||||
<List.Icon size={size} icon="chevron-right" />
|
||||
)}
|
||||
right={({size, color}: {size: number, color: string}): React.Node => (
|
||||
<Animatable.View ref={this.starRef} useNativeDriver>
|
||||
<IconButton
|
||||
size={size}
|
||||
icon="star"
|
||||
onPress={this.onStarPress}
|
||||
color={this.isFav ? colors.tetrisScore : color}
|
||||
/>
|
||||
);
|
||||
}
|
||||
</Animatable.View>
|
||||
)}
|
||||
style={{
|
||||
height: props.height,
|
||||
justifyContent: 'center',
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default withTheme(GroupListItem);
|
||||
|
|
|
|||
|
|
@ -2,48 +2,48 @@
|
|||
|
||||
import * as React from 'react';
|
||||
import {Avatar, List, Text, withTheme} from 'react-native-paper';
|
||||
import i18n from "i18n-js";
|
||||
import i18n from 'i18n-js';
|
||||
import type {ProximoArticleType} from '../../../screens/Services/Proximo/ProximoMainScreen';
|
||||
|
||||
type Props = {
|
||||
onPress: Function,
|
||||
color: string,
|
||||
item: Object,
|
||||
height: number,
|
||||
}
|
||||
type PropsType = {
|
||||
onPress: () => void,
|
||||
color: string,
|
||||
item: ProximoArticleType,
|
||||
height: number,
|
||||
};
|
||||
|
||||
class ProximoListItem extends React.Component<Props> {
|
||||
class ProximoListItem extends React.Component<PropsType> {
|
||||
shouldComponentUpdate(): boolean {
|
||||
return false;
|
||||
}
|
||||
|
||||
colors: Object;
|
||||
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.colors = props.theme.colors;
|
||||
}
|
||||
|
||||
shouldComponentUpdate() {
|
||||
return false;
|
||||
}
|
||||
|
||||
render() {
|
||||
return (
|
||||
<List.Item
|
||||
title={this.props.item.name}
|
||||
description={this.props.item.quantity + ' ' + i18n.t('screens.proximo.inStock')}
|
||||
descriptionStyle={{color: this.props.color}}
|
||||
onPress={this.props.onPress}
|
||||
left={() => <Avatar.Image style={{backgroundColor: 'transparent'}} size={64}
|
||||
source={{uri: this.props.item.image}}/>}
|
||||
right={() =>
|
||||
<Text style={{fontWeight: "bold"}}>
|
||||
{this.props.item.price}€
|
||||
</Text>}
|
||||
style={{
|
||||
height: this.props.height,
|
||||
justifyContent: 'center',
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
render(): React.Node {
|
||||
const {props} = this;
|
||||
return (
|
||||
<List.Item
|
||||
title={props.item.name}
|
||||
description={`${props.item.quantity} ${i18n.t(
|
||||
'screens.proximo.inStock',
|
||||
)}`}
|
||||
descriptionStyle={{color: props.color}}
|
||||
onPress={props.onPress}
|
||||
left={(): React.Node => (
|
||||
<Avatar.Image
|
||||
style={{backgroundColor: 'transparent'}}
|
||||
size={64}
|
||||
source={{uri: props.item.image}}
|
||||
/>
|
||||
)}
|
||||
right={(): React.Node => (
|
||||
<Text style={{fontWeight: 'bold'}}>{props.item.price}€</Text>
|
||||
)}
|
||||
style={{
|
||||
height: props.height,
|
||||
justifyContent: 'center',
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default withTheme(ProximoListItem);
|
||||
|
|
|
|||
|
|
@ -1,194 +1,236 @@
|
|||
import * as React from 'react';
|
||||
import {Avatar, Caption, List, ProgressBar, Surface, Text, withTheme} from 'react-native-paper';
|
||||
import {StyleSheet, View} from "react-native";
|
||||
import ProxiwashConstants from "../../../constants/ProxiwashConstants";
|
||||
import i18n from "i18n-js";
|
||||
import AprilFoolsManager from "../../../managers/AprilFoolsManager";
|
||||
import * as Animatable from "react-native-animatable";
|
||||
import type {CustomTheme} from "../../../managers/ThemeManager";
|
||||
import type {Machine} from "../../../screens/Proxiwash/ProxiwashScreen";
|
||||
// @flow
|
||||
|
||||
type Props = {
|
||||
item: Machine,
|
||||
theme: CustomTheme,
|
||||
onPress: Function,
|
||||
isWatched: boolean,
|
||||
import * as React from 'react';
|
||||
import {
|
||||
Avatar,
|
||||
Caption,
|
||||
List,
|
||||
ProgressBar,
|
||||
Surface,
|
||||
Text,
|
||||
withTheme,
|
||||
} from 'react-native-paper';
|
||||
import {StyleSheet, View} from 'react-native';
|
||||
import i18n from 'i18n-js';
|
||||
import * as Animatable from 'react-native-animatable';
|
||||
import ProxiwashConstants from '../../../constants/ProxiwashConstants';
|
||||
import AprilFoolsManager from '../../../managers/AprilFoolsManager';
|
||||
import type {CustomThemeType} from '../../../managers/ThemeManager';
|
||||
import type {ProxiwashMachineType} from '../../../screens/Proxiwash/ProxiwashScreen';
|
||||
|
||||
type PropsType = {
|
||||
item: ProxiwashMachineType,
|
||||
theme: CustomThemeType,
|
||||
onPress: (
|
||||
title: string,
|
||||
item: ProxiwashMachineType,
|
||||
isDryer: boolean,
|
||||
height: number,
|
||||
}
|
||||
) => void,
|
||||
isWatched: boolean,
|
||||
isDryer: boolean,
|
||||
height: number,
|
||||
};
|
||||
|
||||
const AnimatedIcon = Animatable.createAnimatableComponent(Avatar.Icon);
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
container: {
|
||||
margin: 5,
|
||||
justifyContent: 'center',
|
||||
elevation: 1,
|
||||
},
|
||||
icon: {
|
||||
backgroundColor: 'transparent',
|
||||
},
|
||||
progressBar: {
|
||||
position: 'absolute',
|
||||
left: 0,
|
||||
borderRadius: 4,
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* Component used to display a proxiwash item, showing machine progression and state
|
||||
*/
|
||||
class ProxiwashListItem extends React.Component<Props> {
|
||||
class ProxiwashListItem extends React.Component<PropsType> {
|
||||
stateColors: {[key: string]: string};
|
||||
|
||||
stateColors: Object;
|
||||
stateStrings: Object;
|
||||
stateStrings: {[key: string]: string};
|
||||
|
||||
title: string;
|
||||
title: string;
|
||||
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.stateColors = {};
|
||||
this.stateStrings = {};
|
||||
constructor(props: PropsType) {
|
||||
super(props);
|
||||
this.stateColors = {};
|
||||
this.stateStrings = {};
|
||||
|
||||
this.updateStateStrings();
|
||||
this.updateStateStrings();
|
||||
|
||||
let displayNumber = props.item.number;
|
||||
if (AprilFoolsManager.getInstance().isAprilFoolsEnabled())
|
||||
displayNumber = AprilFoolsManager.getProxiwashMachineDisplayNumber(parseInt(props.item.number));
|
||||
let displayNumber = props.item.number;
|
||||
if (AprilFoolsManager.getInstance().isAprilFoolsEnabled())
|
||||
displayNumber = AprilFoolsManager.getProxiwashMachineDisplayNumber(
|
||||
parseInt(props.item.number, 10),
|
||||
);
|
||||
|
||||
this.title = props.isDryer
|
||||
? i18n.t('screens.proxiwash.dryer')
|
||||
: i18n.t('screens.proxiwash.washer');
|
||||
this.title += ' n°' + displayNumber;
|
||||
}
|
||||
this.title = props.isDryer
|
||||
? i18n.t('screens.proxiwash.dryer')
|
||||
: i18n.t('screens.proxiwash.washer');
|
||||
this.title += ` n°${displayNumber}`;
|
||||
}
|
||||
|
||||
shouldComponentUpdate(nextProps: Props): boolean {
|
||||
const props = this.props;
|
||||
return (nextProps.theme.dark !== props.theme.dark)
|
||||
|| (nextProps.item.state !== props.item.state)
|
||||
|| (nextProps.item.donePercent !== props.item.donePercent)
|
||||
|| (nextProps.isWatched !== props.isWatched);
|
||||
}
|
||||
shouldComponentUpdate(nextProps: PropsType): boolean {
|
||||
const {props} = this;
|
||||
return (
|
||||
nextProps.theme.dark !== props.theme.dark ||
|
||||
nextProps.item.state !== props.item.state ||
|
||||
nextProps.item.donePercent !== props.item.donePercent ||
|
||||
nextProps.isWatched !== props.isWatched
|
||||
);
|
||||
}
|
||||
|
||||
updateStateStrings() {
|
||||
this.stateStrings[ProxiwashConstants.machineStates.AVAILABLE] = i18n.t('screens.proxiwash.states.ready');
|
||||
this.stateStrings[ProxiwashConstants.machineStates.RUNNING] = i18n.t('screens.proxiwash.states.running');
|
||||
this.stateStrings[ProxiwashConstants.machineStates.RUNNING_NOT_STARTED] = i18n.t('screens.proxiwash.states.runningNotStarted');
|
||||
this.stateStrings[ProxiwashConstants.machineStates.FINISHED] = i18n.t('screens.proxiwash.states.finished');
|
||||
this.stateStrings[ProxiwashConstants.machineStates.UNAVAILABLE] = i18n.t('screens.proxiwash.states.broken');
|
||||
this.stateStrings[ProxiwashConstants.machineStates.ERROR] = i18n.t('screens.proxiwash.states.error');
|
||||
this.stateStrings[ProxiwashConstants.machineStates.UNKNOWN] = i18n.t('screens.proxiwash.states.unknown');
|
||||
}
|
||||
onListItemPress = () => {
|
||||
const {props} = this;
|
||||
props.onPress(this.title, props.item, props.isDryer);
|
||||
};
|
||||
|
||||
updateStateColors() {
|
||||
const colors = this.props.theme.colors;
|
||||
this.stateColors[ProxiwashConstants.machineStates.AVAILABLE] = colors.proxiwashReadyColor;
|
||||
this.stateColors[ProxiwashConstants.machineStates.RUNNING] = colors.proxiwashRunningColor;
|
||||
this.stateColors[ProxiwashConstants.machineStates.RUNNING_NOT_STARTED] = colors.proxiwashRunningNotStartedColor;
|
||||
this.stateColors[ProxiwashConstants.machineStates.FINISHED] = colors.proxiwashFinishedColor;
|
||||
this.stateColors[ProxiwashConstants.machineStates.UNAVAILABLE] = colors.proxiwashBrokenColor;
|
||||
this.stateColors[ProxiwashConstants.machineStates.ERROR] = colors.proxiwashErrorColor;
|
||||
this.stateColors[ProxiwashConstants.machineStates.UNKNOWN] = colors.proxiwashUnknownColor;
|
||||
}
|
||||
updateStateStrings() {
|
||||
this.stateStrings[ProxiwashConstants.machineStates.AVAILABLE] = i18n.t(
|
||||
'screens.proxiwash.states.ready',
|
||||
);
|
||||
this.stateStrings[ProxiwashConstants.machineStates.RUNNING] = i18n.t(
|
||||
'screens.proxiwash.states.running',
|
||||
);
|
||||
this.stateStrings[
|
||||
ProxiwashConstants.machineStates.RUNNING_NOT_STARTED
|
||||
] = i18n.t('screens.proxiwash.states.runningNotStarted');
|
||||
this.stateStrings[ProxiwashConstants.machineStates.FINISHED] = i18n.t(
|
||||
'screens.proxiwash.states.finished',
|
||||
);
|
||||
this.stateStrings[ProxiwashConstants.machineStates.UNAVAILABLE] = i18n.t(
|
||||
'screens.proxiwash.states.broken',
|
||||
);
|
||||
this.stateStrings[ProxiwashConstants.machineStates.ERROR] = i18n.t(
|
||||
'screens.proxiwash.states.error',
|
||||
);
|
||||
this.stateStrings[ProxiwashConstants.machineStates.UNKNOWN] = i18n.t(
|
||||
'screens.proxiwash.states.unknown',
|
||||
);
|
||||
}
|
||||
|
||||
onListItemPress = () => this.props.onPress(this.title, this.props.item, this.props.isDryer);
|
||||
updateStateColors() {
|
||||
const {props} = this;
|
||||
const {colors} = props.theme;
|
||||
this.stateColors[ProxiwashConstants.machineStates.AVAILABLE] =
|
||||
colors.proxiwashReadyColor;
|
||||
this.stateColors[ProxiwashConstants.machineStates.RUNNING] =
|
||||
colors.proxiwashRunningColor;
|
||||
this.stateColors[ProxiwashConstants.machineStates.RUNNING_NOT_STARTED] =
|
||||
colors.proxiwashRunningNotStartedColor;
|
||||
this.stateColors[ProxiwashConstants.machineStates.FINISHED] =
|
||||
colors.proxiwashFinishedColor;
|
||||
this.stateColors[ProxiwashConstants.machineStates.UNAVAILABLE] =
|
||||
colors.proxiwashBrokenColor;
|
||||
this.stateColors[ProxiwashConstants.machineStates.ERROR] =
|
||||
colors.proxiwashErrorColor;
|
||||
this.stateColors[ProxiwashConstants.machineStates.UNKNOWN] =
|
||||
colors.proxiwashUnknownColor;
|
||||
}
|
||||
|
||||
render() {
|
||||
const props = this.props;
|
||||
const colors = props.theme.colors;
|
||||
const machineState = props.item.state;
|
||||
const isRunning = machineState === ProxiwashConstants.machineStates.RUNNING;
|
||||
const isReady = machineState === ProxiwashConstants.machineStates.AVAILABLE;
|
||||
const description = isRunning ? props.item.startTime + '/' + props.item.endTime : '';
|
||||
const stateIcon = ProxiwashConstants.stateIcons[machineState];
|
||||
const stateString = this.stateStrings[machineState];
|
||||
const progress = isRunning
|
||||
? props.item.donePercent !== ''
|
||||
? parseFloat(props.item.donePercent) / 100
|
||||
: 0
|
||||
: 1;
|
||||
render(): React.Node {
|
||||
const {props} = this;
|
||||
const {colors} = props.theme;
|
||||
const machineState = props.item.state;
|
||||
const isRunning = machineState === ProxiwashConstants.machineStates.RUNNING;
|
||||
const isReady = machineState === ProxiwashConstants.machineStates.AVAILABLE;
|
||||
const description = isRunning
|
||||
? `${props.item.startTime}/${props.item.endTime}`
|
||||
: '';
|
||||
const stateIcon = ProxiwashConstants.stateIcons[machineState];
|
||||
const stateString = this.stateStrings[machineState];
|
||||
let progress;
|
||||
if (isRunning && props.item.donePercent !== '')
|
||||
progress = parseFloat(props.item.donePercent) / 100;
|
||||
else if (isRunning) progress = 0;
|
||||
else progress = 1;
|
||||
|
||||
const icon = props.isWatched
|
||||
? <AnimatedIcon
|
||||
icon={'bell-ring'}
|
||||
animation={"rubberBand"}
|
||||
useNativeDriver
|
||||
size={50}
|
||||
color={colors.primary}
|
||||
style={styles.icon}
|
||||
/>
|
||||
: <AnimatedIcon
|
||||
icon={props.isDryer ? 'tumble-dryer' : 'washing-machine'}
|
||||
animation={isRunning ? "pulse" : undefined}
|
||||
iterationCount={"infinite"}
|
||||
easing={"linear"}
|
||||
duration={1000}
|
||||
useNativeDriver
|
||||
size={40}
|
||||
color={colors.text}
|
||||
style={styles.icon}
|
||||
/>;
|
||||
this.updateStateColors();
|
||||
return (
|
||||
<Surface
|
||||
style={{
|
||||
...styles.container,
|
||||
height: props.height,
|
||||
borderRadius: 4,
|
||||
}}
|
||||
>
|
||||
{
|
||||
!isReady
|
||||
? <ProgressBar
|
||||
style={{
|
||||
...styles.progressBar,
|
||||
height: props.height
|
||||
}}
|
||||
progress={progress}
|
||||
color={this.stateColors[machineState]}
|
||||
/>
|
||||
: null
|
||||
}
|
||||
<List.Item
|
||||
title={this.title}
|
||||
description={description}
|
||||
style={{
|
||||
height: props.height,
|
||||
justifyContent: 'center',
|
||||
}}
|
||||
onPress={this.onListItemPress}
|
||||
left={() => icon}
|
||||
right={() => (
|
||||
<View style={{flexDirection: 'row',}}>
|
||||
<View style={{justifyContent: 'center',}}>
|
||||
<Text style={
|
||||
machineState === ProxiwashConstants.machineStates.FINISHED ?
|
||||
{fontWeight: 'bold',} : {}
|
||||
}
|
||||
>
|
||||
{stateString}
|
||||
</Text>
|
||||
{
|
||||
machineState === ProxiwashConstants.machineStates.RUNNING
|
||||
? <Caption>{props.item.remainingTime} min</Caption>
|
||||
: null
|
||||
}
|
||||
|
||||
</View>
|
||||
<View style={{justifyContent: 'center',}}>
|
||||
<Avatar.Icon
|
||||
icon={stateIcon}
|
||||
color={colors.text}
|
||||
size={30}
|
||||
style={styles.icon}
|
||||
/>
|
||||
</View>
|
||||
</View>)}
|
||||
const icon = props.isWatched ? (
|
||||
<AnimatedIcon
|
||||
icon="bell-ring"
|
||||
animation="rubberBand"
|
||||
useNativeDriver
|
||||
size={50}
|
||||
color={colors.primary}
|
||||
style={styles.icon}
|
||||
/>
|
||||
) : (
|
||||
<AnimatedIcon
|
||||
icon={props.isDryer ? 'tumble-dryer' : 'washing-machine'}
|
||||
animation={isRunning ? 'pulse' : undefined}
|
||||
iterationCount="infinite"
|
||||
easing="linear"
|
||||
duration={1000}
|
||||
useNativeDriver
|
||||
size={40}
|
||||
color={colors.text}
|
||||
style={styles.icon}
|
||||
/>
|
||||
);
|
||||
this.updateStateColors();
|
||||
return (
|
||||
<Surface
|
||||
style={{
|
||||
...styles.container,
|
||||
height: props.height,
|
||||
borderRadius: 4,
|
||||
}}>
|
||||
{!isReady ? (
|
||||
<ProgressBar
|
||||
style={{
|
||||
...styles.progressBar,
|
||||
height: props.height,
|
||||
}}
|
||||
progress={progress}
|
||||
color={this.stateColors[machineState]}
|
||||
/>
|
||||
) : null}
|
||||
<List.Item
|
||||
title={this.title}
|
||||
description={description}
|
||||
style={{
|
||||
height: props.height,
|
||||
justifyContent: 'center',
|
||||
}}
|
||||
onPress={this.onListItemPress}
|
||||
left={(): React.Node => icon}
|
||||
right={(): React.Node => (
|
||||
<View style={{flexDirection: 'row'}}>
|
||||
<View style={{justifyContent: 'center'}}>
|
||||
<Text
|
||||
style={
|
||||
machineState === ProxiwashConstants.machineStates.FINISHED
|
||||
? {fontWeight: 'bold'}
|
||||
: {}
|
||||
}>
|
||||
{stateString}
|
||||
</Text>
|
||||
{machineState === ProxiwashConstants.machineStates.RUNNING ? (
|
||||
<Caption>{props.item.remainingTime} min</Caption>
|
||||
) : null}
|
||||
</View>
|
||||
<View style={{justifyContent: 'center'}}>
|
||||
<Avatar.Icon
|
||||
icon={stateIcon}
|
||||
color={colors.text}
|
||||
size={30}
|
||||
style={styles.icon}
|
||||
/>
|
||||
</Surface>
|
||||
);
|
||||
}
|
||||
</View>
|
||||
</View>
|
||||
)}
|
||||
/>
|
||||
</Surface>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
container: {
|
||||
margin: 5,
|
||||
justifyContent: 'center',
|
||||
elevation: 1
|
||||
},
|
||||
icon: {
|
||||
backgroundColor: 'transparent'
|
||||
},
|
||||
progressBar: {
|
||||
position: 'absolute',
|
||||
left: 0,
|
||||
borderRadius: 4,
|
||||
},
|
||||
});
|
||||
|
||||
export default withTheme(ProxiwashListItem);
|
||||
|
|
|
|||
|
|
@ -1,72 +1,72 @@
|
|||
// @flow
|
||||
|
||||
import * as React from 'react';
|
||||
import {Avatar, Text, withTheme} from 'react-native-paper';
|
||||
import {StyleSheet, View} from "react-native";
|
||||
import i18n from "i18n-js";
|
||||
import {StyleSheet, View} from 'react-native';
|
||||
import i18n from 'i18n-js';
|
||||
import type {CustomThemeType} from '../../../managers/ThemeManager';
|
||||
|
||||
type Props = {
|
||||
title: string,
|
||||
isDryer: boolean,
|
||||
nbAvailable: number,
|
||||
}
|
||||
type PropsType = {
|
||||
theme: CustomThemeType,
|
||||
title: string,
|
||||
isDryer: boolean,
|
||||
nbAvailable: number,
|
||||
};
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
container: {
|
||||
flexDirection: 'row',
|
||||
marginLeft: 5,
|
||||
marginRight: 5,
|
||||
marginBottom: 10,
|
||||
marginTop: 20,
|
||||
},
|
||||
icon: {
|
||||
backgroundColor: 'transparent',
|
||||
},
|
||||
text: {
|
||||
fontSize: 20,
|
||||
fontWeight: 'bold',
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* Component used to display a proxiwash item, showing machine progression and state
|
||||
*/
|
||||
class ProxiwashListItem extends React.Component<Props> {
|
||||
class ProxiwashListItem extends React.Component<PropsType> {
|
||||
shouldComponentUpdate(nextProps: PropsType): boolean {
|
||||
const {props} = this;
|
||||
return (
|
||||
nextProps.theme.dark !== props.theme.dark ||
|
||||
nextProps.nbAvailable !== props.nbAvailable
|
||||
);
|
||||
}
|
||||
|
||||
constructor(props) {
|
||||
super(props);
|
||||
}
|
||||
|
||||
shouldComponentUpdate(nextProps: Props) {
|
||||
return (nextProps.theme.dark !== this.props.theme.dark)
|
||||
|| (nextProps.nbAvailable !== this.props.nbAvailable)
|
||||
}
|
||||
|
||||
render() {
|
||||
const props = this.props;
|
||||
const subtitle = props.nbAvailable + ' ' + (
|
||||
(props.nbAvailable <= 1)
|
||||
? i18n.t('screens.proxiwash.numAvailable')
|
||||
: i18n.t('screens.proxiwash.numAvailablePlural'));
|
||||
const iconColor = props.nbAvailable > 0
|
||||
? this.props.theme.colors.success
|
||||
: this.props.theme.colors.primary;
|
||||
return (
|
||||
<View style={styles.container}>
|
||||
<Avatar.Icon
|
||||
icon={props.isDryer ? 'tumble-dryer' : 'washing-machine'}
|
||||
color={iconColor}
|
||||
style={styles.icon}
|
||||
/>
|
||||
<View style={{justifyContent: 'center'}}>
|
||||
<Text style={styles.text}>
|
||||
{props.title}
|
||||
</Text>
|
||||
<Text style={{color: this.props.theme.colors.subtitle}}>
|
||||
{subtitle}
|
||||
</Text>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
render(): React.Node {
|
||||
const {props} = this;
|
||||
const subtitle = `${props.nbAvailable} ${
|
||||
props.nbAvailable <= 1
|
||||
? i18n.t('screens.proxiwash.numAvailable')
|
||||
: i18n.t('screens.proxiwash.numAvailablePlural')
|
||||
}`;
|
||||
const iconColor =
|
||||
props.nbAvailable > 0
|
||||
? props.theme.colors.success
|
||||
: props.theme.colors.primary;
|
||||
return (
|
||||
<View style={styles.container}>
|
||||
<Avatar.Icon
|
||||
icon={props.isDryer ? 'tumble-dryer' : 'washing-machine'}
|
||||
color={iconColor}
|
||||
style={styles.icon}
|
||||
/>
|
||||
<View style={{justifyContent: 'center'}}>
|
||||
<Text style={styles.text}>{props.title}</Text>
|
||||
<Text style={{color: props.theme.colors.subtitle}}>{subtitle}</Text>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
container: {
|
||||
flexDirection: 'row',
|
||||
marginLeft: 5,
|
||||
marginRight: 5,
|
||||
marginBottom: 10,
|
||||
marginTop: 20,
|
||||
},
|
||||
icon: {
|
||||
backgroundColor: 'transparent'
|
||||
},
|
||||
text: {
|
||||
fontSize: 20,
|
||||
fontWeight: 'bold',
|
||||
}
|
||||
});
|
||||
|
||||
export default withTheme(ProxiwashListItem);
|
||||
|
|
|
|||
|
|
@ -1,259 +1,269 @@
|
|||
// @flow
|
||||
|
||||
import * as React from 'react';
|
||||
import * as Animatable from "react-native-animatable";
|
||||
import {Image, TouchableWithoutFeedback, View} from "react-native";
|
||||
import type {ViewStyle} from "react-native/Libraries/StyleSheet/StyleSheet";
|
||||
import * as Animatable from 'react-native-animatable';
|
||||
import {Image, TouchableWithoutFeedback, View} from 'react-native';
|
||||
import type {ViewStyle} from 'react-native/Libraries/StyleSheet/StyleSheet';
|
||||
|
||||
type Props = {
|
||||
style?: ViewStyle,
|
||||
emotion: number,
|
||||
animated: boolean,
|
||||
entryAnimation: Animatable.AnimatableProperties | null,
|
||||
loopAnimation: Animatable.AnimatableProperties | null,
|
||||
onPress?: (viewRef: AnimatableViewRef) => null,
|
||||
onLongPress?: (viewRef: AnimatableViewRef) => null,
|
||||
}
|
||||
export type AnimatableViewRefType = {current: null | Animatable.View};
|
||||
|
||||
type State = {
|
||||
currentEmotion: number,
|
||||
}
|
||||
|
||||
export type AnimatableViewRef = {current: null | Animatable.View};
|
||||
|
||||
const MASCOT_IMAGE = require("../../../assets/mascot/mascot.png");
|
||||
const MASCOT_EYES_NORMAL = require("../../../assets/mascot/mascot_eyes_normal.png");
|
||||
const MASCOT_EYES_GIRLY = require("../../../assets/mascot/mascot_eyes_girly.png");
|
||||
const MASCOT_EYES_CUTE = require("../../../assets/mascot/mascot_eyes_cute.png");
|
||||
const MASCOT_EYES_WINK = require("../../../assets/mascot/mascot_eyes_wink.png");
|
||||
const MASCOT_EYES_HEART = require("../../../assets/mascot/mascot_eyes_heart.png");
|
||||
const MASCOT_EYES_ANGRY = require("../../../assets/mascot/mascot_eyes_angry.png");
|
||||
const MASCOT_GLASSES = require("../../../assets/mascot/mascot_glasses.png");
|
||||
const MASCOT_SUNGLASSES = require("../../../assets/mascot/mascot_sunglasses.png");
|
||||
|
||||
export const EYE_STYLE = {
|
||||
NORMAL: 0,
|
||||
GIRLY: 2,
|
||||
CUTE: 3,
|
||||
WINK: 4,
|
||||
HEART: 5,
|
||||
ANGRY: 6,
|
||||
}
|
||||
|
||||
const GLASSES_STYLE = {
|
||||
NORMAL: 0,
|
||||
COOl: 1
|
||||
}
|
||||
|
||||
export const MASCOT_STYLE = {
|
||||
NORMAL: 0,
|
||||
HAPPY: 1,
|
||||
GIRLY: 2,
|
||||
WINK: 3,
|
||||
CUTE: 4,
|
||||
INTELLO: 5,
|
||||
LOVE: 6,
|
||||
COOL: 7,
|
||||
ANGRY: 8,
|
||||
RANDOM: 999,
|
||||
type PropsType = {
|
||||
emotion?: number,
|
||||
animated?: boolean,
|
||||
style?: ViewStyle | null,
|
||||
entryAnimation?: Animatable.AnimatableProperties | null,
|
||||
loopAnimation?: Animatable.AnimatableProperties | null,
|
||||
onPress?: null | ((viewRef: AnimatableViewRefType) => void),
|
||||
onLongPress?: null | ((viewRef: AnimatableViewRefType) => void),
|
||||
};
|
||||
|
||||
type StateType = {
|
||||
currentEmotion: number,
|
||||
};
|
||||
|
||||
class Mascot extends React.Component<Props, State> {
|
||||
const MASCOT_IMAGE = require('../../../assets/mascot/mascot.png');
|
||||
const MASCOT_EYES_NORMAL = require('../../../assets/mascot/mascot_eyes_normal.png');
|
||||
const MASCOT_EYES_GIRLY = require('../../../assets/mascot/mascot_eyes_girly.png');
|
||||
const MASCOT_EYES_CUTE = require('../../../assets/mascot/mascot_eyes_cute.png');
|
||||
const MASCOT_EYES_WINK = require('../../../assets/mascot/mascot_eyes_wink.png');
|
||||
const MASCOT_EYES_HEART = require('../../../assets/mascot/mascot_eyes_heart.png');
|
||||
const MASCOT_EYES_ANGRY = require('../../../assets/mascot/mascot_eyes_angry.png');
|
||||
const MASCOT_GLASSES = require('../../../assets/mascot/mascot_glasses.png');
|
||||
const MASCOT_SUNGLASSES = require('../../../assets/mascot/mascot_sunglasses.png');
|
||||
|
||||
static defaultProps = {
|
||||
animated: false,
|
||||
entryAnimation: {
|
||||
useNativeDriver: true,
|
||||
animation: "rubberBand",
|
||||
duration: 2000,
|
||||
},
|
||||
loopAnimation: {
|
||||
useNativeDriver: true,
|
||||
animation: "swing",
|
||||
duration: 2000,
|
||||
iterationDelay: 250,
|
||||
iterationCount: "infinite",
|
||||
},
|
||||
clickAnimation: {
|
||||
useNativeDriver: true,
|
||||
animation: "rubberBand",
|
||||
duration: 2000,
|
||||
},
|
||||
}
|
||||
export const EYE_STYLE = {
|
||||
NORMAL: 0,
|
||||
GIRLY: 2,
|
||||
CUTE: 3,
|
||||
WINK: 4,
|
||||
HEART: 5,
|
||||
ANGRY: 6,
|
||||
};
|
||||
|
||||
viewRef: AnimatableViewRef;
|
||||
eyeList: { [key: number]: number | string };
|
||||
glassesList: { [key: number]: number | string };
|
||||
const GLASSES_STYLE = {
|
||||
NORMAL: 0,
|
||||
COOl: 1,
|
||||
};
|
||||
|
||||
onPress: (viewRef: AnimatableViewRef) => null;
|
||||
onLongPress: (viewRef: AnimatableViewRef) => null;
|
||||
export const MASCOT_STYLE = {
|
||||
NORMAL: 0,
|
||||
HAPPY: 1,
|
||||
GIRLY: 2,
|
||||
WINK: 3,
|
||||
CUTE: 4,
|
||||
INTELLO: 5,
|
||||
LOVE: 6,
|
||||
COOL: 7,
|
||||
ANGRY: 8,
|
||||
RANDOM: 999,
|
||||
};
|
||||
|
||||
initialEmotion: number;
|
||||
class Mascot extends React.Component<PropsType, StateType> {
|
||||
static defaultProps = {
|
||||
emotion: MASCOT_STYLE.NORMAL,
|
||||
animated: false,
|
||||
style: null,
|
||||
entryAnimation: {
|
||||
useNativeDriver: true,
|
||||
animation: 'rubberBand',
|
||||
duration: 2000,
|
||||
},
|
||||
loopAnimation: {
|
||||
useNativeDriver: true,
|
||||
animation: 'swing',
|
||||
duration: 2000,
|
||||
iterationDelay: 250,
|
||||
iterationCount: 'infinite',
|
||||
},
|
||||
onPress: null,
|
||||
onLongPress: null,
|
||||
};
|
||||
|
||||
constructor(props: Props) {
|
||||
super(props);
|
||||
this.viewRef = React.createRef();
|
||||
this.eyeList = {};
|
||||
this.glassesList = {};
|
||||
this.eyeList[EYE_STYLE.NORMAL] = MASCOT_EYES_NORMAL;
|
||||
this.eyeList[EYE_STYLE.GIRLY] = MASCOT_EYES_GIRLY;
|
||||
this.eyeList[EYE_STYLE.CUTE] = MASCOT_EYES_CUTE;
|
||||
this.eyeList[EYE_STYLE.WINK] = MASCOT_EYES_WINK;
|
||||
this.eyeList[EYE_STYLE.HEART] = MASCOT_EYES_HEART;
|
||||
this.eyeList[EYE_STYLE.ANGRY] = MASCOT_EYES_ANGRY;
|
||||
viewRef: AnimatableViewRefType;
|
||||
|
||||
this.glassesList[GLASSES_STYLE.NORMAL] = MASCOT_GLASSES;
|
||||
this.glassesList[GLASSES_STYLE.COOl] = MASCOT_SUNGLASSES;
|
||||
eyeList: {[key: number]: number | string};
|
||||
|
||||
this.initialEmotion = this.props.emotion;
|
||||
glassesList: {[key: number]: number | string};
|
||||
|
||||
if (this.initialEmotion === MASCOT_STYLE.RANDOM)
|
||||
this.initialEmotion = Math.floor(Math.random() * MASCOT_STYLE.ANGRY) + 1;
|
||||
onPress: (viewRef: AnimatableViewRefType) => void;
|
||||
|
||||
this.state = {
|
||||
currentEmotion: this.initialEmotion
|
||||
onLongPress: (viewRef: AnimatableViewRefType) => void;
|
||||
|
||||
initialEmotion: number;
|
||||
|
||||
constructor(props: PropsType) {
|
||||
super(props);
|
||||
this.viewRef = React.createRef();
|
||||
this.eyeList = {};
|
||||
this.glassesList = {};
|
||||
this.eyeList[EYE_STYLE.NORMAL] = MASCOT_EYES_NORMAL;
|
||||
this.eyeList[EYE_STYLE.GIRLY] = MASCOT_EYES_GIRLY;
|
||||
this.eyeList[EYE_STYLE.CUTE] = MASCOT_EYES_CUTE;
|
||||
this.eyeList[EYE_STYLE.WINK] = MASCOT_EYES_WINK;
|
||||
this.eyeList[EYE_STYLE.HEART] = MASCOT_EYES_HEART;
|
||||
this.eyeList[EYE_STYLE.ANGRY] = MASCOT_EYES_ANGRY;
|
||||
|
||||
this.glassesList[GLASSES_STYLE.NORMAL] = MASCOT_GLASSES;
|
||||
this.glassesList[GLASSES_STYLE.COOl] = MASCOT_SUNGLASSES;
|
||||
|
||||
this.initialEmotion =
|
||||
props.emotion != null ? props.emotion : Mascot.defaultProps.emotion;
|
||||
|
||||
if (this.initialEmotion === MASCOT_STYLE.RANDOM)
|
||||
this.initialEmotion = Math.floor(Math.random() * MASCOT_STYLE.ANGRY) + 1;
|
||||
|
||||
this.state = {
|
||||
currentEmotion: this.initialEmotion,
|
||||
};
|
||||
|
||||
if (props.onPress == null) {
|
||||
this.onPress = (viewRef: AnimatableViewRefType) => {
|
||||
const ref = viewRef.current;
|
||||
if (ref != null) {
|
||||
this.setState({currentEmotion: MASCOT_STYLE.LOVE});
|
||||
ref.rubberBand(1500).then(() => {
|
||||
this.setState({currentEmotion: this.initialEmotion});
|
||||
});
|
||||
}
|
||||
};
|
||||
} else this.onPress = props.onPress;
|
||||
|
||||
if (this.props.onPress == null) {
|
||||
this.onPress = (viewRef: AnimatableViewRef) => {
|
||||
let ref = viewRef.current;
|
||||
if (ref != null) {
|
||||
this.setState({currentEmotion: MASCOT_STYLE.LOVE});
|
||||
ref.rubberBand(1500).then(() => {
|
||||
this.setState({currentEmotion: this.initialEmotion});
|
||||
});
|
||||
|
||||
}
|
||||
return null;
|
||||
}
|
||||
} else
|
||||
this.onPress = this.props.onPress;
|
||||
|
||||
if (this.props.onLongPress == null) {
|
||||
this.onLongPress = (viewRef: AnimatableViewRef) => {
|
||||
let ref = viewRef.current;
|
||||
if (ref != null) {
|
||||
this.setState({currentEmotion: MASCOT_STYLE.ANGRY});
|
||||
ref.tada(1000).then(() => {
|
||||
this.setState({currentEmotion: this.initialEmotion});
|
||||
});
|
||||
|
||||
}
|
||||
return null;
|
||||
}
|
||||
} else
|
||||
this.onLongPress = this.props.onLongPress;
|
||||
|
||||
}
|
||||
|
||||
getGlasses(style: number) {
|
||||
const glasses = this.glassesList[style];
|
||||
return <Image
|
||||
key={"glasses"}
|
||||
source={glasses != null ? glasses : this.glassesList[GLASSES_STYLE.NORMAL]}
|
||||
style={{
|
||||
position: "absolute",
|
||||
top: "15%",
|
||||
left: 0,
|
||||
width: "100%",
|
||||
height: "100%",
|
||||
}}
|
||||
/>
|
||||
}
|
||||
|
||||
getEye(style: number, isRight: boolean, rotation: string="0deg") {
|
||||
const eye = this.eyeList[style];
|
||||
return <Image
|
||||
key={isRight ? "right" : "left"}
|
||||
source={eye != null ? eye : this.eyeList[EYE_STYLE.NORMAL]}
|
||||
style={{
|
||||
position: "absolute",
|
||||
top: "15%",
|
||||
left: isRight ? "-11%" : "11%",
|
||||
width: "100%",
|
||||
height: "100%",
|
||||
transform: [{rotateY: rotation}]
|
||||
}}
|
||||
/>
|
||||
}
|
||||
|
||||
getEyes(emotion: number) {
|
||||
let final = [];
|
||||
final.push(<View
|
||||
key={"container"}
|
||||
style={{
|
||||
position: "absolute",
|
||||
width: "100%",
|
||||
height: "100%",
|
||||
}}/>);
|
||||
if (emotion === MASCOT_STYLE.CUTE) {
|
||||
final.push(this.getEye(EYE_STYLE.CUTE, true));
|
||||
final.push(this.getEye(EYE_STYLE.CUTE, false));
|
||||
} else if (emotion === MASCOT_STYLE.GIRLY) {
|
||||
final.push(this.getEye(EYE_STYLE.GIRLY, true));
|
||||
final.push(this.getEye(EYE_STYLE.GIRLY, false));
|
||||
} else if (emotion === MASCOT_STYLE.HAPPY) {
|
||||
final.push(this.getEye(EYE_STYLE.WINK, true));
|
||||
final.push(this.getEye(EYE_STYLE.WINK, false));
|
||||
} else if (emotion === MASCOT_STYLE.WINK) {
|
||||
final.push(this.getEye(EYE_STYLE.WINK, true));
|
||||
final.push(this.getEye(EYE_STYLE.NORMAL, false));
|
||||
} else if (emotion === MASCOT_STYLE.LOVE) {
|
||||
final.push(this.getEye(EYE_STYLE.HEART, true));
|
||||
final.push(this.getEye(EYE_STYLE.HEART, false));
|
||||
} else if (emotion === MASCOT_STYLE.ANGRY) {
|
||||
final.push(this.getEye(EYE_STYLE.ANGRY, true));
|
||||
final.push(this.getEye(EYE_STYLE.ANGRY, false, "180deg"));
|
||||
} else if (emotion === MASCOT_STYLE.COOL) {
|
||||
final.push(this.getGlasses(GLASSES_STYLE.COOl));
|
||||
} else {
|
||||
final.push(this.getEye(EYE_STYLE.NORMAL, true));
|
||||
final.push(this.getEye(EYE_STYLE.NORMAL, false));
|
||||
if (props.onLongPress == null) {
|
||||
this.onLongPress = (viewRef: AnimatableViewRefType) => {
|
||||
const ref = viewRef.current;
|
||||
if (ref != null) {
|
||||
this.setState({currentEmotion: MASCOT_STYLE.ANGRY});
|
||||
ref.tada(1000).then(() => {
|
||||
this.setState({currentEmotion: this.initialEmotion});
|
||||
});
|
||||
}
|
||||
};
|
||||
} else this.onLongPress = props.onLongPress;
|
||||
}
|
||||
|
||||
if (emotion === MASCOT_STYLE.INTELLO) { // Needs to have normal eyes behind the glasses
|
||||
final.push(this.getGlasses(GLASSES_STYLE.NORMAL));
|
||||
getGlasses(style: number): React.Node {
|
||||
const glasses = this.glassesList[style];
|
||||
return (
|
||||
<Image
|
||||
key="glasses"
|
||||
source={
|
||||
glasses != null ? glasses : this.glassesList[GLASSES_STYLE.NORMAL]
|
||||
}
|
||||
final.push(<View key={"container2"}/>);
|
||||
return final;
|
||||
style={{
|
||||
position: 'absolute',
|
||||
top: '15%',
|
||||
left: 0,
|
||||
width: '100%',
|
||||
height: '100%',
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
getEye(
|
||||
style: number,
|
||||
isRight: boolean,
|
||||
rotation: string = '0deg',
|
||||
): React.Node {
|
||||
const eye = this.eyeList[style];
|
||||
return (
|
||||
<Image
|
||||
key={isRight ? 'right' : 'left'}
|
||||
source={eye != null ? eye : this.eyeList[EYE_STYLE.NORMAL]}
|
||||
style={{
|
||||
position: 'absolute',
|
||||
top: '15%',
|
||||
left: isRight ? '-11%' : '11%',
|
||||
width: '100%',
|
||||
height: '100%',
|
||||
transform: [{rotateY: rotation}],
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
getEyes(emotion: number): React.Node {
|
||||
const final = [];
|
||||
final.push(
|
||||
<View
|
||||
key="container"
|
||||
style={{
|
||||
position: 'absolute',
|
||||
width: '100%',
|
||||
height: '100%',
|
||||
}}
|
||||
/>,
|
||||
);
|
||||
if (emotion === MASCOT_STYLE.CUTE) {
|
||||
final.push(this.getEye(EYE_STYLE.CUTE, true));
|
||||
final.push(this.getEye(EYE_STYLE.CUTE, false));
|
||||
} else if (emotion === MASCOT_STYLE.GIRLY) {
|
||||
final.push(this.getEye(EYE_STYLE.GIRLY, true));
|
||||
final.push(this.getEye(EYE_STYLE.GIRLY, false));
|
||||
} else if (emotion === MASCOT_STYLE.HAPPY) {
|
||||
final.push(this.getEye(EYE_STYLE.WINK, true));
|
||||
final.push(this.getEye(EYE_STYLE.WINK, false));
|
||||
} else if (emotion === MASCOT_STYLE.WINK) {
|
||||
final.push(this.getEye(EYE_STYLE.WINK, true));
|
||||
final.push(this.getEye(EYE_STYLE.NORMAL, false));
|
||||
} else if (emotion === MASCOT_STYLE.LOVE) {
|
||||
final.push(this.getEye(EYE_STYLE.HEART, true));
|
||||
final.push(this.getEye(EYE_STYLE.HEART, false));
|
||||
} else if (emotion === MASCOT_STYLE.ANGRY) {
|
||||
final.push(this.getEye(EYE_STYLE.ANGRY, true));
|
||||
final.push(this.getEye(EYE_STYLE.ANGRY, false, '180deg'));
|
||||
} else if (emotion === MASCOT_STYLE.COOL) {
|
||||
final.push(this.getGlasses(GLASSES_STYLE.COOl));
|
||||
} else {
|
||||
final.push(this.getEye(EYE_STYLE.NORMAL, true));
|
||||
final.push(this.getEye(EYE_STYLE.NORMAL, false));
|
||||
}
|
||||
|
||||
render() {
|
||||
const entryAnimation = this.props.animated ? this.props.entryAnimation : null;
|
||||
const loopAnimation = this.props.animated ? this.props.loopAnimation : null;
|
||||
return (
|
||||
if (emotion === MASCOT_STYLE.INTELLO) {
|
||||
// Needs to have normal eyes behind the glasses
|
||||
final.push(this.getGlasses(GLASSES_STYLE.NORMAL));
|
||||
}
|
||||
final.push(<View key="container2" />);
|
||||
return final;
|
||||
}
|
||||
|
||||
render(): React.Node {
|
||||
const {props, state} = this;
|
||||
const entryAnimation = props.animated ? props.entryAnimation : null;
|
||||
const loopAnimation = props.animated ? props.loopAnimation : null;
|
||||
return (
|
||||
<Animatable.View
|
||||
style={{
|
||||
aspectRatio: 1,
|
||||
...props.style,
|
||||
}}
|
||||
// eslint-disable-next-line react/jsx-props-no-spreading
|
||||
{...entryAnimation}>
|
||||
<TouchableWithoutFeedback
|
||||
onPress={() => {
|
||||
this.onPress(this.viewRef);
|
||||
}}
|
||||
onLongPress={() => {
|
||||
this.onLongPress(this.viewRef);
|
||||
}}>
|
||||
<Animatable.View ref={this.viewRef}>
|
||||
<Animatable.View
|
||||
// eslint-disable-next-line react/jsx-props-no-spreading
|
||||
{...loopAnimation}>
|
||||
<Image
|
||||
source={MASCOT_IMAGE}
|
||||
style={{
|
||||
aspectRatio: 1,
|
||||
...this.props.style
|
||||
width: '100%',
|
||||
height: '100%',
|
||||
}}
|
||||
{...entryAnimation}
|
||||
>
|
||||
<TouchableWithoutFeedback
|
||||
onPress={() => this.onPress(this.viewRef)}
|
||||
onLongPress={() => this.onLongPress(this.viewRef)}
|
||||
>
|
||||
<Animatable.View
|
||||
ref={this.viewRef}
|
||||
>
|
||||
<Animatable.View
|
||||
{...loopAnimation}
|
||||
>
|
||||
<Image
|
||||
source={MASCOT_IMAGE}
|
||||
style={{
|
||||
width: "100%",
|
||||
height:"100%",
|
||||
}}
|
||||
/>
|
||||
{this.getEyes(this.state.currentEmotion)}
|
||||
</Animatable.View>
|
||||
</Animatable.View>
|
||||
</TouchableWithoutFeedback>
|
||||
/>
|
||||
{this.getEyes(state.currentEmotion)}
|
||||
</Animatable.View>
|
||||
);
|
||||
}
|
||||
</Animatable.View>
|
||||
</TouchableWithoutFeedback>
|
||||
</Animatable.View>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default Mascot;
|
||||
|
|
|
|||
|
|
@ -1,283 +1,312 @@
|
|||
// @flow
|
||||
|
||||
import * as React from 'react';
|
||||
import {Avatar, Button, Card, Paragraph, Portal, withTheme} from 'react-native-paper';
|
||||
import Mascot from "./Mascot";
|
||||
import * as Animatable from "react-native-animatable";
|
||||
import {BackHandler, Dimensions, ScrollView, TouchableWithoutFeedback, View} from "react-native";
|
||||
import type {CustomTheme} from "../../managers/ThemeManager";
|
||||
import SpeechArrow from "./SpeechArrow";
|
||||
import AsyncStorageManager from "../../managers/AsyncStorageManager";
|
||||
import {
|
||||
Avatar,
|
||||
Button,
|
||||
Card,
|
||||
Paragraph,
|
||||
Portal,
|
||||
withTheme,
|
||||
} from 'react-native-paper';
|
||||
import * as Animatable from 'react-native-animatable';
|
||||
import {
|
||||
BackHandler,
|
||||
Dimensions,
|
||||
ScrollView,
|
||||
TouchableWithoutFeedback,
|
||||
View,
|
||||
} from 'react-native';
|
||||
import Mascot from './Mascot';
|
||||
import type {CustomThemeType} from '../../managers/ThemeManager';
|
||||
import SpeechArrow from './SpeechArrow';
|
||||
import AsyncStorageManager from '../../managers/AsyncStorageManager';
|
||||
|
||||
type Props = {
|
||||
theme: CustomTheme,
|
||||
icon: string,
|
||||
title: string,
|
||||
message: string,
|
||||
buttons: {
|
||||
action: {
|
||||
message: string,
|
||||
icon: string | null,
|
||||
color: string | null,
|
||||
onPress?: () => void,
|
||||
},
|
||||
cancel: {
|
||||
message: string,
|
||||
icon: string | null,
|
||||
color: string | null,
|
||||
onPress?: () => void,
|
||||
}
|
||||
type PropsType = {
|
||||
theme: CustomThemeType,
|
||||
icon: string,
|
||||
title: string,
|
||||
message: string,
|
||||
buttons: {
|
||||
action: {
|
||||
message: string,
|
||||
icon: string | null,
|
||||
color: string | null,
|
||||
onPress?: () => void,
|
||||
},
|
||||
emotion: number,
|
||||
visible?: boolean,
|
||||
prefKey?: string,
|
||||
}
|
||||
cancel: {
|
||||
message: string,
|
||||
icon: string | null,
|
||||
color: string | null,
|
||||
onPress?: () => void,
|
||||
},
|
||||
},
|
||||
emotion: number,
|
||||
visible?: boolean,
|
||||
prefKey?: string,
|
||||
};
|
||||
|
||||
type State = {
|
||||
shouldRenderDialog: boolean, // Used to stop rendering after hide animation
|
||||
dialogVisible: boolean,
|
||||
}
|
||||
type StateType = {
|
||||
shouldRenderDialog: boolean, // Used to stop rendering after hide animation
|
||||
dialogVisible: boolean,
|
||||
};
|
||||
|
||||
/**
|
||||
* Component used to display a popup with the mascot.
|
||||
*/
|
||||
class MascotPopup extends React.Component<Props, State> {
|
||||
class MascotPopup extends React.Component<PropsType, StateType> {
|
||||
static defaultProps = {
|
||||
visible: null,
|
||||
prefKey: null,
|
||||
};
|
||||
|
||||
mascotSize: number;
|
||||
windowWidth: number;
|
||||
windowHeight: number;
|
||||
mascotSize: number;
|
||||
|
||||
constructor(props: Props) {
|
||||
super(props);
|
||||
windowWidth: number;
|
||||
|
||||
this.windowWidth = Dimensions.get('window').width;
|
||||
this.windowHeight = Dimensions.get('window').height;
|
||||
windowHeight: number;
|
||||
|
||||
this.mascotSize = Dimensions.get('window').height / 6;
|
||||
constructor(props: PropsType) {
|
||||
super(props);
|
||||
|
||||
if (this.props.visible != null) {
|
||||
this.state = {
|
||||
shouldRenderDialog: this.props.visible,
|
||||
dialogVisible: this.props.visible,
|
||||
};
|
||||
} else if (this.props.prefKey != null) {
|
||||
const visible = AsyncStorageManager.getBool(this.props.prefKey);
|
||||
this.state = {
|
||||
shouldRenderDialog: visible,
|
||||
dialogVisible: visible,
|
||||
};
|
||||
} else {
|
||||
this.state = {
|
||||
shouldRenderDialog: false,
|
||||
dialogVisible: false,
|
||||
};
|
||||
}
|
||||
this.windowWidth = Dimensions.get('window').width;
|
||||
this.windowHeight = Dimensions.get('window').height;
|
||||
|
||||
this.mascotSize = Dimensions.get('window').height / 6;
|
||||
|
||||
if (props.visible != null) {
|
||||
this.state = {
|
||||
shouldRenderDialog: props.visible,
|
||||
dialogVisible: props.visible,
|
||||
};
|
||||
} else if (props.prefKey != null) {
|
||||
const visible = AsyncStorageManager.getBool(props.prefKey);
|
||||
this.state = {
|
||||
shouldRenderDialog: visible,
|
||||
dialogVisible: visible,
|
||||
};
|
||||
} else {
|
||||
this.state = {
|
||||
shouldRenderDialog: false,
|
||||
dialogVisible: false,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
onAnimationEnd = () => {
|
||||
this.setState({
|
||||
shouldRenderDialog: false,
|
||||
})
|
||||
componentDidMount(): * {
|
||||
BackHandler.addEventListener(
|
||||
'hardwareBackPress',
|
||||
this.onBackButtonPressAndroid,
|
||||
);
|
||||
}
|
||||
|
||||
shouldComponentUpdate(nextProps: PropsType, nextState: StateType): boolean {
|
||||
const {props, state} = this;
|
||||
if (nextProps.visible) {
|
||||
this.state.shouldRenderDialog = true;
|
||||
this.state.dialogVisible = true;
|
||||
} else if (
|
||||
nextProps.visible !== props.visible ||
|
||||
(!nextState.dialogVisible &&
|
||||
nextState.dialogVisible !== state.dialogVisible)
|
||||
) {
|
||||
this.state.dialogVisible = false;
|
||||
setTimeout(this.onAnimationEnd, 300);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
shouldComponentUpdate(nextProps: Props, nextState: State): boolean {
|
||||
if (nextProps.visible) {
|
||||
this.state.shouldRenderDialog = true;
|
||||
this.state.dialogVisible = true;
|
||||
} else if (nextProps.visible !== this.props.visible
|
||||
|| (!nextState.dialogVisible && nextState.dialogVisible !== this.state.dialogVisible)) {
|
||||
this.state.dialogVisible = false;
|
||||
setTimeout(this.onAnimationEnd, 300);
|
||||
}
|
||||
return true;
|
||||
onAnimationEnd = () => {
|
||||
this.setState({
|
||||
shouldRenderDialog: false,
|
||||
});
|
||||
};
|
||||
|
||||
onBackButtonPressAndroid = (): boolean => {
|
||||
const {state, props} = this;
|
||||
if (state.dialogVisible) {
|
||||
const {cancel} = props.buttons;
|
||||
const {action} = props.buttons;
|
||||
if (cancel != null) this.onDismiss(cancel.onPress);
|
||||
else this.onDismiss(action.onPress);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
componentDidMount(): * {
|
||||
BackHandler.addEventListener(
|
||||
'hardwareBackPress',
|
||||
this.onBackButtonPressAndroid
|
||||
)
|
||||
}
|
||||
|
||||
onBackButtonPressAndroid = () => {
|
||||
if (this.state.dialogVisible) {
|
||||
const cancel = this.props.buttons.cancel;
|
||||
const action = this.props.buttons.action;
|
||||
if (cancel != null)
|
||||
this.onDismiss(cancel.onPress);
|
||||
else
|
||||
this.onDismiss(action.onPress);
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
getSpeechBubble() {
|
||||
return (
|
||||
<Animatable.View
|
||||
style={{
|
||||
marginLeft: "10%",
|
||||
marginRight: "10%",
|
||||
}}
|
||||
useNativeDriver={true}
|
||||
animation={this.state.dialogVisible ? "bounceInLeft" : "bounceOutLeft"}
|
||||
duration={this.state.dialogVisible ? 1000 : 300}
|
||||
>
|
||||
<SpeechArrow
|
||||
style={{marginLeft: this.mascotSize / 3}}
|
||||
size={20}
|
||||
color={this.props.theme.colors.mascotMessageArrow}
|
||||
/>
|
||||
<Card style={{
|
||||
borderColor: this.props.theme.colors.mascotMessageArrow,
|
||||
borderWidth: 4,
|
||||
borderRadius: 10,
|
||||
}}>
|
||||
<Card.Title
|
||||
title={this.props.title}
|
||||
left={this.props.icon != null ?
|
||||
(props) => <Avatar.Icon
|
||||
{...props}
|
||||
size={48}
|
||||
style={{backgroundColor: "transparent"}}
|
||||
color={this.props.theme.colors.primary}
|
||||
icon={this.props.icon}
|
||||
/>
|
||||
|
||||
: null}
|
||||
getSpeechBubble(): React.Node {
|
||||
const {state, props} = this;
|
||||
return (
|
||||
<Animatable.View
|
||||
style={{
|
||||
marginLeft: '10%',
|
||||
marginRight: '10%',
|
||||
}}
|
||||
useNativeDriver
|
||||
animation={state.dialogVisible ? 'bounceInLeft' : 'bounceOutLeft'}
|
||||
duration={state.dialogVisible ? 1000 : 300}>
|
||||
<SpeechArrow
|
||||
style={{marginLeft: this.mascotSize / 3}}
|
||||
size={20}
|
||||
color={props.theme.colors.mascotMessageArrow}
|
||||
/>
|
||||
<Card
|
||||
style={{
|
||||
borderColor: props.theme.colors.mascotMessageArrow,
|
||||
borderWidth: 4,
|
||||
borderRadius: 10,
|
||||
}}>
|
||||
<Card.Title
|
||||
title={props.title}
|
||||
left={
|
||||
props.icon != null
|
||||
? (): React.Node => (
|
||||
<Avatar.Icon
|
||||
size={48}
|
||||
style={{backgroundColor: 'transparent'}}
|
||||
color={props.theme.colors.primary}
|
||||
icon={props.icon}
|
||||
/>
|
||||
|
||||
<Card.Content style={{
|
||||
maxHeight: this.windowHeight / 3
|
||||
}}>
|
||||
<ScrollView>
|
||||
<Paragraph style={{marginBottom: 10}}>
|
||||
{this.props.message}
|
||||
</Paragraph>
|
||||
</ScrollView>
|
||||
</Card.Content>
|
||||
|
||||
<Card.Actions style={{marginTop: 10, marginBottom: 10}}>
|
||||
{this.getButtons()}
|
||||
</Card.Actions>
|
||||
</Card>
|
||||
</Animatable.View>
|
||||
);
|
||||
}
|
||||
|
||||
getMascot() {
|
||||
return (
|
||||
<Animatable.View
|
||||
useNativeDriver={true}
|
||||
animation={this.state.dialogVisible ? "bounceInLeft" : "bounceOutLeft"}
|
||||
duration={this.state.dialogVisible ? 1500 : 200}
|
||||
>
|
||||
<Mascot
|
||||
style={{width: this.mascotSize}}
|
||||
animated={true}
|
||||
emotion={this.props.emotion}
|
||||
/>
|
||||
</Animatable.View>
|
||||
);
|
||||
}
|
||||
|
||||
getButtons() {
|
||||
const action = this.props.buttons.action;
|
||||
const cancel = this.props.buttons.cancel;
|
||||
return (
|
||||
<View style={{
|
||||
marginLeft: "auto",
|
||||
marginRight: "auto",
|
||||
marginTop: "auto",
|
||||
marginBottom: "auto",
|
||||
)
|
||||
: null
|
||||
}
|
||||
/>
|
||||
<Card.Content
|
||||
style={{
|
||||
maxHeight: this.windowHeight / 3,
|
||||
}}>
|
||||
{action != null
|
||||
? <Button
|
||||
style={{
|
||||
marginLeft: 'auto',
|
||||
marginRight: 'auto',
|
||||
marginBottom: 10,
|
||||
}}
|
||||
mode={"contained"}
|
||||
icon={action.icon}
|
||||
color={action.color}
|
||||
onPress={() => this.onDismiss(action.onPress)}
|
||||
>
|
||||
{action.message}
|
||||
</Button>
|
||||
: null}
|
||||
{cancel != null
|
||||
? <Button
|
||||
style={{
|
||||
marginLeft: 'auto',
|
||||
marginRight: 'auto',
|
||||
}}
|
||||
mode={"contained"}
|
||||
icon={cancel.icon}
|
||||
color={cancel.color}
|
||||
onPress={() => this.onDismiss(cancel.onPress)}
|
||||
>
|
||||
{cancel.message}
|
||||
</Button>
|
||||
: null}
|
||||
<ScrollView>
|
||||
<Paragraph style={{marginBottom: 10}}>{props.message}</Paragraph>
|
||||
</ScrollView>
|
||||
</Card.Content>
|
||||
|
||||
<Card.Actions style={{marginTop: 10, marginBottom: 10}}>
|
||||
{this.getButtons()}
|
||||
</Card.Actions>
|
||||
</Card>
|
||||
</Animatable.View>
|
||||
);
|
||||
}
|
||||
|
||||
getMascot(): React.Node {
|
||||
const {props, state} = this;
|
||||
return (
|
||||
<Animatable.View
|
||||
useNativeDriver
|
||||
animation={state.dialogVisible ? 'bounceInLeft' : 'bounceOutLeft'}
|
||||
duration={state.dialogVisible ? 1500 : 200}>
|
||||
<Mascot
|
||||
style={{width: this.mascotSize}}
|
||||
animated
|
||||
emotion={props.emotion}
|
||||
/>
|
||||
</Animatable.View>
|
||||
);
|
||||
}
|
||||
|
||||
getButtons(): React.Node {
|
||||
const {props} = this;
|
||||
const {action} = props.buttons;
|
||||
const {cancel} = props.buttons;
|
||||
return (
|
||||
<View
|
||||
style={{
|
||||
marginLeft: 'auto',
|
||||
marginRight: 'auto',
|
||||
marginTop: 'auto',
|
||||
marginBottom: 'auto',
|
||||
}}>
|
||||
{action != null ? (
|
||||
<Button
|
||||
style={{
|
||||
marginLeft: 'auto',
|
||||
marginRight: 'auto',
|
||||
marginBottom: 10,
|
||||
}}
|
||||
mode="contained"
|
||||
icon={action.icon}
|
||||
color={action.color}
|
||||
onPress={() => {
|
||||
this.onDismiss(action.onPress);
|
||||
}}>
|
||||
{action.message}
|
||||
</Button>
|
||||
) : null}
|
||||
{cancel != null ? (
|
||||
<Button
|
||||
style={{
|
||||
marginLeft: 'auto',
|
||||
marginRight: 'auto',
|
||||
}}
|
||||
mode="contained"
|
||||
icon={cancel.icon}
|
||||
color={cancel.color}
|
||||
onPress={() => {
|
||||
this.onDismiss(cancel.onPress);
|
||||
}}>
|
||||
{cancel.message}
|
||||
</Button>
|
||||
) : null}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
getBackground(): React.Node {
|
||||
const {props, state} = this;
|
||||
return (
|
||||
<TouchableWithoutFeedback
|
||||
onPress={() => {
|
||||
this.onDismiss(props.buttons.cancel.onPress);
|
||||
}}>
|
||||
<Animatable.View
|
||||
style={{
|
||||
position: 'absolute',
|
||||
backgroundColor: 'rgba(0,0,0,0.7)',
|
||||
width: '100%',
|
||||
height: '100%',
|
||||
}}
|
||||
useNativeDriver
|
||||
animation={state.dialogVisible ? 'fadeIn' : 'fadeOut'}
|
||||
duration={state.dialogVisible ? 300 : 300}
|
||||
/>
|
||||
</TouchableWithoutFeedback>
|
||||
);
|
||||
}
|
||||
|
||||
onDismiss = (callback?: () => void) => {
|
||||
const {prefKey} = this.props;
|
||||
if (prefKey != null) {
|
||||
AsyncStorageManager.set(prefKey, false);
|
||||
this.setState({dialogVisible: false});
|
||||
}
|
||||
if (callback != null) callback();
|
||||
};
|
||||
|
||||
render(): React.Node {
|
||||
const {shouldRenderDialog} = this.state;
|
||||
if (shouldRenderDialog) {
|
||||
return (
|
||||
<Portal>
|
||||
{this.getBackground()}
|
||||
<View
|
||||
style={{
|
||||
marginTop: 'auto',
|
||||
marginBottom: 'auto',
|
||||
}}>
|
||||
<View
|
||||
style={{
|
||||
marginTop: -80,
|
||||
width: '100%',
|
||||
}}>
|
||||
{this.getMascot()}
|
||||
{this.getSpeechBubble()}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
getBackground() {
|
||||
return (
|
||||
<TouchableWithoutFeedback onPress={() => this.onDismiss(this.props.buttons.cancel.onPress)}>
|
||||
<Animatable.View
|
||||
style={{
|
||||
position: "absolute",
|
||||
backgroundColor: "rgba(0,0,0,0.7)",
|
||||
width: "100%",
|
||||
height: "100%",
|
||||
}}
|
||||
useNativeDriver={true}
|
||||
animation={this.state.dialogVisible ? "fadeIn" : "fadeOut"}
|
||||
duration={this.state.dialogVisible ? 300 : 300}
|
||||
/>
|
||||
</TouchableWithoutFeedback>
|
||||
|
||||
);
|
||||
}
|
||||
|
||||
onDismiss = (callback?: ()=> void) => {
|
||||
if (this.props.prefKey != null) {
|
||||
AsyncStorageManager.set(this.props.prefKey, false);
|
||||
this.setState({dialogVisible: false});
|
||||
}
|
||||
if (callback != null)
|
||||
callback();
|
||||
}
|
||||
|
||||
render() {
|
||||
if (this.state.shouldRenderDialog) {
|
||||
return (
|
||||
<Portal>
|
||||
{this.getBackground()}
|
||||
<View style={{
|
||||
marginTop: "auto",
|
||||
marginBottom: "auto",
|
||||
}}>
|
||||
<View style={{
|
||||
marginTop: -80,
|
||||
width: "100%"
|
||||
}}>
|
||||
{this.getMascot()}
|
||||
{this.getSpeechBubble()}
|
||||
</View>
|
||||
|
||||
</View>
|
||||
</Portal>
|
||||
);
|
||||
} else
|
||||
return null;
|
||||
|
||||
</View>
|
||||
</Portal>
|
||||
);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export default withTheme(MascotPopup);
|
||||
|
|
|
|||
|
|
@ -1,33 +1,43 @@
|
|||
// @flow
|
||||
|
||||
import * as React from 'react';
|
||||
import {View} from "react-native";
|
||||
import type {ViewStyle} from "react-native/Libraries/StyleSheet/StyleSheet";
|
||||
import {View} from 'react-native';
|
||||
import type {ViewStyle} from 'react-native/Libraries/StyleSheet/StyleSheet';
|
||||
|
||||
type Props = {
|
||||
style?: ViewStyle,
|
||||
size: number,
|
||||
color: string,
|
||||
}
|
||||
|
||||
export default class SpeechArrow extends React.Component<Props> {
|
||||
|
||||
render() {
|
||||
return (
|
||||
<View style={this.props.style}>
|
||||
<View style={{
|
||||
width: 0,
|
||||
height: 0,
|
||||
borderLeftWidth: 0,
|
||||
borderRightWidth: this.props.size,
|
||||
borderBottomWidth: this.props.size,
|
||||
borderStyle: 'solid',
|
||||
backgroundColor: 'transparent',
|
||||
borderLeftColor: 'transparent',
|
||||
borderRightColor: 'transparent',
|
||||
borderBottomColor: this.props.color,
|
||||
}}/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
type PropsType = {
|
||||
style?: ViewStyle | null,
|
||||
size: number,
|
||||
color: string,
|
||||
};
|
||||
|
||||
export default class SpeechArrow extends React.Component<PropsType> {
|
||||
static defaultProps = {
|
||||
style: null,
|
||||
};
|
||||
|
||||
shouldComponentUpdate(): boolean {
|
||||
return false;
|
||||
}
|
||||
|
||||
render(): React.Node {
|
||||
const {props} = this;
|
||||
return (
|
||||
<View style={props.style}>
|
||||
<View
|
||||
style={{
|
||||
width: 0,
|
||||
height: 0,
|
||||
borderLeftWidth: 0,
|
||||
borderRightWidth: props.size,
|
||||
borderBottomWidth: props.size,
|
||||
borderStyle: 'solid',
|
||||
backgroundColor: 'transparent',
|
||||
borderLeftColor: 'transparent',
|
||||
borderRightColor: 'transparent',
|
||||
borderBottomColor: props.color,
|
||||
}}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,60 +1,63 @@
|
|||
import * as React from 'react';
|
||||
import {View} from "react-native";
|
||||
import {withTheme} from 'react-native-paper';
|
||||
import {Agenda} from "react-native-calendars";
|
||||
// @flow
|
||||
|
||||
type Props = {
|
||||
theme: Object,
|
||||
}
|
||||
import * as React from 'react';
|
||||
import {View} from 'react-native';
|
||||
import {withTheme} from 'react-native-paper';
|
||||
import {Agenda} from 'react-native-calendars';
|
||||
import type {CustomThemeType} from '../../managers/ThemeManager';
|
||||
|
||||
type PropsType = {
|
||||
theme: CustomThemeType,
|
||||
onRef: (ref: Agenda) => void,
|
||||
};
|
||||
|
||||
/**
|
||||
* Abstraction layer for Agenda component, using custom configuration
|
||||
*/
|
||||
class CustomAgenda extends React.Component<Props> {
|
||||
class CustomAgenda extends React.Component<PropsType> {
|
||||
getAgenda(): React.Node {
|
||||
const {props} = this;
|
||||
return (
|
||||
<Agenda
|
||||
// eslint-disable-next-line react/jsx-props-no-spreading
|
||||
{...props}
|
||||
ref={props.onRef}
|
||||
theme={{
|
||||
backgroundColor: props.theme.colors.agendaBackgroundColor,
|
||||
calendarBackground: props.theme.colors.background,
|
||||
textSectionTitleColor: props.theme.colors.agendaDayTextColor,
|
||||
selectedDayBackgroundColor: props.theme.colors.primary,
|
||||
selectedDayTextColor: '#ffffff',
|
||||
todayTextColor: props.theme.colors.primary,
|
||||
dayTextColor: props.theme.colors.text,
|
||||
textDisabledColor: props.theme.colors.agendaDayTextColor,
|
||||
dotColor: props.theme.colors.primary,
|
||||
selectedDotColor: '#ffffff',
|
||||
arrowColor: 'orange',
|
||||
monthTextColor: props.theme.colors.primary,
|
||||
indicatorColor: props.theme.colors.primary,
|
||||
textDayFontWeight: '300',
|
||||
textMonthFontWeight: 'bold',
|
||||
textDayHeaderFontWeight: '300',
|
||||
textDayFontSize: 16,
|
||||
textMonthFontSize: 16,
|
||||
textDayHeaderFontSize: 16,
|
||||
agendaDayTextColor: props.theme.colors.agendaDayTextColor,
|
||||
agendaDayNumColor: props.theme.colors.agendaDayTextColor,
|
||||
agendaTodayColor: props.theme.colors.primary,
|
||||
agendaKnobColor: props.theme.colors.primary,
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
getAgenda() {
|
||||
return <Agenda
|
||||
{...this.props}
|
||||
ref={this.props.onRef}
|
||||
theme={{
|
||||
backgroundColor: this.props.theme.colors.agendaBackgroundColor,
|
||||
calendarBackground: this.props.theme.colors.background,
|
||||
textSectionTitleColor: this.props.theme.colors.agendaDayTextColor,
|
||||
selectedDayBackgroundColor: this.props.theme.colors.primary,
|
||||
selectedDayTextColor: '#ffffff',
|
||||
todayTextColor: this.props.theme.colors.primary,
|
||||
dayTextColor: this.props.theme.colors.text,
|
||||
textDisabledColor: this.props.theme.colors.agendaDayTextColor,
|
||||
dotColor: this.props.theme.colors.primary,
|
||||
selectedDotColor: '#ffffff',
|
||||
arrowColor: 'orange',
|
||||
monthTextColor: this.props.theme.colors.primary,
|
||||
indicatorColor: this.props.theme.colors.primary,
|
||||
textDayFontWeight: '300',
|
||||
textMonthFontWeight: 'bold',
|
||||
textDayHeaderFontWeight: '300',
|
||||
textDayFontSize: 16,
|
||||
textMonthFontSize: 16,
|
||||
textDayHeaderFontSize: 16,
|
||||
agendaDayTextColor: this.props.theme.colors.agendaDayTextColor,
|
||||
agendaDayNumColor: this.props.theme.colors.agendaDayTextColor,
|
||||
agendaTodayColor: this.props.theme.colors.primary,
|
||||
agendaKnobColor: this.props.theme.colors.primary,
|
||||
}}
|
||||
/>;
|
||||
}
|
||||
|
||||
render() {
|
||||
// Completely recreate the component on theme change to force theme reload
|
||||
if (this.props.theme.dark)
|
||||
return (
|
||||
<View style={{flex: 1}}>
|
||||
{this.getAgenda()}
|
||||
</View>
|
||||
);
|
||||
else
|
||||
return this.getAgenda();
|
||||
}
|
||||
render(): React.Node {
|
||||
const {props} = this;
|
||||
// Completely recreate the component on theme change to force theme reload
|
||||
if (props.theme.dark)
|
||||
return <View style={{flex: 1}}>{this.getAgenda()}</View>;
|
||||
return this.getAgenda();
|
||||
}
|
||||
}
|
||||
|
||||
export default withTheme(CustomAgenda);
|
||||
|
|
|
|||
|
|
@ -1,47 +1,58 @@
|
|||
/* eslint-disable flowtype/require-parameter-type */
|
||||
// @flow
|
||||
|
||||
import * as React from 'react';
|
||||
import {Text, withTheme} from 'react-native-paper';
|
||||
import HTML from "react-native-render-html";
|
||||
import {Linking} from "react-native";
|
||||
import HTML from 'react-native-render-html';
|
||||
import {Linking} from 'react-native';
|
||||
import type {CustomThemeType} from '../../managers/ThemeManager';
|
||||
|
||||
type Props = {
|
||||
theme: Object,
|
||||
html: string,
|
||||
}
|
||||
type PropsType = {
|
||||
theme: CustomThemeType,
|
||||
html: string,
|
||||
};
|
||||
|
||||
/**
|
||||
* Abstraction layer for Agenda component, using custom configuration
|
||||
*/
|
||||
class CustomHTML extends React.Component<Props> {
|
||||
class CustomHTML extends React.Component<PropsType> {
|
||||
openWebLink = (event: {...}, link: string) => {
|
||||
Linking.openURL(link);
|
||||
};
|
||||
|
||||
openWebLink = (event, link) => {
|
||||
Linking.openURL(link).catch((err) => console.error('Error opening link', err));
|
||||
};
|
||||
getBasicText = (
|
||||
htmlAttribs,
|
||||
children,
|
||||
convertedCSSStyles,
|
||||
passProps,
|
||||
): React.Node => {
|
||||
// eslint-disable-next-line react/jsx-props-no-spreading
|
||||
return <Text {...passProps}>{children}</Text>;
|
||||
};
|
||||
|
||||
getBasicText = (htmlAttribs, children, convertedCSSStyles, passProps) => {
|
||||
return <Text {...passProps}>{children}</Text>;
|
||||
};
|
||||
getListBullet = (): React.Node => {
|
||||
return <Text>- </Text>;
|
||||
};
|
||||
|
||||
getListBullet = (htmlAttribs, children, convertedCSSStyles, passProps) => {
|
||||
return (
|
||||
<Text>- </Text>
|
||||
);
|
||||
};
|
||||
|
||||
render() {
|
||||
// Surround description with p to allow text styling if the description is not html
|
||||
return <HTML
|
||||
html={"<p>" + this.props.html + "</p>"}
|
||||
renderers={{
|
||||
p: this.getBasicText,
|
||||
li: this.getBasicText,
|
||||
}}
|
||||
listsPrefixesRenderers={{
|
||||
ul: this.getListBullet
|
||||
}}
|
||||
ignoredTags={['img']}
|
||||
ignoredStyles={['color', 'background-color']}
|
||||
onLinkPress={this.openWebLink}/>;
|
||||
}
|
||||
render(): React.Node {
|
||||
const {props} = this;
|
||||
// Surround description with p to allow text styling if the description is not html
|
||||
return (
|
||||
<HTML
|
||||
html={`<p>${props.html}</p>`}
|
||||
renderers={{
|
||||
p: this.getBasicText,
|
||||
li: this.getBasicText,
|
||||
}}
|
||||
listsPrefixesRenderers={{
|
||||
ul: this.getListBullet,
|
||||
}}
|
||||
ignoredTags={['img']}
|
||||
ignoredStyles={['color', 'background-color']}
|
||||
onLinkPress={this.openWebLink}
|
||||
/>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default withTheme(CustomHTML);
|
||||
|
|
|
|||
|
|
@ -1,27 +1,39 @@
|
|||
// @flow
|
||||
|
||||
import * as React from 'react';
|
||||
import MaterialCommunityIcons from "react-native-vector-icons/MaterialCommunityIcons";
|
||||
import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons';
|
||||
import {HeaderButton, HeaderButtons} from 'react-navigation-header-buttons';
|
||||
import {withTheme} from "react-native-paper";
|
||||
import {withTheme} from 'react-native-paper';
|
||||
import type {CustomThemeType} from '../../managers/ThemeManager';
|
||||
|
||||
const MaterialHeaderButton = (props: Object) =>
|
||||
const MaterialHeaderButton = (props: {
|
||||
theme: CustomThemeType,
|
||||
color: string,
|
||||
}): React.Node => {
|
||||
const {color, theme} = props;
|
||||
return (
|
||||
// $FlowFixMe
|
||||
<HeaderButton
|
||||
{...props}
|
||||
IconComponent={MaterialCommunityIcons}
|
||||
iconSize={26}
|
||||
color={props.color != null ? props.color : props.theme.colors.text}
|
||||
/>;
|
||||
|
||||
const MaterialHeaderButtons = (props: Object) => {
|
||||
return (
|
||||
<HeaderButtons
|
||||
{...props}
|
||||
HeaderButtonComponent={withTheme(MaterialHeaderButton)}
|
||||
/>
|
||||
);
|
||||
// eslint-disable-next-line react/jsx-props-no-spreading
|
||||
{...props}
|
||||
IconComponent={MaterialCommunityIcons}
|
||||
iconSize={26}
|
||||
color={color != null ? color : theme.colors.text}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
export default withTheme(MaterialHeaderButtons);
|
||||
const MaterialHeaderButtons = (props: {...}): React.Node => {
|
||||
return (
|
||||
// $FlowFixMe
|
||||
<HeaderButtons
|
||||
// eslint-disable-next-line react/jsx-props-no-spreading
|
||||
{...props}
|
||||
HeaderButtonComponent={withTheme(MaterialHeaderButton)}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
export default MaterialHeaderButtons;
|
||||
|
||||
export {Item} from 'react-navigation-header-buttons';
|
||||
|
|
|
|||
|
|
@ -1,411 +1,403 @@
|
|||
// @flow
|
||||
|
||||
import * as React from 'react';
|
||||
import {Platform, StatusBar, StyleSheet, View} from "react-native";
|
||||
import type {MaterialCommunityIconsGlyphs} from "react-native-vector-icons/MaterialCommunityIcons";
|
||||
import MaterialCommunityIcons from "react-native-vector-icons/MaterialCommunityIcons";
|
||||
import {Platform, StatusBar, StyleSheet, View} from 'react-native';
|
||||
import type {MaterialCommunityIconsGlyphs} from 'react-native-vector-icons/MaterialCommunityIcons';
|
||||
import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons';
|
||||
import i18n from 'i18n-js';
|
||||
import AppIntroSlider from "react-native-app-intro-slider";
|
||||
import Update from "../../constants/Update";
|
||||
import ThemeManager from "../../managers/ThemeManager";
|
||||
import AppIntroSlider from 'react-native-app-intro-slider';
|
||||
import LinearGradient from 'react-native-linear-gradient';
|
||||
import Mascot, {MASCOT_STYLE} from "../Mascot/Mascot";
|
||||
import * as Animatable from "react-native-animatable";
|
||||
import {Card} from "react-native-paper";
|
||||
import * as Animatable from 'react-native-animatable';
|
||||
import {Card} from 'react-native-paper';
|
||||
import Update from '../../constants/Update';
|
||||
import ThemeManager from '../../managers/ThemeManager';
|
||||
import Mascot, {MASCOT_STYLE} from '../Mascot/Mascot';
|
||||
|
||||
type Props = {
|
||||
onDone: Function,
|
||||
isUpdate: boolean,
|
||||
isAprilFools: boolean,
|
||||
type PropsType = {
|
||||
onDone: () => void,
|
||||
isUpdate: boolean,
|
||||
isAprilFools: boolean,
|
||||
};
|
||||
|
||||
type State = {
|
||||
currentSlide: number,
|
||||
}
|
||||
|
||||
type Slide = {
|
||||
key: string,
|
||||
title: string,
|
||||
text: string,
|
||||
view: () => React.Node,
|
||||
mascotStyle: number,
|
||||
colors: [string, string]
|
||||
type StateType = {
|
||||
currentSlide: number,
|
||||
};
|
||||
|
||||
type IntroSlideType = {
|
||||
key: string,
|
||||
title: string,
|
||||
text: string,
|
||||
view: () => React.Node,
|
||||
mascotStyle: number,
|
||||
colors: [string, string],
|
||||
};
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
mainContent: {
|
||||
paddingBottom: 100,
|
||||
},
|
||||
text: {
|
||||
color: 'rgba(255, 255, 255, 0.8)',
|
||||
backgroundColor: 'transparent',
|
||||
textAlign: 'center',
|
||||
paddingHorizontal: 16,
|
||||
},
|
||||
title: {
|
||||
fontSize: 22,
|
||||
color: 'white',
|
||||
backgroundColor: 'transparent',
|
||||
textAlign: 'center',
|
||||
marginBottom: 16,
|
||||
},
|
||||
center: {
|
||||
marginTop: 'auto',
|
||||
marginBottom: 'auto',
|
||||
marginRight: 'auto',
|
||||
marginLeft: 'auto',
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* Class used to create intro slides
|
||||
*/
|
||||
export default class CustomIntroSlider extends React.Component<Props, State> {
|
||||
export default class CustomIntroSlider extends React.Component<
|
||||
PropsType,
|
||||
StateType,
|
||||
> {
|
||||
sliderRef: {current: null | AppIntroSlider};
|
||||
|
||||
state = {
|
||||
currentSlide: 0,
|
||||
}
|
||||
introSlides: Array<IntroSlideType>;
|
||||
|
||||
sliderRef: { current: null | AppIntroSlider };
|
||||
updateSlides: Array<IntroSlideType>;
|
||||
|
||||
introSlides: Array<Slide>;
|
||||
updateSlides: Array<Slide>;
|
||||
aprilFoolsSlides: Array<Slide>;
|
||||
currentSlides: Array<Slide>;
|
||||
aprilFoolsSlides: Array<IntroSlideType>;
|
||||
|
||||
/**
|
||||
* Generates intro slides
|
||||
*/
|
||||
constructor() {
|
||||
super();
|
||||
this.sliderRef = React.createRef();
|
||||
this.introSlides = [
|
||||
{
|
||||
key: '0', // Mascot
|
||||
title: i18n.t('intro.slideMain.title'),
|
||||
text: i18n.t('intro.slideMain.text'),
|
||||
view: this.getWelcomeView,
|
||||
mascotStyle: MASCOT_STYLE.NORMAL,
|
||||
colors: ['#be1522', '#57080e'],
|
||||
},
|
||||
{
|
||||
key: '1',
|
||||
title: i18n.t('intro.slidePlanex.title'),
|
||||
text: i18n.t('intro.slidePlanex.text'),
|
||||
view: () => this.getIconView("calendar-clock"),
|
||||
mascotStyle: MASCOT_STYLE.INTELLO,
|
||||
colors: ['#be1522', '#57080e'],
|
||||
},
|
||||
{
|
||||
key: '2',
|
||||
title: i18n.t('intro.slideEvents.title'),
|
||||
text: i18n.t('intro.slideEvents.text'),
|
||||
view: () => this.getIconView("calendar-star",),
|
||||
mascotStyle: MASCOT_STYLE.HAPPY,
|
||||
colors: ['#be1522', '#57080e'],
|
||||
},
|
||||
{
|
||||
key: '3',
|
||||
title: i18n.t('intro.slideServices.title'),
|
||||
text: i18n.t('intro.slideServices.text'),
|
||||
view: () => this.getIconView("view-dashboard-variant",),
|
||||
mascotStyle: MASCOT_STYLE.CUTE,
|
||||
colors: ['#be1522', '#57080e'],
|
||||
},
|
||||
{
|
||||
key: '4',
|
||||
title: i18n.t('intro.slideDone.title'),
|
||||
text: i18n.t('intro.slideDone.text'),
|
||||
view: () => this.getEndView(),
|
||||
mascotStyle: MASCOT_STYLE.COOL,
|
||||
colors: ['#9c165b', '#3e042b'],
|
||||
},
|
||||
];
|
||||
this.updateSlides = [];
|
||||
for (let i = 0; i < Update.slidesNumber; i++) {
|
||||
this.updateSlides.push(
|
||||
{
|
||||
key: i.toString(),
|
||||
title: Update.getInstance().titleList[i],
|
||||
text: Update.getInstance().descriptionList[i],
|
||||
icon: Update.iconList[i],
|
||||
colors: Update.colorsList[i],
|
||||
},
|
||||
);
|
||||
}
|
||||
currentSlides: Array<IntroSlideType>;
|
||||
|
||||
this.aprilFoolsSlides = [
|
||||
{
|
||||
key: '1',
|
||||
title: i18n.t('intro.aprilFoolsSlide.title'),
|
||||
text: i18n.t('intro.aprilFoolsSlide.text'),
|
||||
view: () => <View/>,
|
||||
mascotStyle: MASCOT_STYLE.NORMAL,
|
||||
colors: ['#e01928', '#be1522'],
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Render item to be used for the intro introSlides
|
||||
*
|
||||
* @param item The item to be displayed
|
||||
* @param dimensions Dimensions of the item
|
||||
*/
|
||||
getIntroRenderItem = ({item, dimensions}: { item: Slide, dimensions: { width: number, height: number } }) => {
|
||||
const index = parseInt(item.key);
|
||||
return (
|
||||
<LinearGradient
|
||||
style={[
|
||||
styles.mainContent,
|
||||
dimensions
|
||||
]}
|
||||
colors={item.colors}
|
||||
start={{x: 0, y: 0.1}}
|
||||
end={{x: 0.1, y: 1}}
|
||||
>
|
||||
{this.state.currentSlide === index
|
||||
? <View style={{height: "100%", flex: 1}}>
|
||||
<View style={{flex: 1}}>
|
||||
{item.view()}
|
||||
</View>
|
||||
<Animatable.View
|
||||
animation={"fadeIn"}>
|
||||
{index !== 0 && index !== this.introSlides.length - 1
|
||||
?
|
||||
<Mascot
|
||||
style={{
|
||||
marginLeft: 30,
|
||||
marginBottom: 0,
|
||||
width: 100,
|
||||
marginTop: -30,
|
||||
}}
|
||||
emotion={item.mascotStyle}
|
||||
animated={true}
|
||||
entryAnimation={{
|
||||
animation: "slideInLeft",
|
||||
duration: 500
|
||||
}}
|
||||
loopAnimation={{
|
||||
animation: "pulse",
|
||||
iterationCount: "infinite",
|
||||
duration: 2000,
|
||||
}}
|
||||
/> : null}
|
||||
<View style={{
|
||||
marginLeft: 50,
|
||||
width: 0,
|
||||
height: 0,
|
||||
borderLeftWidth: 20,
|
||||
borderRightWidth: 0,
|
||||
borderBottomWidth: 20,
|
||||
borderStyle: 'solid',
|
||||
backgroundColor: 'transparent',
|
||||
borderLeftColor: 'transparent',
|
||||
borderRightColor: 'transparent',
|
||||
borderBottomColor: "rgba(0,0,0,0.60)",
|
||||
}}/>
|
||||
<Card style={{
|
||||
backgroundColor: "rgba(0,0,0,0.38)",
|
||||
marginHorizontal: 20,
|
||||
borderColor: "rgba(0,0,0,0.60)",
|
||||
borderWidth: 4,
|
||||
borderRadius: 10,
|
||||
}}>
|
||||
<Card.Content>
|
||||
<Animatable.Text
|
||||
animation={"fadeIn"}
|
||||
delay={100}
|
||||
style={styles.title}>
|
||||
{item.title}
|
||||
</Animatable.Text>
|
||||
<Animatable.Text
|
||||
animation={"fadeIn"}
|
||||
delay={200}
|
||||
style={styles.text}>
|
||||
{item.text}
|
||||
</Animatable.Text>
|
||||
</Card.Content>
|
||||
</Card>
|
||||
</Animatable.View>
|
||||
</View> : null}
|
||||
</LinearGradient>
|
||||
);
|
||||
}
|
||||
|
||||
getEndView = () => {
|
||||
return (
|
||||
<View style={{flex: 1}}>
|
||||
<Mascot
|
||||
style={{
|
||||
...styles.center,
|
||||
height: "80%"
|
||||
}}
|
||||
emotion={MASCOT_STYLE.COOL}
|
||||
animated={true}
|
||||
entryAnimation={{
|
||||
animation: "slideInDown",
|
||||
duration: 2000,
|
||||
}}
|
||||
loopAnimation={{
|
||||
animation: "pulse",
|
||||
duration: 2000,
|
||||
iterationCount: "infinite"
|
||||
}}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
getWelcomeView = () => {
|
||||
return (
|
||||
<View style={{flex: 1}}>
|
||||
<Mascot
|
||||
style={{
|
||||
...styles.center,
|
||||
height: "80%"
|
||||
}}
|
||||
emotion={MASCOT_STYLE.NORMAL}
|
||||
animated={true}
|
||||
entryAnimation={{
|
||||
animation: "bounceIn",
|
||||
duration: 2000,
|
||||
}}
|
||||
/>
|
||||
<Animatable.Text
|
||||
useNativeDriver={true}
|
||||
animation={"fadeInUp"}
|
||||
duration={500}
|
||||
|
||||
style={{
|
||||
color: "#fff",
|
||||
textAlign: "center",
|
||||
fontSize: 25,
|
||||
}}>
|
||||
PABLO
|
||||
</Animatable.Text>
|
||||
<Animatable.View
|
||||
useNativeDriver={true}
|
||||
animation={"fadeInUp"}
|
||||
duration={500}
|
||||
delay={200}
|
||||
|
||||
style={{
|
||||
position: "absolute",
|
||||
bottom: 30,
|
||||
right: "20%",
|
||||
width: 50,
|
||||
height: 50,
|
||||
}}>
|
||||
<MaterialCommunityIcons
|
||||
style={{
|
||||
...styles.center,
|
||||
transform: [{rotateZ: "70deg"}],
|
||||
}}
|
||||
name={"undo"}
|
||||
color={'#fff'}
|
||||
size={40}/>
|
||||
</Animatable.View>
|
||||
</View>
|
||||
)
|
||||
}
|
||||
|
||||
getIconView(icon: MaterialCommunityIconsGlyphs) {
|
||||
return (
|
||||
<View style={{flex: 1}}>
|
||||
<Animatable.View
|
||||
style={styles.center}
|
||||
animation={"fadeIn"}
|
||||
>
|
||||
<MaterialCommunityIcons
|
||||
name={icon}
|
||||
color={'#fff'}
|
||||
size={200}/>
|
||||
</Animatable.View>
|
||||
</View>
|
||||
)
|
||||
}
|
||||
|
||||
setStatusBarColor(color: string) {
|
||||
if (Platform.OS === 'android')
|
||||
StatusBar.setBackgroundColor(color, true);
|
||||
}
|
||||
|
||||
onSlideChange = (index: number, lastIndex: number) => {
|
||||
this.setStatusBarColor(this.currentSlides[index].colors[0]);
|
||||
this.setState({currentSlide: index});
|
||||
/**
|
||||
* Generates intro slides
|
||||
*/
|
||||
constructor() {
|
||||
super();
|
||||
this.state = {
|
||||
currentSlide: 0,
|
||||
};
|
||||
|
||||
onSkip = () => {
|
||||
this.setStatusBarColor(this.currentSlides[this.currentSlides.length - 1].colors[0]);
|
||||
if (this.sliderRef.current != null)
|
||||
this.sliderRef.current.goToSlide(this.currentSlides.length - 1);
|
||||
this.sliderRef = React.createRef();
|
||||
this.introSlides = [
|
||||
{
|
||||
key: '0', // Mascot
|
||||
title: i18n.t('intro.slideMain.title'),
|
||||
text: i18n.t('intro.slideMain.text'),
|
||||
view: this.getWelcomeView,
|
||||
mascotStyle: MASCOT_STYLE.NORMAL,
|
||||
colors: ['#be1522', '#57080e'],
|
||||
},
|
||||
{
|
||||
key: '1',
|
||||
title: i18n.t('intro.slidePlanex.title'),
|
||||
text: i18n.t('intro.slidePlanex.text'),
|
||||
view: (): React.Node => CustomIntroSlider.getIconView('calendar-clock'),
|
||||
mascotStyle: MASCOT_STYLE.INTELLO,
|
||||
colors: ['#be1522', '#57080e'],
|
||||
},
|
||||
{
|
||||
key: '2',
|
||||
title: i18n.t('intro.slideEvents.title'),
|
||||
text: i18n.t('intro.slideEvents.text'),
|
||||
view: (): React.Node => CustomIntroSlider.getIconView('calendar-star'),
|
||||
mascotStyle: MASCOT_STYLE.HAPPY,
|
||||
colors: ['#be1522', '#57080e'],
|
||||
},
|
||||
{
|
||||
key: '3',
|
||||
title: i18n.t('intro.slideServices.title'),
|
||||
text: i18n.t('intro.slideServices.text'),
|
||||
view: (): React.Node =>
|
||||
CustomIntroSlider.getIconView('view-dashboard-variant'),
|
||||
mascotStyle: MASCOT_STYLE.CUTE,
|
||||
colors: ['#be1522', '#57080e'],
|
||||
},
|
||||
{
|
||||
key: '4',
|
||||
title: i18n.t('intro.slideDone.title'),
|
||||
text: i18n.t('intro.slideDone.text'),
|
||||
view: (): React.Node => this.getEndView(),
|
||||
mascotStyle: MASCOT_STYLE.COOL,
|
||||
colors: ['#9c165b', '#3e042b'],
|
||||
},
|
||||
];
|
||||
// $FlowFixMe
|
||||
this.updateSlides = [];
|
||||
for (let i = 0; i < Update.slidesNumber; i += 1) {
|
||||
this.updateSlides.push({
|
||||
key: i.toString(),
|
||||
title: Update.getInstance().titleList[i],
|
||||
text: Update.getInstance().descriptionList[i],
|
||||
icon: Update.iconList[i],
|
||||
colors: Update.colorsList[i],
|
||||
});
|
||||
}
|
||||
|
||||
onDone = () => {
|
||||
this.setStatusBarColor(ThemeManager.getCurrentTheme().colors.surface);
|
||||
this.props.onDone();
|
||||
}
|
||||
|
||||
renderNextButton = () => {
|
||||
return (
|
||||
<Animatable.View
|
||||
animation={"fadeIn"}
|
||||
this.aprilFoolsSlides = [
|
||||
{
|
||||
key: '1',
|
||||
title: i18n.t('intro.aprilFoolsSlide.title'),
|
||||
text: i18n.t('intro.aprilFoolsSlide.text'),
|
||||
view: (): React.Node => <View />,
|
||||
mascotStyle: MASCOT_STYLE.NORMAL,
|
||||
colors: ['#e01928', '#be1522'],
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Render item to be used for the intro introSlides
|
||||
*
|
||||
* @param item The item to be displayed
|
||||
* @param dimensions Dimensions of the item
|
||||
*/
|
||||
getIntroRenderItem = ({
|
||||
item,
|
||||
dimensions,
|
||||
}: {
|
||||
item: IntroSlideType,
|
||||
dimensions: {width: number, height: number},
|
||||
}): React.Node => {
|
||||
const {state} = this;
|
||||
const index = parseInt(item.key, 10);
|
||||
return (
|
||||
<LinearGradient
|
||||
style={[styles.mainContent, dimensions]}
|
||||
colors={item.colors}
|
||||
start={{x: 0, y: 0.1}}
|
||||
end={{x: 0.1, y: 1}}>
|
||||
{state.currentSlide === index ? (
|
||||
<View style={{height: '100%', flex: 1}}>
|
||||
<View style={{flex: 1}}>{item.view()}</View>
|
||||
<Animatable.View animation="fadeIn">
|
||||
{index !== 0 && index !== this.introSlides.length - 1 ? (
|
||||
<Mascot
|
||||
style={{
|
||||
marginLeft: 30,
|
||||
marginBottom: 0,
|
||||
width: 100,
|
||||
marginTop: -30,
|
||||
}}
|
||||
emotion={item.mascotStyle}
|
||||
animated
|
||||
entryAnimation={{
|
||||
animation: 'slideInLeft',
|
||||
duration: 500,
|
||||
}}
|
||||
loopAnimation={{
|
||||
animation: 'pulse',
|
||||
iterationCount: 'infinite',
|
||||
duration: 2000,
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
<View
|
||||
style={{
|
||||
borderRadius: 25,
|
||||
padding: 5,
|
||||
backgroundColor: "rgba(0,0,0,0.2)"
|
||||
}}>
|
||||
<MaterialCommunityIcons
|
||||
name={"arrow-right"}
|
||||
color={'#fff'}
|
||||
size={40}/>
|
||||
</Animatable.View>
|
||||
)
|
||||
}
|
||||
|
||||
renderDoneButton = () => {
|
||||
return (
|
||||
<Animatable.View
|
||||
animation={"bounceIn"}
|
||||
|
||||
marginLeft: 50,
|
||||
width: 0,
|
||||
height: 0,
|
||||
borderLeftWidth: 20,
|
||||
borderRightWidth: 0,
|
||||
borderBottomWidth: 20,
|
||||
borderStyle: 'solid',
|
||||
backgroundColor: 'transparent',
|
||||
borderLeftColor: 'transparent',
|
||||
borderRightColor: 'transparent',
|
||||
borderBottomColor: 'rgba(0,0,0,0.60)',
|
||||
}}
|
||||
/>
|
||||
<Card
|
||||
style={{
|
||||
borderRadius: 25,
|
||||
padding: 5,
|
||||
backgroundColor: "rgb(190,21,34)"
|
||||
backgroundColor: 'rgba(0,0,0,0.38)',
|
||||
marginHorizontal: 20,
|
||||
borderColor: 'rgba(0,0,0,0.60)',
|
||||
borderWidth: 4,
|
||||
borderRadius: 10,
|
||||
}}>
|
||||
<MaterialCommunityIcons
|
||||
name={"check"}
|
||||
color={'#fff'}
|
||||
size={40}/>
|
||||
<Card.Content>
|
||||
<Animatable.Text
|
||||
animation="fadeIn"
|
||||
delay={100}
|
||||
style={styles.title}>
|
||||
{item.title}
|
||||
</Animatable.Text>
|
||||
<Animatable.Text
|
||||
animation="fadeIn"
|
||||
delay={200}
|
||||
style={styles.text}>
|
||||
{item.text}
|
||||
</Animatable.Text>
|
||||
</Card.Content>
|
||||
</Card>
|
||||
</Animatable.View>
|
||||
)
|
||||
}
|
||||
</View>
|
||||
) : null}
|
||||
</LinearGradient>
|
||||
);
|
||||
};
|
||||
|
||||
render() {
|
||||
this.currentSlides = this.introSlides;
|
||||
if (this.props.isUpdate)
|
||||
this.currentSlides = this.updateSlides;
|
||||
else if (this.props.isAprilFools)
|
||||
this.currentSlides = this.aprilFoolsSlides;
|
||||
this.setStatusBarColor(this.currentSlides[0].colors[0]);
|
||||
return (
|
||||
<AppIntroSlider
|
||||
ref={this.sliderRef}
|
||||
data={this.currentSlides}
|
||||
extraData={this.state.currentSlide}
|
||||
getEndView = (): React.Node => {
|
||||
return (
|
||||
<View style={{flex: 1}}>
|
||||
<Mascot
|
||||
style={{
|
||||
...styles.center,
|
||||
height: '80%',
|
||||
}}
|
||||
emotion={MASCOT_STYLE.COOL}
|
||||
animated
|
||||
entryAnimation={{
|
||||
animation: 'slideInDown',
|
||||
duration: 2000,
|
||||
}}
|
||||
loopAnimation={{
|
||||
animation: 'pulse',
|
||||
duration: 2000,
|
||||
iterationCount: 'infinite',
|
||||
}}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
};
|
||||
|
||||
renderItem={this.getIntroRenderItem}
|
||||
renderNextButton={this.renderNextButton}
|
||||
renderDoneButton={this.renderDoneButton}
|
||||
getWelcomeView = (): React.Node => {
|
||||
return (
|
||||
<View style={{flex: 1}}>
|
||||
<Mascot
|
||||
style={{
|
||||
...styles.center,
|
||||
height: '80%',
|
||||
}}
|
||||
emotion={MASCOT_STYLE.NORMAL}
|
||||
animated
|
||||
entryAnimation={{
|
||||
animation: 'bounceIn',
|
||||
duration: 2000,
|
||||
}}
|
||||
/>
|
||||
<Animatable.Text
|
||||
useNativeDriver
|
||||
animation="fadeInUp"
|
||||
duration={500}
|
||||
style={{
|
||||
color: '#fff',
|
||||
textAlign: 'center',
|
||||
fontSize: 25,
|
||||
}}>
|
||||
PABLO
|
||||
</Animatable.Text>
|
||||
<Animatable.View
|
||||
useNativeDriver
|
||||
animation="fadeInUp"
|
||||
duration={500}
|
||||
delay={200}
|
||||
style={{
|
||||
position: 'absolute',
|
||||
bottom: 30,
|
||||
right: '20%',
|
||||
width: 50,
|
||||
height: 50,
|
||||
}}>
|
||||
<MaterialCommunityIcons
|
||||
style={{
|
||||
...styles.center,
|
||||
transform: [{rotateZ: '70deg'}],
|
||||
}}
|
||||
name="undo"
|
||||
color="#fff"
|
||||
size={40}
|
||||
/>
|
||||
</Animatable.View>
|
||||
</View>
|
||||
);
|
||||
};
|
||||
|
||||
onDone={this.onDone}
|
||||
onSlideChange={this.onSlideChange}
|
||||
onSkip={this.onSkip}
|
||||
/>
|
||||
);
|
||||
}
|
||||
static getIconView(icon: MaterialCommunityIconsGlyphs): React.Node {
|
||||
return (
|
||||
<View style={{flex: 1}}>
|
||||
<Animatable.View style={styles.center} animation="fadeIn">
|
||||
<MaterialCommunityIcons name={icon} color="#fff" size={200} />
|
||||
</Animatable.View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
static setStatusBarColor(color: string) {
|
||||
if (Platform.OS === 'android') StatusBar.setBackgroundColor(color, true);
|
||||
}
|
||||
|
||||
onSlideChange = (index: number) => {
|
||||
CustomIntroSlider.setStatusBarColor(this.currentSlides[index].colors[0]);
|
||||
this.setState({currentSlide: index});
|
||||
};
|
||||
|
||||
onSkip = () => {
|
||||
CustomIntroSlider.setStatusBarColor(
|
||||
this.currentSlides[this.currentSlides.length - 1].colors[0],
|
||||
);
|
||||
if (this.sliderRef.current != null)
|
||||
this.sliderRef.current.goToSlide(this.currentSlides.length - 1);
|
||||
};
|
||||
|
||||
onDone = () => {
|
||||
const {props} = this;
|
||||
CustomIntroSlider.setStatusBarColor(
|
||||
ThemeManager.getCurrentTheme().colors.surface,
|
||||
);
|
||||
props.onDone();
|
||||
};
|
||||
|
||||
getRenderNextButton = (): React.Node => {
|
||||
return (
|
||||
<Animatable.View
|
||||
animation="fadeIn"
|
||||
style={{
|
||||
borderRadius: 25,
|
||||
padding: 5,
|
||||
backgroundColor: 'rgba(0,0,0,0.2)',
|
||||
}}>
|
||||
<MaterialCommunityIcons name="arrow-right" color="#fff" size={40} />
|
||||
</Animatable.View>
|
||||
);
|
||||
};
|
||||
|
||||
getRenderDoneButton = (): React.Node => {
|
||||
return (
|
||||
<Animatable.View
|
||||
animation="bounceIn"
|
||||
style={{
|
||||
borderRadius: 25,
|
||||
padding: 5,
|
||||
backgroundColor: 'rgb(190,21,34)',
|
||||
}}>
|
||||
<MaterialCommunityIcons name="check" color="#fff" size={40} />
|
||||
</Animatable.View>
|
||||
);
|
||||
};
|
||||
|
||||
render(): React.Node {
|
||||
const {props, state} = this;
|
||||
this.currentSlides = this.introSlides;
|
||||
if (props.isUpdate) this.currentSlides = this.updateSlides;
|
||||
else if (props.isAprilFools) this.currentSlides = this.aprilFoolsSlides;
|
||||
CustomIntroSlider.setStatusBarColor(this.currentSlides[0].colors[0]);
|
||||
return (
|
||||
<AppIntroSlider
|
||||
ref={this.sliderRef}
|
||||
data={this.currentSlides}
|
||||
extraData={state.currentSlide}
|
||||
renderItem={this.getIntroRenderItem}
|
||||
renderNextButton={this.getRenderNextButton}
|
||||
renderDoneButton={this.getRenderDoneButton}
|
||||
onDone={this.onDone}
|
||||
onSlideChange={this.onSlideChange}
|
||||
onSkip={this.onSkip}
|
||||
/>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
mainContent: {
|
||||
paddingBottom: 100,
|
||||
},
|
||||
text: {
|
||||
color: 'rgba(255, 255, 255, 0.8)',
|
||||
backgroundColor: 'transparent',
|
||||
textAlign: 'center',
|
||||
paddingHorizontal: 16,
|
||||
},
|
||||
title: {
|
||||
fontSize: 22,
|
||||
color: 'white',
|
||||
backgroundColor: 'transparent',
|
||||
textAlign: 'center',
|
||||
marginBottom: 16,
|
||||
},
|
||||
center: {
|
||||
marginTop: 'auto',
|
||||
marginBottom: 'auto',
|
||||
marginRight: 'auto',
|
||||
marginLeft: 'auto',
|
||||
},
|
||||
});
|
||||
|
|
|
|||
|
|
@ -2,9 +2,10 @@
|
|||
|
||||
import * as React from 'react';
|
||||
import {withTheme} from 'react-native-paper';
|
||||
import {Modalize} from "react-native-modalize";
|
||||
import {View} from "react-native-animatable";
|
||||
import CustomTabBar from "../Tabbar/CustomTabBar";
|
||||
import {Modalize} from 'react-native-modalize';
|
||||
import {View} from 'react-native-animatable';
|
||||
import CustomTabBar from '../Tabbar/CustomTabBar';
|
||||
import type {CustomThemeType} from '../../managers/ThemeManager';
|
||||
|
||||
/**
|
||||
* Abstraction layer for Modalize component, using custom configuration
|
||||
|
|
@ -12,25 +13,29 @@ import CustomTabBar from "../Tabbar/CustomTabBar";
|
|||
* @param props Props to pass to the element. Must specify an onRef prop to get an Modalize ref.
|
||||
* @return {*}
|
||||
*/
|
||||
function CustomModal(props) {
|
||||
const {colors} = props.theme;
|
||||
return (
|
||||
<Modalize
|
||||
ref={props.onRef}
|
||||
adjustToContentHeight
|
||||
handlePosition={'inside'}
|
||||
modalStyle={{backgroundColor: colors.card}}
|
||||
handleStyle={{backgroundColor: colors.primary}}
|
||||
>
|
||||
<View style={{
|
||||
paddingBottom: CustomTabBar.TAB_BAR_HEIGHT
|
||||
}}>
|
||||
{props.children}
|
||||
</View>
|
||||
|
||||
</Modalize>
|
||||
);
|
||||
function CustomModal(props: {
|
||||
theme: CustomThemeType,
|
||||
onRef: (re: Modalize) => void,
|
||||
children?: React.Node,
|
||||
}): React.Node {
|
||||
const {theme, onRef, children} = props;
|
||||
return (
|
||||
<Modalize
|
||||
ref={onRef}
|
||||
adjustToContentHeight
|
||||
handlePosition="inside"
|
||||
modalStyle={{backgroundColor: theme.colors.card}}
|
||||
handleStyle={{backgroundColor: theme.colors.primary}}>
|
||||
<View
|
||||
style={{
|
||||
paddingBottom: CustomTabBar.TAB_BAR_HEIGHT,
|
||||
}}>
|
||||
{children}
|
||||
</View>
|
||||
</Modalize>
|
||||
);
|
||||
}
|
||||
|
||||
export default withTheme(CustomModal);
|
||||
CustomModal.defaultProps = {children: null};
|
||||
|
||||
export default withTheme(CustomModal);
|
||||
|
|
|
|||
|
|
@ -2,19 +2,19 @@
|
|||
|
||||
import * as React from 'react';
|
||||
import {Text, withTheme} from 'react-native-paper';
|
||||
import {View} from "react-native-animatable";
|
||||
import type {CustomTheme} from "../../managers/ThemeManager";
|
||||
import Slider, {SliderProps} from "@react-native-community/slider";
|
||||
import {View} from 'react-native-animatable';
|
||||
import Slider, {SliderProps} from '@react-native-community/slider';
|
||||
import type {CustomThemeType} from '../../managers/ThemeManager';
|
||||
|
||||
type Props = {
|
||||
theme: CustomTheme,
|
||||
valueSuffix: string,
|
||||
...SliderProps
|
||||
}
|
||||
type PropsType = {
|
||||
theme: CustomThemeType,
|
||||
valueSuffix?: string,
|
||||
...SliderProps,
|
||||
};
|
||||
|
||||
type State = {
|
||||
currentValue: number,
|
||||
}
|
||||
type StateType = {
|
||||
currentValue: number,
|
||||
};
|
||||
|
||||
/**
|
||||
* Abstraction layer for Modalize component, using custom configuration
|
||||
|
|
@ -22,37 +22,44 @@ type State = {
|
|||
* @param props Props to pass to the element. Must specify an onRef prop to get an Modalize ref.
|
||||
* @return {*}
|
||||
*/
|
||||
class CustomSlider extends React.Component<Props, State> {
|
||||
class CustomSlider extends React.Component<PropsType, StateType> {
|
||||
static defaultProps = {
|
||||
valueSuffix: '',
|
||||
};
|
||||
|
||||
static defaultProps = {
|
||||
valueSuffix: "",
|
||||
}
|
||||
constructor(props: PropsType) {
|
||||
super(props);
|
||||
this.state = {
|
||||
currentValue: props.value,
|
||||
};
|
||||
}
|
||||
|
||||
state = {
|
||||
currentValue: this.props.value,
|
||||
}
|
||||
|
||||
onValueChange = (value: number) => {
|
||||
this.setState({currentValue: value});
|
||||
if (this.props.onValueChange != null)
|
||||
this.props.onValueChange(value);
|
||||
}
|
||||
|
||||
render() {
|
||||
return (
|
||||
<View style={{flex: 1, flexDirection: 'row'}}>
|
||||
<Text style={{marginHorizontal: 10, marginTop: 'auto', marginBottom: 'auto'}}>
|
||||
{this.state.currentValue}min
|
||||
</Text>
|
||||
<Slider
|
||||
{...this.props}
|
||||
onValueChange={this.onValueChange}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
onValueChange = (value: number) => {
|
||||
const {props} = this;
|
||||
this.setState({currentValue: value});
|
||||
if (props.onValueChange != null) props.onValueChange(value);
|
||||
};
|
||||
|
||||
render(): React.Node {
|
||||
const {props, state} = this;
|
||||
return (
|
||||
<View style={{flex: 1, flexDirection: 'row'}}>
|
||||
<Text
|
||||
style={{
|
||||
marginHorizontal: 10,
|
||||
marginTop: 'auto',
|
||||
marginBottom: 'auto',
|
||||
}}>
|
||||
{state.currentValue}min
|
||||
</Text>
|
||||
<Slider
|
||||
// eslint-disable-next-line react/jsx-props-no-spreading
|
||||
{...props}
|
||||
onValueChange={this.onValueChange}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default withTheme(CustomSlider);
|
||||
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@
|
|||
import * as React from 'react';
|
||||
import {View} from 'react-native';
|
||||
import {ActivityIndicator, withTheme} from 'react-native-paper';
|
||||
import type {CustomThemeType} from '../../managers/ThemeManager';
|
||||
|
||||
/**
|
||||
* Component used to display a header button
|
||||
|
|
@ -10,28 +11,29 @@ import {ActivityIndicator, withTheme} from 'react-native-paper';
|
|||
* @param props Props to pass to the component
|
||||
* @return {*}
|
||||
*/
|
||||
function BasicLoadingScreen(props) {
|
||||
const {colors} = props.theme;
|
||||
let position = undefined;
|
||||
if (props.isAbsolute !== undefined && props.isAbsolute)
|
||||
position = 'absolute';
|
||||
function BasicLoadingScreen(props: {
|
||||
theme: CustomThemeType,
|
||||
isAbsolute: boolean,
|
||||
}): React.Node {
|
||||
const {theme, isAbsolute} = props;
|
||||
const {colors} = theme;
|
||||
let position;
|
||||
if (isAbsolute != null && isAbsolute) position = 'absolute';
|
||||
|
||||
return (
|
||||
<View style={{
|
||||
backgroundColor: colors.background,
|
||||
position: position,
|
||||
top: 0,
|
||||
right: 0,
|
||||
width: '100%',
|
||||
height: '100%',
|
||||
justifyContent: 'center',
|
||||
}}>
|
||||
<ActivityIndicator
|
||||
animating={true}
|
||||
size={'large'}
|
||||
color={colors.primary}/>
|
||||
</View>
|
||||
);
|
||||
return (
|
||||
<View
|
||||
style={{
|
||||
backgroundColor: colors.background,
|
||||
position,
|
||||
top: 0,
|
||||
right: 0,
|
||||
width: '100%',
|
||||
height: '100%',
|
||||
justifyContent: 'center',
|
||||
}}>
|
||||
<ActivityIndicator animating size="large" color={colors.primary} />
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
export default withTheme(BasicLoadingScreen);
|
||||
|
|
|
|||
|
|
@ -2,191 +2,192 @@
|
|||
|
||||
import * as React from 'react';
|
||||
import {Button, Subheading, withTheme} from 'react-native-paper';
|
||||
import {StyleSheet, View} from "react-native";
|
||||
import MaterialCommunityIcons from "react-native-vector-icons/MaterialCommunityIcons";
|
||||
import {StyleSheet, View} from 'react-native';
|
||||
import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons';
|
||||
import i18n from 'i18n-js';
|
||||
import {ERROR_TYPE} from "../../utils/WebData";
|
||||
import * as Animatable from 'react-native-animatable';
|
||||
import {StackNavigationProp} from '@react-navigation/stack';
|
||||
import {ERROR_TYPE} from '../../utils/WebData';
|
||||
import type {CustomThemeType} from '../../managers/ThemeManager';
|
||||
|
||||
type Props = {
|
||||
navigation: Object,
|
||||
route: Object,
|
||||
errorCode: number,
|
||||
onRefresh: Function,
|
||||
icon: string,
|
||||
message: string,
|
||||
showRetryButton: boolean,
|
||||
}
|
||||
|
||||
type State = {
|
||||
refreshing: boolean,
|
||||
}
|
||||
|
||||
class ErrorView extends React.PureComponent<Props, State> {
|
||||
|
||||
colors: Object;
|
||||
|
||||
message: string;
|
||||
icon: string;
|
||||
|
||||
showLoginButton: boolean;
|
||||
|
||||
static defaultProps = {
|
||||
errorCode: 0,
|
||||
icon: '',
|
||||
message: '',
|
||||
showRetryButton: true,
|
||||
}
|
||||
|
||||
state = {
|
||||
refreshing: false,
|
||||
};
|
||||
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.colors = props.theme.colors;
|
||||
this.icon = "";
|
||||
}
|
||||
|
||||
generateMessage() {
|
||||
this.showLoginButton = false;
|
||||
if (this.props.errorCode !== 0) {
|
||||
switch (this.props.errorCode) {
|
||||
case ERROR_TYPE.BAD_CREDENTIALS:
|
||||
this.message = i18n.t("errors.badCredentials");
|
||||
this.icon = "account-alert-outline";
|
||||
break;
|
||||
case ERROR_TYPE.BAD_TOKEN:
|
||||
this.message = i18n.t("errors.badToken");
|
||||
this.icon = "account-alert-outline";
|
||||
this.showLoginButton = true;
|
||||
break;
|
||||
case ERROR_TYPE.NO_CONSENT:
|
||||
this.message = i18n.t("errors.noConsent");
|
||||
this.icon = "account-remove-outline";
|
||||
break;
|
||||
case ERROR_TYPE.TOKEN_SAVE:
|
||||
this.message = i18n.t("errors.tokenSave");
|
||||
this.icon = "alert-circle-outline";
|
||||
break;
|
||||
case ERROR_TYPE.BAD_INPUT:
|
||||
this.message = i18n.t("errors.badInput");
|
||||
this.icon = "alert-circle-outline";
|
||||
break;
|
||||
case ERROR_TYPE.FORBIDDEN:
|
||||
this.message = i18n.t("errors.forbidden");
|
||||
this.icon = "lock";
|
||||
break;
|
||||
case ERROR_TYPE.CONNECTION_ERROR:
|
||||
this.message = i18n.t("errors.connectionError");
|
||||
this.icon = "access-point-network-off";
|
||||
break;
|
||||
case ERROR_TYPE.SERVER_ERROR:
|
||||
this.message = i18n.t("errors.serverError");
|
||||
this.icon = "server-network-off";
|
||||
break;
|
||||
default:
|
||||
this.message = i18n.t("errors.unknown");
|
||||
this.icon = "alert-circle-outline";
|
||||
break;
|
||||
}
|
||||
this.message += "\n\nCode " + this.props.errorCode;
|
||||
} else {
|
||||
this.message = this.props.message;
|
||||
this.icon = this.props.icon;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
getRetryButton() {
|
||||
return <Button
|
||||
mode={'contained'}
|
||||
icon={'refresh'}
|
||||
onPress={this.props.onRefresh}
|
||||
style={styles.button}
|
||||
>
|
||||
{i18n.t("general.retry")}
|
||||
</Button>;
|
||||
}
|
||||
|
||||
goToLogin = () => {
|
||||
this.props.navigation.navigate("login",
|
||||
{
|
||||
screen: 'login',
|
||||
params: {nextScreen: this.props.route.name}
|
||||
})
|
||||
};
|
||||
|
||||
getLoginButton() {
|
||||
return <Button
|
||||
mode={'contained'}
|
||||
icon={'login'}
|
||||
onPress={this.goToLogin}
|
||||
style={styles.button}
|
||||
>
|
||||
{i18n.t("screens.login.title")}
|
||||
</Button>;
|
||||
}
|
||||
|
||||
render() {
|
||||
this.generateMessage();
|
||||
return (
|
||||
<Animatable.View
|
||||
style={{
|
||||
...styles.outer,
|
||||
backgroundColor: this.colors.background
|
||||
}}
|
||||
animation={"zoomIn"}
|
||||
duration={200}
|
||||
useNativeDriver
|
||||
>
|
||||
<View style={styles.inner}>
|
||||
<View style={styles.iconContainer}>
|
||||
<MaterialCommunityIcons
|
||||
name={this.icon}
|
||||
size={150}
|
||||
color={this.colors.textDisabled}/>
|
||||
</View>
|
||||
<Subheading style={{
|
||||
...styles.subheading,
|
||||
color: this.colors.textDisabled
|
||||
}}>
|
||||
{this.message}
|
||||
</Subheading>
|
||||
{this.props.showRetryButton
|
||||
? (this.showLoginButton
|
||||
? this.getLoginButton()
|
||||
: this.getRetryButton())
|
||||
: null}
|
||||
</View>
|
||||
</Animatable.View>
|
||||
);
|
||||
}
|
||||
}
|
||||
type PropsType = {
|
||||
navigation: StackNavigationProp,
|
||||
theme: CustomThemeType,
|
||||
route: {name: string},
|
||||
onRefresh?: () => void,
|
||||
errorCode?: number,
|
||||
icon?: string,
|
||||
message?: string,
|
||||
showRetryButton?: boolean,
|
||||
};
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
outer: {
|
||||
height: '100%',
|
||||
},
|
||||
inner: {
|
||||
marginTop: 'auto',
|
||||
marginBottom: 'auto',
|
||||
},
|
||||
iconContainer: {
|
||||
marginLeft: 'auto',
|
||||
marginRight: 'auto',
|
||||
marginBottom: 20
|
||||
},
|
||||
subheading: {
|
||||
textAlign: 'center',
|
||||
paddingHorizontal: 20
|
||||
},
|
||||
button: {
|
||||
marginTop: 10,
|
||||
marginLeft: 'auto',
|
||||
marginRight: 'auto',
|
||||
}
|
||||
outer: {
|
||||
height: '100%',
|
||||
},
|
||||
inner: {
|
||||
marginTop: 'auto',
|
||||
marginBottom: 'auto',
|
||||
},
|
||||
iconContainer: {
|
||||
marginLeft: 'auto',
|
||||
marginRight: 'auto',
|
||||
marginBottom: 20,
|
||||
},
|
||||
subheading: {
|
||||
textAlign: 'center',
|
||||
paddingHorizontal: 20,
|
||||
},
|
||||
button: {
|
||||
marginTop: 10,
|
||||
marginLeft: 'auto',
|
||||
marginRight: 'auto',
|
||||
},
|
||||
});
|
||||
|
||||
class ErrorView extends React.PureComponent<PropsType> {
|
||||
static defaultProps = {
|
||||
onRefresh: () => {},
|
||||
errorCode: 0,
|
||||
icon: '',
|
||||
message: '',
|
||||
showRetryButton: true,
|
||||
};
|
||||
|
||||
message: string;
|
||||
|
||||
icon: string;
|
||||
|
||||
showLoginButton: boolean;
|
||||
|
||||
constructor(props: PropsType) {
|
||||
super(props);
|
||||
this.icon = '';
|
||||
}
|
||||
|
||||
getRetryButton(): React.Node {
|
||||
const {props} = this;
|
||||
return (
|
||||
<Button
|
||||
mode="contained"
|
||||
icon="refresh"
|
||||
onPress={props.onRefresh}
|
||||
style={styles.button}>
|
||||
{i18n.t('general.retry')}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
getLoginButton(): React.Node {
|
||||
return (
|
||||
<Button
|
||||
mode="contained"
|
||||
icon="login"
|
||||
onPress={this.goToLogin}
|
||||
style={styles.button}>
|
||||
{i18n.t('screens.login.title')}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
goToLogin = () => {
|
||||
const {props} = this;
|
||||
props.navigation.navigate('login', {
|
||||
screen: 'login',
|
||||
params: {nextScreen: props.route.name},
|
||||
});
|
||||
};
|
||||
|
||||
generateMessage() {
|
||||
const {props} = this;
|
||||
this.showLoginButton = false;
|
||||
if (props.errorCode !== 0) {
|
||||
switch (props.errorCode) {
|
||||
case ERROR_TYPE.BAD_CREDENTIALS:
|
||||
this.message = i18n.t('errors.badCredentials');
|
||||
this.icon = 'account-alert-outline';
|
||||
break;
|
||||
case ERROR_TYPE.BAD_TOKEN:
|
||||
this.message = i18n.t('errors.badToken');
|
||||
this.icon = 'account-alert-outline';
|
||||
this.showLoginButton = true;
|
||||
break;
|
||||
case ERROR_TYPE.NO_CONSENT:
|
||||
this.message = i18n.t('errors.noConsent');
|
||||
this.icon = 'account-remove-outline';
|
||||
break;
|
||||
case ERROR_TYPE.TOKEN_SAVE:
|
||||
this.message = i18n.t('errors.tokenSave');
|
||||
this.icon = 'alert-circle-outline';
|
||||
break;
|
||||
case ERROR_TYPE.BAD_INPUT:
|
||||
this.message = i18n.t('errors.badInput');
|
||||
this.icon = 'alert-circle-outline';
|
||||
break;
|
||||
case ERROR_TYPE.FORBIDDEN:
|
||||
this.message = i18n.t('errors.forbidden');
|
||||
this.icon = 'lock';
|
||||
break;
|
||||
case ERROR_TYPE.CONNECTION_ERROR:
|
||||
this.message = i18n.t('errors.connectionError');
|
||||
this.icon = 'access-point-network-off';
|
||||
break;
|
||||
case ERROR_TYPE.SERVER_ERROR:
|
||||
this.message = i18n.t('errors.serverError');
|
||||
this.icon = 'server-network-off';
|
||||
break;
|
||||
default:
|
||||
this.message = i18n.t('errors.unknown');
|
||||
this.icon = 'alert-circle-outline';
|
||||
break;
|
||||
}
|
||||
this.message += `\n\nCode ${
|
||||
props.errorCode != null ? props.errorCode : -1
|
||||
}`;
|
||||
} else {
|
||||
this.message = props.message != null ? props.message : '';
|
||||
this.icon = props.icon != null ? props.icon : '';
|
||||
}
|
||||
}
|
||||
|
||||
render(): React.Node {
|
||||
const {props} = this;
|
||||
this.generateMessage();
|
||||
let button;
|
||||
if (this.showLoginButton) button = this.getLoginButton();
|
||||
else if (props.showRetryButton) button = this.getRetryButton();
|
||||
else button = null;
|
||||
|
||||
return (
|
||||
<Animatable.View
|
||||
style={{
|
||||
...styles.outer,
|
||||
backgroundColor: props.theme.colors.background,
|
||||
}}
|
||||
animation="zoomIn"
|
||||
duration={200}
|
||||
useNativeDriver>
|
||||
<View style={styles.inner}>
|
||||
<View style={styles.iconContainer}>
|
||||
<MaterialCommunityIcons
|
||||
// $FlowFixMe
|
||||
name={this.icon}
|
||||
size={150}
|
||||
color={props.theme.colors.textDisabled}
|
||||
/>
|
||||
</View>
|
||||
<Subheading
|
||||
style={{
|
||||
...styles.subheading,
|
||||
color: props.theme.colors.textDisabled,
|
||||
}}>
|
||||
{this.message}
|
||||
</Subheading>
|
||||
{button}
|
||||
</View>
|
||||
</Animatable.View>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default withTheme(ErrorView);
|
||||
|
|
|
|||
|
|
@ -1,44 +1,55 @@
|
|||
// @flow
|
||||
|
||||
import * as React from 'react';
|
||||
import {ERROR_TYPE, readData} from "../../utils/WebData";
|
||||
import i18n from "i18n-js";
|
||||
import i18n from 'i18n-js';
|
||||
import {Snackbar} from 'react-native-paper';
|
||||
import {RefreshControl, View} from "react-native";
|
||||
import ErrorView from "./ErrorView";
|
||||
import BasicLoadingScreen from "./BasicLoadingScreen";
|
||||
import {withCollapsible} from "../../utils/withCollapsible";
|
||||
import {RefreshControl, View} from 'react-native';
|
||||
import * as Animatable from 'react-native-animatable';
|
||||
import CustomTabBar from "../Tabbar/CustomTabBar";
|
||||
import {Collapsible} from "react-navigation-collapsible";
|
||||
import {StackNavigationProp} from "@react-navigation/stack";
|
||||
import CollapsibleSectionList from "../Collapsible/CollapsibleSectionList";
|
||||
import {Collapsible} from 'react-navigation-collapsible';
|
||||
import {StackNavigationProp} from '@react-navigation/stack';
|
||||
import ErrorView from './ErrorView';
|
||||
import BasicLoadingScreen from './BasicLoadingScreen';
|
||||
import withCollapsible from '../../utils/withCollapsible';
|
||||
import CustomTabBar from '../Tabbar/CustomTabBar';
|
||||
import {ERROR_TYPE, readData} from '../../utils/WebData';
|
||||
import CollapsibleSectionList from '../Collapsible/CollapsibleSectionList';
|
||||
import type {ApiGenericDataType} from '../../utils/WebData';
|
||||
|
||||
type Props = {
|
||||
navigation: StackNavigationProp,
|
||||
fetchUrl: string,
|
||||
autoRefreshTime: number,
|
||||
refreshOnFocus: boolean,
|
||||
renderItem: (data: { [key: string]: any }) => React.Node,
|
||||
createDataset: (data: { [key: string]: any } | null, isLoading?: boolean) => Array<Object>,
|
||||
onScroll: (event: SyntheticEvent<EventTarget>) => void,
|
||||
collapsibleStack: Collapsible,
|
||||
export type SectionListDataType<T> = Array<{
|
||||
title: string,
|
||||
data: Array<T>,
|
||||
keyExtractor?: (T) => string,
|
||||
}>;
|
||||
|
||||
showError: boolean,
|
||||
itemHeight?: number,
|
||||
updateData?: number,
|
||||
renderListHeaderComponent?: (data: { [key: string]: any } | null) => React.Node,
|
||||
renderSectionHeader?: (data: { section: { [key: string]: any } }, isLoading?: boolean) => React.Node,
|
||||
stickyHeader?: boolean,
|
||||
}
|
||||
type PropsType<T> = {
|
||||
navigation: StackNavigationProp,
|
||||
fetchUrl: string,
|
||||
autoRefreshTime: number,
|
||||
refreshOnFocus: boolean,
|
||||
renderItem: (data: {item: T}) => React.Node,
|
||||
createDataset: (
|
||||
data: ApiGenericDataType | null,
|
||||
isLoading?: boolean,
|
||||
) => SectionListDataType<T>,
|
||||
onScroll: (event: SyntheticEvent<EventTarget>) => void,
|
||||
collapsibleStack: Collapsible,
|
||||
|
||||
type State = {
|
||||
refreshing: boolean,
|
||||
firstLoading: boolean,
|
||||
fetchedData: { [key: string]: any } | null,
|
||||
snackbarVisible: boolean
|
||||
showError?: boolean,
|
||||
itemHeight?: number | null,
|
||||
updateData?: number,
|
||||
renderListHeaderComponent?: (data: ApiGenericDataType | null) => React.Node,
|
||||
renderSectionHeader?: (
|
||||
data: {section: {title: string}},
|
||||
isLoading?: boolean,
|
||||
) => React.Node,
|
||||
stickyHeader?: boolean,
|
||||
};
|
||||
|
||||
type StateType = {
|
||||
refreshing: boolean,
|
||||
fetchedData: ApiGenericDataType | null,
|
||||
snackbarVisible: boolean,
|
||||
};
|
||||
|
||||
const MIN_REFRESH_TIME = 5 * 1000;
|
||||
|
||||
|
|
@ -48,211 +59,216 @@ const MIN_REFRESH_TIME = 5 * 1000;
|
|||
* This is a pure component, meaning it will only update if a shallow comparison of state and props is different.
|
||||
* To force the component to update, change the value of updateData.
|
||||
*/
|
||||
class WebSectionList extends React.PureComponent<Props, State> {
|
||||
class WebSectionList<T> extends React.PureComponent<PropsType<T>, StateType> {
|
||||
static defaultProps = {
|
||||
showError: true,
|
||||
itemHeight: null,
|
||||
updateData: 0,
|
||||
renderListHeaderComponent: (): React.Node => null,
|
||||
renderSectionHeader: (): React.Node => null,
|
||||
stickyHeader: false,
|
||||
};
|
||||
|
||||
static defaultProps = {
|
||||
stickyHeader: false,
|
||||
updateData: 0,
|
||||
showError: true,
|
||||
refreshInterval: IntervalID;
|
||||
|
||||
lastRefresh: Date | null;
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
this.state = {
|
||||
refreshing: false,
|
||||
fetchedData: null,
|
||||
snackbarVisible: false,
|
||||
};
|
||||
}
|
||||
|
||||
refreshInterval: IntervalID;
|
||||
lastRefresh: Date | null;
|
||||
/**
|
||||
* Registers react navigation events on first screen load.
|
||||
* Allows to detect when the screen is focused
|
||||
*/
|
||||
componentDidMount() {
|
||||
const {navigation} = this.props;
|
||||
navigation.addListener('focus', this.onScreenFocus);
|
||||
navigation.addListener('blur', this.onScreenBlur);
|
||||
this.lastRefresh = null;
|
||||
this.onRefresh();
|
||||
}
|
||||
|
||||
state = {
|
||||
refreshing: false,
|
||||
firstLoading: true,
|
||||
fetchedData: null,
|
||||
snackbarVisible: false
|
||||
/**
|
||||
* Refreshes data when focusing the screen and setup a refresh interval if asked to
|
||||
*/
|
||||
onScreenFocus = () => {
|
||||
const {props} = this;
|
||||
if (props.refreshOnFocus && this.lastRefresh) this.onRefresh();
|
||||
if (props.autoRefreshTime > 0)
|
||||
this.refreshInterval = setInterval(this.onRefresh, props.autoRefreshTime);
|
||||
};
|
||||
|
||||
/**
|
||||
* Removes any interval on un-focus
|
||||
*/
|
||||
onScreenBlur = () => {
|
||||
clearInterval(this.refreshInterval);
|
||||
};
|
||||
|
||||
/**
|
||||
* Callback used when fetch is successful.
|
||||
* It will update the displayed data and stop the refresh animation
|
||||
*
|
||||
* @param fetchedData The newly fetched data
|
||||
*/
|
||||
onFetchSuccess = (fetchedData: ApiGenericDataType) => {
|
||||
this.setState({
|
||||
fetchedData,
|
||||
refreshing: false,
|
||||
});
|
||||
this.lastRefresh = new Date();
|
||||
};
|
||||
|
||||
/**
|
||||
* Callback used when fetch encountered an error.
|
||||
* It will reset the displayed data and show an error.
|
||||
*/
|
||||
onFetchError = () => {
|
||||
this.setState({
|
||||
fetchedData: null,
|
||||
refreshing: false,
|
||||
});
|
||||
this.showSnackBar();
|
||||
};
|
||||
|
||||
/**
|
||||
* Refreshes data and shows an animations while doing it
|
||||
*/
|
||||
onRefresh = () => {
|
||||
const {fetchUrl} = this.props;
|
||||
let canRefresh;
|
||||
if (this.lastRefresh != null) {
|
||||
const last = this.lastRefresh;
|
||||
canRefresh = new Date().getTime() - last.getTime() > MIN_REFRESH_TIME;
|
||||
} else canRefresh = true;
|
||||
if (canRefresh) {
|
||||
this.setState({refreshing: true});
|
||||
readData(fetchUrl).then(this.onFetchSuccess).catch(this.onFetchError);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Shows the error popup
|
||||
*/
|
||||
showSnackBar = () => {
|
||||
this.setState({snackbarVisible: true});
|
||||
};
|
||||
|
||||
/**
|
||||
* Hides the error popup
|
||||
*/
|
||||
hideSnackBar = () => {
|
||||
this.setState({snackbarVisible: false});
|
||||
};
|
||||
|
||||
getItemLayout = (
|
||||
data: T,
|
||||
index: number,
|
||||
): {length: number, offset: number, index: number} | null => {
|
||||
const {itemHeight} = this.props;
|
||||
if (itemHeight == null) return null;
|
||||
return {
|
||||
length: itemHeight,
|
||||
offset: itemHeight * index,
|
||||
index,
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* Registers react navigation events on first screen load.
|
||||
* Allows to detect when the screen is focused
|
||||
*/
|
||||
componentDidMount() {
|
||||
this.props.navigation.addListener('focus', this.onScreenFocus);
|
||||
this.props.navigation.addListener('blur', this.onScreenBlur);
|
||||
this.lastRefresh = null;
|
||||
this.onRefresh();
|
||||
getRenderSectionHeader = (data: {section: {title: string}}): React.Node => {
|
||||
const {renderSectionHeader} = this.props;
|
||||
const {refreshing} = this.state;
|
||||
if (renderSectionHeader != null) {
|
||||
return (
|
||||
<Animatable.View animation="fadeInUp" duration={500} useNativeDriver>
|
||||
{renderSectionHeader(data, refreshing)}
|
||||
</Animatable.View>
|
||||
);
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Refreshes data when focusing the screen and setup a refresh interval if asked to
|
||||
*/
|
||||
onScreenFocus = () => {
|
||||
if (this.props.refreshOnFocus && this.lastRefresh)
|
||||
this.onRefresh();
|
||||
if (this.props.autoRefreshTime > 0)
|
||||
this.refreshInterval = setInterval(this.onRefresh, this.props.autoRefreshTime)
|
||||
}
|
||||
getRenderItem = (data: {item: T}): React.Node => {
|
||||
const {renderItem} = this.props;
|
||||
return (
|
||||
<Animatable.View animation="fadeInUp" duration={500} useNativeDriver>
|
||||
{renderItem(data)}
|
||||
</Animatable.View>
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Removes any interval on un-focus
|
||||
*/
|
||||
onScreenBlur = () => {
|
||||
clearInterval(this.refreshInterval);
|
||||
}
|
||||
onScroll = (event: SyntheticEvent<EventTarget>) => {
|
||||
const {onScroll} = this.props;
|
||||
if (onScroll != null) onScroll(event);
|
||||
};
|
||||
|
||||
render(): React.Node {
|
||||
const {props, state} = this;
|
||||
let dataset = [];
|
||||
if (
|
||||
state.fetchedData != null ||
|
||||
(state.fetchedData == null && !props.showError)
|
||||
)
|
||||
dataset = props.createDataset(state.fetchedData, state.refreshing);
|
||||
|
||||
/**
|
||||
* Callback used when fetch is successful.
|
||||
* It will update the displayed data and stop the refresh animation
|
||||
*
|
||||
* @param fetchedData The newly fetched data
|
||||
*/
|
||||
onFetchSuccess = (fetchedData: { [key: string]: any }) => {
|
||||
this.setState({
|
||||
fetchedData: fetchedData,
|
||||
refreshing: false,
|
||||
firstLoading: false
|
||||
});
|
||||
this.lastRefresh = new Date();
|
||||
};
|
||||
|
||||
/**
|
||||
* Callback used when fetch encountered an error.
|
||||
* It will reset the displayed data and show an error.
|
||||
*/
|
||||
onFetchError = () => {
|
||||
this.setState({
|
||||
fetchedData: null,
|
||||
refreshing: false,
|
||||
firstLoading: false
|
||||
});
|
||||
this.showSnackBar();
|
||||
};
|
||||
|
||||
/**
|
||||
* Refreshes data and shows an animations while doing it
|
||||
*/
|
||||
onRefresh = () => {
|
||||
let canRefresh;
|
||||
if (this.lastRefresh != null) {
|
||||
const last = this.lastRefresh;
|
||||
canRefresh = (new Date().getTime() - last.getTime()) > MIN_REFRESH_TIME;
|
||||
} else
|
||||
canRefresh = true;
|
||||
if (canRefresh) {
|
||||
this.setState({refreshing: true});
|
||||
readData(this.props.fetchUrl)
|
||||
.then(this.onFetchSuccess)
|
||||
.catch(this.onFetchError);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Shows the error popup
|
||||
*/
|
||||
showSnackBar = () => this.setState({snackbarVisible: true});
|
||||
|
||||
/**
|
||||
* Hides the error popup
|
||||
*/
|
||||
hideSnackBar = () => this.setState({snackbarVisible: false});
|
||||
|
||||
itemLayout = (data: { [key: string]: any }, index: number) => {
|
||||
const height = this.props.itemHeight;
|
||||
if (height == null)
|
||||
return undefined;
|
||||
return {
|
||||
length: height,
|
||||
offset: height * index,
|
||||
index
|
||||
}
|
||||
};
|
||||
|
||||
renderSectionHeader = (data: { section: { [key: string]: any } }) => {
|
||||
if (this.props.renderSectionHeader != null) {
|
||||
return (
|
||||
<Animatable.View
|
||||
animation={"fadeInUp"}
|
||||
duration={500}
|
||||
useNativeDriver
|
||||
>
|
||||
{this.props.renderSectionHeader(data, this.state.refreshing)}
|
||||
</Animatable.View>
|
||||
);
|
||||
} else
|
||||
return null;
|
||||
}
|
||||
|
||||
renderItem = (data: {
|
||||
item: { [key: string]: any },
|
||||
index: number,
|
||||
section: { [key: string]: any },
|
||||
separators: { [key: string]: any },
|
||||
}) => {
|
||||
return (
|
||||
<Animatable.View
|
||||
animation={"fadeInUp"}
|
||||
duration={500}
|
||||
useNativeDriver
|
||||
>
|
||||
{this.props.renderItem(data)}
|
||||
</Animatable.View>
|
||||
);
|
||||
}
|
||||
|
||||
onScroll = (event: SyntheticEvent<EventTarget>) => {
|
||||
if (this.props.onScroll)
|
||||
this.props.onScroll(event);
|
||||
}
|
||||
|
||||
render() {
|
||||
let dataset = [];
|
||||
if (this.state.fetchedData != null || (this.state.fetchedData == null && !this.props.showError)) {
|
||||
dataset = this.props.createDataset(this.state.fetchedData, this.state.refreshing);
|
||||
}
|
||||
const {containerPaddingTop} = this.props.collapsibleStack;
|
||||
return (
|
||||
<View>
|
||||
<CollapsibleSectionList
|
||||
sections={dataset}
|
||||
extraData={this.props.updateData}
|
||||
refreshControl={
|
||||
<RefreshControl
|
||||
progressViewOffset={containerPaddingTop}
|
||||
refreshing={this.state.refreshing}
|
||||
onRefresh={this.onRefresh}
|
||||
/>
|
||||
}
|
||||
renderSectionHeader={this.renderSectionHeader}
|
||||
renderItem={this.renderItem}
|
||||
stickySectionHeadersEnabled={this.props.stickyHeader}
|
||||
style={{minHeight: '100%'}}
|
||||
ListHeaderComponent={this.props.renderListHeaderComponent != null
|
||||
? this.props.renderListHeaderComponent(this.state.fetchedData)
|
||||
: null}
|
||||
ListEmptyComponent={this.state.refreshing
|
||||
? <BasicLoadingScreen/>
|
||||
: <ErrorView
|
||||
{...this.props}
|
||||
errorCode={ERROR_TYPE.CONNECTION_ERROR}
|
||||
onRefresh={this.onRefresh}/>
|
||||
}
|
||||
getItemLayout={this.props.itemHeight != null ? this.itemLayout : undefined}
|
||||
onScroll={this.onScroll}
|
||||
hasTab={true}
|
||||
/>
|
||||
<Snackbar
|
||||
visible={this.state.snackbarVisible}
|
||||
onDismiss={this.hideSnackBar}
|
||||
action={{
|
||||
label: 'OK',
|
||||
onPress: () => {
|
||||
},
|
||||
}}
|
||||
duration={4000}
|
||||
style={{
|
||||
bottom: CustomTabBar.TAB_BAR_HEIGHT
|
||||
}}
|
||||
>
|
||||
{i18n.t("general.listUpdateFail")}
|
||||
</Snackbar>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
const {containerPaddingTop} = props.collapsibleStack;
|
||||
return (
|
||||
<View>
|
||||
<CollapsibleSectionList
|
||||
sections={dataset}
|
||||
extraData={props.updateData}
|
||||
refreshControl={
|
||||
<RefreshControl
|
||||
progressViewOffset={containerPaddingTop}
|
||||
refreshing={state.refreshing}
|
||||
onRefresh={this.onRefresh}
|
||||
/>
|
||||
}
|
||||
renderSectionHeader={this.getRenderSectionHeader}
|
||||
renderItem={this.getRenderItem}
|
||||
stickySectionHeadersEnabled={props.stickyHeader}
|
||||
style={{minHeight: '100%'}}
|
||||
ListHeaderComponent={
|
||||
props.renderListHeaderComponent != null
|
||||
? props.renderListHeaderComponent(state.fetchedData)
|
||||
: null
|
||||
}
|
||||
ListEmptyComponent={
|
||||
state.refreshing ? (
|
||||
<BasicLoadingScreen />
|
||||
) : (
|
||||
<ErrorView
|
||||
navigation={props.navigation}
|
||||
errorCode={ERROR_TYPE.CONNECTION_ERROR}
|
||||
onRefresh={this.onRefresh}
|
||||
/>
|
||||
)
|
||||
}
|
||||
getItemLayout={props.itemHeight != null ? this.getItemLayout : null}
|
||||
onScroll={this.onScroll}
|
||||
hasTab
|
||||
/>
|
||||
<Snackbar
|
||||
visible={state.snackbarVisible}
|
||||
onDismiss={this.hideSnackBar}
|
||||
action={{
|
||||
label: 'OK',
|
||||
onPress: () => {},
|
||||
}}
|
||||
duration={4000}
|
||||
style={{
|
||||
bottom: CustomTabBar.TAB_BAR_HEIGHT,
|
||||
}}>
|
||||
{i18n.t('general.listUpdateFail')}
|
||||
</Snackbar>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default withCollapsible(WebSectionList);
|
||||
|
|
|
|||
|
|
@ -1,233 +1,247 @@
|
|||
// @flow
|
||||
|
||||
import * as React from 'react';
|
||||
import WebView from "react-native-webview";
|
||||
import BasicLoadingScreen from "./BasicLoadingScreen";
|
||||
import ErrorView from "./ErrorView";
|
||||
import {ERROR_TYPE} from "../../utils/WebData";
|
||||
import MaterialHeaderButtons, {Item} from '../Overrides/CustomHeaderButton';
|
||||
import {Divider, HiddenItem, OverflowMenu} from "react-navigation-header-buttons";
|
||||
import WebView from 'react-native-webview';
|
||||
import {
|
||||
Divider,
|
||||
HiddenItem,
|
||||
OverflowMenu,
|
||||
} from 'react-navigation-header-buttons';
|
||||
import i18n from 'i18n-js';
|
||||
import {Animated, BackHandler, Linking} from "react-native";
|
||||
import {withCollapsible} from "../../utils/withCollapsible";
|
||||
import MaterialCommunityIcons from "react-native-vector-icons/MaterialCommunityIcons";
|
||||
import {withTheme} from "react-native-paper";
|
||||
import type {CustomTheme} from "../../managers/ThemeManager";
|
||||
import {StackNavigationProp} from "@react-navigation/stack";
|
||||
import {Collapsible} from "react-navigation-collapsible";
|
||||
import {Animated, BackHandler, Linking} from 'react-native';
|
||||
import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons';
|
||||
import {withTheme} from 'react-native-paper';
|
||||
import {StackNavigationProp} from '@react-navigation/stack';
|
||||
import {Collapsible} from 'react-navigation-collapsible';
|
||||
import type {CustomThemeType} from '../../managers/ThemeManager';
|
||||
import withCollapsible from '../../utils/withCollapsible';
|
||||
import MaterialHeaderButtons, {Item} from '../Overrides/CustomHeaderButton';
|
||||
import {ERROR_TYPE} from '../../utils/WebData';
|
||||
import ErrorView from './ErrorView';
|
||||
import BasicLoadingScreen from './BasicLoadingScreen';
|
||||
|
||||
type Props = {
|
||||
navigation: StackNavigationProp,
|
||||
theme: CustomTheme,
|
||||
url: string,
|
||||
customJS: string,
|
||||
customPaddingFunction: null | (padding: number) => string,
|
||||
collapsibleStack: Collapsible,
|
||||
onMessage: Function,
|
||||
onScroll: Function,
|
||||
showAdvancedControls: boolean,
|
||||
}
|
||||
type PropsType = {
|
||||
navigation: StackNavigationProp,
|
||||
theme: CustomThemeType,
|
||||
url: string,
|
||||
collapsibleStack: Collapsible,
|
||||
onMessage: (event: {nativeEvent: {data: string}}) => void,
|
||||
onScroll: (event: SyntheticEvent<EventTarget>) => void,
|
||||
customJS?: string,
|
||||
customPaddingFunction?: null | ((padding: number) => string),
|
||||
showAdvancedControls?: boolean,
|
||||
};
|
||||
|
||||
const AnimatedWebView = Animated.createAnimatedComponent(WebView);
|
||||
|
||||
/**
|
||||
* Class defining a webview screen.
|
||||
*/
|
||||
class WebViewScreen extends React.PureComponent<Props> {
|
||||
class WebViewScreen extends React.PureComponent<PropsType> {
|
||||
static defaultProps = {
|
||||
customJS: '',
|
||||
showAdvancedControls: true,
|
||||
customPaddingFunction: null,
|
||||
};
|
||||
|
||||
static defaultProps = {
|
||||
customJS: '',
|
||||
showAdvancedControls: true,
|
||||
customPaddingFunction: null,
|
||||
};
|
||||
webviewRef: {current: null | WebView};
|
||||
|
||||
webviewRef: { current: null | WebView };
|
||||
canGoBack: boolean;
|
||||
|
||||
canGoBack: boolean;
|
||||
constructor() {
|
||||
super();
|
||||
this.webviewRef = React.createRef();
|
||||
this.canGoBack = false;
|
||||
}
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
this.webviewRef = React.createRef();
|
||||
this.canGoBack = false;
|
||||
/**
|
||||
* Creates header buttons and listens to events after mounting
|
||||
*/
|
||||
componentDidMount() {
|
||||
const {props} = this;
|
||||
props.navigation.setOptions({
|
||||
headerRight: props.showAdvancedControls
|
||||
? this.getAdvancedButtons
|
||||
: this.getBasicButton,
|
||||
});
|
||||
props.navigation.addListener('focus', () => {
|
||||
BackHandler.addEventListener(
|
||||
'hardwareBackPress',
|
||||
this.onBackButtonPressAndroid,
|
||||
);
|
||||
});
|
||||
props.navigation.addListener('blur', () => {
|
||||
BackHandler.removeEventListener(
|
||||
'hardwareBackPress',
|
||||
this.onBackButtonPressAndroid,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Goes back on the webview or on the navigation stack if we cannot go back anymore
|
||||
*
|
||||
* @returns {boolean}
|
||||
*/
|
||||
onBackButtonPressAndroid = (): boolean => {
|
||||
if (this.canGoBack) {
|
||||
this.onGoBackClicked();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
/**
|
||||
* Creates header buttons and listens to events after mounting
|
||||
*/
|
||||
componentDidMount() {
|
||||
this.props.navigation.setOptions({
|
||||
headerRight: this.props.showAdvancedControls
|
||||
? this.getAdvancedButtons
|
||||
: this.getBasicButton,
|
||||
});
|
||||
this.props.navigation.addListener(
|
||||
'focus',
|
||||
() =>
|
||||
BackHandler.addEventListener(
|
||||
'hardwareBackPress',
|
||||
this.onBackButtonPressAndroid
|
||||
)
|
||||
);
|
||||
this.props.navigation.addListener(
|
||||
'blur',
|
||||
() =>
|
||||
BackHandler.removeEventListener(
|
||||
'hardwareBackPress',
|
||||
this.onBackButtonPressAndroid
|
||||
)
|
||||
);
|
||||
}
|
||||
/**
|
||||
* Gets header refresh and open in browser buttons
|
||||
*
|
||||
* @return {*}
|
||||
*/
|
||||
getBasicButton = (): React.Node => {
|
||||
return (
|
||||
<MaterialHeaderButtons>
|
||||
<Item
|
||||
title="refresh"
|
||||
iconName="refresh"
|
||||
onPress={this.onRefreshClicked}
|
||||
/>
|
||||
<Item
|
||||
title={i18n.t('general.openInBrowser')}
|
||||
iconName="open-in-new"
|
||||
onPress={this.onOpenClicked}
|
||||
/>
|
||||
</MaterialHeaderButtons>
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Goes back on the webview or on the navigation stack if we cannot go back anymore
|
||||
*
|
||||
* @returns {boolean}
|
||||
*/
|
||||
onBackButtonPressAndroid = () => {
|
||||
if (this.canGoBack) {
|
||||
this.onGoBackClicked();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
/**
|
||||
* Gets header refresh and open in browser buttons
|
||||
*
|
||||
* @return {*}
|
||||
*/
|
||||
getBasicButton = () => {
|
||||
return (
|
||||
<MaterialHeaderButtons>
|
||||
<Item
|
||||
title="refresh"
|
||||
iconName="refresh"
|
||||
onPress={this.onRefreshClicked}/>
|
||||
<Item
|
||||
title={i18n.t("general.openInBrowser")}
|
||||
iconName="open-in-new"
|
||||
onPress={this.onOpenClicked}/>
|
||||
</MaterialHeaderButtons>
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Creates advanced header control buttons.
|
||||
* These buttons allows the user to refresh, go back, go forward and open in the browser.
|
||||
*
|
||||
* @returns {*}
|
||||
*/
|
||||
getAdvancedButtons = () => {
|
||||
return (
|
||||
<MaterialHeaderButtons>
|
||||
<Item
|
||||
title="refresh"
|
||||
iconName="refresh"
|
||||
onPress={this.onRefreshClicked}
|
||||
/>
|
||||
<OverflowMenu
|
||||
style={{marginHorizontal: 10}}
|
||||
OverflowIcon={
|
||||
<MaterialCommunityIcons
|
||||
name="dots-vertical"
|
||||
size={26}
|
||||
color={this.props.theme.colors.text}
|
||||
/>}
|
||||
>
|
||||
<HiddenItem
|
||||
title={i18n.t("general.goBack")}
|
||||
onPress={this.onGoBackClicked}/>
|
||||
<HiddenItem
|
||||
title={i18n.t("general.goForward")}
|
||||
onPress={this.onGoForwardClicked}/>
|
||||
<Divider/>
|
||||
<HiddenItem
|
||||
title={i18n.t("general.openInBrowser")}
|
||||
onPress={this.onOpenClicked}/>
|
||||
</OverflowMenu>
|
||||
</MaterialHeaderButtons>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Callback to use when refresh button is clicked. Reloads the webview.
|
||||
*/
|
||||
onRefreshClicked = () => {
|
||||
if (this.webviewRef.current != null)
|
||||
this.webviewRef.current.reload();
|
||||
}
|
||||
onGoBackClicked = () => {
|
||||
if (this.webviewRef.current != null)
|
||||
this.webviewRef.current.goBack();
|
||||
}
|
||||
onGoForwardClicked = () => {
|
||||
if (this.webviewRef.current != null)
|
||||
this.webviewRef.current.goForward();
|
||||
}
|
||||
onOpenClicked = () => Linking.openURL(this.props.url);
|
||||
|
||||
/**
|
||||
* Injects the given javascript string into the web page
|
||||
*
|
||||
* @param script The script to inject
|
||||
*/
|
||||
injectJavaScript = (script: string) => {
|
||||
if (this.webviewRef.current != null)
|
||||
this.webviewRef.current.injectJavaScript(script);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the loading indicator
|
||||
*
|
||||
* @return {*}
|
||||
*/
|
||||
getRenderLoading = () => <BasicLoadingScreen isAbsolute={true}/>;
|
||||
|
||||
/**
|
||||
* Gets the javascript needed to generate a padding on top of the page
|
||||
* This adds padding to the body and runs the custom padding function given in props
|
||||
*
|
||||
* @param padding The padding to add in pixels
|
||||
* @returns {string}
|
||||
*/
|
||||
getJavascriptPadding(padding: number) {
|
||||
const customPadding = this.props.customPaddingFunction != null ? this.props.customPaddingFunction(padding) : "";
|
||||
return (
|
||||
"document.getElementsByTagName('body')[0].style.paddingTop = '" + padding + "px';" +
|
||||
customPadding +
|
||||
"true;"
|
||||
);
|
||||
}
|
||||
|
||||
onScroll = (event: Object) => {
|
||||
if (this.props.onScroll)
|
||||
this.props.onScroll(event);
|
||||
}
|
||||
|
||||
render() {
|
||||
const {containerPaddingTop, onScrollWithListener} = this.props.collapsibleStack;
|
||||
return (
|
||||
<AnimatedWebView
|
||||
ref={this.webviewRef}
|
||||
source={{uri: this.props.url}}
|
||||
startInLoadingState={true}
|
||||
injectedJavaScript={this.props.customJS}
|
||||
javaScriptEnabled={true}
|
||||
renderLoading={this.getRenderLoading}
|
||||
renderError={() => <ErrorView
|
||||
errorCode={ERROR_TYPE.CONNECTION_ERROR}
|
||||
onRefresh={this.onRefreshClicked}
|
||||
/>}
|
||||
onNavigationStateChange={navState => {
|
||||
this.canGoBack = navState.canGoBack;
|
||||
}}
|
||||
onMessage={this.props.onMessage}
|
||||
onLoad={() => this.injectJavaScript(this.getJavascriptPadding(containerPaddingTop))}
|
||||
// Animations
|
||||
onScroll={onScrollWithListener(this.onScroll)}
|
||||
/**
|
||||
* Creates advanced header control buttons.
|
||||
* These buttons allows the user to refresh, go back, go forward and open in the browser.
|
||||
*
|
||||
* @returns {*}
|
||||
*/
|
||||
getAdvancedButtons = (): React.Node => {
|
||||
const {props} = this;
|
||||
return (
|
||||
<MaterialHeaderButtons>
|
||||
<Item
|
||||
title="refresh"
|
||||
iconName="refresh"
|
||||
onPress={this.onRefreshClicked}
|
||||
/>
|
||||
<OverflowMenu
|
||||
style={{marginHorizontal: 10}}
|
||||
OverflowIcon={
|
||||
<MaterialCommunityIcons
|
||||
name="dots-vertical"
|
||||
size={26}
|
||||
color={props.theme.colors.text}
|
||||
/>
|
||||
);
|
||||
}
|
||||
}>
|
||||
<HiddenItem
|
||||
title={i18n.t('general.goBack')}
|
||||
onPress={this.onGoBackClicked}
|
||||
/>
|
||||
<HiddenItem
|
||||
title={i18n.t('general.goForward')}
|
||||
onPress={this.onGoForwardClicked}
|
||||
/>
|
||||
<Divider />
|
||||
<HiddenItem
|
||||
title={i18n.t('general.openInBrowser')}
|
||||
onPress={this.onOpenClicked}
|
||||
/>
|
||||
</OverflowMenu>
|
||||
</MaterialHeaderButtons>
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Gets the loading indicator
|
||||
*
|
||||
* @return {*}
|
||||
*/
|
||||
getRenderLoading = (): React.Node => <BasicLoadingScreen isAbsolute />;
|
||||
|
||||
/**
|
||||
* Gets the javascript needed to generate a padding on top of the page
|
||||
* This adds padding to the body and runs the custom padding function given in props
|
||||
*
|
||||
* @param padding The padding to add in pixels
|
||||
* @returns {string}
|
||||
*/
|
||||
getJavascriptPadding(padding: number): string {
|
||||
const {props} = this;
|
||||
const customPadding =
|
||||
props.customPaddingFunction != null
|
||||
? props.customPaddingFunction(padding)
|
||||
: '';
|
||||
return `document.getElementsByTagName('body')[0].style.paddingTop = '${padding}px';${customPadding}true;`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Callback to use when refresh button is clicked. Reloads the webview.
|
||||
*/
|
||||
onRefreshClicked = () => {
|
||||
if (this.webviewRef.current != null) this.webviewRef.current.reload();
|
||||
};
|
||||
|
||||
onGoBackClicked = () => {
|
||||
if (this.webviewRef.current != null) this.webviewRef.current.goBack();
|
||||
};
|
||||
|
||||
onGoForwardClicked = () => {
|
||||
if (this.webviewRef.current != null) this.webviewRef.current.goForward();
|
||||
};
|
||||
|
||||
onOpenClicked = () => {
|
||||
const {url} = this.props;
|
||||
Linking.openURL(url);
|
||||
};
|
||||
|
||||
onScroll = (event: SyntheticEvent<EventTarget>) => {
|
||||
const {onScroll} = this.props;
|
||||
if (onScroll) onScroll(event);
|
||||
};
|
||||
|
||||
/**
|
||||
* Injects the given javascript string into the web page
|
||||
*
|
||||
* @param script The script to inject
|
||||
*/
|
||||
injectJavaScript = (script: string) => {
|
||||
if (this.webviewRef.current != null)
|
||||
this.webviewRef.current.injectJavaScript(script);
|
||||
};
|
||||
|
||||
render(): React.Node {
|
||||
const {props} = this;
|
||||
const {containerPaddingTop, onScrollWithListener} = props.collapsibleStack;
|
||||
return (
|
||||
<AnimatedWebView
|
||||
ref={this.webviewRef}
|
||||
source={{uri: props.url}}
|
||||
startInLoadingState
|
||||
injectedJavaScript={props.customJS}
|
||||
javaScriptEnabled
|
||||
renderLoading={this.getRenderLoading}
|
||||
renderError={(): React.Node => (
|
||||
<ErrorView
|
||||
errorCode={ERROR_TYPE.CONNECTION_ERROR}
|
||||
onRefresh={this.onRefreshClicked}
|
||||
/>
|
||||
)}
|
||||
onNavigationStateChange={(navState: {canGoBack: boolean}) => {
|
||||
this.canGoBack = navState.canGoBack;
|
||||
}}
|
||||
onMessage={props.onMessage}
|
||||
onLoad={() => {
|
||||
this.injectJavaScript(this.getJavascriptPadding(containerPaddingTop));
|
||||
}}
|
||||
// Animations
|
||||
onScroll={onScrollWithListener(this.onScroll)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default withCollapsible(withTheme(WebViewScreen));
|
||||
|
|
|
|||
|
|
@ -1,180 +1,217 @@
|
|||
// @flow
|
||||
|
||||
import * as React from 'react';
|
||||
import {withTheme} from 'react-native-paper';
|
||||
import TabIcon from "./TabIcon";
|
||||
import TabHomeIcon from "./TabHomeIcon";
|
||||
import {Animated} from 'react-native';
|
||||
import {Collapsible} from "react-navigation-collapsible";
|
||||
import {withTheme} from 'react-native-paper';
|
||||
import {Collapsible} from 'react-navigation-collapsible';
|
||||
import {StackNavigationProp} from '@react-navigation/stack';
|
||||
import TabIcon from './TabIcon';
|
||||
import TabHomeIcon from './TabHomeIcon';
|
||||
import type {CustomThemeType} from '../../managers/ThemeManager';
|
||||
|
||||
type Props = {
|
||||
state: Object,
|
||||
descriptors: Object,
|
||||
navigation: Object,
|
||||
theme: Object,
|
||||
collapsibleStack: Object,
|
||||
}
|
||||
|
||||
type State = {
|
||||
translateY: AnimatedValue,
|
||||
barSynced: boolean,
|
||||
}
|
||||
|
||||
const TAB_ICONS = {
|
||||
proxiwash: 'tshirt-crew',
|
||||
services: 'account-circle',
|
||||
planning: 'calendar-range',
|
||||
planex: 'clock',
|
||||
type RouteType = {
|
||||
name: string,
|
||||
key: string,
|
||||
params: {collapsible: Collapsible},
|
||||
state: {
|
||||
index: number,
|
||||
routes: Array<RouteType>,
|
||||
},
|
||||
};
|
||||
|
||||
class CustomTabBar extends React.Component<Props, State> {
|
||||
type PropsType = {
|
||||
state: {
|
||||
index: number,
|
||||
routes: Array<RouteType>,
|
||||
},
|
||||
descriptors: {
|
||||
[key: string]: {
|
||||
options: {
|
||||
tabBarLabel: string,
|
||||
title: string,
|
||||
},
|
||||
},
|
||||
},
|
||||
navigation: StackNavigationProp,
|
||||
theme: CustomThemeType,
|
||||
};
|
||||
|
||||
static TAB_BAR_HEIGHT = 48;
|
||||
type StateType = {
|
||||
// eslint-disable-next-line flowtype/no-weak-types
|
||||
translateY: any,
|
||||
};
|
||||
|
||||
state = {
|
||||
translateY: new Animated.Value(0),
|
||||
}
|
||||
const TAB_ICONS = {
|
||||
proxiwash: 'tshirt-crew',
|
||||
services: 'account-circle',
|
||||
planning: 'calendar-range',
|
||||
planex: 'clock',
|
||||
};
|
||||
|
||||
syncTabBar = (route, index) => {
|
||||
const state = this.props.state;
|
||||
const isFocused = state.index === index;
|
||||
if (isFocused) {
|
||||
const stackState = route.state;
|
||||
const stackRoute = stackState ? stackState.routes[stackState.index] : undefined;
|
||||
const params: { collapsible: Collapsible } = stackRoute ? stackRoute.params : undefined;
|
||||
const collapsible = params ? params.collapsible : undefined;
|
||||
if (collapsible) {
|
||||
this.setState({
|
||||
translateY: Animated.multiply(-1.5, collapsible.translateY), // Hide tab bar faster than header bar
|
||||
});
|
||||
}
|
||||
}
|
||||
class CustomTabBar extends React.Component<PropsType, StateType> {
|
||||
static TAB_BAR_HEIGHT = 48;
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
this.state = {
|
||||
translateY: new Animated.Value(0),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Navigates to the given route if it is different from the current one
|
||||
*
|
||||
* @param route Destination route
|
||||
* @param currentIndex The current route index
|
||||
* @param destIndex The destination route index
|
||||
*/
|
||||
onItemPress(route: Object, currentIndex: number, destIndex: number) {
|
||||
const event = this.props.navigation.emit({
|
||||
type: 'tabPress',
|
||||
target: route.key,
|
||||
canPreventDefault: true,
|
||||
/**
|
||||
* Navigates to the given route if it is different from the current one
|
||||
*
|
||||
* @param route Destination route
|
||||
* @param currentIndex The current route index
|
||||
* @param destIndex The destination route index
|
||||
*/
|
||||
onItemPress(route: RouteType, currentIndex: number, destIndex: number) {
|
||||
const {navigation} = this.props;
|
||||
const event = navigation.emit({
|
||||
type: 'tabPress',
|
||||
target: route.key,
|
||||
canPreventDefault: true,
|
||||
});
|
||||
if (currentIndex !== destIndex && !event.defaultPrevented)
|
||||
navigation.navigate(route.name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Navigates to tetris screen on home button long press
|
||||
*
|
||||
* @param route
|
||||
*/
|
||||
onItemLongPress(route: RouteType) {
|
||||
const {navigation} = this.props;
|
||||
const event = navigation.emit({
|
||||
type: 'tabLongPress',
|
||||
target: route.key,
|
||||
canPreventDefault: true,
|
||||
});
|
||||
if (route.name === 'home' && !event.defaultPrevented)
|
||||
navigation.navigate('game-start');
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds the active route and syncs the tab bar animation with the header bar
|
||||
*/
|
||||
onRouteChange = () => {
|
||||
const {props} = this;
|
||||
props.state.routes.map(this.syncTabBar);
|
||||
};
|
||||
|
||||
/**
|
||||
* Gets an icon for the given route if it is not the home one as it uses a custom button
|
||||
*
|
||||
* @param route
|
||||
* @param focused
|
||||
* @returns {null}
|
||||
*/
|
||||
getTabBarIcon = (route: RouteType, focused: boolean): React.Node => {
|
||||
let icon = TAB_ICONS[route.name];
|
||||
icon = focused ? icon : `${icon}-outline`;
|
||||
if (route.name !== 'home') return icon;
|
||||
return null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Gets a tab icon render.
|
||||
* If the given route is focused, it syncs the tab bar and header bar animations together
|
||||
*
|
||||
* @param route The route for the icon
|
||||
* @param index The index of the current route
|
||||
* @returns {*}
|
||||
*/
|
||||
getRenderIcon = (route: RouteType, index: number): React.Node => {
|
||||
const {props} = this;
|
||||
const {state} = props;
|
||||
const {options} = props.descriptors[route.key];
|
||||
let label;
|
||||
if (options.tabBarLabel != null) label = options.tabBarLabel;
|
||||
else if (options.title != null) label = options.title;
|
||||
else label = route.name;
|
||||
|
||||
const onPress = () => {
|
||||
this.onItemPress(route, state.index, index);
|
||||
};
|
||||
const onLongPress = () => {
|
||||
this.onItemLongPress(route);
|
||||
};
|
||||
const isFocused = state.index === index;
|
||||
|
||||
const color = isFocused
|
||||
? props.theme.colors.primary
|
||||
: props.theme.colors.tabIcon;
|
||||
if (route.name !== 'home') {
|
||||
return (
|
||||
<TabIcon
|
||||
onPress={onPress}
|
||||
onLongPress={onLongPress}
|
||||
icon={this.getTabBarIcon(route, isFocused)}
|
||||
color={color}
|
||||
label={label}
|
||||
focused={isFocused}
|
||||
extraData={state.index > index}
|
||||
key={route.key}
|
||||
/>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<TabHomeIcon
|
||||
onPress={onPress}
|
||||
onLongPress={onLongPress}
|
||||
focused={isFocused}
|
||||
key={route.key}
|
||||
tabBarHeight={CustomTabBar.TAB_BAR_HEIGHT}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
getIcons(): React.Node {
|
||||
const {props} = this;
|
||||
return props.state.routes.map(this.getRenderIcon);
|
||||
}
|
||||
|
||||
syncTabBar = (route: RouteType, index: number) => {
|
||||
const {state} = this.props;
|
||||
const isFocused = state.index === index;
|
||||
if (isFocused) {
|
||||
const stackState = route.state;
|
||||
const stackRoute =
|
||||
stackState != null ? stackState.routes[stackState.index] : null;
|
||||
const params: {collapsible: Collapsible} | null =
|
||||
stackRoute != null ? stackRoute.params : null;
|
||||
const collapsible = params != null ? params.collapsible : null;
|
||||
if (collapsible != null) {
|
||||
this.setState({
|
||||
translateY: Animated.multiply(-1.5, collapsible.translateY), // Hide tab bar faster than header bar
|
||||
});
|
||||
if (currentIndex !== destIndex && !event.defaultPrevented)
|
||||
this.props.navigation.navigate(route.name);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Navigates to tetris screen on home button long press
|
||||
*
|
||||
* @param route
|
||||
*/
|
||||
onItemLongPress(route: Object) {
|
||||
const event = this.props.navigation.emit({
|
||||
type: 'tabLongPress',
|
||||
target: route.key,
|
||||
canPreventDefault: true,
|
||||
});
|
||||
if (route.name === "home" && !event.defaultPrevented)
|
||||
this.props.navigation.navigate('game-start');
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets an icon for the given route if it is not the home one as it uses a custom button
|
||||
*
|
||||
* @param route
|
||||
* @param focused
|
||||
* @returns {null}
|
||||
*/
|
||||
tabBarIcon = (route, focused) => {
|
||||
let icon = TAB_ICONS[route.name];
|
||||
icon = focused ? icon : icon + ('-outline');
|
||||
if (route.name !== "home")
|
||||
return icon;
|
||||
else
|
||||
return null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Finds the active route and syncs the tab bar animation with the header bar
|
||||
*/
|
||||
onRouteChange = () => {
|
||||
this.props.state.routes.map(this.syncTabBar)
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a tab icon render.
|
||||
* If the given route is focused, it syncs the tab bar and header bar animations together
|
||||
*
|
||||
* @param route The route for the icon
|
||||
* @param index The index of the current route
|
||||
* @returns {*}
|
||||
*/
|
||||
renderIcon = (route, index) => {
|
||||
const state = this.props.state;
|
||||
const {options} = this.props.descriptors[route.key];
|
||||
const label =
|
||||
options.tabBarLabel != null
|
||||
? options.tabBarLabel
|
||||
: options.title != null
|
||||
? options.title
|
||||
: route.name;
|
||||
|
||||
const onPress = () => this.onItemPress(route, state.index, index);
|
||||
const onLongPress = () => this.onItemLongPress(route);
|
||||
const isFocused = state.index === index;
|
||||
|
||||
const color = isFocused ? this.props.theme.colors.primary : this.props.theme.colors.tabIcon;
|
||||
if (route.name !== "home") {
|
||||
return <TabIcon
|
||||
onPress={onPress}
|
||||
onLongPress={onLongPress}
|
||||
icon={this.tabBarIcon(route, isFocused)}
|
||||
color={color}
|
||||
label={label}
|
||||
focused={isFocused}
|
||||
extraData={state.index > index}
|
||||
key={route.key}
|
||||
/>
|
||||
} else
|
||||
return <TabHomeIcon
|
||||
onPress={onPress}
|
||||
onLongPress={onLongPress}
|
||||
focused={isFocused}
|
||||
key={route.key}
|
||||
tabBarHeight={CustomTabBar.TAB_BAR_HEIGHT}
|
||||
/>
|
||||
};
|
||||
|
||||
getIcons() {
|
||||
return this.props.state.routes.map(this.renderIcon);
|
||||
}
|
||||
|
||||
render() {
|
||||
this.props.navigation.addListener('state', this.onRouteChange);
|
||||
const icons = this.getIcons();
|
||||
return (
|
||||
<Animated.View
|
||||
useNativeDriver
|
||||
style={{
|
||||
flexDirection: 'row',
|
||||
height: CustomTabBar.TAB_BAR_HEIGHT,
|
||||
width: '100%',
|
||||
position: 'absolute',
|
||||
bottom: 0,
|
||||
left: 0,
|
||||
backgroundColor: this.props.theme.colors.surface,
|
||||
transform: [{translateY: this.state.translateY}],
|
||||
}}
|
||||
>
|
||||
{icons}
|
||||
</Animated.View>
|
||||
);
|
||||
}
|
||||
render(): React.Node {
|
||||
const {props, state} = this;
|
||||
props.navigation.addListener('state', this.onRouteChange);
|
||||
const icons = this.getIcons();
|
||||
return (
|
||||
// $FlowFixMe
|
||||
<Animated.View
|
||||
useNativeDriver
|
||||
style={{
|
||||
flexDirection: 'row',
|
||||
height: CustomTabBar.TAB_BAR_HEIGHT,
|
||||
width: '100%',
|
||||
position: 'absolute',
|
||||
bottom: 0,
|
||||
left: 0,
|
||||
backgroundColor: props.theme.colors.surface,
|
||||
transform: [{translateY: state.translateY}],
|
||||
}}>
|
||||
{icons}
|
||||
</Animated.View>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default withTheme(CustomTabBar);
|
||||
|
|
|
|||
|
|
@ -1,106 +1,133 @@
|
|||
// @flow
|
||||
|
||||
import * as React from 'react';
|
||||
import {Image, Platform, View} from "react-native";
|
||||
import {Image, Platform, View} from 'react-native';
|
||||
import {FAB, TouchableRipple, withTheme} from 'react-native-paper';
|
||||
import * as Animatable from "react-native-animatable";
|
||||
import * as Animatable from 'react-native-animatable';
|
||||
import FOCUSED_ICON from '../../../assets/tab-icon.png';
|
||||
import UNFOCUSED_ICON from '../../../assets/tab-icon-outline.png';
|
||||
import type {CustomThemeType} from '../../managers/ThemeManager';
|
||||
|
||||
type Props = {
|
||||
focused: boolean,
|
||||
onPress: Function,
|
||||
onLongPress: Function,
|
||||
theme: Object,
|
||||
tabBarHeight: number,
|
||||
}
|
||||
type PropsType = {
|
||||
focused: boolean,
|
||||
onPress: () => void,
|
||||
onLongPress: () => void,
|
||||
theme: CustomThemeType,
|
||||
tabBarHeight: number,
|
||||
};
|
||||
|
||||
const AnimatedFAB = Animatable.createAnimatableComponent(FAB);
|
||||
|
||||
/**
|
||||
* Abstraction layer for Agenda component, using custom configuration
|
||||
*/
|
||||
class TabHomeIcon extends React.Component<Props> {
|
||||
class TabHomeIcon extends React.Component<PropsType> {
|
||||
constructor(props: PropsType) {
|
||||
super(props);
|
||||
Animatable.initializeRegistryWithDefinitions({
|
||||
fabFocusIn: {
|
||||
'0': {
|
||||
scale: 1,
|
||||
translateY: 0,
|
||||
},
|
||||
'0.9': {
|
||||
scale: 1.2,
|
||||
translateY: -9,
|
||||
},
|
||||
'1': {
|
||||
scale: 1.1,
|
||||
translateY: -7,
|
||||
},
|
||||
},
|
||||
fabFocusOut: {
|
||||
'0': {
|
||||
scale: 1.1,
|
||||
translateY: -6,
|
||||
},
|
||||
'1': {
|
||||
scale: 1,
|
||||
translateY: 0,
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
focusedIcon = require('../../../assets/tab-icon.png');
|
||||
unFocusedIcon = require('../../../assets/tab-icon-outline.png');
|
||||
shouldComponentUpdate(nextProps: PropsType): boolean {
|
||||
const {focused} = this.props;
|
||||
return nextProps.focused !== focused;
|
||||
}
|
||||
|
||||
constructor(props) {
|
||||
super(props);
|
||||
Animatable.initializeRegistryWithDefinitions({
|
||||
fabFocusIn: {
|
||||
"0": {
|
||||
scale: 1, translateY: 0
|
||||
},
|
||||
"0.9": {
|
||||
scale: 1.2, translateY: -9
|
||||
},
|
||||
"1": {
|
||||
scale: 1.1, translateY: -7
|
||||
},
|
||||
},
|
||||
fabFocusOut: {
|
||||
"0": {
|
||||
scale: 1.1, translateY: -6
|
||||
},
|
||||
"1": {
|
||||
scale: 1, translateY: 0
|
||||
},
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
iconRender = ({size, color}) =>
|
||||
this.props.focused
|
||||
? <Image
|
||||
source={this.focusedIcon}
|
||||
style={{width: size, height: size, tintColor: color}}
|
||||
/>
|
||||
: <Image
|
||||
source={this.unFocusedIcon}
|
||||
style={{width: size, height: size, tintColor: color}}
|
||||
/>;
|
||||
|
||||
shouldComponentUpdate(nextProps: Props): boolean {
|
||||
return (nextProps.focused !== this.props.focused);
|
||||
}
|
||||
|
||||
render(): React$Node {
|
||||
const props = this.props;
|
||||
return (
|
||||
<View
|
||||
style={{
|
||||
flex: 1,
|
||||
justifyContent: 'center',
|
||||
}}>
|
||||
<TouchableRipple
|
||||
onPress={props.onPress}
|
||||
onLongPress={props.onLongPress}
|
||||
borderless={true}
|
||||
rippleColor={Platform.OS === 'android' ? this.props.theme.colors.primary : 'transparent'}
|
||||
style={{
|
||||
position: 'absolute',
|
||||
bottom: 0,
|
||||
left: 0,
|
||||
width: '100%',
|
||||
height: this.props.tabBarHeight + 30,
|
||||
marginBottom: -15,
|
||||
}}
|
||||
>
|
||||
<AnimatedFAB
|
||||
duration={200}
|
||||
easing={"ease-out"}
|
||||
animation={props.focused ? "fabFocusIn" : "fabFocusOut"}
|
||||
icon={this.iconRender}
|
||||
style={{
|
||||
marginTop: 15,
|
||||
marginLeft: 'auto',
|
||||
marginRight: 'auto'
|
||||
}}/>
|
||||
</TouchableRipple>
|
||||
</View>
|
||||
|
||||
);
|
||||
}
|
||||
getIconRender = ({
|
||||
size,
|
||||
color,
|
||||
}: {
|
||||
size: number,
|
||||
color: string,
|
||||
}): React.Node => {
|
||||
const {focused} = this.props;
|
||||
if (focused)
|
||||
return (
|
||||
<Image
|
||||
source={FOCUSED_ICON}
|
||||
style={{
|
||||
width: size,
|
||||
height: size,
|
||||
tintColor: color,
|
||||
}}
|
||||
/>
|
||||
);
|
||||
return (
|
||||
<Image
|
||||
source={UNFOCUSED_ICON}
|
||||
style={{
|
||||
width: size,
|
||||
height: size,
|
||||
tintColor: color,
|
||||
}}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
render(): React.Node {
|
||||
const {props} = this;
|
||||
return (
|
||||
<View
|
||||
style={{
|
||||
flex: 1,
|
||||
justifyContent: 'center',
|
||||
}}>
|
||||
<TouchableRipple
|
||||
onPress={props.onPress}
|
||||
onLongPress={props.onLongPress}
|
||||
borderless
|
||||
rippleColor={
|
||||
Platform.OS === 'android'
|
||||
? props.theme.colors.primary
|
||||
: 'transparent'
|
||||
}
|
||||
style={{
|
||||
position: 'absolute',
|
||||
bottom: 0,
|
||||
left: 0,
|
||||
width: '100%',
|
||||
height: props.tabBarHeight + 30,
|
||||
marginBottom: -15,
|
||||
}}>
|
||||
<AnimatedFAB
|
||||
duration={200}
|
||||
easing="ease-out"
|
||||
animation={props.focused ? 'fabFocusIn' : 'fabFocusOut'}
|
||||
icon={this.getIconRender}
|
||||
style={{
|
||||
marginTop: 15,
|
||||
marginLeft: 'auto',
|
||||
marginRight: 'auto',
|
||||
}}
|
||||
/>
|
||||
</TouchableRipple>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default withTheme(TabHomeIcon);
|
||||
export default withTheme(TabHomeIcon);
|
||||
|
|
|
|||
|
|
@ -1,114 +1,117 @@
|
|||
// @flow
|
||||
|
||||
import * as React from 'react';
|
||||
import {View} from "react-native";
|
||||
import {View} from 'react-native';
|
||||
import {TouchableRipple, withTheme} from 'react-native-paper';
|
||||
import type {MaterialCommunityIconsGlyphs} from "react-native-vector-icons/MaterialCommunityIcons";
|
||||
import MaterialCommunityIcons from "react-native-vector-icons/MaterialCommunityIcons";
|
||||
import * as Animatable from "react-native-animatable";
|
||||
|
||||
type Props = {
|
||||
focused: boolean,
|
||||
color: string,
|
||||
label: string,
|
||||
icon: MaterialCommunityIconsGlyphs,
|
||||
onPress: Function,
|
||||
onLongPress: Function,
|
||||
theme: Object,
|
||||
extraData: any,
|
||||
}
|
||||
import type {MaterialCommunityIconsGlyphs} from 'react-native-vector-icons/MaterialCommunityIcons';
|
||||
import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons';
|
||||
import * as Animatable from 'react-native-animatable';
|
||||
import type {CustomThemeType} from '../../managers/ThemeManager';
|
||||
|
||||
type PropsType = {
|
||||
focused: boolean,
|
||||
color: string,
|
||||
label: string,
|
||||
icon: MaterialCommunityIconsGlyphs,
|
||||
onPress: () => void,
|
||||
onLongPress: () => void,
|
||||
theme: CustomThemeType,
|
||||
extraData: null | boolean | number | string,
|
||||
};
|
||||
|
||||
/**
|
||||
* Abstraction layer for Agenda component, using custom configuration
|
||||
*/
|
||||
class TabIcon extends React.Component<Props> {
|
||||
class TabIcon extends React.Component<PropsType> {
|
||||
firstRender: boolean;
|
||||
|
||||
firstRender: boolean;
|
||||
constructor(props: PropsType) {
|
||||
super(props);
|
||||
Animatable.initializeRegistryWithDefinitions({
|
||||
focusIn: {
|
||||
'0': {
|
||||
scale: 1,
|
||||
translateY: 0,
|
||||
},
|
||||
'0.9': {
|
||||
scale: 1.3,
|
||||
translateY: 7,
|
||||
},
|
||||
'1': {
|
||||
scale: 1.2,
|
||||
translateY: 6,
|
||||
},
|
||||
},
|
||||
focusOut: {
|
||||
'0': {
|
||||
scale: 1.2,
|
||||
translateY: 6,
|
||||
},
|
||||
'1': {
|
||||
scale: 1,
|
||||
translateY: 0,
|
||||
},
|
||||
},
|
||||
});
|
||||
this.firstRender = true;
|
||||
}
|
||||
|
||||
constructor(props) {
|
||||
super(props);
|
||||
Animatable.initializeRegistryWithDefinitions({
|
||||
focusIn: {
|
||||
"0": {
|
||||
scale: 1, translateY: 0
|
||||
},
|
||||
"0.9": {
|
||||
scale: 1.3, translateY: 7
|
||||
},
|
||||
"1": {
|
||||
scale: 1.2, translateY: 6
|
||||
},
|
||||
},
|
||||
focusOut: {
|
||||
"0": {
|
||||
scale: 1.2, translateY: 6
|
||||
},
|
||||
"1": {
|
||||
scale: 1, translateY: 0
|
||||
},
|
||||
}
|
||||
});
|
||||
this.firstRender = true;
|
||||
}
|
||||
componentDidMount() {
|
||||
this.firstRender = false;
|
||||
}
|
||||
|
||||
componentDidMount() {
|
||||
this.firstRender = false;
|
||||
}
|
||||
shouldComponentUpdate(nextProps: PropsType): boolean {
|
||||
const {props} = this;
|
||||
return (
|
||||
nextProps.focused !== props.focused ||
|
||||
nextProps.theme.dark !== props.theme.dark ||
|
||||
nextProps.extraData !== props.extraData
|
||||
);
|
||||
}
|
||||
|
||||
shouldComponentUpdate(nextProps: Props): boolean {
|
||||
return (nextProps.focused !== this.props.focused)
|
||||
|| (nextProps.theme.dark !== this.props.theme.dark)
|
||||
|| (nextProps.extraData !== this.props.extraData);
|
||||
}
|
||||
|
||||
render(): React$Node {
|
||||
const props = this.props;
|
||||
return (
|
||||
<TouchableRipple
|
||||
onPress={props.onPress}
|
||||
onLongPress={props.onLongPress}
|
||||
borderless={true}
|
||||
rippleColor={this.props.theme.colors.primary}
|
||||
style={{
|
||||
flex: 1,
|
||||
justifyContent: 'center',
|
||||
}}
|
||||
>
|
||||
<View>
|
||||
<Animatable.View
|
||||
duration={200}
|
||||
easing={"ease-out"}
|
||||
animation={props.focused ? "focusIn" : "focusOut"}
|
||||
useNativeDriver
|
||||
>
|
||||
<MaterialCommunityIcons
|
||||
name={props.icon}
|
||||
color={props.color}
|
||||
size={26}
|
||||
style={{
|
||||
marginLeft: 'auto',
|
||||
marginRight: 'auto',
|
||||
}}
|
||||
/>
|
||||
</Animatable.View>
|
||||
<Animatable.Text
|
||||
animation={props.focused ? "fadeOutDown" : "fadeIn"}
|
||||
useNativeDriver
|
||||
|
||||
style={{
|
||||
color: props.color,
|
||||
marginLeft: 'auto',
|
||||
marginRight: 'auto',
|
||||
fontSize: 10,
|
||||
}}
|
||||
>
|
||||
{props.label}
|
||||
</Animatable.Text>
|
||||
</View>
|
||||
</TouchableRipple>
|
||||
);
|
||||
}
|
||||
render(): React.Node {
|
||||
const {props} = this;
|
||||
return (
|
||||
<TouchableRipple
|
||||
onPress={props.onPress}
|
||||
onLongPress={props.onLongPress}
|
||||
borderless
|
||||
rippleColor={props.theme.colors.primary}
|
||||
style={{
|
||||
flex: 1,
|
||||
justifyContent: 'center',
|
||||
}}>
|
||||
<View>
|
||||
<Animatable.View
|
||||
duration={200}
|
||||
easing="ease-out"
|
||||
animation={props.focused ? 'focusIn' : 'focusOut'}
|
||||
useNativeDriver>
|
||||
<MaterialCommunityIcons
|
||||
name={props.icon}
|
||||
color={props.color}
|
||||
size={26}
|
||||
style={{
|
||||
marginLeft: 'auto',
|
||||
marginRight: 'auto',
|
||||
}}
|
||||
/>
|
||||
</Animatable.View>
|
||||
<Animatable.Text
|
||||
animation={props.focused ? 'fadeOutDown' : 'fadeIn'}
|
||||
useNativeDriver
|
||||
style={{
|
||||
color: props.color,
|
||||
marginLeft: 'auto',
|
||||
marginRight: 'auto',
|
||||
fontSize: 10,
|
||||
}}>
|
||||
{props.label}
|
||||
</Animatable.Text>
|
||||
</View>
|
||||
</TouchableRipple>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default withTheme(TabIcon);
|
||||
|
|
|
|||
|
|
@ -1,13 +1,13 @@
|
|||
export default {
|
||||
websites: {
|
||||
AMICALE: "https://www.amicale-insat.fr/",
|
||||
AVAILABLE_ROOMS: "http://planex.insa-toulouse.fr/salles.php",
|
||||
BIB: "https://bibbox.insa-toulouse.fr/",
|
||||
BLUEMIND: "https://etud-mel.insa-toulouse.fr/webmail/",
|
||||
ELUS_ETUDIANTS: "https://etud.insa-toulouse.fr/~eeinsat/",
|
||||
ENT: "https://ent.insa-toulouse.fr/",
|
||||
INSA_ACCOUNT: "https://moncompte.insa-toulouse.fr/",
|
||||
TUTOR_INSA: "https://www.etud.insa-toulouse.fr/~tutorinsa/",
|
||||
WIKETUD: "https://wiki.etud.insa-toulouse.fr/",
|
||||
},
|
||||
}
|
||||
websites: {
|
||||
AMICALE: 'https://www.amicale-insat.fr/',
|
||||
AVAILABLE_ROOMS: 'http://planex.insa-toulouse.fr/salles.php',
|
||||
BIB: 'https://bibbox.insa-toulouse.fr/',
|
||||
BLUEMIND: 'https://etud-mel.insa-toulouse.fr/webmail/',
|
||||
ELUS_ETUDIANTS: 'https://etud.insa-toulouse.fr/~eeinsat/',
|
||||
ENT: 'https://ent.insa-toulouse.fr/',
|
||||
INSA_ACCOUNT: 'https://moncompte.insa-toulouse.fr/',
|
||||
TUTOR_INSA: 'https://www.etud.insa-toulouse.fr/~tutorinsa/',
|
||||
WIKETUD: 'https://wiki.etud.insa-toulouse.fr/',
|
||||
},
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,20 +1,20 @@
|
|||
export default {
|
||||
machineStates: {
|
||||
"AVAILABLE": 0,
|
||||
"RUNNING": 1,
|
||||
"RUNNING_NOT_STARTED": 2,
|
||||
"FINISHED": 3,
|
||||
"UNAVAILABLE": 4,
|
||||
"ERROR": 5,
|
||||
"UNKNOWN": 6,
|
||||
},
|
||||
stateIcons: {
|
||||
0: 'radiobox-blank',
|
||||
1: 'progress-check',
|
||||
2: 'alert-circle-outline',
|
||||
3: 'check-circle',
|
||||
4: 'alert-octagram-outline',
|
||||
5: 'alert',
|
||||
6: 'help-circle-outline',
|
||||
}
|
||||
machineStates: {
|
||||
AVAILABLE: 0,
|
||||
RUNNING: 1,
|
||||
RUNNING_NOT_STARTED: 2,
|
||||
FINISHED: 3,
|
||||
UNAVAILABLE: 4,
|
||||
ERROR: 5,
|
||||
UNKNOWN: 6,
|
||||
},
|
||||
stateIcons: {
|
||||
0: 'radiobox-blank',
|
||||
1: 'progress-check',
|
||||
2: 'alert-circle-outline',
|
||||
3: 'check-circle',
|
||||
4: 'alert-octagram-outline',
|
||||
5: 'alert',
|
||||
6: 'help-circle-outline',
|
||||
},
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
// @flow
|
||||
|
||||
import i18n from "i18n-js";
|
||||
import i18n from 'i18n-js';
|
||||
|
||||
/**
|
||||
* Singleton used to manage update slides.
|
||||
|
|
@ -14,51 +14,47 @@ import i18n from "i18n-js";
|
|||
* </ul>
|
||||
*/
|
||||
export default class Update {
|
||||
// Increment the number to show the update slide
|
||||
static number = 6;
|
||||
|
||||
// Increment the number to show the update slide
|
||||
static number = 6;
|
||||
// Change the number of slides to display
|
||||
static slidesNumber = 4;
|
||||
// Change the icons to be displayed on the update slide
|
||||
static iconList = [
|
||||
'star',
|
||||
'clock',
|
||||
'qrcode-scan',
|
||||
'account',
|
||||
];
|
||||
static colorsList = [
|
||||
['#e01928', '#be1522'],
|
||||
['#7c33ec', '#5e11d1'],
|
||||
['#337aec', '#114ed1'],
|
||||
['#e01928', '#be1522'],
|
||||
]
|
||||
// Change the number of slides to display
|
||||
static slidesNumber = 4;
|
||||
|
||||
static instance: Update | null = null;
|
||||
// Change the icons to be displayed on the update slide
|
||||
static iconList = ['star', 'clock', 'qrcode-scan', 'account'];
|
||||
|
||||
titleList: Array<string>;
|
||||
descriptionList: Array<string>;
|
||||
static colorsList = [
|
||||
['#e01928', '#be1522'],
|
||||
['#7c33ec', '#5e11d1'],
|
||||
['#337aec', '#114ed1'],
|
||||
['#e01928', '#be1522'],
|
||||
];
|
||||
|
||||
/**
|
||||
* Init translations
|
||||
*/
|
||||
constructor() {
|
||||
this.titleList = [];
|
||||
this.descriptionList = [];
|
||||
for (let i = 0; i < Update.slidesNumber; i++) {
|
||||
this.titleList.push(i18n.t('intro.updateSlide' + i + '.title'))
|
||||
this.descriptionList.push(i18n.t('intro.updateSlide' + i + '.text'))
|
||||
}
|
||||
static instance: Update | null = null;
|
||||
|
||||
titleList: Array<string>;
|
||||
|
||||
descriptionList: Array<string>;
|
||||
|
||||
/**
|
||||
* Init translations
|
||||
*/
|
||||
constructor() {
|
||||
this.titleList = [];
|
||||
this.descriptionList = [];
|
||||
for (let i = 0; i < Update.slidesNumber; i += 1) {
|
||||
this.titleList.push(i18n.t(`intro.updateSlide${i}.title`));
|
||||
this.descriptionList.push(i18n.t(`intro.updateSlide${i}.text`));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get this class instance or create one if none is found
|
||||
*
|
||||
* @returns {Update}
|
||||
*/
|
||||
static getInstance(): Update {
|
||||
return Update.instance === null ?
|
||||
Update.instance = new Update() :
|
||||
Update.instance;
|
||||
}
|
||||
|
||||
};
|
||||
/**
|
||||
* Get this class instance or create one if none is found
|
||||
*
|
||||
* @returns {Update}
|
||||
*/
|
||||
static getInstance(): Update {
|
||||
if (Update.instance == null) Update.instance = new Update();
|
||||
return Update.instance;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,130 +1,138 @@
|
|||
// @flow
|
||||
|
||||
import type {Machine} from "../screens/Proxiwash/ProxiwashScreen";
|
||||
import type {ProxiwashMachineType} from '../screens/Proxiwash/ProxiwashScreen';
|
||||
import type {CustomThemeType} from './ThemeManager';
|
||||
import type {RuFoodCategoryType} from '../screens/Services/SelfMenuScreen';
|
||||
|
||||
/**
|
||||
* Singleton class used to manage april fools
|
||||
*/
|
||||
export default class AprilFoolsManager {
|
||||
static instance: AprilFoolsManager | null = null;
|
||||
|
||||
static instance: AprilFoolsManager | null = null;
|
||||
static fakeMachineNumber = [
|
||||
"",
|
||||
"cos(ln(1))",
|
||||
"0,5⁻¹",
|
||||
"567/189",
|
||||
"√2×√8",
|
||||
"√50×sin(9π/4)",
|
||||
"⌈π+e⌉",
|
||||
"div(rot(B))+7",
|
||||
"4×cosh(0)+4",
|
||||
"8-(-i)²",
|
||||
"|5√2+5√2i|",
|
||||
"1×10¹+1×10⁰",
|
||||
"Re(√192e^(iπ/6))",
|
||||
];
|
||||
aprilFoolsEnabled: boolean;
|
||||
static fakeMachineNumber = [
|
||||
'',
|
||||
'cos(ln(1))',
|
||||
'0,5⁻¹',
|
||||
'567/189',
|
||||
'√2×√8',
|
||||
'√50×sin(9π/4)',
|
||||
'⌈π+e⌉',
|
||||
'div(rot(B))+7',
|
||||
'4×cosh(0)+4',
|
||||
'8-(-i)²',
|
||||
'|5√2+5√2i|',
|
||||
'1×10¹+1×10⁰',
|
||||
'Re(√192e^(iπ/6))',
|
||||
];
|
||||
|
||||
constructor() {
|
||||
let today = new Date();
|
||||
this.aprilFoolsEnabled = (today.getDate() === 1 && today.getMonth() === 3);
|
||||
aprilFoolsEnabled: boolean;
|
||||
|
||||
constructor() {
|
||||
const today = new Date();
|
||||
this.aprilFoolsEnabled = today.getDate() === 1 && today.getMonth() === 3;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get this class instance or create one if none is found
|
||||
* @returns {ThemeManager}
|
||||
*/
|
||||
static getInstance(): AprilFoolsManager {
|
||||
if (AprilFoolsManager.instance == null)
|
||||
AprilFoolsManager.instance = new AprilFoolsManager();
|
||||
return AprilFoolsManager.instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds fake menu entries
|
||||
*
|
||||
* @param menu
|
||||
* @returns {Object}
|
||||
*/
|
||||
static getFakeMenuItem(
|
||||
menu: Array<RuFoodCategoryType>,
|
||||
): Array<RuFoodCategoryType> {
|
||||
menu[1].dishes.splice(4, 0, {name: 'Coq au vin'});
|
||||
menu[1].dishes.splice(2, 0, {name: "Bat'Soupe"});
|
||||
menu[1].dishes.splice(1, 0, {name: 'Pave de loup'});
|
||||
menu[1].dishes.splice(0, 0, {name: 'Béranger à point'});
|
||||
menu[1].dishes.splice(0, 0, {name: "Pieds d'Arnaud"});
|
||||
return menu;
|
||||
}
|
||||
|
||||
/**
|
||||
* Changes proxiwash dryers order
|
||||
*
|
||||
* @param dryers
|
||||
*/
|
||||
static getNewProxiwashDryerOrderedList(
|
||||
dryers: Array<ProxiwashMachineType> | null,
|
||||
) {
|
||||
if (dryers != null) {
|
||||
const second = dryers[1];
|
||||
dryers.splice(1, 1);
|
||||
dryers.push(second);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get this class instance or create one if none is found
|
||||
* @returns {ThemeManager}
|
||||
*/
|
||||
static getInstance(): AprilFoolsManager {
|
||||
return AprilFoolsManager.instance === null ?
|
||||
AprilFoolsManager.instance = new AprilFoolsManager() :
|
||||
AprilFoolsManager.instance;
|
||||
/**
|
||||
* Changes proxiwash washers order
|
||||
*
|
||||
* @param washers
|
||||
*/
|
||||
static getNewProxiwashWasherOrderedList(
|
||||
washers: Array<ProxiwashMachineType> | null,
|
||||
) {
|
||||
if (washers != null) {
|
||||
const first = washers[0];
|
||||
const second = washers[1];
|
||||
const fifth = washers[4];
|
||||
const ninth = washers[8];
|
||||
washers.splice(8, 1, second);
|
||||
washers.splice(4, 1, ninth);
|
||||
washers.splice(1, 1, first);
|
||||
washers.splice(0, 1, fifth);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds fake menu entries
|
||||
*
|
||||
* @param menu
|
||||
* @returns {Object}
|
||||
*/
|
||||
static getFakeMenuItem(menu: Array<{dishes: Array<{name: string}>}>) {
|
||||
menu[1]["dishes"].splice(4, 0, {name: "Coq au vin"});
|
||||
menu[1]["dishes"].splice(2, 0, {name: "Bat'Soupe"});
|
||||
menu[1]["dishes"].splice(1, 0, {name: "Pave de loup"});
|
||||
menu[1]["dishes"].splice(0, 0, {name: "Béranger à point"});
|
||||
menu[1]["dishes"].splice(0, 0, {name: "Pieds d'Arnaud"});
|
||||
return menu;
|
||||
}
|
||||
/**
|
||||
* Gets the new display number for the given machine number
|
||||
*
|
||||
* @param number
|
||||
* @returns {string}
|
||||
*/
|
||||
static getProxiwashMachineDisplayNumber(number: number): string {
|
||||
return AprilFoolsManager.fakeMachineNumber[number];
|
||||
}
|
||||
|
||||
/**
|
||||
* Changes proxiwash dryers order
|
||||
*
|
||||
* @param dryers
|
||||
*/
|
||||
static getNewProxiwashDryerOrderedList(dryers: Array<Machine> | null) {
|
||||
if (dryers != null) {
|
||||
let second = dryers[1];
|
||||
dryers.splice(1, 1);
|
||||
dryers.push(second);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Gets the new and ugly april fools theme
|
||||
*
|
||||
* @param currentTheme
|
||||
* @returns {{colors: {textDisabled: string, agendaDayTextColor: string, surface: string, background: string, dividerBackground: string, accent: string, agendaBackgroundColor: string, tabIcon: string, card: string, primary: string}}}
|
||||
*/
|
||||
static getAprilFoolsTheme(currentTheme: CustomThemeType): CustomThemeType {
|
||||
return {
|
||||
...currentTheme,
|
||||
colors: {
|
||||
...currentTheme.colors,
|
||||
primary: '#00be45',
|
||||
accent: '#00be45',
|
||||
background: '#d02eee',
|
||||
tabIcon: '#380d43',
|
||||
card: '#eed639',
|
||||
surface: '#eed639',
|
||||
dividerBackground: '#c72ce4',
|
||||
textDisabled: '#b9b9b9',
|
||||
|
||||
/**
|
||||
* Changes proxiwash washers order
|
||||
*
|
||||
* @param washers
|
||||
*/
|
||||
static getNewProxiwashWasherOrderedList(washers: Array<Machine> | null) {
|
||||
if (washers != null) {
|
||||
let first = washers[0];
|
||||
let second = washers[1];
|
||||
let fifth = washers[4];
|
||||
let ninth = washers[8];
|
||||
washers.splice(8, 1, second);
|
||||
washers.splice(4, 1, ninth);
|
||||
washers.splice(1, 1, first);
|
||||
washers.splice(0, 1, fifth);
|
||||
}
|
||||
}
|
||||
// Calendar/Agenda
|
||||
agendaBackgroundColor: '#c72ce4',
|
||||
agendaDayTextColor: '#6d6d6d',
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the new display number for the given machine number
|
||||
*
|
||||
* @param number
|
||||
* @returns {string}
|
||||
*/
|
||||
static getProxiwashMachineDisplayNumber(number: number) {
|
||||
return AprilFoolsManager.fakeMachineNumber[number];
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the new and ugly april fools theme
|
||||
*
|
||||
* @param currentTheme
|
||||
* @returns {{colors: {textDisabled: string, agendaDayTextColor: string, surface: string, background: string, dividerBackground: string, accent: string, agendaBackgroundColor: string, tabIcon: string, card: string, primary: string}}}
|
||||
*/
|
||||
static getAprilFoolsTheme(currentTheme: Object) {
|
||||
return {
|
||||
...currentTheme,
|
||||
colors: {
|
||||
...currentTheme.colors,
|
||||
primary: '#00be45',
|
||||
accent: '#00be45',
|
||||
background: '#d02eee',
|
||||
tabIcon: "#380d43",
|
||||
card: "#eed639",
|
||||
surface: "#eed639",
|
||||
dividerBackground: '#c72ce4',
|
||||
textDisabled: '#b9b9b9',
|
||||
|
||||
// Calendar/Agenda
|
||||
agendaBackgroundColor: '#c72ce4',
|
||||
agendaDayTextColor: '#6d6d6d',
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
isAprilFoolsEnabled() {
|
||||
return this.aprilFoolsEnabled;
|
||||
}
|
||||
|
||||
};
|
||||
isAprilFoolsEnabled(): boolean {
|
||||
return this.aprilFoolsEnabled;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
// @flow
|
||||
|
||||
import AsyncStorage from '@react-native-community/async-storage';
|
||||
import {SERVICES_KEY} from "./ServicesManager";
|
||||
import {SERVICES_KEY} from './ServicesManager';
|
||||
|
||||
/**
|
||||
* Singleton used to manage preferences.
|
||||
|
|
@ -10,227 +10,232 @@ import {SERVICES_KEY} from "./ServicesManager";
|
|||
*/
|
||||
|
||||
export default class AsyncStorageManager {
|
||||
static instance: AsyncStorageManager | null = null;
|
||||
|
||||
static instance: AsyncStorageManager | null = null;
|
||||
static PREFERENCES = {
|
||||
debugUnlocked: {
|
||||
key: 'debugUnlocked',
|
||||
default: '0',
|
||||
},
|
||||
showIntro: {
|
||||
key: 'showIntro',
|
||||
default: '1',
|
||||
},
|
||||
updateNumber: {
|
||||
key: 'updateNumber',
|
||||
default: '0',
|
||||
},
|
||||
proxiwashNotifications: {
|
||||
key: 'proxiwashNotifications',
|
||||
default: '5',
|
||||
},
|
||||
nightModeFollowSystem: {
|
||||
key: 'nightModeFollowSystem',
|
||||
default: '1',
|
||||
},
|
||||
nightMode: {
|
||||
key: 'nightMode',
|
||||
default: '1',
|
||||
},
|
||||
defaultStartScreen: {
|
||||
key: 'defaultStartScreen',
|
||||
default: 'home',
|
||||
},
|
||||
servicesShowBanner: {
|
||||
key: 'servicesShowBanner',
|
||||
default: '1',
|
||||
},
|
||||
proxiwashShowBanner: {
|
||||
key: 'proxiwashShowBanner',
|
||||
default: '1',
|
||||
},
|
||||
homeShowBanner: {
|
||||
key: 'homeShowBanner',
|
||||
default: '1',
|
||||
},
|
||||
eventsShowBanner: {
|
||||
key: 'eventsShowBanner',
|
||||
default: '1',
|
||||
},
|
||||
planexShowBanner: {
|
||||
key: 'planexShowBanner',
|
||||
default: '1',
|
||||
},
|
||||
loginShowBanner: {
|
||||
key: 'loginShowBanner',
|
||||
default: '1',
|
||||
},
|
||||
voteShowBanner: {
|
||||
key: 'voteShowBanner',
|
||||
default: '1',
|
||||
},
|
||||
equipmentShowBanner: {
|
||||
key: 'equipmentShowBanner',
|
||||
default: '1',
|
||||
},
|
||||
gameStartShowBanner: {
|
||||
key: 'gameStartShowBanner',
|
||||
default: '1',
|
||||
},
|
||||
proxiwashWatchedMachines: {
|
||||
key: 'proxiwashWatchedMachines',
|
||||
default: '[]',
|
||||
},
|
||||
showAprilFoolsStart: {
|
||||
key: 'showAprilFoolsStart',
|
||||
default: '1',
|
||||
},
|
||||
planexCurrentGroup: {
|
||||
key: 'planexCurrentGroup',
|
||||
default: '',
|
||||
},
|
||||
planexFavoriteGroups: {
|
||||
key: 'planexFavoriteGroups',
|
||||
default: '[]',
|
||||
},
|
||||
dashboardItems: {
|
||||
key: 'dashboardItems',
|
||||
default: JSON.stringify([
|
||||
SERVICES_KEY.EMAIL,
|
||||
SERVICES_KEY.WASHERS,
|
||||
SERVICES_KEY.PROXIMO,
|
||||
SERVICES_KEY.TUTOR_INSA,
|
||||
SERVICES_KEY.RU,
|
||||
]),
|
||||
},
|
||||
gameScores: {
|
||||
key: 'gameScores',
|
||||
default: '[]',
|
||||
},
|
||||
};
|
||||
|
||||
static PREFERENCES = {
|
||||
debugUnlocked: {
|
||||
key: 'debugUnlocked',
|
||||
default: '0',
|
||||
},
|
||||
showIntro: {
|
||||
key: 'showIntro',
|
||||
default: '1',
|
||||
},
|
||||
updateNumber: {
|
||||
key: 'updateNumber',
|
||||
default: '0',
|
||||
},
|
||||
proxiwashNotifications: {
|
||||
key: 'proxiwashNotifications',
|
||||
default: '5',
|
||||
},
|
||||
nightModeFollowSystem: {
|
||||
key: 'nightModeFollowSystem',
|
||||
default: '1',
|
||||
},
|
||||
nightMode: {
|
||||
key: 'nightMode',
|
||||
default: '1',
|
||||
},
|
||||
defaultStartScreen: {
|
||||
key: 'defaultStartScreen',
|
||||
default: 'home',
|
||||
},
|
||||
servicesShowBanner: {
|
||||
key: 'servicesShowBanner',
|
||||
default: '1',
|
||||
},
|
||||
proxiwashShowBanner: {
|
||||
key: 'proxiwashShowBanner',
|
||||
default: '1',
|
||||
},
|
||||
homeShowBanner: {
|
||||
key: 'homeShowBanner',
|
||||
default: '1',
|
||||
},
|
||||
eventsShowBanner: {
|
||||
key: 'eventsShowBanner',
|
||||
default: '1',
|
||||
},
|
||||
planexShowBanner: {
|
||||
key: 'planexShowBanner',
|
||||
default: '1',
|
||||
},
|
||||
loginShowBanner: {
|
||||
key: 'loginShowBanner',
|
||||
default: '1',
|
||||
},
|
||||
voteShowBanner: {
|
||||
key: 'voteShowBanner',
|
||||
default: '1',
|
||||
},
|
||||
equipmentShowBanner: {
|
||||
key: 'equipmentShowBanner',
|
||||
default: '1',
|
||||
},
|
||||
gameStartShowBanner: {
|
||||
key: 'gameStartShowBanner',
|
||||
default: '1',
|
||||
},
|
||||
proxiwashWatchedMachines: {
|
||||
key: 'proxiwashWatchedMachines',
|
||||
default: '[]',
|
||||
},
|
||||
showAprilFoolsStart: {
|
||||
key: 'showAprilFoolsStart',
|
||||
default: '1',
|
||||
},
|
||||
planexCurrentGroup: {
|
||||
key: 'planexCurrentGroup',
|
||||
default: '',
|
||||
},
|
||||
planexFavoriteGroups: {
|
||||
key: 'planexFavoriteGroups',
|
||||
default: '[]',
|
||||
},
|
||||
dashboardItems: {
|
||||
key: 'dashboardItems',
|
||||
default: JSON.stringify([
|
||||
SERVICES_KEY.EMAIL,
|
||||
SERVICES_KEY.WASHERS,
|
||||
SERVICES_KEY.PROXIMO,
|
||||
SERVICES_KEY.TUTOR_INSA,
|
||||
SERVICES_KEY.RU,
|
||||
]),
|
||||
},
|
||||
gameScores: {
|
||||
key: 'gameScores',
|
||||
default: '[]',
|
||||
},
|
||||
}
|
||||
|
||||
#currentPreferences: {[key: string]: string};
|
||||
|
||||
constructor() {
|
||||
this.#currentPreferences = {};
|
||||
}
|
||||
|
||||
/**
|
||||
* Get this class instance or create one if none is found
|
||||
* @returns {AsyncStorageManager}
|
||||
*/
|
||||
static getInstance(): AsyncStorageManager {
|
||||
return AsyncStorageManager.instance === null ?
|
||||
AsyncStorageManager.instance = new AsyncStorageManager() :
|
||||
AsyncStorageManager.instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set preferences object current values from AsyncStorage.
|
||||
* This function should be called at the app's start.
|
||||
*
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
async loadPreferences() {
|
||||
let prefKeys = [];
|
||||
// Get all available keys
|
||||
for (let key in AsyncStorageManager.PREFERENCES) {
|
||||
prefKeys.push(key);
|
||||
}
|
||||
// Get corresponding values
|
||||
let resultArray: Array<Array<string>> = await AsyncStorage.multiGet(prefKeys);
|
||||
// Save those values for later use
|
||||
for (let i = 0; i < resultArray.length; i++) {
|
||||
let key: string = resultArray[i][0];
|
||||
let val: string | null = resultArray[i][1];
|
||||
if (val === null)
|
||||
val = AsyncStorageManager.PREFERENCES[key].default;
|
||||
this.#currentPreferences[key] = val;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves the value associated to the given key to preferences.
|
||||
* This updates the preferences object and saves it to AsyncStorage.
|
||||
*
|
||||
* @param key
|
||||
* @param value
|
||||
*/
|
||||
setPreference(key: string, value: any) {
|
||||
if (AsyncStorageManager.PREFERENCES[key] != null) {
|
||||
let convertedValue = "";
|
||||
if (typeof value === "string")
|
||||
convertedValue = value;
|
||||
else if (typeof value === "boolean" || typeof value === "number")
|
||||
convertedValue = value.toString();
|
||||
else
|
||||
convertedValue = JSON.stringify(value);
|
||||
this.#currentPreferences[key] = convertedValue;
|
||||
AsyncStorage.setItem(key, convertedValue);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the value at the given key.
|
||||
* If the key is not available, returns null
|
||||
*
|
||||
* @param key
|
||||
* @returns {string|null}
|
||||
*/
|
||||
getPreference(key: string) {
|
||||
return this.#currentPreferences[key];
|
||||
}
|
||||
|
||||
/**
|
||||
* aves the value associated to the given key to preferences.
|
||||
*
|
||||
* @param key
|
||||
* @param value
|
||||
*/
|
||||
static set(key: string, value: any) {
|
||||
AsyncStorageManager.getInstance().setPreference(key, value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the string value of the given preference
|
||||
*
|
||||
* @param key
|
||||
* @returns {boolean}
|
||||
*/
|
||||
static getString(key: string) {
|
||||
return AsyncStorageManager.getInstance().getPreference(key);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the boolean value of the given preference
|
||||
*
|
||||
* @param key
|
||||
* @returns {boolean}
|
||||
*/
|
||||
static getBool(key: string) {
|
||||
const value = AsyncStorageManager.getString(key);
|
||||
return value === "1" || value === "true";
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the number value of the given preference
|
||||
*
|
||||
* @param key
|
||||
* @returns {boolean}
|
||||
*/
|
||||
static getNumber(key: string) {
|
||||
return parseFloat(AsyncStorageManager.getString(key));
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the object value of the given preference
|
||||
*
|
||||
* @param key
|
||||
* @returns {boolean}
|
||||
*/
|
||||
static getObject(key: string) {
|
||||
return JSON.parse(AsyncStorageManager.getString(key));
|
||||
#currentPreferences: {[key: string]: string};
|
||||
|
||||
constructor() {
|
||||
this.#currentPreferences = {};
|
||||
}
|
||||
|
||||
/**
|
||||
* Get this class instance or create one if none is found
|
||||
* @returns {AsyncStorageManager}
|
||||
*/
|
||||
static getInstance(): AsyncStorageManager {
|
||||
if (AsyncStorageManager.instance == null)
|
||||
AsyncStorageManager.instance = new AsyncStorageManager();
|
||||
return AsyncStorageManager.instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves the value associated to the given key to preferences.
|
||||
*
|
||||
* @param key
|
||||
* @param value
|
||||
*/
|
||||
static set(
|
||||
key: string,
|
||||
// eslint-disable-next-line flowtype/no-weak-types
|
||||
value: number | string | boolean | {...} | Array<any>,
|
||||
) {
|
||||
AsyncStorageManager.getInstance().setPreference(key, value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the string value of the given preference
|
||||
*
|
||||
* @param key
|
||||
* @returns {string}
|
||||
*/
|
||||
static getString(key: string): string {
|
||||
const value = AsyncStorageManager.getInstance().getPreference(key);
|
||||
return value != null ? value : '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the boolean value of the given preference
|
||||
*
|
||||
* @param key
|
||||
* @returns {boolean}
|
||||
*/
|
||||
static getBool(key: string): boolean {
|
||||
const value = AsyncStorageManager.getString(key);
|
||||
return value === '1' || value === 'true';
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the number value of the given preference
|
||||
*
|
||||
* @param key
|
||||
* @returns {number}
|
||||
*/
|
||||
static getNumber(key: string): number {
|
||||
return parseFloat(AsyncStorageManager.getString(key));
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the object value of the given preference
|
||||
*
|
||||
* @param key
|
||||
* @returns {{...}}
|
||||
*/
|
||||
// eslint-disable-next-line flowtype/no-weak-types
|
||||
static getObject(key: string): any {
|
||||
return JSON.parse(AsyncStorageManager.getString(key));
|
||||
}
|
||||
|
||||
/**
|
||||
* Set preferences object current values from AsyncStorage.
|
||||
* This function should be called at the app's start.
|
||||
*
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
async loadPreferences() {
|
||||
const prefKeys = [];
|
||||
// Get all available keys
|
||||
Object.keys(AsyncStorageManager.PREFERENCES).forEach((key: string) => {
|
||||
prefKeys.push(key);
|
||||
});
|
||||
// Get corresponding values
|
||||
const resultArray = await AsyncStorage.multiGet(prefKeys);
|
||||
// Save those values for later use
|
||||
resultArray.forEach((item: [string, string | null]) => {
|
||||
const key = item[0];
|
||||
let val = item[1];
|
||||
if (val === null) val = AsyncStorageManager.PREFERENCES[key].default;
|
||||
this.#currentPreferences[key] = val;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves the value associated to the given key to preferences.
|
||||
* This updates the preferences object and saves it to AsyncStorage.
|
||||
*
|
||||
* @param key
|
||||
* @param value
|
||||
*/
|
||||
setPreference(
|
||||
key: string,
|
||||
// eslint-disable-next-line flowtype/no-weak-types
|
||||
value: number | string | boolean | {...} | Array<any>,
|
||||
) {
|
||||
if (AsyncStorageManager.PREFERENCES[key] != null) {
|
||||
let convertedValue;
|
||||
if (typeof value === 'string') convertedValue = value;
|
||||
else if (typeof value === 'boolean' || typeof value === 'number')
|
||||
convertedValue = value.toString();
|
||||
else convertedValue = JSON.stringify(value);
|
||||
this.#currentPreferences[key] = convertedValue;
|
||||
AsyncStorage.setItem(key, convertedValue);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the value at the given key.
|
||||
* If the key is not available, returns null
|
||||
*
|
||||
* @param key
|
||||
* @returns {string|null}
|
||||
*/
|
||||
getPreference(key: string): string | null {
|
||||
return this.#currentPreferences[key];
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,8 @@
|
|||
// @flow
|
||||
|
||||
import * as Keychain from 'react-native-keychain';
|
||||
import {apiRequest, ERROR_TYPE} from "../utils/WebData";
|
||||
import type {ApiDataLoginType, ApiGenericDataType} from '../utils/WebData';
|
||||
import {apiRequest, ERROR_TYPE} from '../utils/WebData';
|
||||
|
||||
/**
|
||||
* champ: error
|
||||
|
|
@ -14,161 +15,167 @@ import {apiRequest, ERROR_TYPE} from "../utils/WebData";
|
|||
* 500 : SERVER_ERROR -> pb coté serveur
|
||||
*/
|
||||
|
||||
const SERVER_NAME = "amicale-insat.fr";
|
||||
const AUTH_PATH = "password";
|
||||
const SERVER_NAME = 'amicale-insat.fr';
|
||||
const AUTH_PATH = 'password';
|
||||
|
||||
export default class ConnectionManager {
|
||||
static instance: ConnectionManager | null = null;
|
||||
static instance: ConnectionManager | null = null;
|
||||
|
||||
#email: string;
|
||||
#token: string | null;
|
||||
#email: string;
|
||||
|
||||
constructor() {
|
||||
this.#token = null;
|
||||
}
|
||||
#token: string | null;
|
||||
|
||||
/**
|
||||
* Gets this class instance or create one if none is found
|
||||
*
|
||||
* @returns {ConnectionManager}
|
||||
*/
|
||||
static getInstance(): ConnectionManager {
|
||||
return ConnectionManager.instance === null ?
|
||||
ConnectionManager.instance = new ConnectionManager() :
|
||||
ConnectionManager.instance;
|
||||
}
|
||||
constructor() {
|
||||
this.#token = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the current token
|
||||
*
|
||||
* @returns {string | null}
|
||||
*/
|
||||
getToken(): string | null {
|
||||
return this.#token;
|
||||
}
|
||||
/**
|
||||
* Gets this class instance or create one if none is found
|
||||
*
|
||||
* @returns {ConnectionManager}
|
||||
*/
|
||||
static getInstance(): ConnectionManager {
|
||||
if (ConnectionManager.instance == null)
|
||||
ConnectionManager.instance = new ConnectionManager();
|
||||
return ConnectionManager.instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tries to recover login token from the secure keychain
|
||||
*
|
||||
* @returns {Promise<R>}
|
||||
*/
|
||||
async recoverLogin() {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (this.getToken() !== null)
|
||||
resolve(this.getToken());
|
||||
else {
|
||||
Keychain.getInternetCredentials(SERVER_NAME)
|
||||
.then((data) => {
|
||||
if (data) {
|
||||
this.#token = data.password;
|
||||
resolve(this.#token);
|
||||
} else
|
||||
reject(false);
|
||||
})
|
||||
.catch(() => {
|
||||
reject(false);
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Gets the current token
|
||||
*
|
||||
* @returns {string | null}
|
||||
*/
|
||||
getToken(): string | null {
|
||||
return this.#token;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the user has a valid token
|
||||
*
|
||||
* @returns {boolean}
|
||||
*/
|
||||
isLoggedIn() {
|
||||
return this.getToken() !== null;
|
||||
}
|
||||
/**
|
||||
* Tries to recover login token from the secure keychain
|
||||
*
|
||||
* @returns Promise<string>
|
||||
*/
|
||||
async recoverLogin(): Promise<string> {
|
||||
return new Promise(
|
||||
(resolve: (token: string) => void, reject: () => void) => {
|
||||
const token = this.getToken();
|
||||
if (token != null) resolve(token);
|
||||
else {
|
||||
Keychain.getInternetCredentials(SERVER_NAME)
|
||||
.then((data: Keychain.UserCredentials | false) => {
|
||||
if (
|
||||
data != null &&
|
||||
data.password != null &&
|
||||
typeof data.password === 'string'
|
||||
) {
|
||||
this.#token = data.password;
|
||||
resolve(this.#token);
|
||||
} else reject();
|
||||
})
|
||||
.catch((): void => reject());
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves the login token in the secure keychain
|
||||
*
|
||||
* @param email
|
||||
* @param token
|
||||
* @returns {Promise<R>}
|
||||
*/
|
||||
async saveLogin(email: string, token: string) {
|
||||
return new Promise((resolve, reject) => {
|
||||
Keychain.setInternetCredentials(SERVER_NAME, 'token', token)
|
||||
.then(() => {
|
||||
this.#token = token;
|
||||
this.#email = email;
|
||||
resolve(true);
|
||||
})
|
||||
.catch(() => {
|
||||
reject(false);
|
||||
});
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Check if the user has a valid token
|
||||
*
|
||||
* @returns {boolean}
|
||||
*/
|
||||
isLoggedIn(): boolean {
|
||||
return this.getToken() !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes the login token from the keychain
|
||||
*
|
||||
* @returns {Promise<R>}
|
||||
*/
|
||||
async disconnect() {
|
||||
return new Promise((resolve, reject) => {
|
||||
Keychain.resetInternetCredentials(SERVER_NAME)
|
||||
.then(() => {
|
||||
this.#token = null;
|
||||
resolve(true);
|
||||
})
|
||||
.catch(() => {
|
||||
reject(false);
|
||||
});
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Saves the login token in the secure keychain
|
||||
*
|
||||
* @param email
|
||||
* @param token
|
||||
* @returns Promise<void>
|
||||
*/
|
||||
async saveLogin(email: string, token: string): Promise<void> {
|
||||
return new Promise((resolve: () => void, reject: () => void) => {
|
||||
Keychain.setInternetCredentials(SERVER_NAME, 'token', token)
|
||||
.then(() => {
|
||||
this.#token = token;
|
||||
this.#email = email;
|
||||
resolve();
|
||||
})
|
||||
.catch((): void => reject());
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes the login token from the keychain
|
||||
*
|
||||
* @returns Promise<void>
|
||||
*/
|
||||
async disconnect(): Promise<void> {
|
||||
return new Promise((resolve: () => void, reject: () => void) => {
|
||||
Keychain.resetInternetCredentials(SERVER_NAME)
|
||||
.then(() => {
|
||||
this.#token = null;
|
||||
resolve();
|
||||
})
|
||||
.catch((): void => reject());
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends the given login and password to the api.
|
||||
* If the combination is valid, the login token is received and saved in the secure keychain.
|
||||
* If not, the promise is rejected with the corresponding error code.
|
||||
*
|
||||
* @param email
|
||||
* @param password
|
||||
* @returns {Promise<R>}
|
||||
*/
|
||||
async connect(email: string, password: string) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const data = {
|
||||
email: email,
|
||||
password: password,
|
||||
};
|
||||
apiRequest(AUTH_PATH, 'POST', data)
|
||||
.then((response) => {
|
||||
this.saveLogin(email, response.token)
|
||||
.then(() => {
|
||||
resolve(true);
|
||||
})
|
||||
.catch(() => {
|
||||
reject(ERROR_TYPE.TOKEN_SAVE);
|
||||
});
|
||||
})
|
||||
.catch((error) => reject(error));
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Sends the given login and password to the api.
|
||||
* If the combination is valid, the login token is received and saved in the secure keychain.
|
||||
* If not, the promise is rejected with the corresponding error code.
|
||||
*
|
||||
* @param email
|
||||
* @param password
|
||||
* @returns Promise<void>
|
||||
*/
|
||||
async connect(email: string, password: string): Promise<void> {
|
||||
return new Promise(
|
||||
(resolve: () => void, reject: (error: number) => void) => {
|
||||
const data = {
|
||||
email,
|
||||
password,
|
||||
};
|
||||
apiRequest(AUTH_PATH, 'POST', data)
|
||||
.then((response: ApiDataLoginType) => {
|
||||
if (response.token != null) {
|
||||
this.saveLogin(email, response.token)
|
||||
.then((): void => resolve())
|
||||
.catch((): void => reject(ERROR_TYPE.TOKEN_SAVE));
|
||||
} else reject(ERROR_TYPE.SERVER_ERROR);
|
||||
})
|
||||
.catch((error: number): void => reject(error));
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends an authenticated request with the login token to the API
|
||||
*
|
||||
* @param path
|
||||
* @param params
|
||||
* @returns {Promise<R>}
|
||||
*/
|
||||
async authenticatedRequest(path: string, params: Object) {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (this.getToken() !== null) {
|
||||
let data = {
|
||||
token: this.getToken(),
|
||||
...params
|
||||
};
|
||||
apiRequest(path, 'POST', data)
|
||||
.then((response) => resolve(response))
|
||||
.catch((error) => reject(error));
|
||||
} else
|
||||
reject(ERROR_TYPE.TOKEN_RETRIEVE);
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Sends an authenticated request with the login token to the API
|
||||
*
|
||||
* @param path
|
||||
* @param params
|
||||
* @returns Promise<ApiGenericDataType>
|
||||
*/
|
||||
async authenticatedRequest(
|
||||
path: string,
|
||||
params: {...},
|
||||
): Promise<ApiGenericDataType> {
|
||||
return new Promise(
|
||||
(
|
||||
resolve: (response: ApiGenericDataType) => void,
|
||||
reject: (error: number) => void,
|
||||
) => {
|
||||
if (this.getToken() !== null) {
|
||||
const data = {
|
||||
...params,
|
||||
token: this.getToken(),
|
||||
};
|
||||
apiRequest(path, 'POST', data)
|
||||
.then((response: ApiGenericDataType): void => resolve(response))
|
||||
.catch((error: number): void => reject(error));
|
||||
} else reject(ERROR_TYPE.TOKEN_RETRIEVE);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,27 +1,21 @@
|
|||
// @flow
|
||||
|
||||
import type {ServiceItem} from "./ServicesManager";
|
||||
import ServicesManager from "./ServicesManager";
|
||||
import {StackNavigationProp} from "@react-navigation/stack";
|
||||
import {getSublistWithIds} from "../utils/Utils";
|
||||
import AsyncStorageManager from "./AsyncStorageManager";
|
||||
|
||||
import type {ServiceItemType} from './ServicesManager';
|
||||
import ServicesManager from './ServicesManager';
|
||||
import {getSublistWithIds} from '../utils/Utils';
|
||||
import AsyncStorageManager from './AsyncStorageManager';
|
||||
|
||||
export default class DashboardManager extends ServicesManager {
|
||||
|
||||
constructor(nav: StackNavigationProp) {
|
||||
super(nav)
|
||||
}
|
||||
|
||||
getCurrentDashboard(): Array<ServiceItem> {
|
||||
const dashboardIdList = AsyncStorageManager
|
||||
.getObject(AsyncStorageManager.PREFERENCES.dashboardItems.key);
|
||||
const allDatasets = [
|
||||
...this.amicaleDataset,
|
||||
...this.studentsDataset,
|
||||
...this.insaDataset,
|
||||
...this.specialDataset,
|
||||
];
|
||||
return getSublistWithIds(dashboardIdList, allDatasets);
|
||||
}
|
||||
getCurrentDashboard(): Array<ServiceItemType | null> {
|
||||
const dashboardIdList = AsyncStorageManager.getObject(
|
||||
AsyncStorageManager.PREFERENCES.dashboardItems.key,
|
||||
);
|
||||
const allDatasets = [
|
||||
...this.amicaleDataset,
|
||||
...this.studentsDataset,
|
||||
...this.insaDataset,
|
||||
...this.specialDataset,
|
||||
];
|
||||
return getSublistWithIds(dashboardIdList, allDatasets);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -7,63 +7,68 @@ import i18n from 'i18n-js';
|
|||
* Translations are hardcoded as toLocaleDateString does not work on current android JS engine
|
||||
*/
|
||||
export default class DateManager {
|
||||
static instance: DateManager | null = null;
|
||||
static instance: DateManager | null = null;
|
||||
|
||||
daysOfWeek = [];
|
||||
monthsOfYear = [];
|
||||
daysOfWeek = [];
|
||||
|
||||
constructor() {
|
||||
this.daysOfWeek.push(i18n.t("date.daysOfWeek.sunday")); // 0 represents sunday
|
||||
this.daysOfWeek.push(i18n.t("date.daysOfWeek.monday"));
|
||||
this.daysOfWeek.push(i18n.t("date.daysOfWeek.tuesday"));
|
||||
this.daysOfWeek.push(i18n.t("date.daysOfWeek.wednesday"));
|
||||
this.daysOfWeek.push(i18n.t("date.daysOfWeek.thursday"));
|
||||
this.daysOfWeek.push(i18n.t("date.daysOfWeek.friday"));
|
||||
this.daysOfWeek.push(i18n.t("date.daysOfWeek.saturday"));
|
||||
monthsOfYear = [];
|
||||
|
||||
this.monthsOfYear.push(i18n.t("date.monthsOfYear.january"));
|
||||
this.monthsOfYear.push(i18n.t("date.monthsOfYear.february"));
|
||||
this.monthsOfYear.push(i18n.t("date.monthsOfYear.march"));
|
||||
this.monthsOfYear.push(i18n.t("date.monthsOfYear.april"));
|
||||
this.monthsOfYear.push(i18n.t("date.monthsOfYear.may"));
|
||||
this.monthsOfYear.push(i18n.t("date.monthsOfYear.june"));
|
||||
this.monthsOfYear.push(i18n.t("date.monthsOfYear.july"));
|
||||
this.monthsOfYear.push(i18n.t("date.monthsOfYear.august"));
|
||||
this.monthsOfYear.push(i18n.t("date.monthsOfYear.september"));
|
||||
this.monthsOfYear.push(i18n.t("date.monthsOfYear.october"));
|
||||
this.monthsOfYear.push(i18n.t("date.monthsOfYear.november"));
|
||||
this.monthsOfYear.push(i18n.t("date.monthsOfYear.december"));
|
||||
}
|
||||
constructor() {
|
||||
this.daysOfWeek.push(i18n.t('date.daysOfWeek.sunday')); // 0 represents sunday
|
||||
this.daysOfWeek.push(i18n.t('date.daysOfWeek.monday'));
|
||||
this.daysOfWeek.push(i18n.t('date.daysOfWeek.tuesday'));
|
||||
this.daysOfWeek.push(i18n.t('date.daysOfWeek.wednesday'));
|
||||
this.daysOfWeek.push(i18n.t('date.daysOfWeek.thursday'));
|
||||
this.daysOfWeek.push(i18n.t('date.daysOfWeek.friday'));
|
||||
this.daysOfWeek.push(i18n.t('date.daysOfWeek.saturday'));
|
||||
|
||||
/**
|
||||
* Get this class instance or create one if none is found
|
||||
* @returns {DateManager}
|
||||
*/
|
||||
static getInstance(): DateManager {
|
||||
return DateManager.instance === null ?
|
||||
DateManager.instance = new DateManager() :
|
||||
DateManager.instance;
|
||||
}
|
||||
this.monthsOfYear.push(i18n.t('date.monthsOfYear.january'));
|
||||
this.monthsOfYear.push(i18n.t('date.monthsOfYear.february'));
|
||||
this.monthsOfYear.push(i18n.t('date.monthsOfYear.march'));
|
||||
this.monthsOfYear.push(i18n.t('date.monthsOfYear.april'));
|
||||
this.monthsOfYear.push(i18n.t('date.monthsOfYear.may'));
|
||||
this.monthsOfYear.push(i18n.t('date.monthsOfYear.june'));
|
||||
this.monthsOfYear.push(i18n.t('date.monthsOfYear.july'));
|
||||
this.monthsOfYear.push(i18n.t('date.monthsOfYear.august'));
|
||||
this.monthsOfYear.push(i18n.t('date.monthsOfYear.september'));
|
||||
this.monthsOfYear.push(i18n.t('date.monthsOfYear.october'));
|
||||
this.monthsOfYear.push(i18n.t('date.monthsOfYear.november'));
|
||||
this.monthsOfYear.push(i18n.t('date.monthsOfYear.december'));
|
||||
}
|
||||
|
||||
static isWeekend(date: Date) {
|
||||
return date.getDay() === 6 || date.getDay() === 0;
|
||||
}
|
||||
/**
|
||||
* Get this class instance or create one if none is found
|
||||
* @returns {DateManager}
|
||||
*/
|
||||
static getInstance(): DateManager {
|
||||
if (DateManager.instance == null) DateManager.instance = new DateManager();
|
||||
return DateManager.instance;
|
||||
}
|
||||
|
||||
getMonthsOfYear() {
|
||||
return this.monthsOfYear;
|
||||
}
|
||||
static isWeekend(date: Date): boolean {
|
||||
return date.getDay() === 6 || date.getDay() === 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a translated string representing the given date.
|
||||
*
|
||||
* @param dateString The date with the format YYYY-MM-DD
|
||||
* @return {string} The translated string
|
||||
*/
|
||||
getTranslatedDate(dateString: string) {
|
||||
let dateArray = dateString.split('-');
|
||||
let date = new Date();
|
||||
date.setFullYear(parseInt(dateArray[0]), parseInt(dateArray[1]) - 1, parseInt(dateArray[2]));
|
||||
return this.daysOfWeek[date.getDay()] + " " + date.getDate() + " " + this.monthsOfYear[date.getMonth()] + " " + date.getFullYear();
|
||||
}
|
||||
getMonthsOfYear(): Array<string> {
|
||||
return this.monthsOfYear;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a translated string representing the given date.
|
||||
*
|
||||
* @param dateString The date with the format YYYY-MM-DD
|
||||
* @return {string} The translated string
|
||||
*/
|
||||
getTranslatedDate(dateString: string): string {
|
||||
const dateArray = dateString.split('-');
|
||||
const date = new Date();
|
||||
date.setFullYear(
|
||||
parseInt(dateArray[0], 10),
|
||||
parseInt(dateArray[1], 10) - 1,
|
||||
parseInt(dateArray[2], 10),
|
||||
);
|
||||
return `${this.daysOfWeek[date.getDay()]} ${date.getDate()} ${
|
||||
this.monthsOfYear[date.getMonth()]
|
||||
} ${date.getFullYear()}`;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,22 +1,24 @@
|
|||
// @flow
|
||||
|
||||
import i18n from 'i18n-js';
|
||||
import * as RNLocalize from "react-native-localize";
|
||||
import * as RNLocalize from 'react-native-localize';
|
||||
|
||||
import en from '../../locales/en';
|
||||
import en from '../../locales/en.json';
|
||||
import fr from '../../locales/fr.json';
|
||||
|
||||
/**
|
||||
* Static class used to manage locales
|
||||
*/
|
||||
export default class LocaleManager {
|
||||
|
||||
/**
|
||||
* Initialize translations using language files
|
||||
*/
|
||||
static initTranslations() {
|
||||
i18n.fallbacks = true;
|
||||
i18n.translations = {fr, en};
|
||||
i18n.locale = RNLocalize.findBestAvailableLanguage(["en", "fr"]).languageTag;
|
||||
}
|
||||
/**
|
||||
* Initialize translations using language files
|
||||
*/
|
||||
static initTranslations() {
|
||||
i18n.fallbacks = true;
|
||||
i18n.translations = {fr, en};
|
||||
i18n.locale = RNLocalize.findBestAvailableLanguage([
|
||||
'en',
|
||||
'fr',
|
||||
]).languageTag;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,378 +1,384 @@
|
|||
// @flow
|
||||
|
||||
import i18n from "i18n-js";
|
||||
import AvailableWebsites from "../constants/AvailableWebsites";
|
||||
import {StackNavigationProp} from "@react-navigation/stack";
|
||||
import ConnectionManager from "./ConnectionManager";
|
||||
import type {fullDashboard} from "../screens/Home/HomeScreen";
|
||||
import i18n from 'i18n-js';
|
||||
import {StackNavigationProp} from '@react-navigation/stack';
|
||||
import AvailableWebsites from '../constants/AvailableWebsites';
|
||||
import ConnectionManager from './ConnectionManager';
|
||||
import type {FullDashboardType} from '../screens/Home/HomeScreen';
|
||||
import getStrippedServicesList from '../utils/Services';
|
||||
|
||||
// AMICALE
|
||||
const CLUBS_IMAGE = "https://etud.insa-toulouse.fr/~amicale_app/images/Clubs.png";
|
||||
const PROFILE_IMAGE = "https://etud.insa-toulouse.fr/~amicale_app/images/ProfilAmicaliste.png";
|
||||
const EQUIPMENT_IMAGE = "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";
|
||||
const CLUBS_IMAGE =
|
||||
'https://etud.insa-toulouse.fr/~amicale_app/images/Clubs.png';
|
||||
const PROFILE_IMAGE =
|
||||
'https://etud.insa-toulouse.fr/~amicale_app/images/ProfilAmicaliste.png';
|
||||
const EQUIPMENT_IMAGE =
|
||||
'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
|
||||
const PROXIMO_IMAGE = "https://etud.insa-toulouse.fr/~amicale_app/images/Proximo.png"
|
||||
const WIKETUD_IMAGE = "https://etud.insa-toulouse.fr/~amicale_app/images/Wiketud.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";
|
||||
const PROXIMO_IMAGE =
|
||||
'https://etud.insa-toulouse.fr/~amicale_app/images/Proximo.png';
|
||||
const WIKETUD_IMAGE =
|
||||
'https://etud.insa-toulouse.fr/~amicale_app/images/Wiketud.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
|
||||
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 ROOM_IMAGE = "https://etud.insa-toulouse.fr/~amicale_app/images/Salles.png";
|
||||
const EMAIL_IMAGE = "https://etud.insa-toulouse.fr/~amicale_app/images/Bluemind.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";
|
||||
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 ROOM_IMAGE =
|
||||
'https://etud.insa-toulouse.fr/~amicale_app/images/Salles.png';
|
||||
const EMAIL_IMAGE =
|
||||
'https://etud.insa-toulouse.fr/~amicale_app/images/Bluemind.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
|
||||
const WASHER_IMAGE = "https://etud.insa-toulouse.fr/~amicale_app/images/ProxiwashLaveLinge.png";
|
||||
const DRYER_IMAGE = "https://etud.insa-toulouse.fr/~amicale_app/images/ProxiwashSecheLinge.png";
|
||||
const WASHER_IMAGE =
|
||||
'https://etud.insa-toulouse.fr/~amicale_app/images/ProxiwashLaveLinge.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 = {
|
||||
CLUBS: "clubs",
|
||||
PROFILE: "profile",
|
||||
EQUIPMENT: "equipment",
|
||||
AMICALE_WEBSITE: "amicale_website",
|
||||
VOTE: "vote",
|
||||
PROXIMO: "proximo",
|
||||
WIKETUD: "wiketud",
|
||||
ELUS_ETUDIANTS: "elus_etudiants",
|
||||
TUTOR_INSA: "tutor_insa",
|
||||
RU: "ru",
|
||||
AVAILABLE_ROOMS: "available_rooms",
|
||||
BIB: "bib",
|
||||
EMAIL: "email",
|
||||
ENT: "ent",
|
||||
INSA_ACCOUNT: "insa_account",
|
||||
WASHERS: "washers",
|
||||
DRYERS: "dryers",
|
||||
}
|
||||
CLUBS: 'clubs',
|
||||
PROFILE: 'profile',
|
||||
EQUIPMENT: 'equipment',
|
||||
AMICALE_WEBSITE: 'amicale_website',
|
||||
VOTE: 'vote',
|
||||
PROXIMO: 'proximo',
|
||||
WIKETUD: 'wiketud',
|
||||
ELUS_ETUDIANTS: 'elus_etudiants',
|
||||
TUTOR_INSA: 'tutor_insa',
|
||||
RU: 'ru',
|
||||
AVAILABLE_ROOMS: 'available_rooms',
|
||||
BIB: 'bib',
|
||||
EMAIL: 'email',
|
||||
ENT: 'ent',
|
||||
INSA_ACCOUNT: 'insa_account',
|
||||
WASHERS: 'washers',
|
||||
DRYERS: 'dryers',
|
||||
};
|
||||
|
||||
export const SERVICES_CATEGORIES_KEY = {
|
||||
AMICALE: "amicale",
|
||||
STUDENTS: "students",
|
||||
INSA: "insa",
|
||||
SPECIAL: "special",
|
||||
}
|
||||
AMICALE: 'amicale',
|
||||
STUDENTS: 'students',
|
||||
INSA: 'insa',
|
||||
SPECIAL: 'special',
|
||||
};
|
||||
|
||||
export type ServiceItemType = {
|
||||
key: string,
|
||||
title: string,
|
||||
subtitle: string,
|
||||
image: string,
|
||||
onPress: () => void,
|
||||
badgeFunction?: (dashboard: FullDashboardType) => number,
|
||||
};
|
||||
|
||||
export type ServiceItem = {
|
||||
key: string,
|
||||
title: string,
|
||||
subtitle: string,
|
||||
image: string,
|
||||
onPress: () => void,
|
||||
badgeFunction?: (dashboard: fullDashboard) => number,
|
||||
}
|
||||
|
||||
export type ServiceCategory = {
|
||||
key: string,
|
||||
title: string,
|
||||
subtitle: string,
|
||||
image: string | number,
|
||||
content: Array<ServiceItem>
|
||||
}
|
||||
|
||||
export type ServiceCategoryType = {
|
||||
key: string,
|
||||
title: string,
|
||||
subtitle: string,
|
||||
image: string | number,
|
||||
content: Array<ServiceItemType>,
|
||||
};
|
||||
|
||||
export default class ServicesManager {
|
||||
navigation: StackNavigationProp;
|
||||
|
||||
navigation: StackNavigationProp;
|
||||
amicaleDataset: Array<ServiceItemType>;
|
||||
|
||||
amicaleDataset: Array<ServiceItem>;
|
||||
studentsDataset: Array<ServiceItem>;
|
||||
insaDataset: Array<ServiceItem>;
|
||||
specialDataset: Array<ServiceItem>;
|
||||
studentsDataset: Array<ServiceItemType>;
|
||||
|
||||
categoriesDataset: Array<ServiceCategory>;
|
||||
insaDataset: 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
|
||||
},
|
||||
];
|
||||
}
|
||||
specialDataset: Array<ServiceItemType>;
|
||||
|
||||
/**
|
||||
* 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});
|
||||
}
|
||||
categoriesDataset: Array<ServiceCategoryType>;
|
||||
|
||||
/**
|
||||
* 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 {[]}
|
||||
*/
|
||||
getStrippedList(idList: Array<string>, sourceList: Array<{key: string, [key: string]: any}>) {
|
||||
let newArray = [];
|
||||
for (let i = 0; i < sourceList.length; i++) {
|
||||
const item = sourceList[i];
|
||||
if (!(idList.includes(item.key)))
|
||||
newArray.push(item);
|
||||
}
|
||||
return newArray;
|
||||
}
|
||||
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: (): void => 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: (): 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,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the list of amicale's services
|
||||
*
|
||||
* @param excludedItems Ids of items to exclude from the returned list
|
||||
* @returns {Array<ServiceItem>}
|
||||
*/
|
||||
getAmicaleServices(excludedItems?: Array<string>) {
|
||||
if (excludedItems != null)
|
||||
return this.getStrippedList(excludedItems, this.amicaleDataset)
|
||||
else
|
||||
return this.amicaleDataset;
|
||||
}
|
||||
/**
|
||||
* 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});
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the list of students' services
|
||||
*
|
||||
* @param excludedItems Ids of items to exclude from the returned list
|
||||
* @returns {Array<ServiceItem>}
|
||||
*/
|
||||
getStudentServices(excludedItems?: Array<string>) {
|
||||
if (excludedItems != null)
|
||||
return this.getStrippedList(excludedItems, this.studentsDataset)
|
||||
else
|
||||
return this.studentsDataset;
|
||||
}
|
||||
/**
|
||||
* Gets the list of amicale's services
|
||||
*
|
||||
* @param excludedItems Ids of items to exclude from the returned list
|
||||
* @returns {Array<ServiceItemType>}
|
||||
*/
|
||||
getAmicaleServices(excludedItems?: Array<string>): Array<ServiceItemType> {
|
||||
if (excludedItems != null)
|
||||
return getStrippedServicesList(excludedItems, this.amicaleDataset);
|
||||
return this.amicaleDataset;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the list of INSA's services
|
||||
*
|
||||
* @param excludedItems Ids of items to exclude from the returned list
|
||||
* @returns {Array<ServiceItem>}
|
||||
*/
|
||||
getINSAServices(excludedItems?: Array<string>) {
|
||||
if (excludedItems != null)
|
||||
return this.getStrippedList(excludedItems, this.insaDataset)
|
||||
else
|
||||
return this.insaDataset;
|
||||
}
|
||||
/**
|
||||
* Gets the list of students' services
|
||||
*
|
||||
* @param excludedItems Ids of items to exclude from the returned list
|
||||
* @returns {Array<ServiceItemType>}
|
||||
*/
|
||||
getStudentServices(excludedItems?: Array<string>): Array<ServiceItemType> {
|
||||
if (excludedItems != null)
|
||||
return getStrippedServicesList(excludedItems, this.studentsDataset);
|
||||
return this.studentsDataset;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the list of special services
|
||||
*
|
||||
* @param excludedItems Ids of items to exclude from the returned list
|
||||
* @returns {Array<ServiceItem>}
|
||||
*/
|
||||
getSpecialServices(excludedItems?: Array<string>) {
|
||||
if (excludedItems != null)
|
||||
return this.getStrippedList(excludedItems, this.specialDataset)
|
||||
else
|
||||
return this.specialDataset;
|
||||
}
|
||||
/**
|
||||
* Gets the list of INSA's services
|
||||
*
|
||||
* @param excludedItems Ids of items to exclude from the returned list
|
||||
* @returns {Array<ServiceItemType>}
|
||||
*/
|
||||
getINSAServices(excludedItems?: Array<string>): Array<ServiceItemType> {
|
||||
if (excludedItems != null)
|
||||
return getStrippedServicesList(excludedItems, this.insaDataset);
|
||||
return this.insaDataset;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets all services sorted by category
|
||||
*
|
||||
* @param excludedItems Ids of categories to exclude from the returned list
|
||||
* @returns {Array<ServiceCategory>}
|
||||
*/
|
||||
getCategories(excludedItems?: Array<string>) {
|
||||
if (excludedItems != null)
|
||||
return this.getStrippedList(excludedItems, this.categoriesDataset)
|
||||
else
|
||||
return this.categoriesDataset;
|
||||
}
|
||||
/**
|
||||
* Gets the list of special services
|
||||
*
|
||||
* @param excludedItems Ids of items to exclude from the returned list
|
||||
* @returns {Array<ServiceItemType>}
|
||||
*/
|
||||
getSpecialServices(excludedItems?: Array<string>): Array<ServiceItemType> {
|
||||
if (excludedItems != null)
|
||||
return getStrippedServicesList(excludedItems, this.specialDataset);
|
||||
return this.specialDataset;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,282 +1,288 @@
|
|||
// @flow
|
||||
|
||||
import AsyncStorageManager from "./AsyncStorageManager";
|
||||
import {DarkTheme, DefaultTheme} from 'react-native-paper';
|
||||
import AprilFoolsManager from "./AprilFoolsManager";
|
||||
import {Appearance} from 'react-native-appearance';
|
||||
import AsyncStorageManager from './AsyncStorageManager';
|
||||
import AprilFoolsManager from './AprilFoolsManager';
|
||||
|
||||
const colorScheme = Appearance.getColorScheme();
|
||||
|
||||
export type CustomTheme = {
|
||||
...DefaultTheme,
|
||||
colors: {
|
||||
primary: string,
|
||||
accent: string,
|
||||
tabIcon: string,
|
||||
card: string,
|
||||
dividerBackground: string,
|
||||
ripple: string,
|
||||
textDisabled: string,
|
||||
icon: string,
|
||||
subtitle: string,
|
||||
success: string,
|
||||
warning: string,
|
||||
danger: string,
|
||||
export type CustomThemeType = {
|
||||
...DefaultTheme,
|
||||
colors: {
|
||||
primary: string,
|
||||
accent: string,
|
||||
tabIcon: string,
|
||||
card: string,
|
||||
dividerBackground: string,
|
||||
ripple: string,
|
||||
textDisabled: string,
|
||||
icon: string,
|
||||
subtitle: string,
|
||||
success: string,
|
||||
warning: string,
|
||||
danger: string,
|
||||
|
||||
// Calendar/Agenda
|
||||
agendaBackgroundColor: string,
|
||||
agendaDayTextColor: string,
|
||||
// Calendar/Agenda
|
||||
agendaBackgroundColor: string,
|
||||
agendaDayTextColor: string,
|
||||
|
||||
// PROXIWASH
|
||||
proxiwashFinishedColor: string,
|
||||
proxiwashReadyColor: string,
|
||||
proxiwashRunningColor: string,
|
||||
proxiwashRunningNotStartedColor: string,
|
||||
proxiwashRunningBgColor: string,
|
||||
proxiwashBrokenColor: string,
|
||||
proxiwashErrorColor: string,
|
||||
proxiwashUnknownColor: string,
|
||||
// PROXIWASH
|
||||
proxiwashFinishedColor: string,
|
||||
proxiwashReadyColor: string,
|
||||
proxiwashRunningColor: string,
|
||||
proxiwashRunningNotStartedColor: string,
|
||||
proxiwashRunningBgColor: string,
|
||||
proxiwashBrokenColor: string,
|
||||
proxiwashErrorColor: string,
|
||||
proxiwashUnknownColor: string,
|
||||
|
||||
// Screens
|
||||
planningColor: string,
|
||||
proximoColor: string,
|
||||
proxiwashColor: string,
|
||||
menuColor: string,
|
||||
tutorinsaColor: string,
|
||||
// Screens
|
||||
planningColor: string,
|
||||
proximoColor: string,
|
||||
proxiwashColor: string,
|
||||
menuColor: string,
|
||||
tutorinsaColor: string,
|
||||
|
||||
// Tetris
|
||||
tetrisBackground: string,
|
||||
tetrisBorder: string,
|
||||
tetrisScore: string,
|
||||
tetrisI: string,
|
||||
tetrisO: string,
|
||||
tetrisT: string,
|
||||
tetrisS: string,
|
||||
tetrisZ: string,
|
||||
tetrisJ: string,
|
||||
tetrisL: string,
|
||||
// Tetris
|
||||
tetrisBackground: string,
|
||||
tetrisBorder: string,
|
||||
tetrisScore: string,
|
||||
tetrisI: string,
|
||||
tetrisO: string,
|
||||
tetrisT: string,
|
||||
tetrisS: string,
|
||||
tetrisZ: string,
|
||||
tetrisJ: string,
|
||||
tetrisL: string,
|
||||
|
||||
gameGold: string,
|
||||
gameSilver: string,
|
||||
gameBronze: string,
|
||||
gameGold: string,
|
||||
gameSilver: string,
|
||||
gameBronze: string,
|
||||
|
||||
// Mascot Popup
|
||||
mascotMessageArrow: string,
|
||||
},
|
||||
}
|
||||
// Mascot Popup
|
||||
mascotMessageArrow: string,
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* Singleton class used to manage themes
|
||||
*/
|
||||
export default class ThemeManager {
|
||||
static instance: ThemeManager | null = null;
|
||||
|
||||
static instance: ThemeManager | null = null;
|
||||
updateThemeCallback: Function;
|
||||
updateThemeCallback: null | (() => void);
|
||||
|
||||
constructor() {
|
||||
this.updateThemeCallback = null;
|
||||
}
|
||||
constructor() {
|
||||
this.updateThemeCallback = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the light theme
|
||||
*
|
||||
* @return {CustomTheme} Object containing theme variables
|
||||
* */
|
||||
static getWhiteTheme(): CustomTheme {
|
||||
return {
|
||||
...DefaultTheme,
|
||||
colors: {
|
||||
...DefaultTheme.colors,
|
||||
primary: '#be1522',
|
||||
accent: '#be1522',
|
||||
tabIcon: "#929292",
|
||||
card: "#fff",
|
||||
dividerBackground: '#e2e2e2',
|
||||
ripple: "rgba(0,0,0,0.2)",
|
||||
textDisabled: '#c1c1c1',
|
||||
icon: '#5d5d5d',
|
||||
subtitle: '#707070',
|
||||
success: "#5cb85c",
|
||||
warning: "#f0ad4e",
|
||||
danger: "#d9534f",
|
||||
cc: 'dst',
|
||||
/**
|
||||
* Gets the light theme
|
||||
*
|
||||
* @return {CustomThemeType} Object containing theme variables
|
||||
* */
|
||||
static getWhiteTheme(): CustomThemeType {
|
||||
return {
|
||||
...DefaultTheme,
|
||||
colors: {
|
||||
...DefaultTheme.colors,
|
||||
primary: '#be1522',
|
||||
accent: '#be1522',
|
||||
tabIcon: '#929292',
|
||||
card: '#fff',
|
||||
dividerBackground: '#e2e2e2',
|
||||
ripple: 'rgba(0,0,0,0.2)',
|
||||
textDisabled: '#c1c1c1',
|
||||
icon: '#5d5d5d',
|
||||
subtitle: '#707070',
|
||||
success: '#5cb85c',
|
||||
warning: '#f0ad4e',
|
||||
danger: '#d9534f',
|
||||
cc: 'dst',
|
||||
|
||||
// Calendar/Agenda
|
||||
agendaBackgroundColor: '#f3f3f4',
|
||||
agendaDayTextColor: '#636363',
|
||||
// Calendar/Agenda
|
||||
agendaBackgroundColor: '#f3f3f4',
|
||||
agendaDayTextColor: '#636363',
|
||||
|
||||
// PROXIWASH
|
||||
proxiwashFinishedColor: "#a5dc9d",
|
||||
proxiwashReadyColor: "transparent",
|
||||
proxiwashRunningColor: "#a0ceff",
|
||||
proxiwashRunningNotStartedColor: "#c9e0ff",
|
||||
proxiwashRunningBgColor: "#c7e3ff",
|
||||
proxiwashBrokenColor: "#ffa8a2",
|
||||
proxiwashErrorColor: "#ffa8a2",
|
||||
proxiwashUnknownColor: "#b6b6b6",
|
||||
// PROXIWASH
|
||||
proxiwashFinishedColor: '#a5dc9d',
|
||||
proxiwashReadyColor: 'transparent',
|
||||
proxiwashRunningColor: '#a0ceff',
|
||||
proxiwashRunningNotStartedColor: '#c9e0ff',
|
||||
proxiwashRunningBgColor: '#c7e3ff',
|
||||
proxiwashBrokenColor: '#ffa8a2',
|
||||
proxiwashErrorColor: '#ffa8a2',
|
||||
proxiwashUnknownColor: '#b6b6b6',
|
||||
|
||||
// Screens
|
||||
planningColor: '#d9b10a',
|
||||
proximoColor: '#ec5904',
|
||||
proxiwashColor: '#1fa5ee',
|
||||
menuColor: '#e91314',
|
||||
tutorinsaColor: '#f93943',
|
||||
// Screens
|
||||
planningColor: '#d9b10a',
|
||||
proximoColor: '#ec5904',
|
||||
proxiwashColor: '#1fa5ee',
|
||||
menuColor: '#e91314',
|
||||
tutorinsaColor: '#f93943',
|
||||
|
||||
// Tetris
|
||||
tetrisBackground: '#f0f0f0',
|
||||
tetrisScore: '#e2bd33',
|
||||
tetrisI: '#3cd9e6',
|
||||
tetrisO: '#ffdd00',
|
||||
tetrisT: '#a716e5',
|
||||
tetrisS: '#09c528',
|
||||
tetrisZ: '#ff0009',
|
||||
tetrisJ: '#2a67e3',
|
||||
tetrisL: '#da742d',
|
||||
// Tetris
|
||||
tetrisBackground: '#f0f0f0',
|
||||
tetrisScore: '#e2bd33',
|
||||
tetrisI: '#3cd9e6',
|
||||
tetrisO: '#ffdd00',
|
||||
tetrisT: '#a716e5',
|
||||
tetrisS: '#09c528',
|
||||
tetrisZ: '#ff0009',
|
||||
tetrisJ: '#2a67e3',
|
||||
tetrisL: '#da742d',
|
||||
|
||||
gameGold: "#ffd610",
|
||||
gameSilver: "#7b7b7b",
|
||||
gameBronze: "#a15218",
|
||||
gameGold: '#ffd610',
|
||||
gameSilver: '#7b7b7b',
|
||||
gameBronze: '#a15218',
|
||||
|
||||
// Mascot Popup
|
||||
mascotMessageArrow: "#dedede",
|
||||
},
|
||||
};
|
||||
}
|
||||
// Mascot Popup
|
||||
mascotMessageArrow: '#dedede',
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the dark theme
|
||||
*
|
||||
* @return {CustomTheme} Object containing theme variables
|
||||
* */
|
||||
static getDarkTheme(): CustomTheme {
|
||||
return {
|
||||
...DarkTheme,
|
||||
colors: {
|
||||
...DarkTheme.colors,
|
||||
primary: '#be1522',
|
||||
accent: '#be1522',
|
||||
tabBackground: "#181818",
|
||||
tabIcon: "#6d6d6d",
|
||||
card: "rgb(18,18,18)",
|
||||
dividerBackground: '#222222',
|
||||
ripple: "rgba(255,255,255,0.2)",
|
||||
textDisabled: '#5b5b5b',
|
||||
icon: '#b3b3b3',
|
||||
subtitle: '#aaaaaa',
|
||||
success: "#5cb85c",
|
||||
warning: "#f0ad4e",
|
||||
danger: "#d9534f",
|
||||
/**
|
||||
* Gets the dark theme
|
||||
*
|
||||
* @return {CustomThemeType} Object containing theme variables
|
||||
* */
|
||||
static getDarkTheme(): CustomThemeType {
|
||||
return {
|
||||
...DarkTheme,
|
||||
colors: {
|
||||
...DarkTheme.colors,
|
||||
primary: '#be1522',
|
||||
accent: '#be1522',
|
||||
tabBackground: '#181818',
|
||||
tabIcon: '#6d6d6d',
|
||||
card: 'rgb(18,18,18)',
|
||||
dividerBackground: '#222222',
|
||||
ripple: 'rgba(255,255,255,0.2)',
|
||||
textDisabled: '#5b5b5b',
|
||||
icon: '#b3b3b3',
|
||||
subtitle: '#aaaaaa',
|
||||
success: '#5cb85c',
|
||||
warning: '#f0ad4e',
|
||||
danger: '#d9534f',
|
||||
|
||||
// Calendar/Agenda
|
||||
agendaBackgroundColor: '#171717',
|
||||
agendaDayTextColor: '#6d6d6d',
|
||||
// Calendar/Agenda
|
||||
agendaBackgroundColor: '#171717',
|
||||
agendaDayTextColor: '#6d6d6d',
|
||||
|
||||
// PROXIWASH
|
||||
proxiwashFinishedColor: "#31682c",
|
||||
proxiwashReadyColor: "transparent",
|
||||
proxiwashRunningColor: "#213c79",
|
||||
proxiwashRunningNotStartedColor: "#1e263e",
|
||||
proxiwashRunningBgColor: "#1a2033",
|
||||
proxiwashBrokenColor: "#7e2e2f",
|
||||
proxiwashErrorColor: "#7e2e2f",
|
||||
proxiwashUnknownColor: "#535353",
|
||||
// PROXIWASH
|
||||
proxiwashFinishedColor: '#31682c',
|
||||
proxiwashReadyColor: 'transparent',
|
||||
proxiwashRunningColor: '#213c79',
|
||||
proxiwashRunningNotStartedColor: '#1e263e',
|
||||
proxiwashRunningBgColor: '#1a2033',
|
||||
proxiwashBrokenColor: '#7e2e2f',
|
||||
proxiwashErrorColor: '#7e2e2f',
|
||||
proxiwashUnknownColor: '#535353',
|
||||
|
||||
// Screens
|
||||
planningColor: '#d99e09',
|
||||
proximoColor: '#ec5904',
|
||||
proxiwashColor: '#1fa5ee',
|
||||
menuColor: '#b81213',
|
||||
tutorinsaColor: '#f93943',
|
||||
// Screens
|
||||
planningColor: '#d99e09',
|
||||
proximoColor: '#ec5904',
|
||||
proxiwashColor: '#1fa5ee',
|
||||
menuColor: '#b81213',
|
||||
tutorinsaColor: '#f93943',
|
||||
|
||||
// Tetris
|
||||
tetrisBackground: '#181818',
|
||||
tetrisScore: '#e2d707',
|
||||
tetrisI: '#30b3be',
|
||||
tetrisO: '#c1a700',
|
||||
tetrisT: '#9114c7',
|
||||
tetrisS: '#08a121',
|
||||
tetrisZ: '#b50008',
|
||||
tetrisJ: '#0f37b9',
|
||||
tetrisL: '#b96226',
|
||||
// Tetris
|
||||
tetrisBackground: '#181818',
|
||||
tetrisScore: '#e2d707',
|
||||
tetrisI: '#30b3be',
|
||||
tetrisO: '#c1a700',
|
||||
tetrisT: '#9114c7',
|
||||
tetrisS: '#08a121',
|
||||
tetrisZ: '#b50008',
|
||||
tetrisJ: '#0f37b9',
|
||||
tetrisL: '#b96226',
|
||||
|
||||
gameGold: "#ffd610",
|
||||
gameSilver: "#7b7b7b",
|
||||
gameBronze: "#a15218",
|
||||
gameGold: '#ffd610',
|
||||
gameSilver: '#7b7b7b',
|
||||
gameBronze: '#a15218',
|
||||
|
||||
// Mascot Popup
|
||||
mascotMessageArrow: "#323232",
|
||||
},
|
||||
};
|
||||
}
|
||||
// Mascot Popup
|
||||
mascotMessageArrow: '#323232',
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Get this class instance or create one if none is found
|
||||
*
|
||||
* @returns {ThemeManager}
|
||||
*/
|
||||
static getInstance(): ThemeManager {
|
||||
return ThemeManager.instance === null ?
|
||||
ThemeManager.instance = new ThemeManager() :
|
||||
ThemeManager.instance;
|
||||
}
|
||||
/**
|
||||
* Get this class instance or create one if none is found
|
||||
*
|
||||
* @returns {ThemeManager}
|
||||
*/
|
||||
static getInstance(): ThemeManager {
|
||||
if (ThemeManager.instance == null)
|
||||
ThemeManager.instance = new ThemeManager();
|
||||
return ThemeManager.instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets night mode status.
|
||||
* If Follow System Preferences is enabled, will first use system theme.
|
||||
* If disabled or not available, will use value stored din preferences
|
||||
*
|
||||
* @returns {boolean} Night mode state
|
||||
*/
|
||||
static getNightMode(): boolean {
|
||||
return (AsyncStorageManager.getBool(AsyncStorageManager.PREFERENCES.nightMode.key) &&
|
||||
(!AsyncStorageManager.getBool(AsyncStorageManager.PREFERENCES.nightModeFollowSystem.key)
|
||||
|| colorScheme === 'no-preference')) ||
|
||||
(AsyncStorageManager.getBool(AsyncStorageManager.PREFERENCES.nightModeFollowSystem.key)
|
||||
&& colorScheme === 'dark');
|
||||
}
|
||||
/**
|
||||
* Gets night mode status.
|
||||
* If Follow System Preferences is enabled, will first use system theme.
|
||||
* If disabled or not available, will use value stored din preferences
|
||||
*
|
||||
* @returns {boolean} Night mode state
|
||||
*/
|
||||
static getNightMode(): boolean {
|
||||
return (
|
||||
(AsyncStorageManager.getBool(
|
||||
AsyncStorageManager.PREFERENCES.nightMode.key,
|
||||
) &&
|
||||
(!AsyncStorageManager.getBool(
|
||||
AsyncStorageManager.PREFERENCES.nightModeFollowSystem.key,
|
||||
) ||
|
||||
colorScheme === 'no-preference')) ||
|
||||
(AsyncStorageManager.getBool(
|
||||
AsyncStorageManager.PREFERENCES.nightModeFollowSystem.key,
|
||||
) &&
|
||||
colorScheme === 'dark')
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the current theme based on night mode and events
|
||||
*
|
||||
* @returns {CustomTheme} The current theme
|
||||
*/
|
||||
static getCurrentTheme(): CustomTheme {
|
||||
if (AprilFoolsManager.getInstance().isAprilFoolsEnabled())
|
||||
return AprilFoolsManager.getAprilFoolsTheme(ThemeManager.getWhiteTheme());
|
||||
else
|
||||
return ThemeManager.getBaseTheme()
|
||||
}
|
||||
/**
|
||||
* Get the current theme based on night mode and events
|
||||
*
|
||||
* @returns {CustomThemeType} The current theme
|
||||
*/
|
||||
static getCurrentTheme(): CustomThemeType {
|
||||
if (AprilFoolsManager.getInstance().isAprilFoolsEnabled())
|
||||
return AprilFoolsManager.getAprilFoolsTheme(ThemeManager.getWhiteTheme());
|
||||
return ThemeManager.getBaseTheme();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the theme based on night mode
|
||||
*
|
||||
* @return {CustomTheme} The theme
|
||||
*/
|
||||
static getBaseTheme(): CustomTheme {
|
||||
if (ThemeManager.getNightMode())
|
||||
return ThemeManager.getDarkTheme();
|
||||
else
|
||||
return ThemeManager.getWhiteTheme();
|
||||
}
|
||||
/**
|
||||
* Get the theme based on night mode
|
||||
*
|
||||
* @return {CustomThemeType} The theme
|
||||
*/
|
||||
static getBaseTheme(): CustomThemeType {
|
||||
if (ThemeManager.getNightMode()) return ThemeManager.getDarkTheme();
|
||||
return ThemeManager.getWhiteTheme();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the function to be called when the theme is changed (allows for general reload of the app)
|
||||
*
|
||||
* @param callback Function to call after theme change
|
||||
*/
|
||||
setUpdateThemeCallback(callback: () => void) {
|
||||
this.updateThemeCallback = callback;
|
||||
}
|
||||
/**
|
||||
* Sets the function to be called when the theme is changed (allows for general reload of the app)
|
||||
*
|
||||
* @param callback Function to call after theme change
|
||||
*/
|
||||
setUpdateThemeCallback(callback: () => void) {
|
||||
this.updateThemeCallback = callback;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set night mode and save it to preferences
|
||||
*
|
||||
* @param isNightMode True to enable night mode, false to disable
|
||||
*/
|
||||
setNightMode(isNightMode: boolean) {
|
||||
AsyncStorageManager.set(AsyncStorageManager.PREFERENCES.nightMode.key, isNightMode);
|
||||
if (this.updateThemeCallback != null)
|
||||
this.updateThemeCallback();
|
||||
}
|
||||
|
||||
};
|
||||
/**
|
||||
* Set night mode and save it to preferences
|
||||
*
|
||||
* @param isNightMode True to enable night mode, false to disable
|
||||
*/
|
||||
setNightMode(isNightMode: boolean) {
|
||||
AsyncStorageManager.set(
|
||||
AsyncStorageManager.PREFERENCES.nightMode.key,
|
||||
isNightMode,
|
||||
);
|
||||
if (this.updateThemeCallback != null) this.updateThemeCallback();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,204 +1,231 @@
|
|||
// @flow
|
||||
|
||||
import * as React from 'react';
|
||||
import {createStackNavigator, TransitionPresets} from '@react-navigation/stack';
|
||||
import i18n from 'i18n-js';
|
||||
import {Platform} from 'react-native';
|
||||
import SettingsScreen from '../screens/Other/Settings/SettingsScreen';
|
||||
import AboutScreen from '../screens/About/AboutScreen';
|
||||
import AboutDependenciesScreen from '../screens/About/AboutDependenciesScreen';
|
||||
import DebugScreen from '../screens/About/DebugScreen';
|
||||
import {createStackNavigator, TransitionPresets} from "@react-navigation/stack";
|
||||
import i18n from "i18n-js";
|
||||
import TabNavigator from "./TabNavigator";
|
||||
import GameMainScreen from "../screens/Game/screens/GameMainScreen";
|
||||
import VoteScreen from "../screens/Amicale/VoteScreen";
|
||||
import LoginScreen from "../screens/Amicale/LoginScreen";
|
||||
import {Platform} from "react-native";
|
||||
import SelfMenuScreen from "../screens/Services/SelfMenuScreen";
|
||||
import ProximoMainScreen from "../screens/Services/Proximo/ProximoMainScreen";
|
||||
import ProximoListScreen from "../screens/Services/Proximo/ProximoListScreen";
|
||||
import ProximoAboutScreen from "../screens/Services/Proximo/ProximoAboutScreen";
|
||||
import ProfileScreen from "../screens/Amicale/ProfileScreen";
|
||||
import ClubListScreen from "../screens/Amicale/Clubs/ClubListScreen";
|
||||
import ClubAboutScreen from "../screens/Amicale/Clubs/ClubAboutScreen";
|
||||
import ClubDisplayScreen from "../screens/Amicale/Clubs/ClubDisplayScreen";
|
||||
import {createScreenCollapsibleStack, getWebsiteStack} from "../utils/CollapsibleUtils";
|
||||
import BugReportScreen from "../screens/Other/FeedbackScreen";
|
||||
import WebsiteScreen from "../screens/Services/WebsiteScreen";
|
||||
import EquipmentScreen from "../screens/Amicale/Equipment/EquipmentListScreen";
|
||||
import EquipmentLendScreen from "../screens/Amicale/Equipment/EquipmentRentScreen";
|
||||
import EquipmentConfirmScreen from "../screens/Amicale/Equipment/EquipmentConfirmScreen";
|
||||
import DashboardEditScreen from "../screens/Other/Settings/DashboardEditScreen";
|
||||
import GameStartScreen from "../screens/Game/screens/GameStartScreen";
|
||||
import TabNavigator from './TabNavigator';
|
||||
import GameMainScreen from '../screens/Game/screens/GameMainScreen';
|
||||
import VoteScreen from '../screens/Amicale/VoteScreen';
|
||||
import LoginScreen from '../screens/Amicale/LoginScreen';
|
||||
import SelfMenuScreen from '../screens/Services/SelfMenuScreen';
|
||||
import ProximoMainScreen from '../screens/Services/Proximo/ProximoMainScreen';
|
||||
import ProximoListScreen from '../screens/Services/Proximo/ProximoListScreen';
|
||||
import ProximoAboutScreen from '../screens/Services/Proximo/ProximoAboutScreen';
|
||||
import ProfileScreen from '../screens/Amicale/ProfileScreen';
|
||||
import ClubListScreen from '../screens/Amicale/Clubs/ClubListScreen';
|
||||
import ClubAboutScreen from '../screens/Amicale/Clubs/ClubAboutScreen';
|
||||
import ClubDisplayScreen from '../screens/Amicale/Clubs/ClubDisplayScreen';
|
||||
import {
|
||||
createScreenCollapsibleStack,
|
||||
getWebsiteStack,
|
||||
} from '../utils/CollapsibleUtils';
|
||||
import BugReportScreen from '../screens/Other/FeedbackScreen';
|
||||
import WebsiteScreen from '../screens/Services/WebsiteScreen';
|
||||
import EquipmentScreen from '../screens/Amicale/Equipment/EquipmentListScreen';
|
||||
import EquipmentLendScreen from '../screens/Amicale/Equipment/EquipmentRentScreen';
|
||||
import EquipmentConfirmScreen from '../screens/Amicale/Equipment/EquipmentConfirmScreen';
|
||||
import DashboardEditScreen from '../screens/Other/Settings/DashboardEditScreen';
|
||||
import GameStartScreen from '../screens/Game/screens/GameStartScreen';
|
||||
|
||||
const modalTransition = Platform.OS === 'ios' ? TransitionPresets.ModalPresentationIOS : TransitionPresets.ModalSlideFromBottomIOS;
|
||||
const modalTransition =
|
||||
Platform.OS === 'ios'
|
||||
? TransitionPresets.ModalPresentationIOS
|
||||
: TransitionPresets.ModalTransition;
|
||||
|
||||
const defaultScreenOptions = {
|
||||
gestureEnabled: true,
|
||||
cardOverlayEnabled: true,
|
||||
...TransitionPresets.SlideFromRightIOS,
|
||||
gestureEnabled: true,
|
||||
cardOverlayEnabled: true,
|
||||
...TransitionPresets.SlideFromRightIOS,
|
||||
};
|
||||
|
||||
|
||||
const MainStack = createStackNavigator();
|
||||
|
||||
function MainStackComponent(props: { createTabNavigator: () => React.Node }) {
|
||||
return (
|
||||
<MainStack.Navigator
|
||||
initialRouteName={'main'}
|
||||
headerMode={'screen'}
|
||||
screenOptions={defaultScreenOptions}
|
||||
>
|
||||
<MainStack.Screen
|
||||
name="main"
|
||||
component={props.createTabNavigator}
|
||||
options={{
|
||||
headerShown: false,
|
||||
title: i18n.t('screens.home.title'),
|
||||
}}
|
||||
/>
|
||||
{createScreenCollapsibleStack(
|
||||
"settings",
|
||||
MainStack,
|
||||
SettingsScreen,
|
||||
i18n.t('screens.settings.title'))}
|
||||
{createScreenCollapsibleStack(
|
||||
"dashboard-edit",
|
||||
MainStack,
|
||||
DashboardEditScreen,
|
||||
i18n.t('screens.settings.dashboardEdit.title'))}
|
||||
{createScreenCollapsibleStack(
|
||||
"about",
|
||||
MainStack,
|
||||
AboutScreen,
|
||||
i18n.t('screens.about.title'))}
|
||||
{createScreenCollapsibleStack(
|
||||
"dependencies",
|
||||
MainStack,
|
||||
AboutDependenciesScreen,
|
||||
i18n.t('screens.about.libs'))}
|
||||
{createScreenCollapsibleStack(
|
||||
"debug",
|
||||
MainStack,
|
||||
DebugScreen,
|
||||
i18n.t('screens.about.debug'))}
|
||||
function MainStackComponent(props: {
|
||||
createTabNavigator: () => React.Node,
|
||||
}): React.Node {
|
||||
const {createTabNavigator} = props;
|
||||
return (
|
||||
<MainStack.Navigator
|
||||
initialRouteName="main"
|
||||
headerMode="screen"
|
||||
screenOptions={defaultScreenOptions}>
|
||||
<MainStack.Screen
|
||||
name="main"
|
||||
component={createTabNavigator}
|
||||
options={{
|
||||
headerShown: false,
|
||||
title: i18n.t('screens.home.title'),
|
||||
}}
|
||||
/>
|
||||
{createScreenCollapsibleStack(
|
||||
'settings',
|
||||
MainStack,
|
||||
SettingsScreen,
|
||||
i18n.t('screens.settings.title'),
|
||||
)}
|
||||
{createScreenCollapsibleStack(
|
||||
'dashboard-edit',
|
||||
MainStack,
|
||||
DashboardEditScreen,
|
||||
i18n.t('screens.settings.dashboardEdit.title'),
|
||||
)}
|
||||
{createScreenCollapsibleStack(
|
||||
'about',
|
||||
MainStack,
|
||||
AboutScreen,
|
||||
i18n.t('screens.about.title'),
|
||||
)}
|
||||
{createScreenCollapsibleStack(
|
||||
'dependencies',
|
||||
MainStack,
|
||||
AboutDependenciesScreen,
|
||||
i18n.t('screens.about.libs'),
|
||||
)}
|
||||
{createScreenCollapsibleStack(
|
||||
'debug',
|
||||
MainStack,
|
||||
DebugScreen,
|
||||
i18n.t('screens.about.debug'),
|
||||
)}
|
||||
|
||||
{createScreenCollapsibleStack(
|
||||
"game-start",
|
||||
MainStack,
|
||||
GameStartScreen,
|
||||
i18n.t('screens.game.title'))}
|
||||
<MainStack.Screen
|
||||
name="game-main"
|
||||
component={GameMainScreen}
|
||||
options={{
|
||||
title: i18n.t("screens.game.title"),
|
||||
}}
|
||||
/>
|
||||
{createScreenCollapsibleStack(
|
||||
"login",
|
||||
MainStack,
|
||||
LoginScreen,
|
||||
i18n.t('screens.login.title'),
|
||||
true,
|
||||
{headerTintColor: "#fff"},
|
||||
'transparent')}
|
||||
{getWebsiteStack("website", MainStack, WebsiteScreen, "")}
|
||||
{createScreenCollapsibleStack(
|
||||
'game-start',
|
||||
MainStack,
|
||||
GameStartScreen,
|
||||
i18n.t('screens.game.title'),
|
||||
)}
|
||||
<MainStack.Screen
|
||||
name="game-main"
|
||||
component={GameMainScreen}
|
||||
options={{
|
||||
title: i18n.t('screens.game.title'),
|
||||
}}
|
||||
/>
|
||||
{createScreenCollapsibleStack(
|
||||
'login',
|
||||
MainStack,
|
||||
LoginScreen,
|
||||
i18n.t('screens.login.title'),
|
||||
true,
|
||||
{headerTintColor: '#fff'},
|
||||
'transparent',
|
||||
)}
|
||||
{getWebsiteStack('website', MainStack, WebsiteScreen, '')}
|
||||
|
||||
{createScreenCollapsibleStack(
|
||||
'self-menu',
|
||||
MainStack,
|
||||
SelfMenuScreen,
|
||||
i18n.t('screens.menu.title'),
|
||||
)}
|
||||
{createScreenCollapsibleStack(
|
||||
'proximo',
|
||||
MainStack,
|
||||
ProximoMainScreen,
|
||||
i18n.t('screens.proximo.title'),
|
||||
)}
|
||||
{createScreenCollapsibleStack(
|
||||
'proximo-list',
|
||||
MainStack,
|
||||
ProximoListScreen,
|
||||
i18n.t('screens.proximo.articleList'),
|
||||
)}
|
||||
{createScreenCollapsibleStack(
|
||||
'proximo-about',
|
||||
MainStack,
|
||||
ProximoAboutScreen,
|
||||
i18n.t('screens.proximo.title'),
|
||||
true,
|
||||
{...modalTransition},
|
||||
)}
|
||||
|
||||
{createScreenCollapsibleStack(
|
||||
"self-menu",
|
||||
MainStack,
|
||||
SelfMenuScreen,
|
||||
i18n.t('screens.menu.title'))}
|
||||
{createScreenCollapsibleStack(
|
||||
"proximo",
|
||||
MainStack,
|
||||
ProximoMainScreen,
|
||||
i18n.t('screens.proximo.title'))}
|
||||
{createScreenCollapsibleStack(
|
||||
"proximo-list",
|
||||
MainStack,
|
||||
ProximoListScreen,
|
||||
i18n.t('screens.proximo.articleList'),
|
||||
)}
|
||||
{createScreenCollapsibleStack(
|
||||
"proximo-about",
|
||||
MainStack,
|
||||
ProximoAboutScreen,
|
||||
i18n.t('screens.proximo.title'),
|
||||
true,
|
||||
{...modalTransition},
|
||||
)}
|
||||
{createScreenCollapsibleStack(
|
||||
'profile',
|
||||
MainStack,
|
||||
ProfileScreen,
|
||||
i18n.t('screens.profile.title'),
|
||||
)}
|
||||
{createScreenCollapsibleStack(
|
||||
'club-list',
|
||||
MainStack,
|
||||
ClubListScreen,
|
||||
i18n.t('screens.clubs.title'),
|
||||
)}
|
||||
{createScreenCollapsibleStack(
|
||||
'club-information',
|
||||
MainStack,
|
||||
ClubDisplayScreen,
|
||||
i18n.t('screens.clubs.details'),
|
||||
true,
|
||||
{...modalTransition},
|
||||
)}
|
||||
{createScreenCollapsibleStack(
|
||||
'club-about',
|
||||
MainStack,
|
||||
ClubAboutScreen,
|
||||
i18n.t('screens.clubs.title'),
|
||||
true,
|
||||
{...modalTransition},
|
||||
)}
|
||||
{createScreenCollapsibleStack(
|
||||
'equipment-list',
|
||||
MainStack,
|
||||
EquipmentScreen,
|
||||
i18n.t('screens.equipment.title'),
|
||||
)}
|
||||
{createScreenCollapsibleStack(
|
||||
'equipment-rent',
|
||||
MainStack,
|
||||
EquipmentLendScreen,
|
||||
i18n.t('screens.equipment.book'),
|
||||
)}
|
||||
{createScreenCollapsibleStack(
|
||||
'equipment-confirm',
|
||||
MainStack,
|
||||
EquipmentConfirmScreen,
|
||||
i18n.t('screens.equipment.confirm'),
|
||||
)}
|
||||
{createScreenCollapsibleStack(
|
||||
'vote',
|
||||
MainStack,
|
||||
VoteScreen,
|
||||
i18n.t('screens.vote.title'),
|
||||
)}
|
||||
{createScreenCollapsibleStack(
|
||||
'feedback',
|
||||
MainStack,
|
||||
BugReportScreen,
|
||||
i18n.t('screens.feedback.title'),
|
||||
)}
|
||||
</MainStack.Navigator>
|
||||
);
|
||||
}
|
||||
|
||||
{createScreenCollapsibleStack(
|
||||
"profile",
|
||||
MainStack,
|
||||
ProfileScreen,
|
||||
i18n.t('screens.profile.title'))}
|
||||
{createScreenCollapsibleStack(
|
||||
"club-list",
|
||||
MainStack,
|
||||
ClubListScreen,
|
||||
i18n.t('screens.clubs.title'))}
|
||||
{createScreenCollapsibleStack(
|
||||
"club-information",
|
||||
MainStack,
|
||||
ClubDisplayScreen,
|
||||
i18n.t('screens.clubs.details'),
|
||||
true,
|
||||
{...modalTransition})}
|
||||
{createScreenCollapsibleStack(
|
||||
"club-about",
|
||||
MainStack,
|
||||
ClubAboutScreen,
|
||||
i18n.t('screens.clubs.title'),
|
||||
true,
|
||||
{...modalTransition})}
|
||||
{createScreenCollapsibleStack(
|
||||
"equipment-list",
|
||||
MainStack,
|
||||
EquipmentScreen,
|
||||
i18n.t('screens.equipment.title'))}
|
||||
{createScreenCollapsibleStack(
|
||||
"equipment-rent",
|
||||
MainStack,
|
||||
EquipmentLendScreen,
|
||||
i18n.t('screens.equipment.book'))}
|
||||
{createScreenCollapsibleStack(
|
||||
"equipment-confirm",
|
||||
MainStack,
|
||||
EquipmentConfirmScreen,
|
||||
i18n.t('screens.equipment.confirm'))}
|
||||
{createScreenCollapsibleStack(
|
||||
"vote",
|
||||
MainStack,
|
||||
VoteScreen,
|
||||
i18n.t('screens.vote.title'))}
|
||||
{createScreenCollapsibleStack(
|
||||
"feedback",
|
||||
MainStack,
|
||||
BugReportScreen,
|
||||
i18n.t('screens.feedback.title'))}
|
||||
</MainStack.Navigator>
|
||||
type PropsType = {
|
||||
defaultHomeRoute: string | null,
|
||||
// eslint-disable-next-line flowtype/no-weak-types
|
||||
defaultHomeData: {[key: string]: string},
|
||||
};
|
||||
|
||||
export default class MainNavigator extends React.Component<PropsType> {
|
||||
createTabNavigator: () => React.Node;
|
||||
|
||||
constructor(props: PropsType) {
|
||||
super(props);
|
||||
this.createTabNavigator = (): React.Node => (
|
||||
<TabNavigator
|
||||
defaultHomeRoute={props.defaultHomeRoute}
|
||||
defaultHomeData={props.defaultHomeData}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
type Props = {
|
||||
defaultHomeRoute: string | null,
|
||||
defaultHomeData: { [key: string]: any }
|
||||
}
|
||||
|
||||
export default class MainNavigator extends React.Component<Props> {
|
||||
|
||||
createTabNavigator: () => React.Node;
|
||||
|
||||
constructor(props: Props) {
|
||||
super(props);
|
||||
this.createTabNavigator = () => <TabNavigator {...props}/>
|
||||
}
|
||||
|
||||
render() {
|
||||
return (
|
||||
<MainStackComponent createTabNavigator={this.createTabNavigator}/>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
render(): React.Node {
|
||||
return <MainStackComponent createTabNavigator={this.createTabNavigator} />;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,271 +1,292 @@
|
|||
// @flow
|
||||
|
||||
import * as React from 'react';
|
||||
import {createStackNavigator, TransitionPresets} from '@react-navigation/stack';
|
||||
import {createBottomTabNavigator} from "@react-navigation/bottom-tabs";
|
||||
import {createBottomTabNavigator} from '@react-navigation/bottom-tabs';
|
||||
|
||||
import {Title, useTheme} from 'react-native-paper';
|
||||
import {Platform} from 'react-native';
|
||||
import i18n from 'i18n-js';
|
||||
import {createCollapsibleStack} from 'react-navigation-collapsible';
|
||||
import {View} from 'react-native-animatable';
|
||||
import HomeScreen from '../screens/Home/HomeScreen';
|
||||
import PlanningScreen from '../screens/Planning/PlanningScreen';
|
||||
import PlanningDisplayScreen from '../screens/Planning/PlanningDisplayScreen';
|
||||
import ProxiwashScreen from '../screens/Proxiwash/ProxiwashScreen';
|
||||
import ProxiwashAboutScreen from '../screens/Proxiwash/ProxiwashAboutScreen';
|
||||
import PlanexScreen from '../screens/Planex/PlanexScreen';
|
||||
import AsyncStorageManager from "../managers/AsyncStorageManager";
|
||||
import {Title, useTheme} from 'react-native-paper';
|
||||
import {Platform} from 'react-native';
|
||||
import i18n from "i18n-js";
|
||||
import ClubDisplayScreen from "../screens/Amicale/Clubs/ClubDisplayScreen";
|
||||
import ScannerScreen from "../screens/Home/ScannerScreen";
|
||||
import FeedItemScreen from "../screens/Home/FeedItemScreen";
|
||||
import {createCollapsibleStack} from "react-navigation-collapsible";
|
||||
import GroupSelectionScreen from "../screens/Planex/GroupSelectionScreen";
|
||||
import CustomTabBar from "../components/Tabbar/CustomTabBar";
|
||||
import WebsitesHomeScreen from "../screens/Services/ServicesScreen";
|
||||
import ServicesSectionScreen from "../screens/Services/ServicesSectionScreen";
|
||||
import AmicaleContactScreen from "../screens/Amicale/AmicaleContactScreen";
|
||||
import {createScreenCollapsibleStack, getWebsiteStack} from "../utils/CollapsibleUtils";
|
||||
import {View} from "react-native-animatable";
|
||||
import Mascot, {MASCOT_STYLE} from "../components/Mascot/Mascot";
|
||||
|
||||
const modalTransition = Platform.OS === 'ios' ? TransitionPresets.ModalPresentationIOS : TransitionPresets.ModalSlideFromBottomIOS;
|
||||
import AsyncStorageManager from '../managers/AsyncStorageManager';
|
||||
import ClubDisplayScreen from '../screens/Amicale/Clubs/ClubDisplayScreen';
|
||||
import ScannerScreen from '../screens/Home/ScannerScreen';
|
||||
import FeedItemScreen from '../screens/Home/FeedItemScreen';
|
||||
import GroupSelectionScreen from '../screens/Planex/GroupSelectionScreen';
|
||||
import CustomTabBar from '../components/Tabbar/CustomTabBar';
|
||||
import WebsitesHomeScreen from '../screens/Services/ServicesScreen';
|
||||
import ServicesSectionScreen from '../screens/Services/ServicesSectionScreen';
|
||||
import AmicaleContactScreen from '../screens/Amicale/AmicaleContactScreen';
|
||||
import {
|
||||
createScreenCollapsibleStack,
|
||||
getWebsiteStack,
|
||||
} from '../utils/CollapsibleUtils';
|
||||
import Mascot, {MASCOT_STYLE} from '../components/Mascot/Mascot';
|
||||
|
||||
const modalTransition =
|
||||
Platform.OS === 'ios'
|
||||
? TransitionPresets.ModalPresentationIOS
|
||||
: TransitionPresets.ModalTransition;
|
||||
|
||||
const defaultScreenOptions = {
|
||||
gestureEnabled: true,
|
||||
cardOverlayEnabled: true,
|
||||
...modalTransition,
|
||||
gestureEnabled: true,
|
||||
cardOverlayEnabled: true,
|
||||
...modalTransition,
|
||||
};
|
||||
|
||||
|
||||
const ServicesStack = createStackNavigator();
|
||||
|
||||
function ServicesStackComponent() {
|
||||
return (
|
||||
<ServicesStack.Navigator
|
||||
initialRouteName="index"
|
||||
headerMode={"screen"}
|
||||
screenOptions={defaultScreenOptions}
|
||||
>
|
||||
{createScreenCollapsibleStack(
|
||||
"index",
|
||||
ServicesStack,
|
||||
WebsitesHomeScreen,
|
||||
i18n.t('screens.services.title'))}
|
||||
{createScreenCollapsibleStack(
|
||||
"services-section",
|
||||
ServicesStack,
|
||||
ServicesSectionScreen,
|
||||
"SECTION")}
|
||||
{createScreenCollapsibleStack(
|
||||
"amicale-contact",
|
||||
ServicesStack,
|
||||
AmicaleContactScreen,
|
||||
i18n.t('screens.amicaleAbout.title'))}
|
||||
</ServicesStack.Navigator>
|
||||
);
|
||||
function ServicesStackComponent(): React.Node {
|
||||
return (
|
||||
<ServicesStack.Navigator
|
||||
initialRouteName="index"
|
||||
headerMode="screen"
|
||||
screenOptions={defaultScreenOptions}>
|
||||
{createScreenCollapsibleStack(
|
||||
'index',
|
||||
ServicesStack,
|
||||
WebsitesHomeScreen,
|
||||
i18n.t('screens.services.title'),
|
||||
)}
|
||||
{createScreenCollapsibleStack(
|
||||
'services-section',
|
||||
ServicesStack,
|
||||
ServicesSectionScreen,
|
||||
'SECTION',
|
||||
)}
|
||||
{createScreenCollapsibleStack(
|
||||
'amicale-contact',
|
||||
ServicesStack,
|
||||
AmicaleContactScreen,
|
||||
i18n.t('screens.amicaleAbout.title'),
|
||||
)}
|
||||
</ServicesStack.Navigator>
|
||||
);
|
||||
}
|
||||
|
||||
const ProxiwashStack = createStackNavigator();
|
||||
|
||||
function ProxiwashStackComponent() {
|
||||
return (
|
||||
<ProxiwashStack.Navigator
|
||||
initialRouteName="index"
|
||||
headerMode={"screen"}
|
||||
screenOptions={defaultScreenOptions}
|
||||
>
|
||||
{createScreenCollapsibleStack(
|
||||
"index",
|
||||
ProxiwashStack,
|
||||
ProxiwashScreen,
|
||||
i18n.t('screens.proxiwash.title'))}
|
||||
{createScreenCollapsibleStack(
|
||||
"proxiwash-about",
|
||||
ProxiwashStack,
|
||||
ProxiwashAboutScreen,
|
||||
i18n.t('screens.proxiwash.title'))}
|
||||
</ProxiwashStack.Navigator>
|
||||
);
|
||||
function ProxiwashStackComponent(): React.Node {
|
||||
return (
|
||||
<ProxiwashStack.Navigator
|
||||
initialRouteName="index"
|
||||
headerMode="screen"
|
||||
screenOptions={defaultScreenOptions}>
|
||||
{createScreenCollapsibleStack(
|
||||
'index',
|
||||
ProxiwashStack,
|
||||
ProxiwashScreen,
|
||||
i18n.t('screens.proxiwash.title'),
|
||||
)}
|
||||
{createScreenCollapsibleStack(
|
||||
'proxiwash-about',
|
||||
ProxiwashStack,
|
||||
ProxiwashAboutScreen,
|
||||
i18n.t('screens.proxiwash.title'),
|
||||
)}
|
||||
</ProxiwashStack.Navigator>
|
||||
);
|
||||
}
|
||||
|
||||
const PlanningStack = createStackNavigator();
|
||||
|
||||
function PlanningStackComponent() {
|
||||
return (
|
||||
<PlanningStack.Navigator
|
||||
initialRouteName="index"
|
||||
headerMode={"screen"}
|
||||
screenOptions={defaultScreenOptions}
|
||||
>
|
||||
<PlanningStack.Screen
|
||||
name="index"
|
||||
component={PlanningScreen}
|
||||
options={{title: i18n.t('screens.planning.title'),}}
|
||||
/>
|
||||
{createScreenCollapsibleStack(
|
||||
"planning-information",
|
||||
PlanningStack,
|
||||
PlanningDisplayScreen,
|
||||
i18n.t('screens.planning.eventDetails'))}
|
||||
</PlanningStack.Navigator>
|
||||
);
|
||||
function PlanningStackComponent(): React.Node {
|
||||
return (
|
||||
<PlanningStack.Navigator
|
||||
initialRouteName="index"
|
||||
headerMode="screen"
|
||||
screenOptions={defaultScreenOptions}>
|
||||
<PlanningStack.Screen
|
||||
name="index"
|
||||
component={PlanningScreen}
|
||||
options={{title: i18n.t('screens.planning.title')}}
|
||||
/>
|
||||
{createScreenCollapsibleStack(
|
||||
'planning-information',
|
||||
PlanningStack,
|
||||
PlanningDisplayScreen,
|
||||
i18n.t('screens.planning.eventDetails'),
|
||||
)}
|
||||
</PlanningStack.Navigator>
|
||||
);
|
||||
}
|
||||
|
||||
const HomeStack = createStackNavigator();
|
||||
|
||||
function HomeStackComponent(initialRoute: string | null, defaultData: { [key: string]: any }) {
|
||||
let params = undefined;
|
||||
if (initialRoute != null)
|
||||
params = {data: defaultData, nextScreen: initialRoute, shouldOpen: true};
|
||||
const {colors} = useTheme();
|
||||
return (
|
||||
<HomeStack.Navigator
|
||||
initialRouteName={"index"}
|
||||
headerMode={"screen"}
|
||||
screenOptions={defaultScreenOptions}
|
||||
>
|
||||
{createCollapsibleStack(
|
||||
<HomeStack.Screen
|
||||
name="index"
|
||||
component={HomeScreen}
|
||||
options={{
|
||||
title: i18n.t('screens.home.title'),
|
||||
headerStyle: {
|
||||
backgroundColor: colors.surface,
|
||||
},
|
||||
headerTitle: () =>
|
||||
<View style={{flexDirection: "row"}}>
|
||||
<Mascot
|
||||
style={{
|
||||
width: 50
|
||||
}}
|
||||
emotion={MASCOT_STYLE.RANDOM}
|
||||
animated={true}
|
||||
entryAnimation={{
|
||||
animation: "bounceIn",
|
||||
duration: 1000
|
||||
}}
|
||||
loopAnimation={{
|
||||
animation: "pulse",
|
||||
duration: 2000,
|
||||
iterationCount: "infinite"
|
||||
}}
|
||||
/>
|
||||
<Title style={{
|
||||
marginLeft: 10,
|
||||
marginTop: "auto",
|
||||
marginBottom: "auto",
|
||||
}}>{i18n.t('screens.home.title')}</Title>
|
||||
</View>
|
||||
}}
|
||||
initialParams={params}
|
||||
/>,
|
||||
{
|
||||
collapsedColor: colors.surface,
|
||||
useNativeDriver: true,
|
||||
}
|
||||
)}
|
||||
<HomeStack.Screen
|
||||
name="scanner"
|
||||
component={ScannerScreen}
|
||||
options={{title: i18n.t('screens.scanner.title'),}}
|
||||
/>
|
||||
function HomeStackComponent(
|
||||
initialRoute: string | null,
|
||||
defaultData: {[key: string]: string},
|
||||
): React.Node {
|
||||
let params;
|
||||
if (initialRoute != null)
|
||||
params = {data: defaultData, nextScreen: initialRoute, shouldOpen: true};
|
||||
const {colors} = useTheme();
|
||||
return (
|
||||
<HomeStack.Navigator
|
||||
initialRouteName="index"
|
||||
headerMode="screen"
|
||||
screenOptions={defaultScreenOptions}>
|
||||
{createCollapsibleStack(
|
||||
<HomeStack.Screen
|
||||
name="index"
|
||||
component={HomeScreen}
|
||||
options={{
|
||||
title: i18n.t('screens.home.title'),
|
||||
headerStyle: {
|
||||
backgroundColor: colors.surface,
|
||||
},
|
||||
headerTitle: (): React.Node => (
|
||||
<View style={{flexDirection: 'row'}}>
|
||||
<Mascot
|
||||
style={{
|
||||
width: 50,
|
||||
}}
|
||||
emotion={MASCOT_STYLE.RANDOM}
|
||||
animated
|
||||
entryAnimation={{
|
||||
animation: 'bounceIn',
|
||||
duration: 1000,
|
||||
}}
|
||||
loopAnimation={{
|
||||
animation: 'pulse',
|
||||
duration: 2000,
|
||||
iterationCount: 'infinite',
|
||||
}}
|
||||
/>
|
||||
<Title
|
||||
style={{
|
||||
marginLeft: 10,
|
||||
marginTop: 'auto',
|
||||
marginBottom: 'auto',
|
||||
}}>
|
||||
{i18n.t('screens.home.title')}
|
||||
</Title>
|
||||
</View>
|
||||
),
|
||||
}}
|
||||
initialParams={params}
|
||||
/>,
|
||||
{
|
||||
collapsedColor: colors.surface,
|
||||
useNativeDriver: true,
|
||||
},
|
||||
)}
|
||||
<HomeStack.Screen
|
||||
name="scanner"
|
||||
component={ScannerScreen}
|
||||
options={{title: i18n.t('screens.scanner.title')}}
|
||||
/>
|
||||
|
||||
{createScreenCollapsibleStack(
|
||||
"club-information",
|
||||
HomeStack,
|
||||
ClubDisplayScreen,
|
||||
i18n.t('screens.clubs.details'))}
|
||||
{createScreenCollapsibleStack(
|
||||
"feed-information",
|
||||
HomeStack,
|
||||
FeedItemScreen,
|
||||
i18n.t('screens.home.feed'))}
|
||||
{createScreenCollapsibleStack(
|
||||
"planning-information",
|
||||
HomeStack,
|
||||
PlanningDisplayScreen,
|
||||
i18n.t('screens.planning.eventDetails'))}
|
||||
</HomeStack.Navigator>
|
||||
);
|
||||
{createScreenCollapsibleStack(
|
||||
'club-information',
|
||||
HomeStack,
|
||||
ClubDisplayScreen,
|
||||
i18n.t('screens.clubs.details'),
|
||||
)}
|
||||
{createScreenCollapsibleStack(
|
||||
'feed-information',
|
||||
HomeStack,
|
||||
FeedItemScreen,
|
||||
i18n.t('screens.home.feed'),
|
||||
)}
|
||||
{createScreenCollapsibleStack(
|
||||
'planning-information',
|
||||
HomeStack,
|
||||
PlanningDisplayScreen,
|
||||
i18n.t('screens.planning.eventDetails'),
|
||||
)}
|
||||
</HomeStack.Navigator>
|
||||
);
|
||||
}
|
||||
|
||||
const PlanexStack = createStackNavigator();
|
||||
|
||||
function PlanexStackComponent() {
|
||||
return (
|
||||
<PlanexStack.Navigator
|
||||
initialRouteName="index"
|
||||
headerMode={"screen"}
|
||||
screenOptions={defaultScreenOptions}
|
||||
>
|
||||
{getWebsiteStack(
|
||||
"index",
|
||||
PlanexStack,
|
||||
PlanexScreen,
|
||||
i18n.t("screens.planex.title"))}
|
||||
{createScreenCollapsibleStack(
|
||||
"group-select",
|
||||
PlanexStack,
|
||||
GroupSelectionScreen,
|
||||
"")}
|
||||
</PlanexStack.Navigator>
|
||||
);
|
||||
function PlanexStackComponent(): React.Node {
|
||||
return (
|
||||
<PlanexStack.Navigator
|
||||
initialRouteName="index"
|
||||
headerMode="screen"
|
||||
screenOptions={defaultScreenOptions}>
|
||||
{getWebsiteStack(
|
||||
'index',
|
||||
PlanexStack,
|
||||
PlanexScreen,
|
||||
i18n.t('screens.planex.title'),
|
||||
)}
|
||||
{createScreenCollapsibleStack(
|
||||
'group-select',
|
||||
PlanexStack,
|
||||
GroupSelectionScreen,
|
||||
'',
|
||||
)}
|
||||
</PlanexStack.Navigator>
|
||||
);
|
||||
}
|
||||
|
||||
const Tab = createBottomTabNavigator();
|
||||
|
||||
type Props = {
|
||||
defaultHomeRoute: string | null,
|
||||
defaultHomeData: { [key: string]: any }
|
||||
}
|
||||
|
||||
export default class TabNavigator extends React.Component<Props> {
|
||||
|
||||
createHomeStackComponent: () => HomeStackComponent;
|
||||
defaultRoute: string;
|
||||
|
||||
constructor(props) {
|
||||
super(props);
|
||||
if (props.defaultHomeRoute != null)
|
||||
this.defaultRoute = 'home';
|
||||
else
|
||||
this.defaultRoute = AsyncStorageManager.getString(AsyncStorageManager.PREFERENCES.defaultStartScreen.key).toLowerCase();
|
||||
this.createHomeStackComponent = () => HomeStackComponent(props.defaultHomeRoute, props.defaultHomeData);
|
||||
}
|
||||
|
||||
render() {
|
||||
return (
|
||||
<Tab.Navigator
|
||||
initialRouteName={this.defaultRoute}
|
||||
tabBar={props => <CustomTabBar {...props} />}
|
||||
>
|
||||
<Tab.Screen
|
||||
name="services"
|
||||
option
|
||||
component={ServicesStackComponent}
|
||||
options={{title: i18n.t('screens.services.title')}}
|
||||
/>
|
||||
<Tab.Screen
|
||||
name="proxiwash"
|
||||
component={ProxiwashStackComponent}
|
||||
options={{title: i18n.t('screens.proxiwash.title')}}
|
||||
/>
|
||||
<Tab.Screen
|
||||
name="home"
|
||||
component={this.createHomeStackComponent}
|
||||
options={{title: i18n.t('screens.home.title')}}
|
||||
/>
|
||||
<Tab.Screen
|
||||
name="planning"
|
||||
component={PlanningStackComponent}
|
||||
options={{title: i18n.t('screens.planning.title')}}
|
||||
/>
|
||||
|
||||
<Tab.Screen
|
||||
name="planex"
|
||||
component={PlanexStackComponent}
|
||||
options={{title: i18n.t("screens.planex.title")}}
|
||||
/>
|
||||
</Tab.Navigator>
|
||||
);
|
||||
}
|
||||
type PropsType = {
|
||||
defaultHomeRoute: string | null,
|
||||
defaultHomeData: {[key: string]: string},
|
||||
};
|
||||
|
||||
export default class TabNavigator extends React.Component<PropsType> {
|
||||
createHomeStackComponent: () => React.Node;
|
||||
|
||||
defaultRoute: string;
|
||||
|
||||
constructor(props: PropsType) {
|
||||
super(props);
|
||||
if (props.defaultHomeRoute != null) this.defaultRoute = 'home';
|
||||
else
|
||||
this.defaultRoute = AsyncStorageManager.getString(
|
||||
AsyncStorageManager.PREFERENCES.defaultStartScreen.key,
|
||||
).toLowerCase();
|
||||
this.createHomeStackComponent = (): React.Node =>
|
||||
HomeStackComponent(props.defaultHomeRoute, props.defaultHomeData);
|
||||
}
|
||||
|
||||
render(): React.Node {
|
||||
return (
|
||||
<Tab.Navigator
|
||||
initialRouteName={this.defaultRoute}
|
||||
// eslint-disable-next-line react/jsx-props-no-spreading
|
||||
tabBar={(props: {...}): React.Node => <CustomTabBar {...props} />}>
|
||||
<Tab.Screen
|
||||
name="services"
|
||||
option
|
||||
component={ServicesStackComponent}
|
||||
options={{title: i18n.t('screens.services.title')}}
|
||||
/>
|
||||
<Tab.Screen
|
||||
name="proxiwash"
|
||||
component={ProxiwashStackComponent}
|
||||
options={{title: i18n.t('screens.proxiwash.title')}}
|
||||
/>
|
||||
<Tab.Screen
|
||||
name="home"
|
||||
component={this.createHomeStackComponent}
|
||||
options={{title: i18n.t('screens.home.title')}}
|
||||
/>
|
||||
<Tab.Screen
|
||||
name="planning"
|
||||
component={PlanningStackComponent}
|
||||
options={{title: i18n.t('screens.planning.title')}}
|
||||
/>
|
||||
|
||||
<Tab.Screen
|
||||
name="planex"
|
||||
component={PlanexStackComponent}
|
||||
options={{title: i18n.t('screens.planex.title')}}
|
||||
/>
|
||||
</Tab.Navigator>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,36 +1,31 @@
|
|||
// @flow
|
||||
|
||||
import * as React from 'react';
|
||||
import packageJson from '../../../package';
|
||||
import {List} from 'react-native-paper';
|
||||
import {StackNavigationProp} from "@react-navigation/stack";
|
||||
import CollapsibleFlatList from "../../components/Collapsible/CollapsibleFlatList";
|
||||
import {View} from "react-native-animatable";
|
||||
import {View} from 'react-native-animatable';
|
||||
import CollapsibleFlatList from '../../components/Collapsible/CollapsibleFlatList';
|
||||
import packageJson from '../../../package.json';
|
||||
|
||||
type listItem = {
|
||||
name: string,
|
||||
version: string
|
||||
type ListItemType = {
|
||||
name: string,
|
||||
version: string,
|
||||
};
|
||||
|
||||
/**
|
||||
* Generates the dependencies list from the raw json
|
||||
*
|
||||
* @param object The raw json
|
||||
* @return {Array<listItem>}
|
||||
* @return {Array<ListItemType>}
|
||||
*/
|
||||
function generateListFromObject(object: { [key: string]: string }): Array<listItem> {
|
||||
let list = [];
|
||||
let keys = Object.keys(object);
|
||||
let values = Object.values(object);
|
||||
for (let i = 0; i < keys.length; i++) {
|
||||
list.push({name: keys[i], version: values[i]});
|
||||
}
|
||||
//$FlowFixMe
|
||||
return list;
|
||||
}
|
||||
|
||||
type Props = {
|
||||
navigation: StackNavigationProp,
|
||||
function generateListFromObject(object: {
|
||||
[key: string]: string,
|
||||
}): Array<ListItemType> {
|
||||
const list = [];
|
||||
const keys = Object.keys(object);
|
||||
keys.forEach((key: string) => {
|
||||
list.push({name: key, version: object[key]});
|
||||
});
|
||||
return list;
|
||||
}
|
||||
|
||||
const LIST_ITEM_HEIGHT = 64;
|
||||
|
|
@ -38,38 +33,45 @@ const LIST_ITEM_HEIGHT = 64;
|
|||
/**
|
||||
* Class defining a screen showing the list of libraries used by the app, taken from package.json
|
||||
*/
|
||||
export default class AboutDependenciesScreen extends React.Component<Props> {
|
||||
export default class AboutDependenciesScreen extends React.Component<null> {
|
||||
data: Array<ListItemType>;
|
||||
|
||||
data: Array<listItem>;
|
||||
constructor() {
|
||||
super();
|
||||
this.data = generateListFromObject(packageJson.dependencies);
|
||||
}
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
this.data = generateListFromObject(packageJson.dependencies);
|
||||
}
|
||||
keyExtractor = (item: ListItemType): string => item.name;
|
||||
|
||||
keyExtractor = (item: listItem) => item.name;
|
||||
getRenderItem = ({item}: {item: ListItemType}): React.Node => (
|
||||
<List.Item
|
||||
title={item.name}
|
||||
description={item.version.replace('^', '').replace('~', '')}
|
||||
style={{height: LIST_ITEM_HEIGHT}}
|
||||
/>
|
||||
);
|
||||
|
||||
renderItem = ({item}: { item: listItem }) =>
|
||||
<List.Item
|
||||
title={item.name}
|
||||
description={item.version.replace('^', '').replace('~', '')}
|
||||
style={{height: LIST_ITEM_HEIGHT}}
|
||||
/>;
|
||||
getItemLayout = (
|
||||
data: ListItemType,
|
||||
index: number,
|
||||
): {length: number, offset: number, index: number} => ({
|
||||
length: LIST_ITEM_HEIGHT,
|
||||
offset: LIST_ITEM_HEIGHT * index,
|
||||
index,
|
||||
});
|
||||
|
||||
itemLayout = (data: any, index: number) => ({length: LIST_ITEM_HEIGHT, offset: LIST_ITEM_HEIGHT * index, index});
|
||||
|
||||
render() {
|
||||
return (
|
||||
<View>
|
||||
<CollapsibleFlatList
|
||||
data={this.data}
|
||||
keyExtractor={this.keyExtractor}
|
||||
renderItem={this.renderItem}
|
||||
// Performance props, see https://reactnative.dev/docs/optimizing-flatlist-configuration
|
||||
removeClippedSubviews={true}
|
||||
getItemLayout={this.itemLayout}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
render(): React.Node {
|
||||
return (
|
||||
<View>
|
||||
<CollapsibleFlatList
|
||||
data={this.data}
|
||||
keyExtractor={this.keyExtractor}
|
||||
renderItem={this.getRenderItem}
|
||||
// Performance props, see https://reactnative.dev/docs/optimizing-flatlist-configuration
|
||||
removeClippedSubviews
|
||||
getItemLayout={this.getItemLayout}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,351 +1,388 @@
|
|||
// @flow
|
||||
|
||||
import * as React from 'react';
|
||||
import {FlatList, Linking, Platform, View} from 'react-native';
|
||||
import i18n from "i18n-js";
|
||||
import {FlatList, Linking, Platform} from 'react-native';
|
||||
import i18n from 'i18n-js';
|
||||
import {Avatar, Card, List, Title, withTheme} from 'react-native-paper';
|
||||
import packageJson from "../../../package.json";
|
||||
import {StackNavigationProp} from "@react-navigation/stack";
|
||||
import CollapsibleFlatList from "../../components/Collapsible/CollapsibleFlatList";
|
||||
import {StackNavigationProp} from '@react-navigation/stack';
|
||||
import packageJson from '../../../package.json';
|
||||
import CollapsibleFlatList from '../../components/Collapsible/CollapsibleFlatList';
|
||||
import APP_LOGO from '../../../assets/android.icon.png';
|
||||
|
||||
type ListItem = {
|
||||
onPressCallback: () => void,
|
||||
icon: string,
|
||||
text: string,
|
||||
showChevron: boolean
|
||||
type ListItemType = {
|
||||
onPressCallback: () => void,
|
||||
icon: string,
|
||||
text: string,
|
||||
showChevron: boolean,
|
||||
};
|
||||
|
||||
const links = {
|
||||
appstore: 'https://apps.apple.com/us/app/campus-amicale-insat/id1477722148',
|
||||
playstore: 'https://play.google.com/store/apps/details?id=fr.amicaleinsat.application',
|
||||
git: 'https://git.etud.insa-toulouse.fr/vergnet/application-amicale/src/branch/master/README.md',
|
||||
changelog: 'https://git.etud.insa-toulouse.fr/vergnet/application-amicale/src/branch/master/Changelog.md',
|
||||
license: 'https://git.etud.insa-toulouse.fr/vergnet/application-amicale/src/branch/master/LICENSE',
|
||||
authorMail: "mailto:vergnet@etud.insa-toulouse.fr?" +
|
||||
"subject=" +
|
||||
"Application Amicale INSA Toulouse" +
|
||||
"&body=" +
|
||||
"Coucou !\n\n",
|
||||
authorLinkedin: 'https://www.linkedin.com/in/arnaud-vergnet-434ba5179/',
|
||||
yohanMail: "mailto:ysimard@etud.insa-toulouse.fr?" +
|
||||
"subject=" +
|
||||
"Application Amicale INSA Toulouse" +
|
||||
"&body=" +
|
||||
"Coucou !\n\n",
|
||||
yohanLinkedin: 'https://www.linkedin.com/in/yohan-simard',
|
||||
react: 'https://facebook.github.io/react-native/',
|
||||
meme: "https://www.youtube.com/watch?v=dQw4w9WgXcQ"
|
||||
appstore: 'https://apps.apple.com/us/app/campus-amicale-insat/id1477722148',
|
||||
playstore:
|
||||
'https://play.google.com/store/apps/details?id=fr.amicaleinsat.application',
|
||||
git:
|
||||
'https://git.etud.insa-toulouse.fr/vergnet/application-amicale/src/branch/master/README.md',
|
||||
changelog:
|
||||
'https://git.etud.insa-toulouse.fr/vergnet/application-amicale/src/branch/master/Changelog.md',
|
||||
license:
|
||||
'https://git.etud.insa-toulouse.fr/vergnet/application-amicale/src/branch/master/LICENSE',
|
||||
authorMail:
|
||||
'mailto:vergnet@etud.insa-toulouse.fr?' +
|
||||
'subject=' +
|
||||
'Application Amicale INSA Toulouse' +
|
||||
'&body=' +
|
||||
'Coucou !\n\n',
|
||||
authorLinkedin: 'https://www.linkedin.com/in/arnaud-vergnet-434ba5179/',
|
||||
yohanMail:
|
||||
'mailto:ysimard@etud.insa-toulouse.fr?' +
|
||||
'subject=' +
|
||||
'Application Amicale INSA Toulouse' +
|
||||
'&body=' +
|
||||
'Coucou !\n\n',
|
||||
yohanLinkedin: 'https://www.linkedin.com/in/yohan-simard',
|
||||
react: 'https://facebook.github.io/react-native/',
|
||||
meme: 'https://www.youtube.com/watch?v=dQw4w9WgXcQ',
|
||||
};
|
||||
|
||||
type Props = {
|
||||
navigation: StackNavigationProp,
|
||||
type PropsType = {
|
||||
navigation: StackNavigationProp,
|
||||
};
|
||||
|
||||
/**
|
||||
* Opens a link in the device's browser
|
||||
* @param link The link to open
|
||||
*/
|
||||
function openWebLink(link) {
|
||||
Linking.openURL(link).catch((err) => console.error('Error opening link', err));
|
||||
function openWebLink(link: string) {
|
||||
Linking.openURL(link);
|
||||
}
|
||||
|
||||
/**
|
||||
* Class defining an about screen. This screen shows the user information about the app and it's author.
|
||||
*/
|
||||
class AboutScreen extends React.Component<Props> {
|
||||
class AboutScreen extends React.Component<PropsType> {
|
||||
/**
|
||||
* Data to be displayed in the app card
|
||||
*/
|
||||
appData = [
|
||||
{
|
||||
onPressCallback: () => {
|
||||
openWebLink(Platform.OS === 'ios' ? links.appstore : links.playstore);
|
||||
},
|
||||
icon: Platform.OS === 'ios' ? 'apple' : 'google-play',
|
||||
text:
|
||||
Platform.OS === 'ios'
|
||||
? i18n.t('screens.about.appstore')
|
||||
: i18n.t('screens.about.playstore'),
|
||||
showChevron: true,
|
||||
},
|
||||
{
|
||||
onPressCallback: () => {
|
||||
const {navigation} = this.props;
|
||||
navigation.navigate('feedback');
|
||||
},
|
||||
icon: 'bug',
|
||||
text: i18n.t('screens.feedback.homeButtonTitle'),
|
||||
showChevron: true,
|
||||
},
|
||||
{
|
||||
onPressCallback: () => {
|
||||
openWebLink(links.git);
|
||||
},
|
||||
icon: 'git',
|
||||
text: 'Git',
|
||||
showChevron: true,
|
||||
},
|
||||
{
|
||||
onPressCallback: () => {
|
||||
openWebLink(links.changelog);
|
||||
},
|
||||
icon: 'refresh',
|
||||
text: i18n.t('screens.about.changelog'),
|
||||
showChevron: true,
|
||||
},
|
||||
{
|
||||
onPressCallback: () => {
|
||||
openWebLink(links.license);
|
||||
},
|
||||
icon: 'file-document',
|
||||
text: i18n.t('screens.about.license'),
|
||||
showChevron: true,
|
||||
},
|
||||
];
|
||||
|
||||
/**
|
||||
* Data to be displayed in the app card
|
||||
*/
|
||||
appData = [
|
||||
{
|
||||
onPressCallback: () => openWebLink(Platform.OS === "ios" ? links.appstore : links.playstore),
|
||||
icon: Platform.OS === "ios" ? 'apple' : 'google-play',
|
||||
text: Platform.OS === "ios" ? i18n.t('screens.about.appstore') : i18n.t('screens.about.playstore'),
|
||||
showChevron: true
|
||||
},
|
||||
{
|
||||
onPressCallback: () => this.props.navigation.navigate("feedback"),
|
||||
icon: 'bug',
|
||||
text: i18n.t("screens.feedback.homeButtonTitle"),
|
||||
showChevron: true
|
||||
},
|
||||
{
|
||||
onPressCallback: () => openWebLink(links.git),
|
||||
icon: 'git',
|
||||
text: 'Git',
|
||||
showChevron: true
|
||||
},
|
||||
{
|
||||
onPressCallback: () => openWebLink(links.changelog),
|
||||
icon: 'refresh',
|
||||
text: i18n.t('screens.about.changelog'),
|
||||
showChevron: true
|
||||
},
|
||||
{
|
||||
onPressCallback: () => openWebLink(links.license),
|
||||
icon: 'file-document',
|
||||
text: i18n.t('screens.about.license'),
|
||||
showChevron: true
|
||||
},
|
||||
];
|
||||
/**
|
||||
* Data to be displayed in the author card
|
||||
*/
|
||||
authorData = [
|
||||
{
|
||||
onPressCallback: () => openWebLink(links.meme),
|
||||
icon: 'account-circle',
|
||||
text: 'Arnaud VERGNET',
|
||||
showChevron: false
|
||||
},
|
||||
{
|
||||
onPressCallback: () => openWebLink(links.authorMail),
|
||||
icon: 'email',
|
||||
text: i18n.t('screens.about.authorMail'),
|
||||
showChevron: true
|
||||
},
|
||||
{
|
||||
onPressCallback: () => openWebLink(links.authorLinkedin),
|
||||
icon: 'linkedin',
|
||||
text: 'Linkedin',
|
||||
showChevron: true
|
||||
},
|
||||
];
|
||||
/**
|
||||
* Data to be displayed in the additional developer card
|
||||
*/
|
||||
additionalDevData = [
|
||||
{
|
||||
onPressCallback: () => console.log('Meme this'),
|
||||
icon: 'account',
|
||||
text: 'Yohan SIMARD',
|
||||
showChevron: false
|
||||
},
|
||||
{
|
||||
onPressCallback: () => openWebLink(links.yohanMail),
|
||||
icon: 'email',
|
||||
text: i18n.t('screens.about.authorMail'),
|
||||
showChevron: true
|
||||
},
|
||||
{
|
||||
onPressCallback: () => openWebLink(links.yohanLinkedin),
|
||||
icon: 'linkedin',
|
||||
text: 'Linkedin',
|
||||
showChevron: true
|
||||
},
|
||||
];
|
||||
/**
|
||||
* Data to be displayed in the technologies card
|
||||
*/
|
||||
technoData = [
|
||||
{
|
||||
onPressCallback: () => openWebLink(links.react),
|
||||
icon: 'react',
|
||||
text: i18n.t('screens.about.reactNative'),
|
||||
showChevron: true
|
||||
},
|
||||
{
|
||||
onPressCallback: () => this.props.navigation.navigate('dependencies'),
|
||||
icon: 'developer-board',
|
||||
text: i18n.t('screens.about.libs'),
|
||||
showChevron: true
|
||||
},
|
||||
];
|
||||
/**
|
||||
* Order of information cards
|
||||
*/
|
||||
dataOrder = [
|
||||
{
|
||||
id: 'app',
|
||||
},
|
||||
{
|
||||
id: 'team',
|
||||
},
|
||||
{
|
||||
id: 'techno',
|
||||
},
|
||||
];
|
||||
/**
|
||||
* Data to be displayed in the author card
|
||||
*/
|
||||
authorData = [
|
||||
{
|
||||
onPressCallback: () => {
|
||||
openWebLink(links.meme);
|
||||
},
|
||||
icon: 'account-circle',
|
||||
text: 'Arnaud VERGNET',
|
||||
showChevron: false,
|
||||
},
|
||||
{
|
||||
onPressCallback: () => {
|
||||
openWebLink(links.authorMail);
|
||||
},
|
||||
icon: 'email',
|
||||
text: i18n.t('screens.about.authorMail'),
|
||||
showChevron: true,
|
||||
},
|
||||
{
|
||||
onPressCallback: () => {
|
||||
openWebLink(links.authorLinkedin);
|
||||
},
|
||||
icon: 'linkedin',
|
||||
text: 'Linkedin',
|
||||
showChevron: true,
|
||||
},
|
||||
];
|
||||
|
||||
/**
|
||||
* Gets the app icon
|
||||
*
|
||||
* @param props
|
||||
* @return {*}
|
||||
*/
|
||||
getAppIcon(props) {
|
||||
return (
|
||||
/**
|
||||
* Data to be displayed in the additional developer card
|
||||
*/
|
||||
additionalDevData = [
|
||||
{
|
||||
onPressCallback: () => {},
|
||||
icon: 'account',
|
||||
text: 'Yohan SIMARD',
|
||||
showChevron: false,
|
||||
},
|
||||
{
|
||||
onPressCallback: () => {
|
||||
openWebLink(links.yohanMail);
|
||||
},
|
||||
icon: 'email',
|
||||
text: i18n.t('screens.about.authorMail'),
|
||||
showChevron: true,
|
||||
},
|
||||
{
|
||||
onPressCallback: () => {
|
||||
openWebLink(links.yohanLinkedin);
|
||||
},
|
||||
icon: 'linkedin',
|
||||
text: 'Linkedin',
|
||||
showChevron: true,
|
||||
},
|
||||
];
|
||||
|
||||
/**
|
||||
* Data to be displayed in the technologies card
|
||||
*/
|
||||
technoData = [
|
||||
{
|
||||
onPressCallback: () => {
|
||||
openWebLink(links.react);
|
||||
},
|
||||
icon: 'react',
|
||||
text: i18n.t('screens.about.reactNative'),
|
||||
showChevron: true,
|
||||
},
|
||||
{
|
||||
onPressCallback: () => {
|
||||
const {navigation} = this.props;
|
||||
navigation.navigate('dependencies');
|
||||
},
|
||||
icon: 'developer-board',
|
||||
text: i18n.t('screens.about.libs'),
|
||||
showChevron: true,
|
||||
},
|
||||
];
|
||||
|
||||
/**
|
||||
* Order of information cards
|
||||
*/
|
||||
dataOrder = [
|
||||
{
|
||||
id: 'app',
|
||||
},
|
||||
{
|
||||
id: 'team',
|
||||
},
|
||||
{
|
||||
id: 'techno',
|
||||
},
|
||||
];
|
||||
|
||||
/**
|
||||
* Gets the app card showing information and links about the app.
|
||||
*
|
||||
* @return {*}
|
||||
*/
|
||||
getAppCard(): React.Node {
|
||||
return (
|
||||
<Card style={{marginBottom: 10}}>
|
||||
<Card.Title
|
||||
title="Campus"
|
||||
subtitle={packageJson.version}
|
||||
left={({size}: {size: number}): React.Node => (
|
||||
<Avatar.Image
|
||||
{...props}
|
||||
source={require('../../../assets/android.icon.png')}
|
||||
style={{backgroundColor: 'transparent'}}
|
||||
size={size}
|
||||
source={APP_LOGO}
|
||||
style={{backgroundColor: 'transparent'}}
|
||||
/>
|
||||
);
|
||||
)}
|
||||
/>
|
||||
<Card.Content>
|
||||
<FlatList
|
||||
data={this.appData}
|
||||
keyExtractor={this.keyExtractor}
|
||||
renderItem={this.getCardItem}
|
||||
/>
|
||||
</Card.Content>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the team card showing information and links about the team
|
||||
*
|
||||
* @return {*}
|
||||
*/
|
||||
getTeamCard(): React.Node {
|
||||
return (
|
||||
<Card style={{marginBottom: 10}}>
|
||||
<Card.Title
|
||||
title={i18n.t('screens.about.team')}
|
||||
left={({size, color}: {size: number, color: string}): React.Node => (
|
||||
<Avatar.Icon size={size} color={color} icon="account-multiple" />
|
||||
)}
|
||||
/>
|
||||
<Card.Content>
|
||||
<Title>{i18n.t('screens.about.author')}</Title>
|
||||
<FlatList
|
||||
data={this.authorData}
|
||||
keyExtractor={this.keyExtractor}
|
||||
listKey="1"
|
||||
renderItem={this.getCardItem}
|
||||
/>
|
||||
<Title>{i18n.t('screens.about.additionalDev')}</Title>
|
||||
<FlatList
|
||||
data={this.additionalDevData}
|
||||
keyExtractor={this.keyExtractor}
|
||||
listKey="2"
|
||||
renderItem={this.getCardItem}
|
||||
/>
|
||||
</Card.Content>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the techno card showing information and links about the technologies used in the app
|
||||
*
|
||||
* @return {*}
|
||||
*/
|
||||
getTechnoCard(): React.Node {
|
||||
return (
|
||||
<Card style={{marginBottom: 10}}>
|
||||
<Card.Content>
|
||||
<Title>{i18n.t('screens.about.technologies')}</Title>
|
||||
<FlatList
|
||||
data={this.technoData}
|
||||
keyExtractor={this.keyExtractor}
|
||||
renderItem={this.getCardItem}
|
||||
/>
|
||||
</Card.Content>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a chevron icon
|
||||
*
|
||||
* @param props
|
||||
* @return {*}
|
||||
*/
|
||||
static getChevronIcon({
|
||||
size,
|
||||
color,
|
||||
}: {
|
||||
size: number,
|
||||
color: string,
|
||||
}): React.Node {
|
||||
return <List.Icon size={size} color={color} icon="chevron-right" />;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a custom list item icon
|
||||
*
|
||||
* @param item The item to show the icon for
|
||||
* @param props
|
||||
* @return {*}
|
||||
*/
|
||||
static getItemIcon(
|
||||
item: ListItemType,
|
||||
{size, color}: {size: number, color: string},
|
||||
): React.Node {
|
||||
return <List.Icon size={size} color={color} icon={item.icon} />;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a clickable card item to be rendered inside a card.
|
||||
*
|
||||
* @returns {*}
|
||||
*/
|
||||
getCardItem = ({item}: {item: ListItemType}): React.Node => {
|
||||
const getItemIcon = (props: {size: number, color: string}): React.Node =>
|
||||
AboutScreen.getItemIcon(item, props);
|
||||
if (item.showChevron) {
|
||||
return (
|
||||
<List.Item
|
||||
title={item.text}
|
||||
left={getItemIcon}
|
||||
right={AboutScreen.getChevronIcon}
|
||||
onPress={item.onPressCallback}
|
||||
/>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<List.Item
|
||||
title={item.text}
|
||||
left={getItemIcon}
|
||||
onPress={item.onPressCallback}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Extracts a key from the given item
|
||||
*
|
||||
* @param item The item to extract the key from
|
||||
* @return {string} The extracted key
|
||||
*/
|
||||
keyExtractor(item: ListItem): string {
|
||||
return item.icon;
|
||||
/**
|
||||
* Gets a card, depending on the given item's id
|
||||
*
|
||||
* @param item The item to show
|
||||
* @return {*}
|
||||
*/
|
||||
getMainCard = ({item}: {item: {id: string}}): React.Node => {
|
||||
switch (item.id) {
|
||||
case 'app':
|
||||
return this.getAppCard();
|
||||
case 'team':
|
||||
return this.getTeamCard();
|
||||
case 'techno':
|
||||
return this.getTechnoCard();
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Gets the app card showing information and links about the app.
|
||||
*
|
||||
* @return {*}
|
||||
*/
|
||||
getAppCard() {
|
||||
return (
|
||||
<Card style={{marginBottom: 10}}>
|
||||
<Card.Title
|
||||
title={"Campus"}
|
||||
subtitle={packageJson.version}
|
||||
left={this.getAppIcon}/>
|
||||
<Card.Content>
|
||||
<FlatList
|
||||
data={this.appData}
|
||||
keyExtractor={this.keyExtractor}
|
||||
renderItem={this.getCardItem}
|
||||
/>
|
||||
</Card.Content>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
/**
|
||||
* Extracts a key from the given item
|
||||
*
|
||||
* @param item The item to extract the key from
|
||||
* @return {string} The extracted key
|
||||
*/
|
||||
keyExtractor = (item: ListItemType): string => item.icon;
|
||||
|
||||
/**
|
||||
* Gets the team card showing information and links about the team
|
||||
*
|
||||
* @return {*}
|
||||
*/
|
||||
getTeamCard() {
|
||||
return (
|
||||
<Card style={{marginBottom: 10}}>
|
||||
<Card.Title
|
||||
title={i18n.t('screens.about.team')}
|
||||
left={(props) => <Avatar.Icon {...props} icon={'account-multiple'}/>}/>
|
||||
<Card.Content>
|
||||
<Title>{i18n.t('screens.about.author')}</Title>
|
||||
<FlatList
|
||||
data={this.authorData}
|
||||
keyExtractor={this.keyExtractor}
|
||||
listKey={"1"}
|
||||
renderItem={this.getCardItem}
|
||||
/>
|
||||
<Title>{i18n.t('screens.about.additionalDev')}</Title>
|
||||
<FlatList
|
||||
data={this.additionalDevData}
|
||||
keyExtractor={this.keyExtractor}
|
||||
listKey={"2"}
|
||||
renderItem={this.getCardItem}
|
||||
/>
|
||||
</Card.Content>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the techno card showing information and links about the technologies used in the app
|
||||
*
|
||||
* @return {*}
|
||||
*/
|
||||
getTechnoCard() {
|
||||
return (
|
||||
<Card style={{marginBottom: 10}}>
|
||||
<Card.Content>
|
||||
<Title>{i18n.t('screens.about.technologies')}</Title>
|
||||
<FlatList
|
||||
data={this.technoData}
|
||||
keyExtractor={this.keyExtractor}
|
||||
renderItem={this.getCardItem}
|
||||
/>
|
||||
</Card.Content>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a chevron icon
|
||||
*
|
||||
* @param props
|
||||
* @return {*}
|
||||
*/
|
||||
getChevronIcon(props) {
|
||||
return (
|
||||
<List.Icon {...props} icon={'chevron-right'}/>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a custom list item icon
|
||||
*
|
||||
* @param item The item to show the icon for
|
||||
* @param props
|
||||
* @return {*}
|
||||
*/
|
||||
getItemIcon(item: ListItem, props) {
|
||||
return (
|
||||
<List.Icon {...props} icon={item.icon}/>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a clickable card item to be rendered inside a card.
|
||||
*
|
||||
* @returns {*}
|
||||
*/
|
||||
getCardItem = ({item}: { item: ListItem }) => {
|
||||
const getItemIcon = this.getItemIcon.bind(this, item);
|
||||
if (item.showChevron) {
|
||||
return (
|
||||
<List.Item
|
||||
title={item.text}
|
||||
left={getItemIcon}
|
||||
right={this.getChevronIcon}
|
||||
onPress={item.onPressCallback}
|
||||
/>
|
||||
);
|
||||
} else {
|
||||
return (
|
||||
<List.Item
|
||||
title={item.text}
|
||||
left={getItemIcon}
|
||||
onPress={item.onPressCallback}
|
||||
/>
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Gets a card, depending on the given item's id
|
||||
*
|
||||
* @param item The item to show
|
||||
* @return {*}
|
||||
*/
|
||||
getMainCard = ({item}: { item: { id: string } }) => {
|
||||
switch (item.id) {
|
||||
case 'app':
|
||||
return this.getAppCard();
|
||||
case 'team':
|
||||
return this.getTeamCard();
|
||||
case 'techno':
|
||||
return this.getTechnoCard();
|
||||
}
|
||||
return <View/>;
|
||||
};
|
||||
|
||||
render() {
|
||||
return (
|
||||
<CollapsibleFlatList
|
||||
style={{padding: 5}}
|
||||
data={this.dataOrder}
|
||||
renderItem={this.getMainCard}
|
||||
/>
|
||||
);
|
||||
}
|
||||
render(): React.Node {
|
||||
return (
|
||||
<CollapsibleFlatList
|
||||
style={{padding: 5}}
|
||||
data={this.dataOrder}
|
||||
renderItem={this.getMainCard}
|
||||
/>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default withTheme(AboutScreen);
|
||||
|
|
|
|||
|
|
@ -1,183 +1,211 @@
|
|||
// @flow
|
||||
|
||||
import * as React from 'react';
|
||||
import {View} from "react-native";
|
||||
import AsyncStorageManager from "../../managers/AsyncStorageManager";
|
||||
import CustomModal from "../../components/Overrides/CustomModal";
|
||||
import {Button, List, Subheading, TextInput, Title, withTheme} from 'react-native-paper';
|
||||
import {StackNavigationProp} from "@react-navigation/stack";
|
||||
import {Modalize} from "react-native-modalize";
|
||||
import type {CustomTheme} from "../../managers/ThemeManager";
|
||||
import CollapsibleFlatList from "../../components/Collapsible/CollapsibleFlatList";
|
||||
import {View} from 'react-native';
|
||||
import {
|
||||
Button,
|
||||
List,
|
||||
Subheading,
|
||||
TextInput,
|
||||
Title,
|
||||
withTheme,
|
||||
} from 'react-native-paper';
|
||||
import {Modalize} from 'react-native-modalize';
|
||||
import CustomModal from '../../components/Overrides/CustomModal';
|
||||
import AsyncStorageManager from '../../managers/AsyncStorageManager';
|
||||
import type {CustomThemeType} from '../../managers/ThemeManager';
|
||||
import CollapsibleFlatList from '../../components/Collapsible/CollapsibleFlatList';
|
||||
|
||||
type PreferenceItem = {
|
||||
key: string,
|
||||
default: string,
|
||||
current: string,
|
||||
}
|
||||
|
||||
type Props = {
|
||||
navigation: StackNavigationProp,
|
||||
theme: CustomTheme
|
||||
type PreferenceItemType = {
|
||||
key: string,
|
||||
default: string,
|
||||
current: string,
|
||||
};
|
||||
|
||||
type State = {
|
||||
modalCurrentDisplayItem: PreferenceItem,
|
||||
currentPreferences: Array<PreferenceItem>,
|
||||
}
|
||||
type PropsType = {
|
||||
theme: CustomThemeType,
|
||||
};
|
||||
|
||||
type StateType = {
|
||||
modalCurrentDisplayItem: PreferenceItemType,
|
||||
currentPreferences: Array<PreferenceItemType>,
|
||||
};
|
||||
|
||||
/**
|
||||
* Class defining the Debug screen.
|
||||
* This screen allows the user to get and modify information on the app/device.
|
||||
*/
|
||||
class DebugScreen extends React.Component<Props, State> {
|
||||
class DebugScreen extends React.Component<PropsType, StateType> {
|
||||
modalRef: Modalize;
|
||||
|
||||
modalRef: Modalize;
|
||||
modalInputValue: string;
|
||||
modalInputValue: string;
|
||||
|
||||
/**
|
||||
* Copies user preferences to state for easier manipulation
|
||||
*
|
||||
* @param props
|
||||
*/
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.modalInputValue = "";
|
||||
let currentPreferences : Array<PreferenceItem> = [];
|
||||
Object.values(AsyncStorageManager.PREFERENCES).map((object: any) => {
|
||||
let newObject: PreferenceItem = {...object};
|
||||
newObject.current = AsyncStorageManager.getString(newObject.key);
|
||||
currentPreferences.push(newObject);
|
||||
});
|
||||
this.state = {
|
||||
modalCurrentDisplayItem: {},
|
||||
currentPreferences: currentPreferences
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Shows the edit modal
|
||||
*
|
||||
* @param item
|
||||
*/
|
||||
showEditModal(item: PreferenceItem) {
|
||||
this.setState({
|
||||
modalCurrentDisplayItem: item
|
||||
});
|
||||
if (this.modalRef) {
|
||||
this.modalRef.open();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the edit modal content
|
||||
*
|
||||
* @return {*}
|
||||
*/
|
||||
getModalContent() {
|
||||
return (
|
||||
<View style={{
|
||||
flex: 1,
|
||||
padding: 20
|
||||
}}>
|
||||
<Title>{this.state.modalCurrentDisplayItem.key}</Title>
|
||||
<Subheading>Default: {this.state.modalCurrentDisplayItem.default}</Subheading>
|
||||
<Subheading>Current: {this.state.modalCurrentDisplayItem.current}</Subheading>
|
||||
<TextInput
|
||||
label='New Value'
|
||||
onChangeText={(text) => this.modalInputValue = text}
|
||||
/>
|
||||
<View style={{
|
||||
flexDirection: 'row',
|
||||
marginTop: 10,
|
||||
}}>
|
||||
<Button
|
||||
mode="contained"
|
||||
dark={true}
|
||||
color={this.props.theme.colors.success}
|
||||
onPress={() => this.saveNewPrefs(this.state.modalCurrentDisplayItem.key, this.modalInputValue)}>
|
||||
Save new value
|
||||
</Button>
|
||||
<Button
|
||||
mode="contained"
|
||||
dark={true}
|
||||
color={this.props.theme.colors.danger}
|
||||
onPress={() => this.saveNewPrefs(this.state.modalCurrentDisplayItem.key, this.state.modalCurrentDisplayItem.default)}>
|
||||
Reset to default
|
||||
</Button>
|
||||
</View>
|
||||
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds the index of the given key in the preferences array
|
||||
*
|
||||
* @param key THe key to find the index of
|
||||
* @returns {number}
|
||||
*/
|
||||
findIndexOfKey(key: string) {
|
||||
let index = -1;
|
||||
for (let i = 0; i < this.state.currentPreferences.length; i++) {
|
||||
if (this.state.currentPreferences[i].key === key) {
|
||||
index = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return index;
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves the new value of the given preference
|
||||
*
|
||||
* @param key The pref key
|
||||
* @param value The pref value
|
||||
*/
|
||||
saveNewPrefs(key: string, value: string) {
|
||||
this.setState((prevState) => {
|
||||
let currentPreferences = [...prevState.currentPreferences];
|
||||
currentPreferences[this.findIndexOfKey(key)].current = value;
|
||||
return {currentPreferences};
|
||||
});
|
||||
AsyncStorageManager.set(key, value);
|
||||
this.modalRef.close();
|
||||
}
|
||||
|
||||
/**
|
||||
* Callback used when receiving the modal ref
|
||||
*
|
||||
* @param ref
|
||||
*/
|
||||
onModalRef = (ref: Modalize) => {
|
||||
this.modalRef = ref;
|
||||
}
|
||||
|
||||
renderItem = ({item}: {item: PreferenceItem}) => {
|
||||
return (
|
||||
<List.Item
|
||||
title={item.key}
|
||||
description={'Click to edit'}
|
||||
onPress={() => this.showEditModal(item)}
|
||||
/>
|
||||
);
|
||||
/**
|
||||
* Copies user preferences to state for easier manipulation
|
||||
*
|
||||
* @param props
|
||||
*/
|
||||
constructor(props: PropsType) {
|
||||
super(props);
|
||||
this.modalInputValue = '';
|
||||
const currentPreferences: Array<PreferenceItemType> = [];
|
||||
// eslint-disable-next-line flowtype/no-weak-types
|
||||
Object.values(AsyncStorageManager.PREFERENCES).forEach((object: any) => {
|
||||
const newObject: PreferenceItemType = {...object};
|
||||
newObject.current = AsyncStorageManager.getString(newObject.key);
|
||||
currentPreferences.push(newObject);
|
||||
});
|
||||
this.state = {
|
||||
modalCurrentDisplayItem: {},
|
||||
currentPreferences,
|
||||
};
|
||||
}
|
||||
|
||||
render() {
|
||||
return (
|
||||
<View>
|
||||
<CustomModal onRef={this.onModalRef}>
|
||||
{this.getModalContent()}
|
||||
</CustomModal>
|
||||
{/*$FlowFixMe*/}
|
||||
<CollapsibleFlatList
|
||||
data={this.state.currentPreferences}
|
||||
extraData={this.state.currentPreferences}
|
||||
renderItem={this.renderItem}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
/**
|
||||
* Gets the edit modal content
|
||||
*
|
||||
* @return {*}
|
||||
*/
|
||||
getModalContent(): React.Node {
|
||||
const {props, state} = this;
|
||||
return (
|
||||
<View
|
||||
style={{
|
||||
flex: 1,
|
||||
padding: 20,
|
||||
}}>
|
||||
<Title>{state.modalCurrentDisplayItem.key}</Title>
|
||||
<Subheading>
|
||||
Default: {state.modalCurrentDisplayItem.default}
|
||||
</Subheading>
|
||||
<Subheading>
|
||||
Current: {state.modalCurrentDisplayItem.current}
|
||||
</Subheading>
|
||||
<TextInput
|
||||
label="New Value"
|
||||
onChangeText={(text: string) => {
|
||||
this.modalInputValue = text;
|
||||
}}
|
||||
/>
|
||||
<View
|
||||
style={{
|
||||
flexDirection: 'row',
|
||||
marginTop: 10,
|
||||
}}>
|
||||
<Button
|
||||
mode="contained"
|
||||
dark
|
||||
color={props.theme.colors.success}
|
||||
onPress={() => {
|
||||
this.saveNewPrefs(
|
||||
state.modalCurrentDisplayItem.key,
|
||||
this.modalInputValue,
|
||||
);
|
||||
}}>
|
||||
Save new value
|
||||
</Button>
|
||||
<Button
|
||||
mode="contained"
|
||||
dark
|
||||
color={props.theme.colors.danger}
|
||||
onPress={() => {
|
||||
this.saveNewPrefs(
|
||||
state.modalCurrentDisplayItem.key,
|
||||
state.modalCurrentDisplayItem.default,
|
||||
);
|
||||
}}>
|
||||
Reset to default
|
||||
</Button>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
getRenderItem = ({item}: {item: PreferenceItemType}): React.Node => {
|
||||
return (
|
||||
<List.Item
|
||||
title={item.key}
|
||||
description="Click to edit"
|
||||
onPress={() => {
|
||||
this.showEditModal(item);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Callback used when receiving the modal ref
|
||||
*
|
||||
* @param ref
|
||||
*/
|
||||
onModalRef = (ref: Modalize) => {
|
||||
this.modalRef = ref;
|
||||
};
|
||||
|
||||
/**
|
||||
* Shows the edit modal
|
||||
*
|
||||
* @param item
|
||||
*/
|
||||
showEditModal(item: PreferenceItemType) {
|
||||
this.setState({
|
||||
modalCurrentDisplayItem: item,
|
||||
});
|
||||
if (this.modalRef) this.modalRef.open();
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds the index of the given key in the preferences array
|
||||
*
|
||||
* @param key THe key to find the index of
|
||||
* @returns {number}
|
||||
*/
|
||||
findIndexOfKey(key: string): number {
|
||||
const {currentPreferences} = this.state;
|
||||
let index = -1;
|
||||
for (let i = 0; i < currentPreferences.length; i += 1) {
|
||||
if (currentPreferences[i].key === key) {
|
||||
index = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return index;
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves the new value of the given preference
|
||||
*
|
||||
* @param key The pref key
|
||||
* @param value The pref value
|
||||
*/
|
||||
saveNewPrefs(key: string, value: string) {
|
||||
this.setState((prevState: StateType): {
|
||||
currentPreferences: Array<PreferenceItemType>,
|
||||
} => {
|
||||
const currentPreferences = [...prevState.currentPreferences];
|
||||
currentPreferences[this.findIndexOfKey(key)].current = value;
|
||||
return {currentPreferences};
|
||||
});
|
||||
AsyncStorageManager.set(key, value);
|
||||
this.modalRef.close();
|
||||
}
|
||||
|
||||
render(): React.Node {
|
||||
const {state} = this;
|
||||
return (
|
||||
<View>
|
||||
<CustomModal onRef={this.onModalRef}>
|
||||
{this.getModalContent()}
|
||||
</CustomModal>
|
||||
{/* $FlowFixMe */}
|
||||
<CollapsibleFlatList
|
||||
data={state.currentPreferences}
|
||||
extraData={state.currentPreferences}
|
||||
renderItem={this.getRenderItem}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default withTheme(DebugScreen);
|
||||
|
|
|
|||
|
|
@ -4,137 +4,157 @@ import * as React from 'react';
|
|||
import {FlatList, Image, Linking, View} from 'react-native';
|
||||
import {Card, List, Text, withTheme} from 'react-native-paper';
|
||||
import i18n from 'i18n-js';
|
||||
import type {MaterialCommunityIconsGlyphs} from "react-native-vector-icons/MaterialCommunityIcons";
|
||||
import CollapsibleFlatList from "../../components/Collapsible/CollapsibleFlatList";
|
||||
import type {MaterialCommunityIconsGlyphs} from 'react-native-vector-icons/MaterialCommunityIcons';
|
||||
import CollapsibleFlatList from '../../components/Collapsible/CollapsibleFlatList';
|
||||
import AMICALE_LOGO from '../../../assets/amicale.png';
|
||||
|
||||
type Props = {
|
||||
type DatasetItemType = {
|
||||
name: string,
|
||||
email: string,
|
||||
icon: MaterialCommunityIconsGlyphs,
|
||||
};
|
||||
|
||||
type DatasetItem = {
|
||||
name: string,
|
||||
email: string,
|
||||
icon: MaterialCommunityIconsGlyphs,
|
||||
}
|
||||
|
||||
/**
|
||||
* Class defining a planning event information page.
|
||||
*/
|
||||
class AmicaleContactScreen extends React.Component<Props> {
|
||||
class AmicaleContactScreen extends React.Component<null> {
|
||||
// Dataset containing information about contacts
|
||||
CONTACT_DATASET: Array<DatasetItemType>;
|
||||
|
||||
// Dataset containing information about contacts
|
||||
CONTACT_DATASET: Array<DatasetItem>;
|
||||
constructor() {
|
||||
super();
|
||||
this.CONTACT_DATASET = [
|
||||
{
|
||||
name: i18n.t('screens.amicaleAbout.roles.interSchools'),
|
||||
email: 'inter.ecoles@amicale-insat.fr',
|
||||
icon: 'share-variant',
|
||||
},
|
||||
{
|
||||
name: i18n.t('screens.amicaleAbout.roles.culture'),
|
||||
email: 'culture@amicale-insat.fr',
|
||||
icon: 'book',
|
||||
},
|
||||
{
|
||||
name: i18n.t('screens.amicaleAbout.roles.animation'),
|
||||
email: 'animation@amicale-insat.fr',
|
||||
icon: 'emoticon',
|
||||
},
|
||||
{
|
||||
name: i18n.t('screens.amicaleAbout.roles.clubs'),
|
||||
email: 'clubs@amicale-insat.fr',
|
||||
icon: 'account-group',
|
||||
},
|
||||
{
|
||||
name: i18n.t('screens.amicaleAbout.roles.event'),
|
||||
email: 'evenements@amicale-insat.fr',
|
||||
icon: 'calendar-range',
|
||||
},
|
||||
{
|
||||
name: i18n.t('screens.amicaleAbout.roles.tech'),
|
||||
email: 'technique@amicale-insat.fr',
|
||||
icon: 'cog',
|
||||
},
|
||||
{
|
||||
name: i18n.t('screens.amicaleAbout.roles.communication'),
|
||||
email: 'amicale@amicale-insat.fr',
|
||||
icon: 'comment-account',
|
||||
},
|
||||
{
|
||||
name: i18n.t('screens.amicaleAbout.roles.intraSchools'),
|
||||
email: 'intra.ecoles@amicale-insat.fr',
|
||||
icon: 'school',
|
||||
},
|
||||
{
|
||||
name: i18n.t('screens.amicaleAbout.roles.publicRelations'),
|
||||
email: 'rp@amicale-insat.fr',
|
||||
icon: 'account-tie',
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
constructor(props: Props) {
|
||||
super(props);
|
||||
this.CONTACT_DATASET = [
|
||||
{
|
||||
name: i18n.t("screens.amicaleAbout.roles.interSchools"),
|
||||
email: "inter.ecoles@amicale-insat.fr",
|
||||
icon: "share-variant"
|
||||
},
|
||||
{
|
||||
name: i18n.t("screens.amicaleAbout.roles.culture"),
|
||||
email: "culture@amicale-insat.fr",
|
||||
icon: "book"
|
||||
},
|
||||
{
|
||||
name: i18n.t("screens.amicaleAbout.roles.animation"),
|
||||
email: "animation@amicale-insat.fr",
|
||||
icon: "emoticon"
|
||||
},
|
||||
{
|
||||
name: i18n.t("screens.amicaleAbout.roles.clubs"),
|
||||
email: "clubs@amicale-insat.fr",
|
||||
icon: "account-group"
|
||||
},
|
||||
{
|
||||
name: i18n.t("screens.amicaleAbout.roles.event"),
|
||||
email: "evenements@amicale-insat.fr",
|
||||
icon: "calendar-range"
|
||||
},
|
||||
{
|
||||
name: i18n.t("screens.amicaleAbout.roles.tech"),
|
||||
email: "technique@amicale-insat.fr",
|
||||
icon: "cog"
|
||||
},
|
||||
{
|
||||
name: i18n.t("screens.amicaleAbout.roles.communication"),
|
||||
email: "amicale@amicale-insat.fr",
|
||||
icon: "comment-account"
|
||||
},
|
||||
{
|
||||
name: i18n.t("screens.amicaleAbout.roles.intraSchools"),
|
||||
email: "intra.ecoles@amicale-insat.fr",
|
||||
icon: "school"
|
||||
},
|
||||
{
|
||||
name: i18n.t("screens.amicaleAbout.roles.publicRelations"),
|
||||
email: "rp@amicale-insat.fr",
|
||||
icon: "account-tie"
|
||||
},
|
||||
];
|
||||
}
|
||||
keyExtractor = (item: DatasetItemType): string => item.email;
|
||||
|
||||
keyExtractor = (item: DatasetItem) => item.email;
|
||||
getChevronIcon = ({
|
||||
size,
|
||||
color,
|
||||
}: {
|
||||
size: number,
|
||||
color: string,
|
||||
}): React.Node => (
|
||||
<List.Icon size={size} color={color} icon="chevron-right" />
|
||||
);
|
||||
|
||||
getChevronIcon = (props) => <List.Icon {...props} icon={'chevron-right'}/>;
|
||||
|
||||
renderItem = ({item}: { item: DatasetItem }) => {
|
||||
const onPress = () => Linking.openURL('mailto:' + item.email);
|
||||
return <List.Item
|
||||
title={item.name}
|
||||
description={item.email}
|
||||
left={(props) => <List.Icon {...props} icon={item.icon}/>}
|
||||
right={this.getChevronIcon}
|
||||
onPress={onPress}
|
||||
/>
|
||||
getRenderItem = ({item}: {item: DatasetItemType}): React.Node => {
|
||||
const onPress = () => {
|
||||
Linking.openURL(`mailto:${item.email}`);
|
||||
};
|
||||
return (
|
||||
<List.Item
|
||||
title={item.name}
|
||||
description={item.email}
|
||||
left={({size, color}: {size: number, color: string}): React.Node => (
|
||||
<List.Icon size={size} color={color} icon={item.icon} />
|
||||
)}
|
||||
right={this.getChevronIcon}
|
||||
onPress={onPress}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
getScreen = () => {
|
||||
return (
|
||||
<View>
|
||||
<View style={{
|
||||
width: '100%',
|
||||
height: 100,
|
||||
marginTop: 20,
|
||||
marginBottom: 20,
|
||||
justifyContent: 'center',
|
||||
alignItems: 'center'
|
||||
}}>
|
||||
<Image
|
||||
source={require('../../../assets/amicale.png')}
|
||||
style={{flex: 1, resizeMode: "contain"}}
|
||||
resizeMode="contain"/>
|
||||
</View>
|
||||
<Card style={{margin: 5}}>
|
||||
<Card.Title
|
||||
title={i18n.t("screens.amicaleAbout.title")}
|
||||
subtitle={i18n.t("screens.amicaleAbout.subtitle")}
|
||||
left={props => <List.Icon {...props} icon={'information'}/>}
|
||||
/>
|
||||
<Card.Content>
|
||||
<Text>{i18n.t("screens.amicaleAbout.message")}</Text>
|
||||
{/*$FlowFixMe*/}
|
||||
<FlatList
|
||||
data={this.CONTACT_DATASET}
|
||||
keyExtractor={this.keyExtractor}
|
||||
renderItem={this.renderItem}
|
||||
/>
|
||||
</Card.Content>
|
||||
</Card>
|
||||
</View>
|
||||
);
|
||||
};
|
||||
|
||||
render() {
|
||||
return (
|
||||
<CollapsibleFlatList
|
||||
data={[{key: "1"}]}
|
||||
renderItem={this.getScreen}
|
||||
hasTab={true}
|
||||
getScreen = (): React.Node => {
|
||||
return (
|
||||
<View>
|
||||
<View
|
||||
style={{
|
||||
width: '100%',
|
||||
height: 100,
|
||||
marginTop: 20,
|
||||
marginBottom: 20,
|
||||
justifyContent: 'center',
|
||||
alignItems: 'center',
|
||||
}}>
|
||||
<Image
|
||||
source={AMICALE_LOGO}
|
||||
style={{flex: 1, resizeMode: 'contain'}}
|
||||
resizeMode="contain"
|
||||
/>
|
||||
</View>
|
||||
<Card style={{margin: 5}}>
|
||||
<Card.Title
|
||||
title={i18n.t('screens.amicaleAbout.title')}
|
||||
subtitle={i18n.t('screens.amicaleAbout.subtitle')}
|
||||
left={({
|
||||
size,
|
||||
color,
|
||||
}: {
|
||||
size: number,
|
||||
color: string,
|
||||
}): React.Node => (
|
||||
<List.Icon size={size} color={color} icon="information" />
|
||||
)}
|
||||
/>
|
||||
<Card.Content>
|
||||
<Text>{i18n.t('screens.amicaleAbout.message')}</Text>
|
||||
<FlatList
|
||||
data={this.CONTACT_DATASET}
|
||||
keyExtractor={this.keyExtractor}
|
||||
renderItem={this.getRenderItem}
|
||||
/>
|
||||
);
|
||||
}
|
||||
</Card.Content>
|
||||
</Card>
|
||||
</View>
|
||||
);
|
||||
};
|
||||
|
||||
render(): React.Node {
|
||||
return (
|
||||
<CollapsibleFlatList
|
||||
data={[{key: '1'}]}
|
||||
renderItem={this.getScreen}
|
||||
hasTab
|
||||
/>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default withTheme(AmicaleContactScreen);
|
||||
|
|
|
|||
|
|
@ -4,49 +4,49 @@ import * as React from 'react';
|
|||
import {Image, View} from 'react-native';
|
||||
import {Card, List, Text, withTheme} from 'react-native-paper';
|
||||
import i18n from 'i18n-js';
|
||||
import Autolink from "react-native-autolink";
|
||||
import CollapsibleScrollView from "../../../components/Collapsible/CollapsibleScrollView";
|
||||
|
||||
type Props = {};
|
||||
import Autolink from 'react-native-autolink';
|
||||
import CollapsibleScrollView from '../../../components/Collapsible/CollapsibleScrollView';
|
||||
import AMICALE_ICON from '../../../../assets/amicale.png';
|
||||
|
||||
const CONTACT_LINK = 'clubs@amicale-insat.fr';
|
||||
|
||||
class ClubAboutScreen extends React.Component<Props> {
|
||||
|
||||
render() {
|
||||
return (
|
||||
<CollapsibleScrollView style={{padding: 5}}>
|
||||
<View style={{
|
||||
width: '100%',
|
||||
height: 100,
|
||||
marginTop: 20,
|
||||
marginBottom: 20,
|
||||
justifyContent: 'center',
|
||||
alignItems: 'center'
|
||||
}}>
|
||||
<Image
|
||||
source={require('../../../../assets/amicale.png')}
|
||||
style={{flex: 1, resizeMode: "contain"}}
|
||||
resizeMode="contain"/>
|
||||
</View>
|
||||
<Text>{i18n.t("screens.clubs.about.text")}</Text>
|
||||
<Card style={{margin: 5}}>
|
||||
<Card.Title
|
||||
title={i18n.t("screens.clubs.about.title")}
|
||||
subtitle={i18n.t("screens.clubs.about.subtitle")}
|
||||
left={props => <List.Icon {...props} icon={'information'}/>}
|
||||
/>
|
||||
<Card.Content>
|
||||
<Text>{i18n.t("screens.clubs.about.message")}</Text>
|
||||
<Autolink
|
||||
text={CONTACT_LINK}
|
||||
component={Text}
|
||||
/>
|
||||
</Card.Content>
|
||||
</Card>
|
||||
</CollapsibleScrollView>
|
||||
);
|
||||
}
|
||||
// eslint-disable-next-line react/prefer-stateless-function
|
||||
class ClubAboutScreen extends React.Component<null> {
|
||||
render(): React.Node {
|
||||
return (
|
||||
<CollapsibleScrollView style={{padding: 5}}>
|
||||
<View
|
||||
style={{
|
||||
width: '100%',
|
||||
height: 100,
|
||||
marginTop: 20,
|
||||
marginBottom: 20,
|
||||
justifyContent: 'center',
|
||||
alignItems: 'center',
|
||||
}}>
|
||||
<Image
|
||||
source={AMICALE_ICON}
|
||||
style={{flex: 1, resizeMode: 'contain'}}
|
||||
resizeMode="contain"
|
||||
/>
|
||||
</View>
|
||||
<Text>{i18n.t('screens.clubs.about.text')}</Text>
|
||||
<Card style={{margin: 5}}>
|
||||
<Card.Title
|
||||
title={i18n.t('screens.clubs.about.title')}
|
||||
subtitle={i18n.t('screens.clubs.about.subtitle')}
|
||||
left={({size}: {size: number}): React.Node => (
|
||||
<List.Icon size={size} icon="information" />
|
||||
)}
|
||||
/>
|
||||
<Card.Content>
|
||||
<Text>{i18n.t('screens.clubs.about.message')}</Text>
|
||||
<Autolink text={CONTACT_LINK} component={Text} />
|
||||
</Card.Content>
|
||||
</Card>
|
||||
</CollapsibleScrollView>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default withTheme(ClubAboutScreen);
|
||||
|
|
|
|||
|
|
@ -2,252 +2,276 @@
|
|||
|
||||
import * as React from 'react';
|
||||
import {Linking, View} from 'react-native';
|
||||
import {Avatar, Button, Card, Chip, Paragraph, withTheme} from 'react-native-paper';
|
||||
import {
|
||||
Avatar,
|
||||
Button,
|
||||
Card,
|
||||
Chip,
|
||||
Paragraph,
|
||||
withTheme,
|
||||
} from 'react-native-paper';
|
||||
import ImageModal from 'react-native-image-modal';
|
||||
import i18n from "i18n-js";
|
||||
import AuthenticatedScreen from "../../../components/Amicale/AuthenticatedScreen";
|
||||
import CustomHTML from "../../../components/Overrides/CustomHTML";
|
||||
import CustomTabBar from "../../../components/Tabbar/CustomTabBar";
|
||||
import type {category, club} from "./ClubListScreen";
|
||||
import type {CustomTheme} from "../../../managers/ThemeManager";
|
||||
import {StackNavigationProp} from "@react-navigation/stack";
|
||||
import {ERROR_TYPE} from "../../../utils/WebData";
|
||||
import CollapsibleScrollView from "../../../components/Collapsible/CollapsibleScrollView";
|
||||
import i18n from 'i18n-js';
|
||||
import {StackNavigationProp} from '@react-navigation/stack';
|
||||
import AuthenticatedScreen from '../../../components/Amicale/AuthenticatedScreen';
|
||||
import CustomHTML from '../../../components/Overrides/CustomHTML';
|
||||
import CustomTabBar from '../../../components/Tabbar/CustomTabBar';
|
||||
import type {ClubCategoryType, ClubType} from './ClubListScreen';
|
||||
import type {CustomThemeType} from '../../../managers/ThemeManager';
|
||||
import {ERROR_TYPE} from '../../../utils/WebData';
|
||||
import CollapsibleScrollView from '../../../components/Collapsible/CollapsibleScrollView';
|
||||
import type {ApiGenericDataType} from '../../../utils/WebData';
|
||||
|
||||
type Props = {
|
||||
navigation: StackNavigationProp,
|
||||
route: {
|
||||
params?: {
|
||||
data?: club,
|
||||
categories?: Array<category>,
|
||||
clubId?: number,
|
||||
}, ...
|
||||
type PropsType = {
|
||||
navigation: StackNavigationProp,
|
||||
route: {
|
||||
params?: {
|
||||
data?: ClubType,
|
||||
categories?: Array<ClubCategoryType>,
|
||||
clubId?: number,
|
||||
},
|
||||
theme: CustomTheme
|
||||
...
|
||||
},
|
||||
theme: CustomThemeType,
|
||||
};
|
||||
|
||||
type State = {
|
||||
imageModalVisible: boolean,
|
||||
};
|
||||
|
||||
const AMICALE_MAIL = "clubs@amicale-insat.fr";
|
||||
const AMICALE_MAIL = 'clubs@amicale-insat.fr';
|
||||
|
||||
/**
|
||||
* 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 clubId parameter, will fetch the information on the server
|
||||
*/
|
||||
class ClubDisplayScreen extends React.Component<Props, State> {
|
||||
class ClubDisplayScreen extends React.Component<PropsType> {
|
||||
displayData: ClubType | null;
|
||||
|
||||
displayData: club | null;
|
||||
categories: Array<category> | null;
|
||||
clubId: number;
|
||||
categories: Array<ClubCategoryType> | null;
|
||||
|
||||
shouldFetchData: boolean;
|
||||
clubId: number;
|
||||
|
||||
state = {
|
||||
imageModalVisible: false,
|
||||
};
|
||||
shouldFetchData: boolean;
|
||||
|
||||
constructor(props) {
|
||||
super(props);
|
||||
if (this.props.route.params != null) {
|
||||
if (this.props.route.params.data != null && this.props.route.params.categories != null) {
|
||||
this.displayData = this.props.route.params.data;
|
||||
this.categories = this.props.route.params.categories;
|
||||
this.clubId = this.props.route.params.data.id;
|
||||
this.shouldFetchData = false;
|
||||
} else if (this.props.route.params.clubId != null) {
|
||||
this.displayData = null;
|
||||
this.categories = null;
|
||||
this.clubId = this.props.route.params.clubId;
|
||||
this.shouldFetchData = true;
|
||||
}
|
||||
}
|
||||
constructor(props: PropsType) {
|
||||
super(props);
|
||||
if (props.route.params != null) {
|
||||
if (
|
||||
props.route.params.data != null &&
|
||||
props.route.params.categories != null
|
||||
) {
|
||||
this.displayData = props.route.params.data;
|
||||
this.categories = props.route.params.categories;
|
||||
this.clubId = props.route.params.data.id;
|
||||
this.shouldFetchData = false;
|
||||
} else if (props.route.params.clubId != null) {
|
||||
this.displayData = null;
|
||||
this.categories = null;
|
||||
this.clubId = props.route.params.clubId;
|
||||
this.shouldFetchData = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the name of the category with the given ID
|
||||
*
|
||||
* @param id The category's ID
|
||||
* @returns {string|*}
|
||||
*/
|
||||
getCategoryName(id: number) {
|
||||
if (this.categories !== null) {
|
||||
for (let i = 0; i < this.categories.length; i++) {
|
||||
if (id === this.categories[i].id)
|
||||
return this.categories[i].name;
|
||||
}
|
||||
}
|
||||
return "";
|
||||
/**
|
||||
* Gets the name of the category with the given ID
|
||||
*
|
||||
* @param id The category's ID
|
||||
* @returns {string|*}
|
||||
*/
|
||||
getCategoryName(id: number): string {
|
||||
let categoryName = '';
|
||||
if (this.categories !== null) {
|
||||
this.categories.forEach((item: ClubCategoryType) => {
|
||||
if (id === item.id) categoryName = item.name;
|
||||
});
|
||||
}
|
||||
return categoryName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the view for rendering categories
|
||||
*
|
||||
* @param categories The categories to display (max 2)
|
||||
* @returns {null|*}
|
||||
*/
|
||||
getCategoriesRender(categories: [number, number]) {
|
||||
if (this.categories === null)
|
||||
return null;
|
||||
/**
|
||||
* Gets the view for rendering categories
|
||||
*
|
||||
* @param categories The categories to display (max 2)
|
||||
* @returns {null|*}
|
||||
*/
|
||||
getCategoriesRender(categories: Array<number | null>): React.Node {
|
||||
if (this.categories == null) return null;
|
||||
|
||||
let final = [];
|
||||
for (let i = 0; i < categories.length; i++) {
|
||||
let cat = categories[i];
|
||||
if (cat !== null) {
|
||||
final.push(
|
||||
<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>
|
||||
const final = [];
|
||||
categories.forEach((cat: number | null) => {
|
||||
if (cat != null) {
|
||||
final.push(
|
||||
<Chip style={{marginRight: 5}} key={cat}>
|
||||
{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): 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 />
|
||||
)}
|
||||
|
||||
/**
|
||||
* 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 {*}
|
||||
*/
|
||||
getEmailButton(email: string | null, hasManagers: boolean) {
|
||||
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>
|
||||
);
|
||||
{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>
|
||||
);
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Updates the header title to match the given club
|
||||
*
|
||||
* @param data The club data
|
||||
*/
|
||||
updateHeaderTitle(data: club) {
|
||||
this.props.navigation.setOptions({title: data.name})
|
||||
}
|
||||
/**
|
||||
* Updates the header title to match the given club
|
||||
*
|
||||
* @param data The club data
|
||||
*/
|
||||
updateHeaderTitle(data: ClubType) {
|
||||
const {props} = this;
|
||||
props.navigation.setOptions({title: data.name});
|
||||
}
|
||||
|
||||
getScreen = (response: Array<{ [key: string]: any } | null>) => {
|
||||
let data: club | null = null;
|
||||
if (response[0] != null) {
|
||||
data = response[0];
|
||||
this.updateHeaderTitle(data);
|
||||
}
|
||||
if (data != null) {
|
||||
return (
|
||||
<CollapsibleScrollView
|
||||
style={{paddingLeft: 5, paddingRight: 5}}
|
||||
hasTab={true}
|
||||
>
|
||||
{this.getCategoriesRender(data.category)}
|
||||
{data.logo !== null ?
|
||||
<View style={{
|
||||
marginLeft: 'auto',
|
||||
marginRight: 'auto',
|
||||
marginTop: 10,
|
||||
marginBottom: 10,
|
||||
}}>
|
||||
<ImageModal
|
||||
resizeMode="contain"
|
||||
imageBackgroundColor={this.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
|
||||
<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]);
|
||||
}
|
||||
render(): React.Node {
|
||||
const {props} = this;
|
||||
if (this.shouldFetchData)
|
||||
return (
|
||||
<AuthenticatedScreen
|
||||
navigation={props.navigation}
|
||||
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,
|
||||
},
|
||||
]}
|
||||
/>
|
||||
);
|
||||
return this.getScreen([this.displayData]);
|
||||
}
|
||||
}
|
||||
|
||||
export default withTheme(ClubDisplayScreen);
|
||||
|
|
|
|||
|
|
@ -1,237 +1,271 @@
|
|||
// @flow
|
||||
|
||||
import * as React from 'react';
|
||||
import {Platform} from "react-native";
|
||||
import {Platform} from 'react-native';
|
||||
import {Searchbar} from 'react-native-paper';
|
||||
import AuthenticatedScreen from "../../../components/Amicale/AuthenticatedScreen";
|
||||
import i18n from "i18n-js";
|
||||
import ClubListItem from "../../../components/Lists/Clubs/ClubListItem";
|
||||
import {isItemInCategoryFilter, stringMatchQuery} from "../../../utils/Search";
|
||||
import ClubListHeader from "../../../components/Lists/Clubs/ClubListHeader";
|
||||
import MaterialHeaderButtons, {Item} from "../../../components/Overrides/CustomHeaderButton";
|
||||
import {StackNavigationProp} from "@react-navigation/stack";
|
||||
import type {CustomTheme} from "../../../managers/ThemeManager";
|
||||
import CollapsibleFlatList from "../../../components/Collapsible/CollapsibleFlatList";
|
||||
import i18n from 'i18n-js';
|
||||
import {StackNavigationProp} from '@react-navigation/stack';
|
||||
import AuthenticatedScreen from '../../../components/Amicale/AuthenticatedScreen';
|
||||
import ClubListItem from '../../../components/Lists/Clubs/ClubListItem';
|
||||
import {isItemInCategoryFilter, stringMatchQuery} from '../../../utils/Search';
|
||||
import ClubListHeader from '../../../components/Lists/Clubs/ClubListHeader';
|
||||
import MaterialHeaderButtons, {
|
||||
Item,
|
||||
} from '../../../components/Overrides/CustomHeaderButton';
|
||||
import CollapsibleFlatList from '../../../components/Collapsible/CollapsibleFlatList';
|
||||
|
||||
export type category = {
|
||||
id: number,
|
||||
name: string,
|
||||
export type ClubCategoryType = {
|
||||
id: number,
|
||||
name: string,
|
||||
};
|
||||
|
||||
export type club = {
|
||||
id: number,
|
||||
name: string,
|
||||
description: string,
|
||||
logo: string,
|
||||
email: string | null,
|
||||
category: [number, number],
|
||||
responsibles: Array<string>,
|
||||
export type ClubType = {
|
||||
id: number,
|
||||
name: string,
|
||||
description: string,
|
||||
logo: string,
|
||||
email: string | null,
|
||||
category: Array<number | null>,
|
||||
responsibles: Array<string>,
|
||||
};
|
||||
|
||||
type Props = {
|
||||
navigation: StackNavigationProp,
|
||||
theme: CustomTheme,
|
||||
}
|
||||
type PropsType = {
|
||||
navigation: StackNavigationProp,
|
||||
};
|
||||
|
||||
type State = {
|
||||
currentlySelectedCategories: Array<number>,
|
||||
currentSearchString: string,
|
||||
}
|
||||
type StateType = {
|
||||
currentlySelectedCategories: Array<number>,
|
||||
currentSearchString: string,
|
||||
};
|
||||
|
||||
const LIST_ITEM_HEIGHT = 96;
|
||||
|
||||
class ClubListScreen extends React.Component<Props, State> {
|
||||
class ClubListScreen extends React.Component<PropsType, StateType> {
|
||||
categories: Array<ClubCategoryType>;
|
||||
|
||||
state = {
|
||||
currentlySelectedCategories: [],
|
||||
currentSearchString: '',
|
||||
constructor() {
|
||||
super();
|
||||
this.state = {
|
||||
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},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the header content
|
||||
*/
|
||||
componentDidMount() {
|
||||
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.
|
||||
* It opens the modal to show detailed information about the article
|
||||
*
|
||||
* @param item The article pressed
|
||||
*/
|
||||
onListItemPress(item: ClubType) {
|
||||
const {props} = this;
|
||||
props.navigation.navigate('club-information', {
|
||||
data: item,
|
||||
categories: this.categories,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Callback used when the search changes
|
||||
*
|
||||
* @param str The new search string
|
||||
*/
|
||||
onSearchStringChange = (str: string) => {
|
||||
this.updateFilteredData(str, null);
|
||||
};
|
||||
|
||||
/**
|
||||
* 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<{
|
||||
categories: Array<ClubCategoryType>,
|
||||
clubs: Array<ClubType>,
|
||||
} | null>,
|
||||
): React.Node => {
|
||||
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
|
||||
getItemLayout={this.itemLayout}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Gets the header search bar
|
||||
*
|
||||
* @return {*}
|
||||
*/
|
||||
getSearchBar = () => {
|
||||
return (
|
||||
<Searchbar
|
||||
placeholder={i18n.t('screens.proximo.search')}
|
||||
onChangeText={this.onSearchStringChange}
|
||||
/>
|
||||
);
|
||||
/**
|
||||
* 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);
|
||||
};
|
||||
|
||||
/**
|
||||
* Gets the header button
|
||||
* @return {*}
|
||||
*/
|
||||
getHeaderButtons = () => {
|
||||
const onPress = () => this.props.navigation.navigate("club-about");
|
||||
return <MaterialHeaderButtons>
|
||||
<Item title="main" iconName="information" onPress={onPress}/>
|
||||
</MaterialHeaderButtons>;
|
||||
};
|
||||
|
||||
/**
|
||||
* Callback used when the search changes
|
||||
*
|
||||
* @param str The new search string
|
||||
*/
|
||||
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,
|
||||
})
|
||||
if (this.shouldRenderItem(item)) {
|
||||
return (
|
||||
<ClubListItem
|
||||
categoryTranslator={this.getCategoryOfId}
|
||||
item={item}
|
||||
onPress={onPress}
|
||||
height={LIST_ITEM_HEIGHT}
|
||||
/>
|
||||
);
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Gets the list header, with controls to change the categories filter
|
||||
*
|
||||
* @returns {*}
|
||||
*/
|
||||
getListHeader() {
|
||||
return <ClubListHeader
|
||||
categories={this.categories}
|
||||
selectedCategories={this.state.currentlySelectedCategories}
|
||||
onChipSelect={this.onChipSelect}
|
||||
/>;
|
||||
keyExtractor = (item: ClubType): string => item.id.toString();
|
||||
|
||||
itemLayout = (
|
||||
data: {...},
|
||||
index: number,
|
||||
): {length: number, offset: number, index: number} => ({
|
||||
length: LIST_ITEM_HEIGHT,
|
||||
offset: LIST_ITEM_HEIGHT * index,
|
||||
index,
|
||||
});
|
||||
|
||||
/**
|
||||
* 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,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the category object of the given ID
|
||||
*
|
||||
* @param id The ID of the category to find
|
||||
* @returns {*}
|
||||
*/
|
||||
getCategoryOfId = (id: number) => {
|
||||
for (let i = 0; i < this.categories.length; i++) {
|
||||
if (id === this.categories[i].id)
|
||||
return this.categories[i];
|
||||
}
|
||||
};
|
||||
/**
|
||||
* Checks if the given item should be rendered according to current name and category filters
|
||||
*
|
||||
* @param item The club to check
|
||||
* @returns {boolean}
|
||||
*/
|
||||
shouldRenderItem(item: ClubType): boolean {
|
||||
const {state} = this;
|
||||
let shouldRender =
|
||||
state.currentlySelectedCategories.length === 0 ||
|
||||
isItemInCategoryFilter(state.currentlySelectedCategories, item.category);
|
||||
if (shouldRender)
|
||||
shouldRender = stringMatchQuery(item.name, state.currentSearchString);
|
||||
return shouldRender;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the given item should be rendered according to current name and category filters
|
||||
*
|
||||
* @param item The club to check
|
||||
* @returns {boolean}
|
||||
*/
|
||||
shouldRenderItem(item: club) {
|
||||
let shouldRender = this.state.currentlySelectedCategories.length === 0
|
||||
|| isItemInCategoryFilter(this.state.currentlySelectedCategories, item.category);
|
||||
if (shouldRender)
|
||||
shouldRender = stringMatchQuery(item.name, this.state.currentSearchString);
|
||||
return shouldRender;
|
||||
}
|
||||
|
||||
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}
|
||||
/>
|
||||
);
|
||||
}
|
||||
render(): React.Node {
|
||||
const {props} = this;
|
||||
return (
|
||||
<AuthenticatedScreen
|
||||
navigation={props.navigation}
|
||||
requests={[
|
||||
{
|
||||
link: 'clubs/list',
|
||||
params: {},
|
||||
mandatory: true,
|
||||
},
|
||||
]}
|
||||
renderFunction={this.getScreen}
|
||||
/>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default ClubListScreen;
|
||||
|
|
|
|||
|
|
@ -1,105 +1,102 @@
|
|||
// @flow
|
||||
|
||||
import * as React from 'react';
|
||||
import {Button, Caption, Card, Headline, Paragraph, withTheme} from 'react-native-paper';
|
||||
import {StackNavigationProp} from "@react-navigation/stack";
|
||||
import type {CustomTheme} from "../../../managers/ThemeManager";
|
||||
import type {Device} from "./EquipmentListScreen";
|
||||
import {View} from "react-native";
|
||||
import i18n from "i18n-js";
|
||||
import {getRelativeDateString} from "../../../utils/EquipmentBooking";
|
||||
import CollapsibleScrollView from "../../../components/Collapsible/CollapsibleScrollView";
|
||||
import {
|
||||
Button,
|
||||
Caption,
|
||||
Card,
|
||||
Headline,
|
||||
Paragraph,
|
||||
withTheme,
|
||||
} from 'react-native-paper';
|
||||
import {View} from 'react-native';
|
||||
import i18n from 'i18n-js';
|
||||
import type {CustomThemeType} from '../../../managers/ThemeManager';
|
||||
import type {DeviceType} from './EquipmentListScreen';
|
||||
import {getRelativeDateString} from '../../../utils/EquipmentBooking';
|
||||
import CollapsibleScrollView from '../../../components/Collapsible/CollapsibleScrollView';
|
||||
|
||||
type Props = {
|
||||
navigation: StackNavigationProp,
|
||||
route: {
|
||||
params?: {
|
||||
item?: Device,
|
||||
dates: [string, string]
|
||||
},
|
||||
type PropsType = {
|
||||
route: {
|
||||
params?: {
|
||||
item?: DeviceType,
|
||||
dates: [string, string],
|
||||
},
|
||||
theme: CustomTheme,
|
||||
}
|
||||
},
|
||||
theme: CustomThemeType,
|
||||
};
|
||||
|
||||
class EquipmentConfirmScreen extends React.Component<PropsType> {
|
||||
item: DeviceType | null;
|
||||
|
||||
class EquipmentConfirmScreen extends React.Component<Props> {
|
||||
dates: [string, string] | null;
|
||||
|
||||
item: Device | null;
|
||||
dates: [string, string] | null;
|
||||
|
||||
constructor(props: Props) {
|
||||
super(props);
|
||||
if (this.props.route.params != null) {
|
||||
if (this.props.route.params.item != null)
|
||||
this.item = this.props.route.params.item;
|
||||
else
|
||||
this.item = null;
|
||||
if (this.props.route.params.dates != null)
|
||||
this.dates = this.props.route.params.dates;
|
||||
else
|
||||
this.dates = null;
|
||||
}
|
||||
constructor(props: PropsType) {
|
||||
super(props);
|
||||
if (props.route.params != null) {
|
||||
if (props.route.params.item != null) this.item = props.route.params.item;
|
||||
else this.item = null;
|
||||
if (props.route.params.dates != null)
|
||||
this.dates = props.route.params.dates;
|
||||
else this.dates = null;
|
||||
}
|
||||
}
|
||||
|
||||
render() {
|
||||
const item = this.item;
|
||||
const dates = this.dates;
|
||||
if (item != null && dates != null) {
|
||||
const start = new Date(dates[0]);
|
||||
const end = new Date(dates[1]);
|
||||
return (
|
||||
<CollapsibleScrollView>
|
||||
<Card style={{margin: 5}}>
|
||||
<Card.Content>
|
||||
<View style={{flex: 1}}>
|
||||
<View style={{
|
||||
marginLeft: "auto",
|
||||
marginRight: "auto",
|
||||
flexDirection: "row",
|
||||
flexWrap: "wrap",
|
||||
}}>
|
||||
<Headline style={{textAlign: "center"}}>
|
||||
{item.name}
|
||||
</Headline>
|
||||
<Caption style={{
|
||||
textAlign: "center",
|
||||
lineHeight: 35,
|
||||
marginLeft: 10,
|
||||
}}>
|
||||
({i18n.t('screens.equipment.bail', {cost: item.caution})})
|
||||
</Caption>
|
||||
</View>
|
||||
</View>
|
||||
<Button
|
||||
icon={"check-circle-outline"}
|
||||
color={this.props.theme.colors.success}
|
||||
mode="text"
|
||||
>
|
||||
{
|
||||
start == null
|
||||
? i18n.t('screens.equipment.booking')
|
||||
: end != null && start.getTime() !== end.getTime()
|
||||
? i18n.t('screens.equipment.bookingPeriod', {
|
||||
begin: getRelativeDateString(start),
|
||||
end: getRelativeDateString(end)
|
||||
})
|
||||
: i18n.t('screens.equipment.bookingDay', {
|
||||
date: getRelativeDateString(start)
|
||||
})
|
||||
}
|
||||
</Button>
|
||||
<Paragraph style={{textAlign: "center"}}>
|
||||
{i18n.t("screens.equipment.bookingConfirmedMessage")}
|
||||
</Paragraph>
|
||||
</Card.Content>
|
||||
</Card>
|
||||
</CollapsibleScrollView>
|
||||
);
|
||||
} else
|
||||
return null;
|
||||
|
||||
render(): React.Node {
|
||||
const {item, dates, props} = this;
|
||||
if (item != null && dates != null) {
|
||||
const start = new Date(dates[0]);
|
||||
const end = new Date(dates[1]);
|
||||
let buttonText;
|
||||
if (start == null) buttonText = i18n.t('screens.equipment.booking');
|
||||
else if (end != null && start.getTime() !== end.getTime())
|
||||
buttonText = i18n.t('screens.equipment.bookingPeriod', {
|
||||
begin: getRelativeDateString(start),
|
||||
end: getRelativeDateString(end),
|
||||
});
|
||||
else
|
||||
buttonText = i18n.t('screens.equipment.bookingDay', {
|
||||
date: getRelativeDateString(start),
|
||||
});
|
||||
return (
|
||||
<CollapsibleScrollView>
|
||||
<Card style={{margin: 5}}>
|
||||
<Card.Content>
|
||||
<View style={{flex: 1}}>
|
||||
<View
|
||||
style={{
|
||||
marginLeft: 'auto',
|
||||
marginRight: 'auto',
|
||||
flexDirection: 'row',
|
||||
flexWrap: 'wrap',
|
||||
}}>
|
||||
<Headline style={{textAlign: 'center'}}>{item.name}</Headline>
|
||||
<Caption
|
||||
style={{
|
||||
textAlign: 'center',
|
||||
lineHeight: 35,
|
||||
marginLeft: 10,
|
||||
}}>
|
||||
({i18n.t('screens.equipment.bail', {cost: item.caution})})
|
||||
</Caption>
|
||||
</View>
|
||||
</View>
|
||||
<Button
|
||||
icon="check-circle-outline"
|
||||
color={props.theme.colors.success}
|
||||
mode="text">
|
||||
{buttonText}
|
||||
</Button>
|
||||
<Paragraph style={{textAlign: 'center'}}>
|
||||
{i18n.t('screens.equipment.bookingConfirmedMessage')}
|
||||
</Paragraph>
|
||||
</Card.Content>
|
||||
</Card>
|
||||
</CollapsibleScrollView>
|
||||
);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export default withTheme(EquipmentConfirmScreen);
|
||||
|
|
|
|||
|
|
@ -1,193 +1,197 @@
|
|||
// @flow
|
||||
|
||||
import * as React from 'react';
|
||||
import {View} from "react-native";
|
||||
import {View} from 'react-native';
|
||||
import {Button, withTheme} from 'react-native-paper';
|
||||
import AuthenticatedScreen from "../../../components/Amicale/AuthenticatedScreen";
|
||||
import {StackNavigationProp} from "@react-navigation/stack";
|
||||
import type {CustomTheme} from "../../../managers/ThemeManager";
|
||||
import i18n from "i18n-js";
|
||||
import type {club} from "../Clubs/ClubListScreen";
|
||||
import EquipmentListItem from "../../../components/Lists/Equipment/EquipmentListItem";
|
||||
import MascotPopup from "../../../components/Mascot/MascotPopup";
|
||||
import {MASCOT_STYLE} from "../../../components/Mascot/Mascot";
|
||||
import AsyncStorageManager from "../../../managers/AsyncStorageManager";
|
||||
import CollapsibleFlatList from "../../../components/Collapsible/CollapsibleFlatList";
|
||||
import {StackNavigationProp} from '@react-navigation/stack';
|
||||
import i18n from 'i18n-js';
|
||||
import AuthenticatedScreen from '../../../components/Amicale/AuthenticatedScreen';
|
||||
import type {ClubType} from '../Clubs/ClubListScreen';
|
||||
import EquipmentListItem from '../../../components/Lists/Equipment/EquipmentListItem';
|
||||
import MascotPopup from '../../../components/Mascot/MascotPopup';
|
||||
import {MASCOT_STYLE} from '../../../components/Mascot/Mascot';
|
||||
import AsyncStorageManager from '../../../managers/AsyncStorageManager';
|
||||
import CollapsibleFlatList from '../../../components/Collapsible/CollapsibleFlatList';
|
||||
import type {ApiGenericDataType} from '../../../utils/WebData';
|
||||
|
||||
type Props = {
|
||||
navigation: StackNavigationProp,
|
||||
theme: CustomTheme,
|
||||
}
|
||||
|
||||
type State = {
|
||||
mascotDialogVisible: boolean,
|
||||
}
|
||||
|
||||
export type Device = {
|
||||
id: number,
|
||||
name: string,
|
||||
caution: number,
|
||||
booked_at: Array<{ begin: string, end: string }>,
|
||||
type PropsType = {
|
||||
navigation: StackNavigationProp,
|
||||
};
|
||||
|
||||
export type RentedDevice = {
|
||||
device_id: number,
|
||||
device_name: string,
|
||||
begin: string,
|
||||
end: string,
|
||||
}
|
||||
type StateType = {
|
||||
mascotDialogVisible: boolean,
|
||||
};
|
||||
|
||||
export type DeviceType = {
|
||||
id: number,
|
||||
name: string,
|
||||
caution: number,
|
||||
booked_at: Array<{begin: string, end: string}>,
|
||||
};
|
||||
|
||||
export type RentedDeviceType = {
|
||||
device_id: number,
|
||||
device_name: string,
|
||||
begin: string,
|
||||
end: string,
|
||||
};
|
||||
|
||||
const LIST_ITEM_HEIGHT = 64;
|
||||
|
||||
class EquipmentListScreen extends React.Component<Props, State> {
|
||||
class EquipmentListScreen extends React.Component<PropsType, StateType> {
|
||||
data: Array<DeviceType>;
|
||||
|
||||
state = {
|
||||
mascotDialogVisible: AsyncStorageManager.getBool(AsyncStorageManager.PREFERENCES.equipmentShowBanner.key),
|
||||
}
|
||||
userRents: Array<RentedDeviceType>;
|
||||
|
||||
data: Array<Device>;
|
||||
userRents: Array<RentedDevice>;
|
||||
authRef: {current: null | AuthenticatedScreen};
|
||||
|
||||
authRef: { current: null | AuthenticatedScreen };
|
||||
canRefresh: boolean;
|
||||
canRefresh: boolean;
|
||||
|
||||
constructor(props: Props) {
|
||||
super(props);
|
||||
this.canRefresh = false;
|
||||
this.authRef = React.createRef();
|
||||
this.props.navigation.addListener('focus', this.onScreenFocus);
|
||||
}
|
||||
|
||||
onScreenFocus = () => {
|
||||
if (this.canRefresh && this.authRef.current != null)
|
||||
this.authRef.current.reload();
|
||||
this.canRefresh = true;
|
||||
constructor(props: PropsType) {
|
||||
super(props);
|
||||
this.state = {
|
||||
mascotDialogVisible: AsyncStorageManager.getBool(
|
||||
AsyncStorageManager.PREFERENCES.equipmentShowBanner.key,
|
||||
),
|
||||
};
|
||||
this.canRefresh = false;
|
||||
this.authRef = React.createRef();
|
||||
props.navigation.addListener('focus', this.onScreenFocus);
|
||||
}
|
||||
|
||||
getRenderItem = ({item}: { item: Device }) => {
|
||||
return (
|
||||
<EquipmentListItem
|
||||
navigation={this.props.navigation}
|
||||
item={item}
|
||||
userDeviceRentDates={this.getUserDeviceRentDates(item)}
|
||||
height={LIST_ITEM_HEIGHT}/>
|
||||
);
|
||||
};
|
||||
onScreenFocus = () => {
|
||||
if (this.canRefresh && this.authRef.current != null)
|
||||
this.authRef.current.reload();
|
||||
this.canRefresh = true;
|
||||
};
|
||||
|
||||
getUserDeviceRentDates(item: Device) {
|
||||
let dates = null;
|
||||
for (let i = 0; i < this.userRents.length; i++) {
|
||||
let device = this.userRents[i];
|
||||
if (item.id === device.device_id) {
|
||||
dates = [device.begin, device.end];
|
||||
break;
|
||||
}
|
||||
}
|
||||
return dates;
|
||||
getRenderItem = ({item}: {item: DeviceType}): React.Node => {
|
||||
const {navigation} = this.props;
|
||||
return (
|
||||
<EquipmentListItem
|
||||
navigation={navigation}
|
||||
item={item}
|
||||
userDeviceRentDates={this.getUserDeviceRentDates(item)}
|
||||
height={LIST_ITEM_HEIGHT}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
getUserDeviceRentDates(item: DeviceType): [number, number] | null {
|
||||
let dates = null;
|
||||
this.userRents.forEach((device: RentedDeviceType) => {
|
||||
if (item.id === device.device_id) {
|
||||
dates = [device.begin, device.end];
|
||||
}
|
||||
});
|
||||
return dates;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the list header, with explains this screen's purpose
|
||||
*
|
||||
* @returns {*}
|
||||
*/
|
||||
getListHeader(): React.Node {
|
||||
return (
|
||||
<View
|
||||
style={{
|
||||
width: '100%',
|
||||
marginTop: 10,
|
||||
marginBottom: 10,
|
||||
}}>
|
||||
<Button
|
||||
mode="contained"
|
||||
icon="help-circle"
|
||||
onPress={this.showMascotDialog}
|
||||
style={{
|
||||
marginRight: 'auto',
|
||||
marginLeft: 'auto',
|
||||
}}>
|
||||
{i18n.t('screens.equipment.mascotDialog.title')}
|
||||
</Button>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
keyExtractor = (item: ClubType): string => item.id.toString();
|
||||
|
||||
/**
|
||||
* Gets the main screen component with the fetched data
|
||||
*
|
||||
* @param data The data fetched from the server
|
||||
* @returns {*}
|
||||
*/
|
||||
getScreen = (data: Array<ApiGenericDataType | null>): React.Node => {
|
||||
if (data[0] != null) {
|
||||
const fetchedData = data[0];
|
||||
if (fetchedData != null) this.data = fetchedData.devices;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the list header, with explains this screen's purpose
|
||||
*
|
||||
* @returns {*}
|
||||
*/
|
||||
getListHeader() {
|
||||
return (
|
||||
<View style={{
|
||||
width: "100%",
|
||||
marginTop: 10,
|
||||
marginBottom: 10,
|
||||
}}>
|
||||
<Button
|
||||
mode={"contained"}
|
||||
icon={"help-circle"}
|
||||
onPress={this.showMascotDialog}
|
||||
style={{
|
||||
marginRight: "auto",
|
||||
marginLeft: "auto",
|
||||
}}>
|
||||
{i18n.t("screens.equipment.mascotDialog.title")}
|
||||
</Button>
|
||||
</View>
|
||||
);
|
||||
if (data[1] != null) {
|
||||
const fetchedData = data[1];
|
||||
if (fetchedData != null) this.userRents = fetchedData.locations;
|
||||
}
|
||||
return (
|
||||
<CollapsibleFlatList
|
||||
keyExtractor={this.keyExtractor}
|
||||
renderItem={this.getRenderItem}
|
||||
ListHeaderComponent={this.getListHeader()}
|
||||
data={this.data}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
keyExtractor = (item: club) => item.id.toString();
|
||||
showMascotDialog = () => {
|
||||
this.setState({mascotDialogVisible: true});
|
||||
};
|
||||
|
||||
/**
|
||||
* Gets the main screen component with the fetched data
|
||||
*
|
||||
* @param data The data fetched from the server
|
||||
* @returns {*}
|
||||
*/
|
||||
getScreen = (data: Array<{ [key: string]: any } | null>) => {
|
||||
if (data[0] != null) {
|
||||
const fetchedData = data[0];
|
||||
if (fetchedData != null)
|
||||
this.data = fetchedData["devices"];
|
||||
}
|
||||
if (data[1] != null) {
|
||||
const fetchedData = data[1];
|
||||
if (fetchedData != null)
|
||||
this.userRents = fetchedData["locations"];
|
||||
}
|
||||
return (
|
||||
<CollapsibleFlatList
|
||||
keyExtractor={this.keyExtractor}
|
||||
renderItem={this.getRenderItem}
|
||||
ListHeaderComponent={this.getListHeader()}
|
||||
data={this.data}
|
||||
/>
|
||||
)
|
||||
};
|
||||
hideMascotDialog = () => {
|
||||
AsyncStorageManager.set(
|
||||
AsyncStorageManager.PREFERENCES.equipmentShowBanner.key,
|
||||
false,
|
||||
);
|
||||
this.setState({mascotDialogVisible: false});
|
||||
};
|
||||
|
||||
showMascotDialog = () => {
|
||||
this.setState({mascotDialogVisible: true})
|
||||
};
|
||||
|
||||
hideMascotDialog = () => {
|
||||
AsyncStorageManager.set(AsyncStorageManager.PREFERENCES.equipmentShowBanner.key, false);
|
||||
this.setState({mascotDialogVisible: false})
|
||||
};
|
||||
|
||||
render() {
|
||||
return (
|
||||
<View style={{flex: 1}}>
|
||||
<AuthenticatedScreen
|
||||
{...this.props}
|
||||
ref={this.authRef}
|
||||
requests={[
|
||||
{
|
||||
link: 'location/all',
|
||||
params: {},
|
||||
mandatory: true,
|
||||
},
|
||||
{
|
||||
link: 'location/my',
|
||||
params: {},
|
||||
mandatory: false,
|
||||
}
|
||||
]}
|
||||
renderFunction={this.getScreen}
|
||||
/>
|
||||
<MascotPopup
|
||||
visible={this.state.mascotDialogVisible}
|
||||
title={i18n.t("screens.equipment.mascotDialog.title")}
|
||||
message={i18n.t("screens.equipment.mascotDialog.message")}
|
||||
icon={"vote"}
|
||||
buttons={{
|
||||
action: null,
|
||||
cancel: {
|
||||
message: i18n.t("screens.equipment.mascotDialog.button"),
|
||||
icon: "check",
|
||||
onPress: this.hideMascotDialog,
|
||||
}
|
||||
}}
|
||||
emotion={MASCOT_STYLE.WINK}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
render(): React.Node {
|
||||
const {props, state} = this;
|
||||
return (
|
||||
<View style={{flex: 1}}>
|
||||
<AuthenticatedScreen
|
||||
navigation={props.navigation}
|
||||
ref={this.authRef}
|
||||
requests={[
|
||||
{
|
||||
link: 'location/all',
|
||||
params: {},
|
||||
mandatory: true,
|
||||
},
|
||||
{
|
||||
link: 'location/my',
|
||||
params: {},
|
||||
mandatory: false,
|
||||
},
|
||||
]}
|
||||
renderFunction={this.getScreen}
|
||||
/>
|
||||
<MascotPopup
|
||||
visible={state.mascotDialogVisible}
|
||||
title={i18n.t('screens.equipment.mascotDialog.title')}
|
||||
message={i18n.t('screens.equipment.mascotDialog.message')}
|
||||
icon="vote"
|
||||
buttons={{
|
||||
action: null,
|
||||
cancel: {
|
||||
message: i18n.t('screens.equipment.mascotDialog.button'),
|
||||
icon: 'check',
|
||||
onPress: this.hideMascotDialog,
|
||||
},
|
||||
}}
|
||||
emotion={MASCOT_STYLE.WINK}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default withTheme(EquipmentListScreen);
|
||||
|
|
|
|||
|
|
@ -1,441 +1,441 @@
|
|||
// @flow
|
||||
|
||||
import * as React from 'react';
|
||||
import {Button, Caption, Card, Headline, Subheading, withTheme} from 'react-native-paper';
|
||||
import {StackNavigationProp} from "@react-navigation/stack";
|
||||
import type {CustomTheme} from "../../../managers/ThemeManager";
|
||||
import type {Device} from "./EquipmentListScreen";
|
||||
import {BackHandler, View} from "react-native";
|
||||
import * as Animatable from "react-native-animatable";
|
||||
import i18n from "i18n-js";
|
||||
import {CalendarList} from "react-native-calendars";
|
||||
import LoadingConfirmDialog from "../../../components/Dialogs/LoadingConfirmDialog";
|
||||
import ErrorDialog from "../../../components/Dialogs/ErrorDialog";
|
||||
import {
|
||||
generateMarkedDates,
|
||||
getFirstEquipmentAvailability,
|
||||
getISODate,
|
||||
getRelativeDateString,
|
||||
getValidRange,
|
||||
isEquipmentAvailable
|
||||
} from "../../../utils/EquipmentBooking";
|
||||
import ConnectionManager from "../../../managers/ConnectionManager";
|
||||
import CollapsibleScrollView from "../../../components/Collapsible/CollapsibleScrollView";
|
||||
Button,
|
||||
Caption,
|
||||
Card,
|
||||
Headline,
|
||||
Subheading,
|
||||
withTheme,
|
||||
} from 'react-native-paper';
|
||||
import {StackNavigationProp} from '@react-navigation/stack';
|
||||
import {BackHandler, View} from 'react-native';
|
||||
import * as Animatable from 'react-native-animatable';
|
||||
import i18n from 'i18n-js';
|
||||
import {CalendarList} from 'react-native-calendars';
|
||||
import type {DeviceType} from './EquipmentListScreen';
|
||||
import type {CustomThemeType} from '../../../managers/ThemeManager';
|
||||
import LoadingConfirmDialog from '../../../components/Dialogs/LoadingConfirmDialog';
|
||||
import ErrorDialog from '../../../components/Dialogs/ErrorDialog';
|
||||
import {
|
||||
generateMarkedDates,
|
||||
getFirstEquipmentAvailability,
|
||||
getISODate,
|
||||
getRelativeDateString,
|
||||
getValidRange,
|
||||
isEquipmentAvailable,
|
||||
} from '../../../utils/EquipmentBooking';
|
||||
import ConnectionManager from '../../../managers/ConnectionManager';
|
||||
import CollapsibleScrollView from '../../../components/Collapsible/CollapsibleScrollView';
|
||||
|
||||
type Props = {
|
||||
navigation: StackNavigationProp,
|
||||
route: {
|
||||
params?: {
|
||||
item?: Device,
|
||||
},
|
||||
type PropsType = {
|
||||
navigation: StackNavigationProp,
|
||||
route: {
|
||||
params?: {
|
||||
item?: DeviceType,
|
||||
},
|
||||
theme: CustomTheme,
|
||||
}
|
||||
},
|
||||
theme: CustomThemeType,
|
||||
};
|
||||
|
||||
type State = {
|
||||
dialogVisible: boolean,
|
||||
errorDialogVisible: boolean,
|
||||
markedDates: { [key: string]: { startingDay: boolean, endingDay: boolean, color: string } },
|
||||
currentError: number,
|
||||
}
|
||||
export type MarkedDatesObjectType = {
|
||||
[key: string]: {startingDay: boolean, endingDay: boolean, color: string},
|
||||
};
|
||||
|
||||
class EquipmentRentScreen extends React.Component<Props, State> {
|
||||
type StateType = {
|
||||
dialogVisible: boolean,
|
||||
errorDialogVisible: boolean,
|
||||
markedDates: MarkedDatesObjectType,
|
||||
currentError: number,
|
||||
};
|
||||
|
||||
state = {
|
||||
dialogVisible: false,
|
||||
errorDialogVisible: false,
|
||||
markedDates: {},
|
||||
currentError: 0,
|
||||
}
|
||||
class EquipmentRentScreen extends React.Component<PropsType, StateType> {
|
||||
item: DeviceType | null;
|
||||
|
||||
item: Device | null;
|
||||
bookedDates: Array<string>;
|
||||
bookedDates: Array<string>;
|
||||
|
||||
bookRef: { current: null | Animatable.View }
|
||||
canBookEquipment: boolean;
|
||||
bookRef: {current: null | Animatable.View};
|
||||
|
||||
lockedDates: { [key: string]: { startingDay: boolean, endingDay: boolean, color: string } }
|
||||
canBookEquipment: boolean;
|
||||
|
||||
constructor(props: Props) {
|
||||
super(props);
|
||||
this.resetSelection();
|
||||
this.bookRef = React.createRef();
|
||||
this.canBookEquipment = false;
|
||||
this.bookedDates = [];
|
||||
if (this.props.route.params != null) {
|
||||
if (this.props.route.params.item != null)
|
||||
this.item = this.props.route.params.item;
|
||||
else
|
||||
this.item = null;
|
||||
}
|
||||
const item = this.item;
|
||||
if (item != null) {
|
||||
this.lockedDates = {};
|
||||
for (let i = 0; i < item.booked_at.length; i++) {
|
||||
const range = getValidRange(new Date(item.booked_at[i].begin), new Date(item.booked_at[i].end), null);
|
||||
this.lockedDates = {
|
||||
...this.lockedDates,
|
||||
...generateMarkedDates(
|
||||
false,
|
||||
this.props.theme,
|
||||
range
|
||||
)
|
||||
};
|
||||
}
|
||||
}
|
||||
lockedDates: {
|
||||
[key: string]: {startingDay: boolean, endingDay: boolean, color: string},
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Captures focus and blur events to hook on android back button
|
||||
*/
|
||||
componentDidMount() {
|
||||
this.props.navigation.addListener(
|
||||
'focus',
|
||||
() =>
|
||||
BackHandler.addEventListener(
|
||||
'hardwareBackPress',
|
||||
this.onBackButtonPressAndroid
|
||||
)
|
||||
);
|
||||
this.props.navigation.addListener(
|
||||
'blur',
|
||||
() =>
|
||||
BackHandler.removeEventListener(
|
||||
'hardwareBackPress',
|
||||
this.onBackButtonPressAndroid
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Overrides default android back button behaviour to deselect date if any is selected.
|
||||
*
|
||||
* @return {boolean}
|
||||
*/
|
||||
onBackButtonPressAndroid = () => {
|
||||
if (this.bookedDates.length > 0) {
|
||||
this.resetSelection();
|
||||
this.updateMarkedSelection();
|
||||
return true;
|
||||
} else
|
||||
return false;
|
||||
constructor(props: PropsType) {
|
||||
super(props);
|
||||
this.state = {
|
||||
dialogVisible: false,
|
||||
errorDialogVisible: false,
|
||||
markedDates: {},
|
||||
currentError: 0,
|
||||
};
|
||||
|
||||
/**
|
||||
* Selects a new date on the calendar.
|
||||
* If both start and end dates are already selected, unselect all.
|
||||
*
|
||||
* @param day The day selected
|
||||
*/
|
||||
selectNewDate = (day: { dateString: string, day: number, month: number, timestamp: number, year: number }) => {
|
||||
const selected = new Date(day.dateString);
|
||||
const start = this.getBookStartDate();
|
||||
|
||||
if (!(this.lockedDates.hasOwnProperty(day.dateString))) {
|
||||
if (start === null) {
|
||||
this.updateSelectionRange(selected, selected);
|
||||
this.enableBooking();
|
||||
} else if (start.getTime() === selected.getTime()) {
|
||||
this.resetSelection();
|
||||
} else if (this.bookedDates.length === 1) {
|
||||
this.updateSelectionRange(start, selected);
|
||||
this.enableBooking();
|
||||
} else
|
||||
this.resetSelection();
|
||||
this.updateMarkedSelection();
|
||||
}
|
||||
this.resetSelection();
|
||||
this.bookRef = React.createRef();
|
||||
this.canBookEquipment = false;
|
||||
this.bookedDates = [];
|
||||
if (props.route.params != null) {
|
||||
if (props.route.params.item != null) this.item = props.route.params.item;
|
||||
else this.item = null;
|
||||
}
|
||||
|
||||
updateSelectionRange(start: Date, end: Date) {
|
||||
this.bookedDates = getValidRange(start, end, this.item);
|
||||
const {item} = this;
|
||||
if (item != null) {
|
||||
this.lockedDates = {};
|
||||
item.booked_at.forEach((date: {begin: string, end: string}) => {
|
||||
const range = getValidRange(
|
||||
new Date(date.begin),
|
||||
new Date(date.end),
|
||||
null,
|
||||
);
|
||||
this.lockedDates = {
|
||||
...this.lockedDates,
|
||||
...generateMarkedDates(false, props.theme, range),
|
||||
};
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
updateMarkedSelection() {
|
||||
this.setState({
|
||||
markedDates: generateMarkedDates(
|
||||
true,
|
||||
this.props.theme,
|
||||
this.bookedDates
|
||||
),
|
||||
});
|
||||
/**
|
||||
* Captures focus and blur events to hook on android back button
|
||||
*/
|
||||
componentDidMount() {
|
||||
const {navigation} = this.props;
|
||||
navigation.addListener('focus', () => {
|
||||
BackHandler.addEventListener(
|
||||
'hardwareBackPress',
|
||||
this.onBackButtonPressAndroid,
|
||||
);
|
||||
});
|
||||
navigation.addListener('blur', () => {
|
||||
BackHandler.removeEventListener(
|
||||
'hardwareBackPress',
|
||||
this.onBackButtonPressAndroid,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Overrides default android back button behaviour to deselect date if any is selected.
|
||||
*
|
||||
* @return {boolean}
|
||||
*/
|
||||
onBackButtonPressAndroid = (): boolean => {
|
||||
if (this.bookedDates.length > 0) {
|
||||
this.resetSelection();
|
||||
this.updateMarkedSelection();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
enableBooking() {
|
||||
if (!this.canBookEquipment) {
|
||||
this.showBookButton();
|
||||
this.canBookEquipment = true;
|
||||
}
|
||||
onDialogDismiss = () => {
|
||||
this.setState({dialogVisible: false});
|
||||
};
|
||||
|
||||
onErrorDialogDismiss = () => {
|
||||
this.setState({errorDialogVisible: false});
|
||||
};
|
||||
|
||||
/**
|
||||
* Sends the selected data to the server and waits for a response.
|
||||
* If the request is a success, navigate to the recap screen.
|
||||
* If it is an error, display the error to the user.
|
||||
*
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
onDialogAccept = (): Promise<void> => {
|
||||
return new Promise((resolve: () => void) => {
|
||||
const {item, props} = this;
|
||||
const start = this.getBookStartDate();
|
||||
const end = this.getBookEndDate();
|
||||
if (item != null && start != null && end != null) {
|
||||
ConnectionManager.getInstance()
|
||||
.authenticatedRequest('location/booking', {
|
||||
device: item.id,
|
||||
begin: getISODate(start),
|
||||
end: getISODate(end),
|
||||
})
|
||||
.then(() => {
|
||||
this.onDialogDismiss();
|
||||
props.navigation.replace('equipment-confirm', {
|
||||
item: this.item,
|
||||
dates: [getISODate(start), getISODate(end)],
|
||||
});
|
||||
resolve();
|
||||
})
|
||||
.catch((error: number) => {
|
||||
this.onDialogDismiss();
|
||||
this.showErrorDialog(error);
|
||||
resolve();
|
||||
});
|
||||
} else {
|
||||
this.onDialogDismiss();
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
getBookStartDate(): Date | null {
|
||||
return this.bookedDates.length > 0 ? new Date(this.bookedDates[0]) : null;
|
||||
}
|
||||
|
||||
getBookEndDate(): Date | null {
|
||||
const {length} = this.bookedDates;
|
||||
return length > 0 ? new Date(this.bookedDates[length - 1]) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Selects a new date on the calendar.
|
||||
* If both start and end dates are already selected, unselect all.
|
||||
*
|
||||
* @param day The day selected
|
||||
*/
|
||||
selectNewDate = (day: {
|
||||
dateString: string,
|
||||
day: number,
|
||||
month: number,
|
||||
timestamp: number,
|
||||
year: number,
|
||||
}) => {
|
||||
const selected = new Date(day.dateString);
|
||||
const start = this.getBookStartDate();
|
||||
|
||||
if (!this.lockedDates[day.dateString] != null) {
|
||||
if (start === null) {
|
||||
this.updateSelectionRange(selected, selected);
|
||||
this.enableBooking();
|
||||
} else if (start.getTime() === selected.getTime()) {
|
||||
this.resetSelection();
|
||||
} else if (this.bookedDates.length === 1) {
|
||||
this.updateSelectionRange(start, selected);
|
||||
this.enableBooking();
|
||||
} else this.resetSelection();
|
||||
this.updateMarkedSelection();
|
||||
}
|
||||
};
|
||||
|
||||
resetSelection() {
|
||||
if (this.canBookEquipment)
|
||||
this.hideBookButton();
|
||||
this.canBookEquipment = false;
|
||||
this.bookedDates = [];
|
||||
showErrorDialog = (error: number) => {
|
||||
this.setState({
|
||||
errorDialogVisible: true,
|
||||
currentError: error,
|
||||
});
|
||||
};
|
||||
|
||||
showDialog = () => {
|
||||
this.setState({dialogVisible: true});
|
||||
};
|
||||
|
||||
/**
|
||||
* Shows the book button by plying a fade animation
|
||||
*/
|
||||
showBookButton() {
|
||||
if (this.bookRef.current != null) {
|
||||
this.bookRef.current.fadeInUp(500);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Shows the book button by plying a fade animation
|
||||
*/
|
||||
showBookButton() {
|
||||
if (this.bookRef.current != null) {
|
||||
this.bookRef.current.fadeInUp(500);
|
||||
}
|
||||
/**
|
||||
* Hides the book button by plying a fade animation
|
||||
*/
|
||||
hideBookButton() {
|
||||
if (this.bookRef.current != null) {
|
||||
this.bookRef.current.fadeOutDown(500);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Hides the book button by plying a fade animation
|
||||
*/
|
||||
hideBookButton() {
|
||||
if (this.bookRef.current != null) {
|
||||
this.bookRef.current.fadeOutDown(500);
|
||||
}
|
||||
enableBooking() {
|
||||
if (!this.canBookEquipment) {
|
||||
this.showBookButton();
|
||||
this.canBookEquipment = true;
|
||||
}
|
||||
}
|
||||
|
||||
showDialog = () => {
|
||||
this.setState({dialogVisible: true});
|
||||
}
|
||||
resetSelection() {
|
||||
if (this.canBookEquipment) this.hideBookButton();
|
||||
this.canBookEquipment = false;
|
||||
this.bookedDates = [];
|
||||
}
|
||||
|
||||
showErrorDialog = (error: number) => {
|
||||
this.setState({
|
||||
errorDialogVisible: true,
|
||||
currentError: error,
|
||||
});
|
||||
}
|
||||
updateSelectionRange(start: Date, end: Date) {
|
||||
this.bookedDates = getValidRange(start, end, this.item);
|
||||
}
|
||||
|
||||
onDialogDismiss = () => {
|
||||
this.setState({dialogVisible: false});
|
||||
}
|
||||
updateMarkedSelection() {
|
||||
const {theme} = this.props;
|
||||
this.setState({
|
||||
markedDates: generateMarkedDates(true, theme, this.bookedDates),
|
||||
});
|
||||
}
|
||||
|
||||
onErrorDialogDismiss = () => {
|
||||
this.setState({errorDialogVisible: false});
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends the selected data to the server and waits for a response.
|
||||
* If the request is a success, navigate to the recap screen.
|
||||
* If it is an error, display the error to the user.
|
||||
*
|
||||
* @returns {Promise<R>}
|
||||
*/
|
||||
onDialogAccept = () => {
|
||||
return new Promise((resolve) => {
|
||||
const item = this.item;
|
||||
const start = this.getBookStartDate();
|
||||
const end = this.getBookEndDate();
|
||||
if (item != null && start != null && end != null) {
|
||||
console.log({
|
||||
"device": item.id,
|
||||
"begin": getISODate(start),
|
||||
"end": getISODate(end),
|
||||
})
|
||||
ConnectionManager.getInstance().authenticatedRequest(
|
||||
"location/booking",
|
||||
{
|
||||
"device": item.id,
|
||||
"begin": getISODate(start),
|
||||
"end": getISODate(end),
|
||||
})
|
||||
.then(() => {
|
||||
this.onDialogDismiss();
|
||||
this.props.navigation.replace("equipment-confirm", {
|
||||
item: this.item,
|
||||
dates: [getISODate(start), getISODate(end)]
|
||||
});
|
||||
resolve();
|
||||
})
|
||||
.catch((error: number) => {
|
||||
this.onDialogDismiss();
|
||||
this.showErrorDialog(error);
|
||||
resolve();
|
||||
});
|
||||
} else {
|
||||
this.onDialogDismiss();
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
getBookStartDate() {
|
||||
return this.bookedDates.length > 0 ? new Date(this.bookedDates[0]) : null;
|
||||
}
|
||||
|
||||
getBookEndDate() {
|
||||
const length = this.bookedDates.length;
|
||||
return length > 0 ? new Date(this.bookedDates[length - 1]) : null;
|
||||
}
|
||||
|
||||
render() {
|
||||
const item = this.item;
|
||||
const start = this.getBookStartDate();
|
||||
const end = this.getBookEndDate();
|
||||
|
||||
if (item != null) {
|
||||
const isAvailable = isEquipmentAvailable(item);
|
||||
const firstAvailability = getFirstEquipmentAvailability(item);
|
||||
return (
|
||||
render(): React.Node {
|
||||
const {item, props, state} = this;
|
||||
const start = this.getBookStartDate();
|
||||
const end = this.getBookEndDate();
|
||||
let subHeadingText;
|
||||
if (start == null) subHeadingText = i18n.t('screens.equipment.booking');
|
||||
else if (end != null && start.getTime() !== end.getTime())
|
||||
subHeadingText = i18n.t('screens.equipment.bookingPeriod', {
|
||||
begin: getRelativeDateString(start),
|
||||
end: getRelativeDateString(end),
|
||||
});
|
||||
else
|
||||
i18n.t('screens.equipment.bookingDay', {
|
||||
date: getRelativeDateString(start),
|
||||
});
|
||||
if (item != null) {
|
||||
const isAvailable = isEquipmentAvailable(item);
|
||||
const firstAvailability = getFirstEquipmentAvailability(item);
|
||||
return (
|
||||
<View style={{flex: 1}}>
|
||||
<CollapsibleScrollView>
|
||||
<Card style={{margin: 5}}>
|
||||
<Card.Content>
|
||||
<View style={{flex: 1}}>
|
||||
<CollapsibleScrollView>
|
||||
<Card style={{margin: 5}}>
|
||||
<Card.Content>
|
||||
<View style={{flex: 1}}>
|
||||
<View style={{
|
||||
marginLeft: "auto",
|
||||
marginRight: "auto",
|
||||
flexDirection: "row",
|
||||
flexWrap: "wrap",
|
||||
}}>
|
||||
<Headline style={{textAlign: "center"}}>
|
||||
{item.name}
|
||||
</Headline>
|
||||
<Caption style={{
|
||||
textAlign: "center",
|
||||
lineHeight: 35,
|
||||
marginLeft: 10,
|
||||
}}>
|
||||
({i18n.t('screens.equipment.bail', {cost: item.caution})})
|
||||
</Caption>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
<Button
|
||||
icon={isAvailable ? "check-circle-outline" : "update"}
|
||||
color={isAvailable ? this.props.theme.colors.success : this.props.theme.colors.primary}
|
||||
mode="text"
|
||||
>
|
||||
{i18n.t('screens.equipment.available', {date: getRelativeDateString(firstAvailability)})}
|
||||
</Button>
|
||||
<Subheading style={{
|
||||
textAlign: "center",
|
||||
marginBottom: 10,
|
||||
minHeight: 50
|
||||
}}>
|
||||
{
|
||||
start == null
|
||||
? i18n.t('screens.equipment.booking')
|
||||
: end != null && start.getTime() !== end.getTime()
|
||||
? i18n.t('screens.equipment.bookingPeriod', {
|
||||
begin: getRelativeDateString(start),
|
||||
end: getRelativeDateString(end)
|
||||
})
|
||||
: i18n.t('screens.equipment.bookingDay', {
|
||||
date: getRelativeDateString(start)
|
||||
})
|
||||
}
|
||||
|
||||
</Subheading>
|
||||
</Card.Content>
|
||||
</Card>
|
||||
<CalendarList
|
||||
// Minimum date that can be selected, dates before minDate will be grayed out. Default = undefined
|
||||
minDate={new Date()}
|
||||
// Max amount of months allowed to scroll to the past. Default = 50
|
||||
pastScrollRange={0}
|
||||
// Max amount of months allowed to scroll to the future. Default = 50
|
||||
futureScrollRange={3}
|
||||
// Enable horizontal scrolling, default = false
|
||||
horizontal={true}
|
||||
// Enable paging on horizontal, default = false
|
||||
pagingEnabled={true}
|
||||
// Handler which gets executed on day press. Default = undefined
|
||||
onDayPress={this.selectNewDate}
|
||||
// If firstDay=1 week starts from Monday. Note that dayNames and dayNamesShort should still start from Sunday.
|
||||
firstDay={1}
|
||||
// Disable all touch events for disabled days. can be override with disableTouchEvent in markedDates
|
||||
disableAllTouchEventsForDisabledDays={true}
|
||||
// Hide month navigation arrows.
|
||||
hideArrows={false}
|
||||
// Date marking style [simple/period/multi-dot/custom]. Default = 'simple'
|
||||
markingType={'period'}
|
||||
markedDates={{...this.lockedDates, ...this.state.markedDates}}
|
||||
|
||||
theme={{
|
||||
backgroundColor: this.props.theme.colors.agendaBackgroundColor,
|
||||
calendarBackground: this.props.theme.colors.background,
|
||||
textSectionTitleColor: this.props.theme.colors.agendaDayTextColor,
|
||||
selectedDayBackgroundColor: this.props.theme.colors.primary,
|
||||
selectedDayTextColor: '#ffffff',
|
||||
todayTextColor: this.props.theme.colors.text,
|
||||
dayTextColor: this.props.theme.colors.text,
|
||||
textDisabledColor: this.props.theme.colors.agendaDayTextColor,
|
||||
dotColor: this.props.theme.colors.primary,
|
||||
selectedDotColor: '#ffffff',
|
||||
arrowColor: this.props.theme.colors.primary,
|
||||
monthTextColor: this.props.theme.colors.text,
|
||||
indicatorColor: this.props.theme.colors.primary,
|
||||
textDayFontFamily: 'monospace',
|
||||
textMonthFontFamily: 'monospace',
|
||||
textDayHeaderFontFamily: 'monospace',
|
||||
textDayFontWeight: '300',
|
||||
textMonthFontWeight: 'bold',
|
||||
textDayHeaderFontWeight: '300',
|
||||
textDayFontSize: 16,
|
||||
textMonthFontSize: 16,
|
||||
textDayHeaderFontSize: 16,
|
||||
'stylesheet.day.period': {
|
||||
base: {
|
||||
overflow: 'hidden',
|
||||
height: 34,
|
||||
width: 34,
|
||||
alignItems: 'center',
|
||||
|
||||
}
|
||||
}
|
||||
}}
|
||||
style={{marginBottom: 50}}
|
||||
/>
|
||||
</CollapsibleScrollView>
|
||||
<LoadingConfirmDialog
|
||||
visible={this.state.dialogVisible}
|
||||
onDismiss={this.onDialogDismiss}
|
||||
onAccept={this.onDialogAccept}
|
||||
title={i18n.t('screens.equipment.dialogTitle')}
|
||||
titleLoading={i18n.t('screens.equipment.dialogTitleLoading')}
|
||||
message={i18n.t('screens.equipment.dialogMessage')}
|
||||
/>
|
||||
|
||||
<ErrorDialog
|
||||
visible={this.state.errorDialogVisible}
|
||||
onDismiss={this.onErrorDialogDismiss}
|
||||
errorCode={this.state.currentError}
|
||||
/>
|
||||
<Animatable.View
|
||||
ref={this.bookRef}
|
||||
style={{
|
||||
position: "absolute",
|
||||
bottom: 0,
|
||||
left: 0,
|
||||
width: "100%",
|
||||
flex: 1,
|
||||
transform: [
|
||||
{translateY: 100},
|
||||
]
|
||||
}}>
|
||||
<Button
|
||||
icon="bookmark-check"
|
||||
mode="contained"
|
||||
onPress={this.showDialog}
|
||||
style={{
|
||||
width: "80%",
|
||||
flex: 1,
|
||||
marginLeft: "auto",
|
||||
marginRight: "auto",
|
||||
marginBottom: 20,
|
||||
borderRadius: 10
|
||||
}}
|
||||
>
|
||||
{i18n.t('screens.equipment.bookButton')}
|
||||
</Button>
|
||||
</Animatable.View>
|
||||
|
||||
<View
|
||||
style={{
|
||||
marginLeft: 'auto',
|
||||
marginRight: 'auto',
|
||||
flexDirection: 'row',
|
||||
flexWrap: 'wrap',
|
||||
}}>
|
||||
<Headline style={{textAlign: 'center'}}>
|
||||
{item.name}
|
||||
</Headline>
|
||||
<Caption
|
||||
style={{
|
||||
textAlign: 'center',
|
||||
lineHeight: 35,
|
||||
marginLeft: 10,
|
||||
}}>
|
||||
({i18n.t('screens.equipment.bail', {cost: item.caution})})
|
||||
</Caption>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
)
|
||||
} else
|
||||
return <View/>;
|
||||
}
|
||||
<Button
|
||||
icon={isAvailable ? 'check-circle-outline' : 'update'}
|
||||
color={
|
||||
isAvailable
|
||||
? props.theme.colors.success
|
||||
: props.theme.colors.primary
|
||||
}
|
||||
mode="text">
|
||||
{i18n.t('screens.equipment.available', {
|
||||
date: getRelativeDateString(firstAvailability),
|
||||
})}
|
||||
</Button>
|
||||
<Subheading
|
||||
style={{
|
||||
textAlign: 'center',
|
||||
marginBottom: 10,
|
||||
minHeight: 50,
|
||||
}}>
|
||||
{subHeadingText}
|
||||
</Subheading>
|
||||
</Card.Content>
|
||||
</Card>
|
||||
<CalendarList
|
||||
// Minimum date that can be selected, dates before minDate will be grayed out. Default = undefined
|
||||
minDate={new Date()}
|
||||
// Max amount of months allowed to scroll to the past. Default = 50
|
||||
pastScrollRange={0}
|
||||
// Max amount of months allowed to scroll to the future. Default = 50
|
||||
futureScrollRange={3}
|
||||
// Enable horizontal scrolling, default = false
|
||||
horizontal
|
||||
// Enable paging on horizontal, default = false
|
||||
pagingEnabled
|
||||
// Handler which gets executed on day press. Default = undefined
|
||||
onDayPress={this.selectNewDate}
|
||||
// If firstDay=1 week starts from Monday. Note that dayNames and dayNamesShort should still start from Sunday.
|
||||
firstDay={1}
|
||||
// Disable all touch events for disabled days. can be override with disableTouchEvent in markedDates
|
||||
disableAllTouchEventsForDisabledDays
|
||||
// Hide month navigation arrows.
|
||||
hideArrows={false}
|
||||
// Date marking style [simple/period/multi-dot/custom]. Default = 'simple'
|
||||
markingType="period"
|
||||
markedDates={{...this.lockedDates, ...state.markedDates}}
|
||||
theme={{
|
||||
backgroundColor: props.theme.colors.agendaBackgroundColor,
|
||||
calendarBackground: props.theme.colors.background,
|
||||
textSectionTitleColor: props.theme.colors.agendaDayTextColor,
|
||||
selectedDayBackgroundColor: props.theme.colors.primary,
|
||||
selectedDayTextColor: '#ffffff',
|
||||
todayTextColor: props.theme.colors.text,
|
||||
dayTextColor: props.theme.colors.text,
|
||||
textDisabledColor: props.theme.colors.agendaDayTextColor,
|
||||
dotColor: props.theme.colors.primary,
|
||||
selectedDotColor: '#ffffff',
|
||||
arrowColor: props.theme.colors.primary,
|
||||
monthTextColor: props.theme.colors.text,
|
||||
indicatorColor: props.theme.colors.primary,
|
||||
textDayFontFamily: 'monospace',
|
||||
textMonthFontFamily: 'monospace',
|
||||
textDayHeaderFontFamily: 'monospace',
|
||||
textDayFontWeight: '300',
|
||||
textMonthFontWeight: 'bold',
|
||||
textDayHeaderFontWeight: '300',
|
||||
textDayFontSize: 16,
|
||||
textMonthFontSize: 16,
|
||||
textDayHeaderFontSize: 16,
|
||||
'stylesheet.day.period': {
|
||||
base: {
|
||||
overflow: 'hidden',
|
||||
height: 34,
|
||||
width: 34,
|
||||
alignItems: 'center',
|
||||
},
|
||||
},
|
||||
}}
|
||||
style={{marginBottom: 50}}
|
||||
/>
|
||||
</CollapsibleScrollView>
|
||||
<LoadingConfirmDialog
|
||||
visible={state.dialogVisible}
|
||||
onDismiss={this.onDialogDismiss}
|
||||
onAccept={this.onDialogAccept}
|
||||
title={i18n.t('screens.equipment.dialogTitle')}
|
||||
titleLoading={i18n.t('screens.equipment.dialogTitleLoading')}
|
||||
message={i18n.t('screens.equipment.dialogMessage')}
|
||||
/>
|
||||
|
||||
<ErrorDialog
|
||||
visible={state.errorDialogVisible}
|
||||
onDismiss={this.onErrorDialogDismiss}
|
||||
errorCode={state.currentError}
|
||||
/>
|
||||
<Animatable.View
|
||||
ref={this.bookRef}
|
||||
style={{
|
||||
position: 'absolute',
|
||||
bottom: 0,
|
||||
left: 0,
|
||||
width: '100%',
|
||||
flex: 1,
|
||||
transform: [{translateY: 100}],
|
||||
}}>
|
||||
<Button
|
||||
icon="bookmark-check"
|
||||
mode="contained"
|
||||
onPress={this.showDialog}
|
||||
style={{
|
||||
width: '80%',
|
||||
flex: 1,
|
||||
marginLeft: 'auto',
|
||||
marginRight: 'auto',
|
||||
marginBottom: 20,
|
||||
borderRadius: 10,
|
||||
}}>
|
||||
{i18n.t('screens.equipment.bookButton')}
|
||||
</Button>
|
||||
</Animatable.View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export default withTheme(EquipmentRentScreen);
|
||||
|
|
|
|||
|
|
@ -1,417 +1,446 @@
|
|||
// @flow
|
||||
|
||||
import * as React from 'react';
|
||||
import {Image, KeyboardAvoidingView, StyleSheet, View} from "react-native";
|
||||
import {Button, Card, HelperText, TextInput, withTheme} from 'react-native-paper';
|
||||
import ConnectionManager from "../../managers/ConnectionManager";
|
||||
import {Image, KeyboardAvoidingView, StyleSheet, View} from 'react-native';
|
||||
import {
|
||||
Button,
|
||||
Card,
|
||||
HelperText,
|
||||
TextInput,
|
||||
withTheme,
|
||||
} from 'react-native-paper';
|
||||
import i18n from 'i18n-js';
|
||||
import ErrorDialog from "../../components/Dialogs/ErrorDialog";
|
||||
import type {CustomTheme} from "../../managers/ThemeManager";
|
||||
import AsyncStorageManager from "../../managers/AsyncStorageManager";
|
||||
import {StackNavigationProp} from "@react-navigation/stack";
|
||||
import AvailableWebsites from "../../constants/AvailableWebsites";
|
||||
import {MASCOT_STYLE} from "../../components/Mascot/Mascot";
|
||||
import MascotPopup from "../../components/Mascot/MascotPopup";
|
||||
import LinearGradient from "react-native-linear-gradient";
|
||||
import CollapsibleScrollView from "../../components/Collapsible/CollapsibleScrollView";
|
||||
import {StackNavigationProp} from '@react-navigation/stack';
|
||||
import LinearGradient from 'react-native-linear-gradient';
|
||||
import ConnectionManager from '../../managers/ConnectionManager';
|
||||
import ErrorDialog from '../../components/Dialogs/ErrorDialog';
|
||||
import type {CustomThemeType} from '../../managers/ThemeManager';
|
||||
import AsyncStorageManager from '../../managers/AsyncStorageManager';
|
||||
import AvailableWebsites from '../../constants/AvailableWebsites';
|
||||
import {MASCOT_STYLE} from '../../components/Mascot/Mascot';
|
||||
import MascotPopup from '../../components/Mascot/MascotPopup';
|
||||
import CollapsibleScrollView from '../../components/Collapsible/CollapsibleScrollView';
|
||||
|
||||
type Props = {
|
||||
navigation: StackNavigationProp,
|
||||
route: { params: { nextScreen: string } },
|
||||
theme: CustomTheme
|
||||
}
|
||||
type PropsType = {
|
||||
navigation: StackNavigationProp,
|
||||
route: {params: {nextScreen: string}},
|
||||
theme: CustomThemeType,
|
||||
};
|
||||
|
||||
type State = {
|
||||
email: string,
|
||||
password: string,
|
||||
isEmailValidated: boolean,
|
||||
isPasswordValidated: boolean,
|
||||
loading: boolean,
|
||||
dialogVisible: boolean,
|
||||
dialogError: number,
|
||||
mascotDialogVisible: boolean,
|
||||
}
|
||||
type StateType = {
|
||||
email: string,
|
||||
password: string,
|
||||
isEmailValidated: boolean,
|
||||
isPasswordValidated: boolean,
|
||||
loading: boolean,
|
||||
dialogVisible: boolean,
|
||||
dialogError: number,
|
||||
mascotDialogVisible: boolean,
|
||||
};
|
||||
|
||||
const ICON_AMICALE = require('../../../assets/amicale.png');
|
||||
|
||||
const RESET_PASSWORD_PATH = "https://www.amicale-insat.fr/password/reset";
|
||||
const RESET_PASSWORD_PATH = 'https://www.amicale-insat.fr/password/reset';
|
||||
|
||||
const emailRegex = /^.+@.+\..+$/;
|
||||
|
||||
class LoginScreen extends React.Component<Props, State> {
|
||||
|
||||
state = {
|
||||
email: '',
|
||||
password: '',
|
||||
isEmailValidated: false,
|
||||
isPasswordValidated: false,
|
||||
loading: false,
|
||||
dialogVisible: false,
|
||||
dialogError: 0,
|
||||
mascotDialogVisible: AsyncStorageManager.getBool(AsyncStorageManager.PREFERENCES.loginShowBanner.key),
|
||||
};
|
||||
|
||||
onEmailChange: (value: string) => null;
|
||||
onPasswordChange: (value: string) => null;
|
||||
passwordInputRef: { current: null | TextInput };
|
||||
|
||||
nextScreen: string | null;
|
||||
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.passwordInputRef = React.createRef();
|
||||
this.onEmailChange = this.onInputChange.bind(this, true);
|
||||
this.onPasswordChange = this.onInputChange.bind(this, false);
|
||||
this.props.navigation.addListener('focus', this.onScreenFocus);
|
||||
}
|
||||
|
||||
onScreenFocus = () => {
|
||||
this.handleNavigationParams();
|
||||
};
|
||||
|
||||
/**
|
||||
* Saves the screen to navigate to after a successful login if one was provided in navigation parameters
|
||||
*/
|
||||
handleNavigationParams() {
|
||||
if (this.props.route.params != null) {
|
||||
if (this.props.route.params.nextScreen != null)
|
||||
this.nextScreen = this.props.route.params.nextScreen;
|
||||
else
|
||||
this.nextScreen = null;
|
||||
}
|
||||
}
|
||||
|
||||
hideMascotDialog = () => {
|
||||
AsyncStorageManager.set(AsyncStorageManager.PREFERENCES.loginShowBanner.key, false);
|
||||
this.setState({mascotDialogVisible: false})
|
||||
};
|
||||
|
||||
showMascotDialog = () => {
|
||||
this.setState({mascotDialogVisible: true})
|
||||
};
|
||||
|
||||
/**
|
||||
* Shows an error dialog with the corresponding login error
|
||||
*
|
||||
* @param error The error given by the login request
|
||||
*/
|
||||
showErrorDialog = (error: number) =>
|
||||
this.setState({
|
||||
dialogVisible: true,
|
||||
dialogError: error,
|
||||
});
|
||||
|
||||
hideErrorDialog = () => this.setState({dialogVisible: false});
|
||||
|
||||
/**
|
||||
* Navigates to the screen specified in navigation parameters or simply go back tha stack.
|
||||
* Saves in user preferences to not show the login banner again.
|
||||
*/
|
||||
handleSuccess = () => {
|
||||
// Do not show the home login banner again
|
||||
AsyncStorageManager.set(AsyncStorageManager.PREFERENCES.homeShowBanner.key, false);
|
||||
if (this.nextScreen == null)
|
||||
this.props.navigation.goBack();
|
||||
else
|
||||
this.props.navigation.replace(this.nextScreen);
|
||||
};
|
||||
|
||||
/**
|
||||
* Navigates to the Amicale website screen with the reset password link as navigation parameters
|
||||
*/
|
||||
onResetPasswordClick = () => this.props.navigation.navigate("website", {
|
||||
host: AvailableWebsites.websites.AMICALE,
|
||||
path: RESET_PASSWORD_PATH,
|
||||
title: i18n.t('screens.websites.amicale')
|
||||
});
|
||||
|
||||
/**
|
||||
* The user has unfocused the input, his email is ready to be validated
|
||||
*/
|
||||
validateEmail = () => this.setState({isEmailValidated: true});
|
||||
|
||||
/**
|
||||
* Checks if the entered email is valid (matches the regex)
|
||||
*
|
||||
* @returns {boolean}
|
||||
*/
|
||||
isEmailValid() {
|
||||
return emailRegex.test(this.state.email);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if we should tell the user his email is invalid.
|
||||
* We should only show this if his email is invalid and has been checked when un-focusing the input
|
||||
*
|
||||
* @returns {boolean|boolean}
|
||||
*/
|
||||
shouldShowEmailError() {
|
||||
return this.state.isEmailValidated && !this.isEmailValid();
|
||||
}
|
||||
|
||||
/**
|
||||
* The user has unfocused the input, his password is ready to be validated
|
||||
*/
|
||||
validatePassword = () => this.setState({isPasswordValidated: true});
|
||||
|
||||
/**
|
||||
* Checks if the user has entered a password
|
||||
*
|
||||
* @returns {boolean}
|
||||
*/
|
||||
isPasswordValid() {
|
||||
return this.state.password !== '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if we should tell the user his password is invalid.
|
||||
* We should only show this if his password is invalid and has been checked when un-focusing the input
|
||||
*
|
||||
* @returns {boolean|boolean}
|
||||
*/
|
||||
shouldShowPasswordError() {
|
||||
return this.state.isPasswordValidated && !this.isPasswordValid();
|
||||
}
|
||||
|
||||
/**
|
||||
* If the email and password are valid, and we are not loading a request, then the login button can be enabled
|
||||
*
|
||||
* @returns {boolean}
|
||||
*/
|
||||
shouldEnableLogin() {
|
||||
return this.isEmailValid() && this.isPasswordValid() && !this.state.loading;
|
||||
}
|
||||
|
||||
/**
|
||||
* Called when the user input changes in the email or password field.
|
||||
* This saves the new value in the State and disabled input validation (to prevent errors to show while typing)
|
||||
*
|
||||
* @param isEmail True if the field is the email field
|
||||
* @param value The new field value
|
||||
*/
|
||||
onInputChange(isEmail: boolean, value: string) {
|
||||
if (isEmail) {
|
||||
this.setState({
|
||||
email: value,
|
||||
isEmailValidated: false,
|
||||
});
|
||||
} else {
|
||||
this.setState({
|
||||
password: value,
|
||||
isPasswordValidated: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Focuses the password field when the email field is done
|
||||
*
|
||||
* @returns {*}
|
||||
*/
|
||||
onEmailSubmit = () => {
|
||||
if (this.passwordInputRef.current != null)
|
||||
this.passwordInputRef.current.focus();
|
||||
}
|
||||
|
||||
/**
|
||||
* Called when the user clicks on login or finishes to type his password.
|
||||
*
|
||||
* Checks if we should allow the user to login,
|
||||
* then makes the login request and enters a loading state until the request finishes
|
||||
*
|
||||
*/
|
||||
onSubmit = () => {
|
||||
if (this.shouldEnableLogin()) {
|
||||
this.setState({loading: true});
|
||||
ConnectionManager.getInstance().connect(this.state.email, this.state.password)
|
||||
.then(this.handleSuccess)
|
||||
.catch(this.showErrorDialog)
|
||||
.finally(() => {
|
||||
this.setState({loading: false});
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Gets the form input
|
||||
*
|
||||
* @returns {*}
|
||||
*/
|
||||
getFormInput() {
|
||||
return (
|
||||
<View>
|
||||
<TextInput
|
||||
label={i18n.t("screens.login.email")}
|
||||
mode='outlined'
|
||||
value={this.state.email}
|
||||
onChangeText={this.onEmailChange}
|
||||
onBlur={this.validateEmail}
|
||||
onSubmitEditing={this.onEmailSubmit}
|
||||
error={this.shouldShowEmailError()}
|
||||
textContentType={'emailAddress'}
|
||||
autoCapitalize={'none'}
|
||||
autoCompleteType={'email'}
|
||||
autoCorrect={false}
|
||||
keyboardType={'email-address'}
|
||||
returnKeyType={'next'}
|
||||
secureTextEntry={false}
|
||||
/>
|
||||
<HelperText
|
||||
type="error"
|
||||
visible={this.shouldShowEmailError()}
|
||||
>
|
||||
{i18n.t("screens.login.emailError")}
|
||||
</HelperText>
|
||||
<TextInput
|
||||
ref={this.passwordInputRef}
|
||||
label={i18n.t("screens.login.password")}
|
||||
mode='outlined'
|
||||
value={this.state.password}
|
||||
onChangeText={this.onPasswordChange}
|
||||
onBlur={this.validatePassword}
|
||||
onSubmitEditing={this.onSubmit}
|
||||
error={this.shouldShowPasswordError()}
|
||||
textContentType={'password'}
|
||||
autoCapitalize={'none'}
|
||||
autoCompleteType={'password'}
|
||||
autoCorrect={false}
|
||||
keyboardType={'default'}
|
||||
returnKeyType={'done'}
|
||||
secureTextEntry={true}
|
||||
/>
|
||||
<HelperText
|
||||
type="error"
|
||||
visible={this.shouldShowPasswordError()}
|
||||
>
|
||||
{i18n.t("screens.login.passwordError")}
|
||||
</HelperText>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the card containing the input form
|
||||
* @returns {*}
|
||||
*/
|
||||
getMainCard() {
|
||||
return (
|
||||
<View style={styles.card}>
|
||||
<Card.Title
|
||||
title={i18n.t("screens.login.title")}
|
||||
titleStyle={{color: "#fff"}}
|
||||
subtitle={i18n.t("screens.login.subtitle")}
|
||||
subtitleStyle={{color: "#fff"}}
|
||||
left={(props) => <Image
|
||||
{...props}
|
||||
source={ICON_AMICALE}
|
||||
style={{
|
||||
width: props.size,
|
||||
height: props.size,
|
||||
}}/>}
|
||||
/>
|
||||
<Card.Content>
|
||||
{this.getFormInput()}
|
||||
<Card.Actions style={{flexWrap: "wrap"}}>
|
||||
<Button
|
||||
icon="lock-question"
|
||||
mode="contained"
|
||||
onPress={this.onResetPasswordClick}
|
||||
color={this.props.theme.colors.warning}
|
||||
style={{marginRight: 'auto', marginBottom: 20}}>
|
||||
{i18n.t("screens.login.resetPassword")}
|
||||
</Button>
|
||||
<Button
|
||||
icon="send"
|
||||
mode="contained"
|
||||
disabled={!this.shouldEnableLogin()}
|
||||
loading={this.state.loading}
|
||||
onPress={this.onSubmit}
|
||||
style={{marginLeft: 'auto'}}>
|
||||
{i18n.t("screens.login.title")}
|
||||
</Button>
|
||||
|
||||
</Card.Actions>
|
||||
<Card.Actions>
|
||||
<Button
|
||||
icon="help-circle"
|
||||
mode="contained"
|
||||
onPress={this.showMascotDialog}
|
||||
style={{
|
||||
marginLeft: 'auto',
|
||||
marginRight: 'auto',
|
||||
}}>
|
||||
{i18n.t("screens.login.mascotDialog.title")}
|
||||
</Button>
|
||||
</Card.Actions>
|
||||
</Card.Content>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
render() {
|
||||
return (
|
||||
<LinearGradient
|
||||
style={{
|
||||
height: "100%"
|
||||
}}
|
||||
colors={['#9e0d18', '#530209']}
|
||||
start={{x: 0, y: 0.1}}
|
||||
end={{x: 0.1, y: 1}}>
|
||||
<KeyboardAvoidingView
|
||||
behavior={"height"}
|
||||
contentContainerStyle={styles.container}
|
||||
style={styles.container}
|
||||
enabled
|
||||
keyboardVerticalOffset={100}
|
||||
>
|
||||
<CollapsibleScrollView>
|
||||
<View style={{height: "100%"}}>
|
||||
{this.getMainCard()}
|
||||
</View>
|
||||
<MascotPopup
|
||||
visible={this.state.mascotDialogVisible}
|
||||
title={i18n.t("screens.login.mascotDialog.title")}
|
||||
message={i18n.t("screens.login.mascotDialog.message")}
|
||||
icon={"help"}
|
||||
buttons={{
|
||||
action: null,
|
||||
cancel: {
|
||||
message: i18n.t("screens.login.mascotDialog.button"),
|
||||
icon: "check",
|
||||
onPress: this.hideMascotDialog,
|
||||
}
|
||||
}}
|
||||
emotion={MASCOT_STYLE.NORMAL}
|
||||
/>
|
||||
<ErrorDialog
|
||||
visible={this.state.dialogVisible}
|
||||
onDismiss={this.hideErrorDialog}
|
||||
errorCode={this.state.dialogError}
|
||||
/>
|
||||
</CollapsibleScrollView>
|
||||
</KeyboardAvoidingView>
|
||||
</LinearGradient>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
container: {
|
||||
flex: 1,
|
||||
},
|
||||
card: {
|
||||
marginTop: 'auto',
|
||||
marginBottom: 'auto',
|
||||
},
|
||||
header: {
|
||||
fontSize: 36,
|
||||
marginBottom: 48
|
||||
},
|
||||
textInput: {},
|
||||
btnContainer: {
|
||||
marginTop: 5,
|
||||
marginBottom: 10,
|
||||
}
|
||||
container: {
|
||||
flex: 1,
|
||||
},
|
||||
card: {
|
||||
marginTop: 'auto',
|
||||
marginBottom: 'auto',
|
||||
},
|
||||
header: {
|
||||
fontSize: 36,
|
||||
marginBottom: 48,
|
||||
},
|
||||
textInput: {},
|
||||
btnContainer: {
|
||||
marginTop: 5,
|
||||
marginBottom: 10,
|
||||
},
|
||||
});
|
||||
|
||||
class LoginScreen extends React.Component<PropsType, StateType> {
|
||||
onEmailChange: (value: string) => void;
|
||||
|
||||
onPasswordChange: (value: string) => void;
|
||||
|
||||
passwordInputRef: {current: null | TextInput};
|
||||
|
||||
nextScreen: string | null;
|
||||
|
||||
constructor(props: PropsType) {
|
||||
super(props);
|
||||
this.passwordInputRef = React.createRef();
|
||||
this.onEmailChange = (value: string) => {
|
||||
this.onInputChange(true, value);
|
||||
};
|
||||
this.onPasswordChange = (value: string) => {
|
||||
this.onInputChange(false, value);
|
||||
};
|
||||
props.navigation.addListener('focus', this.onScreenFocus);
|
||||
this.state = {
|
||||
email: '',
|
||||
password: '',
|
||||
isEmailValidated: false,
|
||||
isPasswordValidated: false,
|
||||
loading: false,
|
||||
dialogVisible: false,
|
||||
dialogError: 0,
|
||||
mascotDialogVisible: AsyncStorageManager.getBool(
|
||||
AsyncStorageManager.PREFERENCES.loginShowBanner.key,
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
onScreenFocus = () => {
|
||||
this.handleNavigationParams();
|
||||
};
|
||||
|
||||
/**
|
||||
* Navigates to the Amicale website screen with the reset password link as navigation parameters
|
||||
*/
|
||||
onResetPasswordClick = () => {
|
||||
const {navigation} = this.props;
|
||||
navigation.navigate('website', {
|
||||
host: AvailableWebsites.websites.AMICALE,
|
||||
path: RESET_PASSWORD_PATH,
|
||||
title: i18n.t('screens.websites.amicale'),
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Called when the user input changes in the email or password field.
|
||||
* This saves the new value in the State and disabled input validation (to prevent errors to show while typing)
|
||||
*
|
||||
* @param isEmail True if the field is the email field
|
||||
* @param value The new field value
|
||||
*/
|
||||
onInputChange(isEmail: boolean, value: string) {
|
||||
if (isEmail) {
|
||||
this.setState({
|
||||
email: value,
|
||||
isEmailValidated: false,
|
||||
});
|
||||
} else {
|
||||
this.setState({
|
||||
password: value,
|
||||
isPasswordValidated: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Focuses the password field when the email field is done
|
||||
*
|
||||
* @returns {*}
|
||||
*/
|
||||
onEmailSubmit = () => {
|
||||
if (this.passwordInputRef.current != null)
|
||||
this.passwordInputRef.current.focus();
|
||||
};
|
||||
|
||||
/**
|
||||
* Called when the user clicks on login or finishes to type his password.
|
||||
*
|
||||
* Checks if we should allow the user to login,
|
||||
* then makes the login request and enters a loading state until the request finishes
|
||||
*
|
||||
*/
|
||||
onSubmit = () => {
|
||||
const {email, password} = this.state;
|
||||
if (this.shouldEnableLogin()) {
|
||||
this.setState({loading: true});
|
||||
ConnectionManager.getInstance()
|
||||
.connect(email, password)
|
||||
.then(this.handleSuccess)
|
||||
.catch(this.showErrorDialog)
|
||||
.finally(() => {
|
||||
this.setState({loading: false});
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Gets the form input
|
||||
*
|
||||
* @returns {*}
|
||||
*/
|
||||
getFormInput(): React.Node {
|
||||
const {email, password} = this.state;
|
||||
return (
|
||||
<View>
|
||||
<TextInput
|
||||
label={i18n.t('screens.login.email')}
|
||||
mode="outlined"
|
||||
value={email}
|
||||
onChangeText={this.onEmailChange}
|
||||
onBlur={this.validateEmail}
|
||||
onSubmitEditing={this.onEmailSubmit}
|
||||
error={this.shouldShowEmailError()}
|
||||
textContentType="emailAddress"
|
||||
autoCapitalize="none"
|
||||
autoCompleteType="email"
|
||||
autoCorrect={false}
|
||||
keyboardType="email-address"
|
||||
returnKeyType="next"
|
||||
secureTextEntry={false}
|
||||
/>
|
||||
<HelperText type="error" visible={this.shouldShowEmailError()}>
|
||||
{i18n.t('screens.login.emailError')}
|
||||
</HelperText>
|
||||
<TextInput
|
||||
ref={this.passwordInputRef}
|
||||
label={i18n.t('screens.login.password')}
|
||||
mode="outlined"
|
||||
value={password}
|
||||
onChangeText={this.onPasswordChange}
|
||||
onBlur={this.validatePassword}
|
||||
onSubmitEditing={this.onSubmit}
|
||||
error={this.shouldShowPasswordError()}
|
||||
textContentType="password"
|
||||
autoCapitalize="none"
|
||||
autoCompleteType="password"
|
||||
autoCorrect={false}
|
||||
keyboardType="default"
|
||||
returnKeyType="done"
|
||||
secureTextEntry
|
||||
/>
|
||||
<HelperText type="error" visible={this.shouldShowPasswordError()}>
|
||||
{i18n.t('screens.login.passwordError')}
|
||||
</HelperText>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the card containing the input form
|
||||
* @returns {*}
|
||||
*/
|
||||
getMainCard(): React.Node {
|
||||
const {props, state} = this;
|
||||
return (
|
||||
<View style={styles.card}>
|
||||
<Card.Title
|
||||
title={i18n.t('screens.login.title')}
|
||||
titleStyle={{color: '#fff'}}
|
||||
subtitle={i18n.t('screens.login.subtitle')}
|
||||
subtitleStyle={{color: '#fff'}}
|
||||
left={({size}: {size: number}): React.Node => (
|
||||
<Image
|
||||
source={ICON_AMICALE}
|
||||
style={{
|
||||
width: size,
|
||||
height: size,
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
<Card.Content>
|
||||
{this.getFormInput()}
|
||||
<Card.Actions style={{flexWrap: 'wrap'}}>
|
||||
<Button
|
||||
icon="lock-question"
|
||||
mode="contained"
|
||||
onPress={this.onResetPasswordClick}
|
||||
color={props.theme.colors.warning}
|
||||
style={{marginRight: 'auto', marginBottom: 20}}>
|
||||
{i18n.t('screens.login.resetPassword')}
|
||||
</Button>
|
||||
<Button
|
||||
icon="send"
|
||||
mode="contained"
|
||||
disabled={!this.shouldEnableLogin()}
|
||||
loading={state.loading}
|
||||
onPress={this.onSubmit}
|
||||
style={{marginLeft: 'auto'}}>
|
||||
{i18n.t('screens.login.title')}
|
||||
</Button>
|
||||
</Card.Actions>
|
||||
<Card.Actions>
|
||||
<Button
|
||||
icon="help-circle"
|
||||
mode="contained"
|
||||
onPress={this.showMascotDialog}
|
||||
style={{
|
||||
marginLeft: 'auto',
|
||||
marginRight: 'auto',
|
||||
}}>
|
||||
{i18n.t('screens.login.mascotDialog.title')}
|
||||
</Button>
|
||||
</Card.Actions>
|
||||
</Card.Content>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The user has unfocused the input, his email is ready to be validated
|
||||
*/
|
||||
validateEmail = () => {
|
||||
this.setState({isEmailValidated: true});
|
||||
};
|
||||
|
||||
/**
|
||||
* The user has unfocused the input, his password is ready to be validated
|
||||
*/
|
||||
validatePassword = () => {
|
||||
this.setState({isPasswordValidated: true});
|
||||
};
|
||||
|
||||
hideMascotDialog = () => {
|
||||
AsyncStorageManager.set(
|
||||
AsyncStorageManager.PREFERENCES.loginShowBanner.key,
|
||||
false,
|
||||
);
|
||||
this.setState({mascotDialogVisible: false});
|
||||
};
|
||||
|
||||
showMascotDialog = () => {
|
||||
this.setState({mascotDialogVisible: true});
|
||||
};
|
||||
|
||||
/**
|
||||
* Shows an error dialog with the corresponding login error
|
||||
*
|
||||
* @param error The error given by the login request
|
||||
*/
|
||||
showErrorDialog = (error: number) => {
|
||||
this.setState({
|
||||
dialogVisible: true,
|
||||
dialogError: error,
|
||||
});
|
||||
};
|
||||
|
||||
hideErrorDialog = () => {
|
||||
this.setState({dialogVisible: false});
|
||||
};
|
||||
|
||||
/**
|
||||
* Navigates to the screen specified in navigation parameters or simply go back tha stack.
|
||||
* Saves in user preferences to not show the login banner again.
|
||||
*/
|
||||
handleSuccess = () => {
|
||||
const {navigation} = this.props;
|
||||
// Do not show the home login banner again
|
||||
AsyncStorageManager.set(
|
||||
AsyncStorageManager.PREFERENCES.homeShowBanner.key,
|
||||
false,
|
||||
);
|
||||
if (this.nextScreen == null) navigation.goBack();
|
||||
else navigation.replace(this.nextScreen);
|
||||
};
|
||||
|
||||
/**
|
||||
* Saves the screen to navigate to after a successful login if one was provided in navigation parameters
|
||||
*/
|
||||
handleNavigationParams() {
|
||||
const {route} = this.props;
|
||||
if (route.params != null) {
|
||||
if (route.params.nextScreen != null)
|
||||
this.nextScreen = route.params.nextScreen;
|
||||
else this.nextScreen = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the entered email is valid (matches the regex)
|
||||
*
|
||||
* @returns {boolean}
|
||||
*/
|
||||
isEmailValid(): boolean {
|
||||
const {email} = this.state;
|
||||
return emailRegex.test(email);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if we should tell the user his email is invalid.
|
||||
* We should only show this if his email is invalid and has been checked when un-focusing the input
|
||||
*
|
||||
* @returns {boolean|boolean}
|
||||
*/
|
||||
shouldShowEmailError(): boolean {
|
||||
const {isEmailValidated} = this.state;
|
||||
return isEmailValidated && !this.isEmailValid();
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the user has entered a password
|
||||
*
|
||||
* @returns {boolean}
|
||||
*/
|
||||
isPasswordValid(): boolean {
|
||||
const {password} = this.state;
|
||||
return password !== '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if we should tell the user his password is invalid.
|
||||
* We should only show this if his password is invalid and has been checked when un-focusing the input
|
||||
*
|
||||
* @returns {boolean|boolean}
|
||||
*/
|
||||
shouldShowPasswordError(): boolean {
|
||||
const {isPasswordValidated} = this.state;
|
||||
return isPasswordValidated && !this.isPasswordValid();
|
||||
}
|
||||
|
||||
/**
|
||||
* If the email and password are valid, and we are not loading a request, then the login button can be enabled
|
||||
*
|
||||
* @returns {boolean}
|
||||
*/
|
||||
shouldEnableLogin(): boolean {
|
||||
const {loading} = this.state;
|
||||
return this.isEmailValid() && this.isPasswordValid() && !loading;
|
||||
}
|
||||
|
||||
render(): React.Node {
|
||||
const {mascotDialogVisible, dialogVisible, dialogError} = this.state;
|
||||
return (
|
||||
<LinearGradient
|
||||
style={{
|
||||
height: '100%',
|
||||
}}
|
||||
colors={['#9e0d18', '#530209']}
|
||||
start={{x: 0, y: 0.1}}
|
||||
end={{x: 0.1, y: 1}}>
|
||||
<KeyboardAvoidingView
|
||||
behavior="height"
|
||||
contentContainerStyle={styles.container}
|
||||
style={styles.container}
|
||||
enabled
|
||||
keyboardVerticalOffset={100}>
|
||||
<CollapsibleScrollView>
|
||||
<View style={{height: '100%'}}>{this.getMainCard()}</View>
|
||||
<MascotPopup
|
||||
visible={mascotDialogVisible}
|
||||
title={i18n.t('screens.login.mascotDialog.title')}
|
||||
message={i18n.t('screens.login.mascotDialog.message')}
|
||||
icon="help"
|
||||
buttons={{
|
||||
action: null,
|
||||
cancel: {
|
||||
message: i18n.t('screens.login.mascotDialog.button'),
|
||||
icon: 'check',
|
||||
onPress: this.hideMascotDialog,
|
||||
},
|
||||
}}
|
||||
emotion={MASCOT_STYLE.NORMAL}
|
||||
/>
|
||||
<ErrorDialog
|
||||
visible={dialogVisible}
|
||||
onDismiss={this.hideErrorDialog}
|
||||
errorCode={dialogError}
|
||||
/>
|
||||
</CollapsibleScrollView>
|
||||
</KeyboardAvoidingView>
|
||||
</LinearGradient>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default withTheme(LoginScreen);
|
||||
|
|
|
|||
|
|
@ -1,432 +1,467 @@
|
|||
// @flow
|
||||
|
||||
import * as React from 'react';
|
||||
import {FlatList, StyleSheet, View} from "react-native";
|
||||
import {Avatar, Button, Card, Divider, List, Paragraph, withTheme} from 'react-native-paper';
|
||||
import AuthenticatedScreen from "../../components/Amicale/AuthenticatedScreen";
|
||||
import {FlatList, StyleSheet, View} from 'react-native';
|
||||
import {
|
||||
Avatar,
|
||||
Button,
|
||||
Card,
|
||||
Divider,
|
||||
List,
|
||||
Paragraph,
|
||||
withTheme,
|
||||
} from 'react-native-paper';
|
||||
import i18n from 'i18n-js';
|
||||
import LogoutDialog from "../../components/Amicale/LogoutDialog";
|
||||
import MaterialHeaderButtons, {Item} from "../../components/Overrides/CustomHeaderButton";
|
||||
import type {cardList} from "../../components/Lists/CardList/CardList";
|
||||
import CardList from "../../components/Lists/CardList/CardList";
|
||||
import {StackNavigationProp} from "@react-navigation/stack";
|
||||
import type {CustomTheme} from "../../managers/ThemeManager";
|
||||
import AvailableWebsites from "../../constants/AvailableWebsites";
|
||||
import Mascot, {MASCOT_STYLE} from "../../components/Mascot/Mascot";
|
||||
import ServicesManager, {SERVICES_KEY} from "../../managers/ServicesManager";
|
||||
import CollapsibleFlatList from "../../components/Collapsible/CollapsibleFlatList";
|
||||
import {StackNavigationProp} from '@react-navigation/stack';
|
||||
import AuthenticatedScreen from '../../components/Amicale/AuthenticatedScreen';
|
||||
import LogoutDialog from '../../components/Amicale/LogoutDialog';
|
||||
import MaterialHeaderButtons, {
|
||||
Item,
|
||||
} from '../../components/Overrides/CustomHeaderButton';
|
||||
import CardList from '../../components/Lists/CardList/CardList';
|
||||
import type {CustomThemeType} from '../../managers/ThemeManager';
|
||||
import AvailableWebsites from '../../constants/AvailableWebsites';
|
||||
import Mascot, {MASCOT_STYLE} from '../../components/Mascot/Mascot';
|
||||
import ServicesManager, {SERVICES_KEY} from '../../managers/ServicesManager';
|
||||
import CollapsibleFlatList from '../../components/Collapsible/CollapsibleFlatList';
|
||||
import type {ServiceItemType} from '../../managers/ServicesManager';
|
||||
|
||||
type Props = {
|
||||
navigation: StackNavigationProp,
|
||||
theme: CustomTheme,
|
||||
}
|
||||
type PropsType = {
|
||||
navigation: StackNavigationProp,
|
||||
theme: CustomThemeType,
|
||||
};
|
||||
|
||||
type State = {
|
||||
dialogVisible: boolean,
|
||||
}
|
||||
type StateType = {
|
||||
dialogVisible: boolean,
|
||||
};
|
||||
|
||||
type ProfileData = {
|
||||
first_name: string,
|
||||
last_name: string,
|
||||
email: string,
|
||||
birthday: string,
|
||||
phone: string,
|
||||
branch: string,
|
||||
link: string,
|
||||
validity: boolean,
|
||||
clubs: Array<Club>,
|
||||
}
|
||||
type Club = {
|
||||
id: number,
|
||||
name: string,
|
||||
is_manager: boolean,
|
||||
}
|
||||
type ClubType = {
|
||||
id: number,
|
||||
name: string,
|
||||
is_manager: boolean,
|
||||
};
|
||||
|
||||
class ProfileScreen extends React.Component<Props, State> {
|
||||
|
||||
state = {
|
||||
dialogVisible: false,
|
||||
};
|
||||
|
||||
data: ProfileData;
|
||||
|
||||
flatListData: Array<{ id: string }>;
|
||||
amicaleDataset: cardList;
|
||||
|
||||
constructor(props: Props) {
|
||||
super(props);
|
||||
this.flatListData = [
|
||||
{id: '0'},
|
||||
{id: '1'},
|
||||
{id: '2'},
|
||||
{id: '3'},
|
||||
]
|
||||
const services = new ServicesManager(props.navigation);
|
||||
this.amicaleDataset = services.getAmicaleServices([SERVICES_KEY.PROFILE]);
|
||||
}
|
||||
|
||||
componentDidMount() {
|
||||
this.props.navigation.setOptions({
|
||||
headerRight: this.getHeaderButton,
|
||||
});
|
||||
}
|
||||
|
||||
showDisconnectDialog = () => this.setState({dialogVisible: true});
|
||||
|
||||
hideDisconnectDialog = () => this.setState({dialogVisible: false});
|
||||
|
||||
/**
|
||||
* Gets the logout header button
|
||||
*
|
||||
* @returns {*}
|
||||
*/
|
||||
getHeaderButton = () => <MaterialHeaderButtons>
|
||||
<Item title="logout" iconName="logout" onPress={this.showDisconnectDialog}/>
|
||||
</MaterialHeaderButtons>;
|
||||
|
||||
/**
|
||||
* Gets the main screen component with the fetched data
|
||||
*
|
||||
* @param data The data fetched from the server
|
||||
* @returns {*}
|
||||
*/
|
||||
getScreen = (data: Array<{ [key: string]: any } | null>) => {
|
||||
if (data[0] != null) {
|
||||
this.data = data[0];
|
||||
}
|
||||
return (
|
||||
<View style={{flex: 1}}>
|
||||
<CollapsibleFlatList
|
||||
renderItem={this.getRenderItem}
|
||||
data={this.flatListData}
|
||||
/>
|
||||
<LogoutDialog
|
||||
{...this.props}
|
||||
visible={this.state.dialogVisible}
|
||||
onDismiss={this.hideDisconnectDialog}
|
||||
/>
|
||||
</View>
|
||||
)
|
||||
};
|
||||
|
||||
getRenderItem = ({item}: { item: { id: string } }) => {
|
||||
switch (item.id) {
|
||||
case '0':
|
||||
return this.getWelcomeCard();
|
||||
case '1':
|
||||
return this.getPersonalCard();
|
||||
case '2':
|
||||
return this.getClubCard();
|
||||
default:
|
||||
return this.getMembershipCar();
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Gets the list of services available with the Amicale account
|
||||
*
|
||||
* @returns {*}
|
||||
*/
|
||||
getServicesList() {
|
||||
return (
|
||||
<CardList
|
||||
dataset={this.amicaleDataset}
|
||||
isHorizontal={true}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a card welcoming the user to his account
|
||||
*
|
||||
* @returns {*}
|
||||
*/
|
||||
getWelcomeCard() {
|
||||
return (
|
||||
<Card style={styles.card}>
|
||||
<Card.Title
|
||||
title={i18n.t("screens.profile.welcomeTitle", {name: this.data.first_name})}
|
||||
left={() =>
|
||||
<Mascot
|
||||
style={{
|
||||
width: 60
|
||||
}}
|
||||
emotion={MASCOT_STYLE.COOL}
|
||||
animated={true}
|
||||
entryAnimation={{
|
||||
animation: "bounceIn",
|
||||
duration: 1000
|
||||
}}
|
||||
/>}
|
||||
titleStyle={{marginLeft: 10}}
|
||||
/>
|
||||
<Card.Content>
|
||||
<Divider/>
|
||||
<Paragraph>
|
||||
{i18n.t("screens.profile.welcomeDescription")}
|
||||
</Paragraph>
|
||||
{this.getServicesList()}
|
||||
<Paragraph>
|
||||
{i18n.t("screens.profile.welcomeFeedback")}
|
||||
</Paragraph>
|
||||
<Divider/>
|
||||
<Card.Actions>
|
||||
<Button
|
||||
icon="bug"
|
||||
mode="contained"
|
||||
onPress={() => this.props.navigation.navigate('feedback')}
|
||||
style={styles.editButton}>
|
||||
{i18n.t("screens.feedback.homeButtonTitle")}
|
||||
</Button>
|
||||
</Card.Actions>
|
||||
</Card.Content>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the given field is available
|
||||
*
|
||||
* @param field The field to check
|
||||
* @return {boolean}
|
||||
*/
|
||||
isFieldAvailable(field: ?string) {
|
||||
return field !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the given field value.
|
||||
* If the field does not have a value, returns a placeholder text
|
||||
*
|
||||
* @param field The field to get the value from
|
||||
* @return {*}
|
||||
*/
|
||||
getFieldValue(field: ?string) {
|
||||
return this.isFieldAvailable(field)
|
||||
? field
|
||||
: i18n.t("screens.profile.noData");
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a list item showing personal information
|
||||
*
|
||||
* @param field The field to display
|
||||
* @param icon The icon to use
|
||||
* @return {*}
|
||||
*/
|
||||
getPersonalListItem(field: ?string, icon: string) {
|
||||
let title = this.isFieldAvailable(field) ? this.getFieldValue(field) : ':(';
|
||||
let subtitle = this.isFieldAvailable(field) ? '' : this.getFieldValue(field);
|
||||
return (
|
||||
<List.Item
|
||||
title={title}
|
||||
description={subtitle}
|
||||
left={props => <List.Icon
|
||||
{...props}
|
||||
icon={icon}
|
||||
color={this.isFieldAvailable(field) ? undefined : this.props.theme.colors.textDisabled}
|
||||
/>}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a card containing user personal information
|
||||
*
|
||||
* @return {*}
|
||||
*/
|
||||
getPersonalCard() {
|
||||
return (
|
||||
<Card style={styles.card}>
|
||||
<Card.Title
|
||||
title={this.data.first_name + ' ' + this.data.last_name}
|
||||
subtitle={this.data.email}
|
||||
left={(props) => <Avatar.Icon
|
||||
{...props}
|
||||
icon="account"
|
||||
color={this.props.theme.colors.primary}
|
||||
style={styles.icon}
|
||||
/>}
|
||||
/>
|
||||
<Card.Content>
|
||||
<Divider/>
|
||||
<List.Section>
|
||||
<List.Subheader>{i18n.t("screens.profile.personalInformation")}</List.Subheader>
|
||||
{this.getPersonalListItem(this.data.birthday, "cake-variant")}
|
||||
{this.getPersonalListItem(this.data.phone, "phone")}
|
||||
{this.getPersonalListItem(this.data.email, "email")}
|
||||
{this.getPersonalListItem(this.data.branch, "school")}
|
||||
</List.Section>
|
||||
<Divider/>
|
||||
<Card.Actions>
|
||||
<Button
|
||||
icon="account-edit"
|
||||
mode="contained"
|
||||
onPress={() => this.props.navigation.navigate("website", {
|
||||
host: AvailableWebsites.websites.AMICALE,
|
||||
path: this.data.link,
|
||||
title: i18n.t('screens.websites.amicale')
|
||||
})}
|
||||
style={styles.editButton}>
|
||||
{i18n.t("screens.profile.editInformation")}
|
||||
</Button>
|
||||
</Card.Actions>
|
||||
</Card.Content>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a cars containing clubs the user is part of
|
||||
*
|
||||
* @return {*}
|
||||
*/
|
||||
getClubCard() {
|
||||
return (
|
||||
<Card style={styles.card}>
|
||||
<Card.Title
|
||||
title={i18n.t("screens.profile.clubs")}
|
||||
subtitle={i18n.t("screens.profile.clubsSubtitle")}
|
||||
left={(props) => <Avatar.Icon
|
||||
{...props}
|
||||
icon="account-group"
|
||||
color={this.props.theme.colors.primary}
|
||||
style={styles.icon}
|
||||
/>}
|
||||
/>
|
||||
<Card.Content>
|
||||
<Divider/>
|
||||
{this.getClubList(this.data.clubs)}
|
||||
</Card.Content>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a card showing if the user has payed his membership
|
||||
*
|
||||
* @return {*}
|
||||
*/
|
||||
getMembershipCar() {
|
||||
return (
|
||||
<Card style={styles.card}>
|
||||
<Card.Title
|
||||
title={i18n.t("screens.profile.membership")}
|
||||
subtitle={i18n.t("screens.profile.membershipSubtitle")}
|
||||
left={(props) => <Avatar.Icon
|
||||
{...props}
|
||||
icon="credit-card"
|
||||
color={this.props.theme.colors.primary}
|
||||
style={styles.icon}
|
||||
/>}
|
||||
/>
|
||||
<Card.Content>
|
||||
<List.Section>
|
||||
{this.getMembershipItem(this.data.validity)}
|
||||
</List.Section>
|
||||
</Card.Content>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the item showing if the user has payed his membership
|
||||
*
|
||||
* @return {*}
|
||||
*/
|
||||
getMembershipItem(state: boolean) {
|
||||
return (
|
||||
<List.Item
|
||||
title={state ? i18n.t("screens.profile.membershipPayed") : i18n.t("screens.profile.membershipNotPayed")}
|
||||
left={props => <List.Icon
|
||||
{...props}
|
||||
color={state ? this.props.theme.colors.success : this.props.theme.colors.danger}
|
||||
icon={state ? 'check' : 'close'}
|
||||
/>}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens the club details screen for the club of given ID
|
||||
* @param id The club's id to open
|
||||
*/
|
||||
openClubDetailsScreen(id: number) {
|
||||
this.props.navigation.navigate("club-information", {clubId: id});
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a list item for the club list
|
||||
*
|
||||
* @param item The club to render
|
||||
* @return {*}
|
||||
*/
|
||||
clubListItem = ({item}: { item: Club }) => {
|
||||
const onPress = () => this.openClubDetailsScreen(item.id);
|
||||
let description = i18n.t("screens.profile.isMember");
|
||||
let icon = (props) => <List.Icon {...props} icon="chevron-right"/>;
|
||||
if (item.is_manager) {
|
||||
description = i18n.t("screens.profile.isManager");
|
||||
icon = (props) => <List.Icon {...props} icon="star" color={this.props.theme.colors.primary}/>;
|
||||
}
|
||||
return <List.Item
|
||||
title={item.name}
|
||||
description={description}
|
||||
left={icon}
|
||||
onPress={onPress}
|
||||
/>;
|
||||
};
|
||||
|
||||
clubKeyExtractor = (item: Club) => item.name;
|
||||
|
||||
sortClubList = (a: Club, b: Club) => a.is_manager ? -1 : 1;
|
||||
|
||||
/**
|
||||
* Renders the list of clubs the user is part of
|
||||
*
|
||||
* @param list The club list
|
||||
* @return {*}
|
||||
*/
|
||||
getClubList(list: Array<Club>) {
|
||||
list.sort(this.sortClubList);
|
||||
return (
|
||||
//$FlowFixMe
|
||||
<FlatList
|
||||
renderItem={this.clubListItem}
|
||||
keyExtractor={this.clubKeyExtractor}
|
||||
data={list}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
render() {
|
||||
return (
|
||||
<AuthenticatedScreen
|
||||
{...this.props}
|
||||
requests={[
|
||||
{
|
||||
link: 'user/profile',
|
||||
params: {},
|
||||
mandatory: true,
|
||||
}
|
||||
]}
|
||||
renderFunction={this.getScreen}
|
||||
/>
|
||||
);
|
||||
}
|
||||
}
|
||||
type ProfileDataType = {
|
||||
first_name: string,
|
||||
last_name: string,
|
||||
email: string,
|
||||
birthday: string,
|
||||
phone: string,
|
||||
branch: string,
|
||||
link: string,
|
||||
validity: boolean,
|
||||
clubs: Array<ClubType>,
|
||||
};
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
card: {
|
||||
margin: 10,
|
||||
},
|
||||
icon: {
|
||||
backgroundColor: 'transparent'
|
||||
},
|
||||
editButton: {
|
||||
marginLeft: 'auto'
|
||||
}
|
||||
|
||||
card: {
|
||||
margin: 10,
|
||||
},
|
||||
icon: {
|
||||
backgroundColor: 'transparent',
|
||||
},
|
||||
editButton: {
|
||||
marginLeft: 'auto',
|
||||
},
|
||||
});
|
||||
|
||||
class ProfileScreen extends React.Component<PropsType, StateType> {
|
||||
data: ProfileDataType;
|
||||
|
||||
flatListData: Array<{id: string}>;
|
||||
|
||||
amicaleDataset: Array<ServiceItemType>;
|
||||
|
||||
constructor(props: PropsType) {
|
||||
super(props);
|
||||
this.flatListData = [{id: '0'}, {id: '1'}, {id: '2'}, {id: '3'}];
|
||||
const services = new ServicesManager(props.navigation);
|
||||
this.amicaleDataset = services.getAmicaleServices([SERVICES_KEY.PROFILE]);
|
||||
this.state = {
|
||||
dialogVisible: false,
|
||||
};
|
||||
}
|
||||
|
||||
componentDidMount() {
|
||||
const {navigation} = this.props;
|
||||
navigation.setOptions({
|
||||
headerRight: this.getHeaderButton,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the logout header button
|
||||
*
|
||||
* @returns {*}
|
||||
*/
|
||||
getHeaderButton = (): React.Node => (
|
||||
<MaterialHeaderButtons>
|
||||
<Item
|
||||
title="logout"
|
||||
iconName="logout"
|
||||
onPress={this.showDisconnectDialog}
|
||||
/>
|
||||
</MaterialHeaderButtons>
|
||||
);
|
||||
|
||||
/**
|
||||
* Gets the main screen component with the fetched data
|
||||
*
|
||||
* @param data The data fetched from the server
|
||||
* @returns {*}
|
||||
*/
|
||||
getScreen = (data: Array<ProfileDataType | null>): React.Node => {
|
||||
const {dialogVisible} = this.state;
|
||||
const {navigation} = this.props;
|
||||
// eslint-disable-next-line prefer-destructuring
|
||||
if (data[0] != null) this.data = data[0];
|
||||
|
||||
return (
|
||||
<View style={{flex: 1}}>
|
||||
<CollapsibleFlatList
|
||||
renderItem={this.getRenderItem}
|
||||
data={this.flatListData}
|
||||
/>
|
||||
<LogoutDialog
|
||||
navigation={navigation}
|
||||
visible={dialogVisible}
|
||||
onDismiss={this.hideDisconnectDialog}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
};
|
||||
|
||||
getRenderItem = ({item}: {item: {id: string}}): React.Node => {
|
||||
switch (item.id) {
|
||||
case '0':
|
||||
return this.getWelcomeCard();
|
||||
case '1':
|
||||
return this.getPersonalCard();
|
||||
case '2':
|
||||
return this.getClubCard();
|
||||
default:
|
||||
return this.getMembershipCar();
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Gets the list of services available with the Amicale account
|
||||
*
|
||||
* @returns {*}
|
||||
*/
|
||||
getServicesList(): React.Node {
|
||||
return <CardList dataset={this.amicaleDataset} isHorizontal />;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a card welcoming the user to his account
|
||||
*
|
||||
* @returns {*}
|
||||
*/
|
||||
getWelcomeCard(): React.Node {
|
||||
const {navigation} = this.props;
|
||||
return (
|
||||
<Card style={styles.card}>
|
||||
<Card.Title
|
||||
title={i18n.t('screens.profile.welcomeTitle', {
|
||||
name: this.data.first_name,
|
||||
})}
|
||||
left={(): React.Node => (
|
||||
<Mascot
|
||||
style={{
|
||||
width: 60,
|
||||
}}
|
||||
emotion={MASCOT_STYLE.COOL}
|
||||
animated
|
||||
entryAnimation={{
|
||||
animation: 'bounceIn',
|
||||
duration: 1000,
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
titleStyle={{marginLeft: 10}}
|
||||
/>
|
||||
<Card.Content>
|
||||
<Divider />
|
||||
<Paragraph>{i18n.t('screens.profile.welcomeDescription')}</Paragraph>
|
||||
{this.getServicesList()}
|
||||
<Paragraph>{i18n.t('screens.profile.welcomeFeedback')}</Paragraph>
|
||||
<Divider />
|
||||
<Card.Actions>
|
||||
<Button
|
||||
icon="bug"
|
||||
mode="contained"
|
||||
onPress={() => {
|
||||
navigation.navigate('feedback');
|
||||
}}
|
||||
style={styles.editButton}>
|
||||
{i18n.t('screens.feedback.homeButtonTitle')}
|
||||
</Button>
|
||||
</Card.Actions>
|
||||
</Card.Content>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the given field value.
|
||||
* If the field does not have a value, returns a placeholder text
|
||||
*
|
||||
* @param field The field to get the value from
|
||||
* @return {*}
|
||||
*/
|
||||
static getFieldValue(field: ?string): string {
|
||||
return field != null ? field : i18n.t('screens.profile.noData');
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a list item showing personal information
|
||||
*
|
||||
* @param field The field to display
|
||||
* @param icon The icon to use
|
||||
* @return {*}
|
||||
*/
|
||||
getPersonalListItem(field: ?string, icon: string): React.Node {
|
||||
const {theme} = this.props;
|
||||
const title = field != null ? ProfileScreen.getFieldValue(field) : ':(';
|
||||
const subtitle = field != null ? '' : ProfileScreen.getFieldValue(field);
|
||||
return (
|
||||
<List.Item
|
||||
title={title}
|
||||
description={subtitle}
|
||||
left={({size}: {size: number}): React.Node => (
|
||||
<List.Icon
|
||||
size={size}
|
||||
icon={icon}
|
||||
color={field != null ? null : theme.colors.textDisabled}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a card containing user personal information
|
||||
*
|
||||
* @return {*}
|
||||
*/
|
||||
getPersonalCard(): React.Node {
|
||||
const {theme, navigation} = this.props;
|
||||
return (
|
||||
<Card style={styles.card}>
|
||||
<Card.Title
|
||||
title={`${this.data.first_name} ${this.data.last_name}`}
|
||||
subtitle={this.data.email}
|
||||
left={({size}: {size: number}): React.Node => (
|
||||
<Avatar.Icon
|
||||
size={size}
|
||||
icon="account"
|
||||
color={theme.colors.primary}
|
||||
style={styles.icon}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
<Card.Content>
|
||||
<Divider />
|
||||
<List.Section>
|
||||
<List.Subheader>
|
||||
{i18n.t('screens.profile.personalInformation')}
|
||||
</List.Subheader>
|
||||
{this.getPersonalListItem(this.data.birthday, 'cake-variant')}
|
||||
{this.getPersonalListItem(this.data.phone, 'phone')}
|
||||
{this.getPersonalListItem(this.data.email, 'email')}
|
||||
{this.getPersonalListItem(this.data.branch, 'school')}
|
||||
</List.Section>
|
||||
<Divider />
|
||||
<Card.Actions>
|
||||
<Button
|
||||
icon="account-edit"
|
||||
mode="contained"
|
||||
onPress={() => {
|
||||
navigation.navigate('website', {
|
||||
host: AvailableWebsites.websites.AMICALE,
|
||||
path: this.data.link,
|
||||
title: i18n.t('screens.websites.amicale'),
|
||||
});
|
||||
}}
|
||||
style={styles.editButton}>
|
||||
{i18n.t('screens.profile.editInformation')}
|
||||
</Button>
|
||||
</Card.Actions>
|
||||
</Card.Content>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a cars containing clubs the user is part of
|
||||
*
|
||||
* @return {*}
|
||||
*/
|
||||
getClubCard(): React.Node {
|
||||
const {theme} = this.props;
|
||||
return (
|
||||
<Card style={styles.card}>
|
||||
<Card.Title
|
||||
title={i18n.t('screens.profile.clubs')}
|
||||
subtitle={i18n.t('screens.profile.clubsSubtitle')}
|
||||
left={({size}: {size: number}): React.Node => (
|
||||
<Avatar.Icon
|
||||
size={size}
|
||||
icon="account-group"
|
||||
color={theme.colors.primary}
|
||||
style={styles.icon}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
<Card.Content>
|
||||
<Divider />
|
||||
{this.getClubList(this.data.clubs)}
|
||||
</Card.Content>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a card showing if the user has payed his membership
|
||||
*
|
||||
* @return {*}
|
||||
*/
|
||||
getMembershipCar(): React.Node {
|
||||
const {theme} = this.props;
|
||||
return (
|
||||
<Card style={styles.card}>
|
||||
<Card.Title
|
||||
title={i18n.t('screens.profile.membership')}
|
||||
subtitle={i18n.t('screens.profile.membershipSubtitle')}
|
||||
left={({size}: {size: number}): React.Node => (
|
||||
<Avatar.Icon
|
||||
size={size}
|
||||
icon="credit-card"
|
||||
color={theme.colors.primary}
|
||||
style={styles.icon}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
<Card.Content>
|
||||
<List.Section>
|
||||
{this.getMembershipItem(this.data.validity)}
|
||||
</List.Section>
|
||||
</Card.Content>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the item showing if the user has payed his membership
|
||||
*
|
||||
* @return {*}
|
||||
*/
|
||||
getMembershipItem(state: boolean): React.Node {
|
||||
const {theme} = this.props;
|
||||
return (
|
||||
<List.Item
|
||||
title={
|
||||
state
|
||||
? i18n.t('screens.profile.membershipPayed')
|
||||
: i18n.t('screens.profile.membershipNotPayed')
|
||||
}
|
||||
left={({size}: {size: number}): React.Node => (
|
||||
<List.Icon
|
||||
size={size}
|
||||
color={state ? theme.colors.success : theme.colors.danger}
|
||||
icon={state ? 'check' : 'close'}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a list item for the club list
|
||||
*
|
||||
* @param item The club to render
|
||||
* @return {*}
|
||||
*/
|
||||
getClubListItem = ({item}: {item: ClubType}): React.Node => {
|
||||
const {theme} = this.props;
|
||||
const onPress = () => {
|
||||
this.openClubDetailsScreen(item.id);
|
||||
};
|
||||
let description = i18n.t('screens.profile.isMember');
|
||||
let icon = ({size, color}: {size: number, color: string}): React.Node => (
|
||||
<List.Icon size={size} color={color} icon="chevron-right" />
|
||||
);
|
||||
if (item.is_manager) {
|
||||
description = i18n.t('screens.profile.isManager');
|
||||
icon = ({size}: {size: number}): React.Node => (
|
||||
<List.Icon size={size} icon="star" color={theme.colors.primary} />
|
||||
);
|
||||
}
|
||||
return (
|
||||
<List.Item
|
||||
title={item.name}
|
||||
description={description}
|
||||
left={icon}
|
||||
onPress={onPress}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Renders the list of clubs the user is part of
|
||||
*
|
||||
* @param list The club list
|
||||
* @return {*}
|
||||
*/
|
||||
getClubList(list: Array<ClubType>): React.Node {
|
||||
list.sort(this.sortClubList);
|
||||
return (
|
||||
<FlatList
|
||||
renderItem={this.getClubListItem}
|
||||
keyExtractor={this.clubKeyExtractor}
|
||||
data={list}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
clubKeyExtractor = (item: ClubType): string => item.name;
|
||||
|
||||
sortClubList = (a: ClubType): number => (a.is_manager ? -1 : 1);
|
||||
|
||||
showDisconnectDialog = () => {
|
||||
this.setState({dialogVisible: true});
|
||||
};
|
||||
|
||||
hideDisconnectDialog = () => {
|
||||
this.setState({dialogVisible: false});
|
||||
};
|
||||
|
||||
/**
|
||||
* Opens the club details screen for the club of given ID
|
||||
* @param id The club's id to open
|
||||
*/
|
||||
openClubDetailsScreen(id: number) {
|
||||
const {navigation} = this.props;
|
||||
navigation.navigate('club-information', {clubId: id});
|
||||
}
|
||||
|
||||
render(): React.Node {
|
||||
const {navigation} = this.props;
|
||||
return (
|
||||
<AuthenticatedScreen
|
||||
navigation={navigation}
|
||||
requests={[
|
||||
{
|
||||
link: 'user/profile',
|
||||
params: {},
|
||||
mandatory: true,
|
||||
},
|
||||
]}
|
||||
renderFunction={this.getScreen}
|
||||
/>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default withTheme(ProfileScreen);
|
||||
|
|
|
|||
|
|
@ -1,46 +1,47 @@
|
|||
// @flow
|
||||
|
||||
import * as React from 'react';
|
||||
import {RefreshControl, View} from "react-native";
|
||||
import AuthenticatedScreen from "../../components/Amicale/AuthenticatedScreen";
|
||||
import {getTimeOnlyString, stringToDate} from "../../utils/Planning";
|
||||
import VoteTease from "../../components/Amicale/Vote/VoteTease";
|
||||
import VoteSelect from "../../components/Amicale/Vote/VoteSelect";
|
||||
import VoteResults from "../../components/Amicale/Vote/VoteResults";
|
||||
import VoteWait from "../../components/Amicale/Vote/VoteWait";
|
||||
import {StackNavigationProp} from "@react-navigation/stack";
|
||||
import i18n from "i18n-js";
|
||||
import {MASCOT_STYLE} from "../../components/Mascot/Mascot";
|
||||
import MascotPopup from "../../components/Mascot/MascotPopup";
|
||||
import AsyncStorageManager from "../../managers/AsyncStorageManager";
|
||||
import {Button} from "react-native-paper";
|
||||
import VoteNotAvailable from "../../components/Amicale/Vote/VoteNotAvailable";
|
||||
import CollapsibleFlatList from "../../components/Collapsible/CollapsibleFlatList";
|
||||
import {RefreshControl, View} from 'react-native';
|
||||
import {StackNavigationProp} from '@react-navigation/stack';
|
||||
import i18n from 'i18n-js';
|
||||
import {Button} from 'react-native-paper';
|
||||
import AuthenticatedScreen from '../../components/Amicale/AuthenticatedScreen';
|
||||
import {getTimeOnlyString, stringToDate} from '../../utils/Planning';
|
||||
import VoteTease from '../../components/Amicale/Vote/VoteTease';
|
||||
import VoteSelect from '../../components/Amicale/Vote/VoteSelect';
|
||||
import VoteResults from '../../components/Amicale/Vote/VoteResults';
|
||||
import VoteWait from '../../components/Amicale/Vote/VoteWait';
|
||||
import {MASCOT_STYLE} from '../../components/Mascot/Mascot';
|
||||
import MascotPopup from '../../components/Mascot/MascotPopup';
|
||||
import AsyncStorageManager from '../../managers/AsyncStorageManager';
|
||||
import VoteNotAvailable from '../../components/Amicale/Vote/VoteNotAvailable';
|
||||
import CollapsibleFlatList from '../../components/Collapsible/CollapsibleFlatList';
|
||||
import type {ApiGenericDataType} from '../../utils/WebData';
|
||||
|
||||
export type team = {
|
||||
id: number,
|
||||
name: string,
|
||||
votes: number,
|
||||
}
|
||||
|
||||
type teamResponse = {
|
||||
has_voted: boolean,
|
||||
teams: Array<team>,
|
||||
export type VoteTeamType = {
|
||||
id: number,
|
||||
name: string,
|
||||
votes: number,
|
||||
};
|
||||
|
||||
type stringVoteDates = {
|
||||
date_begin: string,
|
||||
date_end: string,
|
||||
date_result_begin: string,
|
||||
date_result_end: string,
|
||||
}
|
||||
type TeamResponseType = {
|
||||
has_voted: boolean,
|
||||
teams: Array<VoteTeamType>,
|
||||
};
|
||||
|
||||
type objectVoteDates = {
|
||||
date_begin: Date,
|
||||
date_end: Date,
|
||||
date_result_begin: Date,
|
||||
date_result_end: Date,
|
||||
}
|
||||
type VoteDatesStringType = {
|
||||
date_begin: string,
|
||||
date_end: string,
|
||||
date_result_begin: string,
|
||||
date_result_end: string,
|
||||
};
|
||||
|
||||
type VoteDatesObjectType = {
|
||||
date_begin: Date,
|
||||
date_end: Date,
|
||||
date_result_begin: Date,
|
||||
date_result_end: Date,
|
||||
};
|
||||
|
||||
// const FAKE_DATE = {
|
||||
// "date_begin": "2020-08-19 15:50",
|
||||
|
|
@ -92,287 +93,322 @@ type objectVoteDates = {
|
|||
|
||||
const MIN_REFRESH_TIME = 5 * 1000;
|
||||
|
||||
type Props = {
|
||||
navigation: StackNavigationProp
|
||||
}
|
||||
type PropsType = {
|
||||
navigation: StackNavigationProp,
|
||||
};
|
||||
|
||||
type State = {
|
||||
hasVoted: boolean,
|
||||
mascotDialogVisible: boolean,
|
||||
}
|
||||
type StateType = {
|
||||
hasVoted: boolean,
|
||||
mascotDialogVisible: boolean,
|
||||
};
|
||||
|
||||
/**
|
||||
* Screen displaying vote information and controls
|
||||
*/
|
||||
export default class VoteScreen extends React.Component<Props, State> {
|
||||
export default class VoteScreen extends React.Component<PropsType, StateType> {
|
||||
teams: Array<VoteTeamType>;
|
||||
|
||||
state = {
|
||||
hasVoted: false,
|
||||
mascotDialogVisible: AsyncStorageManager.getBool(AsyncStorageManager.PREFERENCES.voteShowBanner.key),
|
||||
hasVoted: boolean;
|
||||
|
||||
datesString: null | VoteDatesStringType;
|
||||
|
||||
dates: null | VoteDatesObjectType;
|
||||
|
||||
today: Date;
|
||||
|
||||
mainFlatListData: Array<{key: string}>;
|
||||
|
||||
lastRefresh: Date | null;
|
||||
|
||||
authRef: {current: null | AuthenticatedScreen};
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
this.state = {
|
||||
hasVoted: false,
|
||||
mascotDialogVisible: AsyncStorageManager.getBool(
|
||||
AsyncStorageManager.PREFERENCES.voteShowBanner.key,
|
||||
),
|
||||
};
|
||||
this.hasVoted = false;
|
||||
this.today = new Date();
|
||||
this.authRef = React.createRef();
|
||||
this.lastRefresh = null;
|
||||
this.mainFlatListData = [{key: 'main'}, {key: 'info'}];
|
||||
}
|
||||
|
||||
teams: Array<team>;
|
||||
hasVoted: boolean;
|
||||
datesString: null | stringVoteDates;
|
||||
dates: null | objectVoteDates;
|
||||
/**
|
||||
* Gets the string representation of the given date.
|
||||
*
|
||||
* If the given date is the same day as today, only return the tile.
|
||||
* Otherwise, return the full date.
|
||||
*
|
||||
* @param date The Date object representation of the wanted date
|
||||
* @param dateString The string representation of the wanted date
|
||||
* @returns {string}
|
||||
*/
|
||||
getDateString(date: Date, dateString: string): string {
|
||||
if (this.today.getDate() === date.getDate()) {
|
||||
const str = getTimeOnlyString(dateString);
|
||||
return str != null ? str : '';
|
||||
}
|
||||
return dateString;
|
||||
}
|
||||
|
||||
today: Date;
|
||||
getMainRenderItem = ({item}: {item: {key: string}}): React.Node => {
|
||||
if (item.key === 'info')
|
||||
return (
|
||||
<View>
|
||||
<Button
|
||||
mode="contained"
|
||||
icon="help-circle"
|
||||
onPress={this.showMascotDialog}
|
||||
style={{
|
||||
marginLeft: 'auto',
|
||||
marginRight: 'auto',
|
||||
marginTop: 20,
|
||||
}}>
|
||||
{i18n.t('screens.vote.mascotDialog.title')}
|
||||
</Button>
|
||||
</View>
|
||||
);
|
||||
return this.getContent();
|
||||
};
|
||||
|
||||
mainFlatListData: Array<{ key: string }>;
|
||||
lastRefresh: Date | null;
|
||||
getScreen = (data: Array<ApiGenericDataType | null>): React.Node => {
|
||||
const {state} = this;
|
||||
// data[0] = FAKE_TEAMS2;
|
||||
// data[1] = FAKE_DATE;
|
||||
this.lastRefresh = new Date();
|
||||
|
||||
authRef: { current: null | AuthenticatedScreen };
|
||||
const teams: TeamResponseType | null = data[0];
|
||||
const dateStrings: VoteDatesStringType | null = data[1];
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
this.hasVoted = false;
|
||||
this.today = new Date();
|
||||
this.authRef = React.createRef();
|
||||
this.lastRefresh = null;
|
||||
this.mainFlatListData = [
|
||||
{key: 'main'},
|
||||
{key: 'info'},
|
||||
]
|
||||
if (dateStrings != null && dateStrings.date_begin == null)
|
||||
this.datesString = null;
|
||||
else this.datesString = dateStrings;
|
||||
|
||||
if (teams != null) {
|
||||
this.teams = teams.teams;
|
||||
this.hasVoted = teams.has_voted;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reloads vote data if last refresh delta is smaller than the minimum refresh time
|
||||
*/
|
||||
reloadData = () => {
|
||||
let canRefresh;
|
||||
const lastRefresh = this.lastRefresh;
|
||||
if (lastRefresh != null)
|
||||
canRefresh = (new Date().getTime() - lastRefresh.getTime()) > MIN_REFRESH_TIME;
|
||||
else
|
||||
canRefresh = true;
|
||||
if (canRefresh && this.authRef.current != null)
|
||||
this.authRef.current.reload()
|
||||
};
|
||||
|
||||
/**
|
||||
* Generates the objects containing string and Date representations of key vote dates
|
||||
*/
|
||||
generateDateObject() {
|
||||
const strings = this.datesString;
|
||||
if (strings != null) {
|
||||
const dateBegin = stringToDate(strings.date_begin);
|
||||
const dateEnd = stringToDate(strings.date_end);
|
||||
const dateResultBegin = stringToDate(strings.date_result_begin);
|
||||
const dateResultEnd = stringToDate(strings.date_result_end);
|
||||
if (dateBegin != null && dateEnd != null && dateResultBegin != null && dateResultEnd != null) {
|
||||
this.dates = {
|
||||
date_begin: dateBegin,
|
||||
date_end: dateEnd,
|
||||
date_result_begin: dateResultBegin,
|
||||
date_result_end: dateResultEnd,
|
||||
};
|
||||
} else
|
||||
this.dates = null;
|
||||
} else
|
||||
this.dates = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the string representation of the given date.
|
||||
*
|
||||
* If the given date is the same day as today, only return the tile.
|
||||
* Otherwise, return the full date.
|
||||
*
|
||||
* @param date The Date object representation of the wanted date
|
||||
* @param dateString The string representation of the wanted date
|
||||
* @returns {string}
|
||||
*/
|
||||
getDateString(date: Date, dateString: string): string {
|
||||
if (this.today.getDate() === date.getDate()) {
|
||||
const str = getTimeOnlyString(dateString);
|
||||
return str != null ? str : "";
|
||||
} else
|
||||
return dateString;
|
||||
}
|
||||
|
||||
isVoteRunning() {
|
||||
return this.dates != null && this.today > this.dates.date_begin && this.today < this.dates.date_end;
|
||||
}
|
||||
|
||||
isVoteStarted() {
|
||||
return this.dates != null && this.today > this.dates.date_begin;
|
||||
}
|
||||
|
||||
isResultRunning() {
|
||||
return this.dates != null && this.today > this.dates.date_result_begin && this.today < this.dates.date_result_end;
|
||||
}
|
||||
|
||||
isResultStarted() {
|
||||
return this.dates != null && this.today > this.dates.date_result_begin;
|
||||
}
|
||||
|
||||
mainRenderItem = ({item}: { item: { key: string } }) => {
|
||||
if (item.key === 'info')
|
||||
return (
|
||||
<View>
|
||||
<Button
|
||||
mode={"contained"}
|
||||
icon={"help-circle"}
|
||||
onPress={this.showMascotDialog}
|
||||
style={{
|
||||
marginLeft: "auto",
|
||||
marginRight: "auto",
|
||||
marginTop: 20
|
||||
}}>
|
||||
{i18n.t("screens.vote.mascotDialog.title")}
|
||||
</Button>
|
||||
</View>
|
||||
);
|
||||
else
|
||||
return this.getContent();
|
||||
};
|
||||
|
||||
getScreen = (data: Array<{ [key: string]: any } | null>) => {
|
||||
// data[0] = FAKE_TEAMS2;
|
||||
// data[1] = FAKE_DATE;
|
||||
this.lastRefresh = new Date();
|
||||
|
||||
const teams: teamResponse | null = data[0];
|
||||
const dateStrings: stringVoteDates | null = data[1];
|
||||
|
||||
if (dateStrings != null && dateStrings.date_begin == null)
|
||||
this.datesString = null;
|
||||
else
|
||||
this.datesString = dateStrings;
|
||||
|
||||
if (teams != null) {
|
||||
this.teams = teams.teams;
|
||||
this.hasVoted = teams.has_voted;
|
||||
this.generateDateObject();
|
||||
return (
|
||||
<CollapsibleFlatList
|
||||
data={this.mainFlatListData}
|
||||
refreshControl={
|
||||
<RefreshControl refreshing={false} onRefresh={this.reloadData} />
|
||||
}
|
||||
extraData={state.hasVoted.toString()}
|
||||
renderItem={this.getMainRenderItem}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
this.generateDateObject();
|
||||
return (
|
||||
<CollapsibleFlatList
|
||||
data={this.mainFlatListData}
|
||||
refreshControl={
|
||||
<RefreshControl
|
||||
refreshing={false}
|
||||
onRefresh={this.reloadData}
|
||||
/>
|
||||
}
|
||||
extraData={this.state.hasVoted.toString()}
|
||||
renderItem={this.mainRenderItem}
|
||||
/>
|
||||
);
|
||||
};
|
||||
getContent(): React.Node {
|
||||
const {state} = this;
|
||||
if (!this.isVoteStarted()) return this.getTeaseVoteCard();
|
||||
if (this.isVoteRunning() && !this.hasVoted && !state.hasVoted)
|
||||
return this.getVoteCard();
|
||||
if (!this.isResultStarted()) return this.getWaitVoteCard();
|
||||
if (this.isResultRunning()) return this.getVoteResultCard();
|
||||
return <VoteNotAvailable />;
|
||||
}
|
||||
|
||||
getContent() {
|
||||
if (!this.isVoteStarted())
|
||||
return this.getTeaseVoteCard();
|
||||
else if (this.isVoteRunning() && (!this.hasVoted && !this.state.hasVoted))
|
||||
return this.getVoteCard();
|
||||
else if (!this.isResultStarted())
|
||||
return this.getWaitVoteCard();
|
||||
else if (this.isResultRunning())
|
||||
return this.getVoteResultCard();
|
||||
else
|
||||
return <VoteNotAvailable/>;
|
||||
}
|
||||
onVoteSuccess = (): void => this.setState({hasVoted: true});
|
||||
|
||||
onVoteSuccess = () => this.setState({hasVoted: true});
|
||||
/**
|
||||
* The user has not voted yet, and the votes are open
|
||||
*/
|
||||
getVoteCard(): React.Node {
|
||||
return (
|
||||
<VoteSelect
|
||||
teams={this.teams}
|
||||
onVoteSuccess={this.onVoteSuccess}
|
||||
onVoteError={this.reloadData}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The user has not voted yet, and the votes are open
|
||||
*/
|
||||
getVoteCard() {
|
||||
return <VoteSelect teams={this.teams} onVoteSuccess={this.onVoteSuccess} onVoteError={this.reloadData}/>;
|
||||
}
|
||||
/**
|
||||
* Votes have ended, results can be displayed
|
||||
*/
|
||||
getVoteResultCard(): React.Node {
|
||||
if (this.dates != null && this.datesString != null)
|
||||
return (
|
||||
<VoteResults
|
||||
teams={this.teams}
|
||||
dateEnd={this.getDateString(
|
||||
this.dates.date_result_end,
|
||||
this.datesString.date_result_end,
|
||||
)}
|
||||
/>
|
||||
);
|
||||
return <VoteNotAvailable />;
|
||||
}
|
||||
|
||||
/**
|
||||
* Votes have ended, results can be displayed
|
||||
*/
|
||||
getVoteResultCard() {
|
||||
if (this.dates != null && this.datesString != null)
|
||||
return <VoteResults
|
||||
teams={this.teams}
|
||||
dateEnd={this.getDateString(
|
||||
this.dates.date_result_end,
|
||||
this.datesString.date_result_end)}
|
||||
/>;
|
||||
else
|
||||
return <VoteNotAvailable/>;
|
||||
}
|
||||
/**
|
||||
* Vote will open shortly
|
||||
*/
|
||||
getTeaseVoteCard(): React.Node {
|
||||
if (this.dates != null && this.datesString != null)
|
||||
return (
|
||||
<VoteTease
|
||||
startDate={this.getDateString(
|
||||
this.dates.date_begin,
|
||||
this.datesString.date_begin,
|
||||
)}
|
||||
/>
|
||||
);
|
||||
return <VoteNotAvailable />;
|
||||
}
|
||||
|
||||
/**
|
||||
* Vote will open shortly
|
||||
*/
|
||||
getTeaseVoteCard() {
|
||||
if (this.dates != null && this.datesString != null)
|
||||
return <VoteTease
|
||||
startDate={this.getDateString(this.dates.date_begin, this.datesString.date_begin)}/>;
|
||||
else
|
||||
return <VoteNotAvailable/>;
|
||||
}
|
||||
/**
|
||||
* Votes have ended, or user has voted waiting for results
|
||||
*/
|
||||
getWaitVoteCard(): React.Node {
|
||||
const {state} = this;
|
||||
let startDate = null;
|
||||
if (
|
||||
this.dates != null &&
|
||||
this.datesString != null &&
|
||||
this.dates.date_result_begin != null
|
||||
)
|
||||
startDate = this.getDateString(
|
||||
this.dates.date_result_begin,
|
||||
this.datesString.date_result_begin,
|
||||
);
|
||||
return (
|
||||
<VoteWait
|
||||
startDate={startDate}
|
||||
hasVoted={this.hasVoted || state.hasVoted}
|
||||
justVoted={state.hasVoted}
|
||||
isVoteRunning={this.isVoteRunning()}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Votes have ended, or user has voted waiting for results
|
||||
*/
|
||||
getWaitVoteCard() {
|
||||
let startDate = null;
|
||||
if (this.dates != null && this.datesString != null && this.dates.date_result_begin != null)
|
||||
startDate = this.getDateString(this.dates.date_result_begin, this.datesString.date_result_begin);
|
||||
return <VoteWait startDate={startDate} hasVoted={this.hasVoted || this.state.hasVoted}
|
||||
justVoted={this.state.hasVoted}
|
||||
isVoteRunning={this.isVoteRunning()}/>;
|
||||
}
|
||||
/**
|
||||
* Reloads vote data if last refresh delta is smaller than the minimum refresh time
|
||||
*/
|
||||
reloadData = () => {
|
||||
let canRefresh;
|
||||
const {lastRefresh} = this;
|
||||
if (lastRefresh != null)
|
||||
canRefresh =
|
||||
new Date().getTime() - lastRefresh.getTime() > MIN_REFRESH_TIME;
|
||||
else canRefresh = true;
|
||||
if (canRefresh && this.authRef.current != null)
|
||||
this.authRef.current.reload();
|
||||
};
|
||||
|
||||
showMascotDialog = () => {
|
||||
this.setState({mascotDialogVisible: true})
|
||||
};
|
||||
showMascotDialog = () => {
|
||||
this.setState({mascotDialogVisible: true});
|
||||
};
|
||||
|
||||
hideMascotDialog = () => {
|
||||
AsyncStorageManager.set(AsyncStorageManager.PREFERENCES.voteShowBanner.key, false);
|
||||
this.setState({mascotDialogVisible: false})
|
||||
};
|
||||
hideMascotDialog = () => {
|
||||
AsyncStorageManager.set(
|
||||
AsyncStorageManager.PREFERENCES.voteShowBanner.key,
|
||||
false,
|
||||
);
|
||||
this.setState({mascotDialogVisible: false});
|
||||
};
|
||||
|
||||
/**
|
||||
* Renders the authenticated screen.
|
||||
*
|
||||
* Teams and dates are not mandatory to allow showing the information box even if api requests fail
|
||||
*
|
||||
* @returns {*}
|
||||
*/
|
||||
render() {
|
||||
return (
|
||||
<View style={{flex: 1}}>
|
||||
<AuthenticatedScreen
|
||||
{...this.props}
|
||||
ref={this.authRef}
|
||||
requests={[
|
||||
{
|
||||
link: 'elections/teams',
|
||||
params: {},
|
||||
mandatory: false,
|
||||
},
|
||||
{
|
||||
link: 'elections/dates',
|
||||
params: {},
|
||||
mandatory: false,
|
||||
},
|
||||
]}
|
||||
renderFunction={this.getScreen}
|
||||
/>
|
||||
<MascotPopup
|
||||
visible={this.state.mascotDialogVisible}
|
||||
title={i18n.t("screens.vote.mascotDialog.title")}
|
||||
message={i18n.t("screens.vote.mascotDialog.message")}
|
||||
icon={"vote"}
|
||||
buttons={{
|
||||
action: null,
|
||||
cancel: {
|
||||
message: i18n.t("screens.vote.mascotDialog.button"),
|
||||
icon: "check",
|
||||
onPress: this.hideMascotDialog,
|
||||
}
|
||||
}}
|
||||
emotion={MASCOT_STYLE.CUTE}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
isVoteStarted(): boolean {
|
||||
return this.dates != null && this.today > this.dates.date_begin;
|
||||
}
|
||||
|
||||
isResultRunning(): boolean {
|
||||
return (
|
||||
this.dates != null &&
|
||||
this.today > this.dates.date_result_begin &&
|
||||
this.today < this.dates.date_result_end
|
||||
);
|
||||
}
|
||||
|
||||
isResultStarted(): boolean {
|
||||
return this.dates != null && this.today > this.dates.date_result_begin;
|
||||
}
|
||||
|
||||
isVoteRunning(): boolean {
|
||||
return (
|
||||
this.dates != null &&
|
||||
this.today > this.dates.date_begin &&
|
||||
this.today < this.dates.date_end
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates the objects containing string and Date representations of key vote dates
|
||||
*/
|
||||
generateDateObject() {
|
||||
const strings = this.datesString;
|
||||
if (strings != null) {
|
||||
const dateBegin = stringToDate(strings.date_begin);
|
||||
const dateEnd = stringToDate(strings.date_end);
|
||||
const dateResultBegin = stringToDate(strings.date_result_begin);
|
||||
const dateResultEnd = stringToDate(strings.date_result_end);
|
||||
if (
|
||||
dateBegin != null &&
|
||||
dateEnd != null &&
|
||||
dateResultBegin != null &&
|
||||
dateResultEnd != null
|
||||
) {
|
||||
this.dates = {
|
||||
date_begin: dateBegin,
|
||||
date_end: dateEnd,
|
||||
date_result_begin: dateResultBegin,
|
||||
date_result_end: dateResultEnd,
|
||||
};
|
||||
} else this.dates = null;
|
||||
} else this.dates = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the authenticated screen.
|
||||
*
|
||||
* Teams and dates are not mandatory to allow showing the information box even if api requests fail
|
||||
*
|
||||
* @returns {*}
|
||||
*/
|
||||
render(): React.Node {
|
||||
const {props, state} = this;
|
||||
return (
|
||||
<View style={{flex: 1}}>
|
||||
<AuthenticatedScreen
|
||||
navigation={props.navigation}
|
||||
ref={this.authRef}
|
||||
requests={[
|
||||
{
|
||||
link: 'elections/teams',
|
||||
params: {},
|
||||
mandatory: false,
|
||||
},
|
||||
{
|
||||
link: 'elections/dates',
|
||||
params: {},
|
||||
mandatory: false,
|
||||
},
|
||||
]}
|
||||
renderFunction={this.getScreen}
|
||||
/>
|
||||
<MascotPopup
|
||||
visible={state.mascotDialogVisible}
|
||||
title={i18n.t('screens.vote.mascotDialog.title')}
|
||||
message={i18n.t('screens.vote.mascotDialog.message')}
|
||||
icon="vote"
|
||||
buttons={{
|
||||
action: null,
|
||||
cancel: {
|
||||
message: i18n.t('screens.vote.mascotDialog.button'),
|
||||
icon: 'check',
|
||||
onPress: this.hideMascotDialog,
|
||||
},
|
||||
}}
|
||||
emotion={MASCOT_STYLE.CUTE}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,13 +1,13 @@
|
|||
// @flow
|
||||
|
||||
import type {CustomTheme} from "../../../managers/ThemeManager";
|
||||
import type {CustomThemeType} from '../../../managers/ThemeManager';
|
||||
|
||||
export type Coordinates = {
|
||||
x: number,
|
||||
y: number,
|
||||
}
|
||||
export type CoordinatesType = {
|
||||
x: number,
|
||||
y: number,
|
||||
};
|
||||
|
||||
type Shape = Array<Array<number>>;
|
||||
export type ShapeType = Array<Array<number>>;
|
||||
|
||||
/**
|
||||
* Abstract class used to represent a BaseShape.
|
||||
|
|
@ -15,96 +15,98 @@ type Shape = Array<Array<number>>;
|
|||
* and in methods to implement
|
||||
*/
|
||||
export default class BaseShape {
|
||||
#currentShape: ShapeType;
|
||||
|
||||
#currentShape: Shape;
|
||||
#rotation: number;
|
||||
position: Coordinates;
|
||||
theme: CustomTheme;
|
||||
#rotation: number;
|
||||
|
||||
/**
|
||||
* Prevent instantiation if classname is BaseShape to force class to be abstract
|
||||
*/
|
||||
constructor(theme: CustomTheme) {
|
||||
if (this.constructor === BaseShape)
|
||||
throw new Error("Abstract class can't be instantiated");
|
||||
this.theme = theme;
|
||||
this.#rotation = 0;
|
||||
this.position = {x: 0, y: 0};
|
||||
this.#currentShape = this.getShapes()[this.#rotation];
|
||||
}
|
||||
position: CoordinatesType;
|
||||
|
||||
/**
|
||||
* Gets this shape's color.
|
||||
* Must be implemented by child class
|
||||
*/
|
||||
getColor(): string {
|
||||
throw new Error("Method 'getColor()' must be implemented");
|
||||
}
|
||||
theme: CustomThemeType;
|
||||
|
||||
/**
|
||||
* Gets this object's all possible shapes as an array.
|
||||
* Must be implemented by child class.
|
||||
*
|
||||
* Used by tests to read private fields
|
||||
*/
|
||||
getShapes(): Array<Shape> {
|
||||
throw new Error("Method 'getShapes()' must be implemented");
|
||||
}
|
||||
/**
|
||||
* Prevent instantiation if classname is BaseShape to force class to be abstract
|
||||
*/
|
||||
constructor(theme: CustomThemeType) {
|
||||
if (this.constructor === BaseShape)
|
||||
throw new Error("Abstract class can't be instantiated");
|
||||
this.theme = theme;
|
||||
this.#rotation = 0;
|
||||
this.position = {x: 0, y: 0};
|
||||
this.#currentShape = this.getShapes()[this.#rotation];
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets this object's current shape.
|
||||
*/
|
||||
getCurrentShape(): Shape {
|
||||
return this.#currentShape;
|
||||
}
|
||||
/**
|
||||
* Gets this shape's color.
|
||||
* Must be implemented by child class
|
||||
*/
|
||||
// eslint-disable-next-line class-methods-use-this
|
||||
getColor(): string {
|
||||
throw new Error("Method 'getColor()' must be implemented");
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets this object's coordinates.
|
||||
* This will return an array of coordinates representing the positions of the cells used by this object.
|
||||
*
|
||||
* @param isAbsolute Should we take into account the current position of the object?
|
||||
* @return {Array<Coordinates>} This object cells coordinates
|
||||
*/
|
||||
getCellsCoordinates(isAbsolute: boolean): Array<Coordinates> {
|
||||
let coordinates = [];
|
||||
for (let row = 0; row < this.#currentShape.length; row++) {
|
||||
for (let col = 0; col < this.#currentShape[row].length; col++) {
|
||||
if (this.#currentShape[row][col] === 1)
|
||||
if (isAbsolute)
|
||||
coordinates.push({x: this.position.x + col, y: this.position.y + row});
|
||||
else
|
||||
coordinates.push({x: col, y: row});
|
||||
}
|
||||
/**
|
||||
* Gets this object's all possible shapes as an array.
|
||||
* Must be implemented by child class.
|
||||
*
|
||||
* Used by tests to read private fields
|
||||
*/
|
||||
// eslint-disable-next-line class-methods-use-this
|
||||
getShapes(): Array<ShapeType> {
|
||||
throw new Error("Method 'getShapes()' must be implemented");
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets this object's current shape.
|
||||
*/
|
||||
getCurrentShape(): ShapeType {
|
||||
return this.#currentShape;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets this object's coordinates.
|
||||
* This will return an array of coordinates representing the positions of the cells used by this object.
|
||||
*
|
||||
* @param isAbsolute Should we take into account the current position of the object?
|
||||
* @return {Array<CoordinatesType>} This object cells coordinates
|
||||
*/
|
||||
getCellsCoordinates(isAbsolute: boolean): Array<CoordinatesType> {
|
||||
const coordinates = [];
|
||||
for (let row = 0; row < this.#currentShape.length; row += 1) {
|
||||
for (let col = 0; col < this.#currentShape[row].length; col += 1) {
|
||||
if (this.#currentShape[row][col] === 1) {
|
||||
if (isAbsolute) {
|
||||
coordinates.push({
|
||||
x: this.position.x + col,
|
||||
y: this.position.y + row,
|
||||
});
|
||||
} else coordinates.push({x: col, y: row});
|
||||
}
|
||||
return coordinates;
|
||||
}
|
||||
}
|
||||
return coordinates;
|
||||
}
|
||||
|
||||
/**
|
||||
* Rotate this object
|
||||
*
|
||||
* @param isForward Should we rotate clockwise?
|
||||
*/
|
||||
rotate(isForward: boolean) {
|
||||
if (isForward)
|
||||
this.#rotation++;
|
||||
else
|
||||
this.#rotation--;
|
||||
if (this.#rotation > 3)
|
||||
this.#rotation = 0;
|
||||
else if (this.#rotation < 0)
|
||||
this.#rotation = 3;
|
||||
this.#currentShape = this.getShapes()[this.#rotation];
|
||||
}
|
||||
|
||||
/**
|
||||
* Move this object
|
||||
*
|
||||
* @param x Position X offset to add
|
||||
* @param y Position Y offset to add
|
||||
*/
|
||||
move(x: number, y: number) {
|
||||
this.position.x += x;
|
||||
this.position.y += y;
|
||||
}
|
||||
/**
|
||||
* Rotate this object
|
||||
*
|
||||
* @param isForward Should we rotate clockwise?
|
||||
*/
|
||||
rotate(isForward: boolean) {
|
||||
if (isForward) this.#rotation += 1;
|
||||
else this.#rotation -= 1;
|
||||
if (this.#rotation > 3) this.#rotation = 0;
|
||||
else if (this.#rotation < 0) this.#rotation = 3;
|
||||
this.#currentShape = this.getShapes()[this.#rotation];
|
||||
}
|
||||
|
||||
/**
|
||||
* Move this object
|
||||
*
|
||||
* @param x Position X offset to add
|
||||
* @param y Position Y offset to add
|
||||
*/
|
||||
move(x: number, y: number) {
|
||||
this.position.x += x;
|
||||
this.position.y += y;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,45 +1,46 @@
|
|||
// @flow
|
||||
|
||||
import BaseShape from "./BaseShape";
|
||||
import type {CustomTheme} from "../../../managers/ThemeManager";
|
||||
import BaseShape from './BaseShape';
|
||||
import type {CustomThemeType} from '../../../managers/ThemeManager';
|
||||
import type {ShapeType} from './BaseShape';
|
||||
|
||||
export default class ShapeI extends BaseShape {
|
||||
constructor(theme: CustomThemeType) {
|
||||
super(theme);
|
||||
this.position.x = 3;
|
||||
}
|
||||
|
||||
constructor(theme: CustomTheme) {
|
||||
super(theme);
|
||||
this.position.x = 3;
|
||||
}
|
||||
getColor(): string {
|
||||
return this.theme.colors.tetrisI;
|
||||
}
|
||||
|
||||
getColor(): string {
|
||||
return this.theme.colors.tetrisI;
|
||||
}
|
||||
|
||||
getShapes() {
|
||||
return [
|
||||
[
|
||||
[0, 0, 0, 0],
|
||||
[1, 1, 1, 1],
|
||||
[0, 0, 0, 0],
|
||||
[0, 0, 0, 0],
|
||||
],
|
||||
[
|
||||
[0, 0, 1, 0],
|
||||
[0, 0, 1, 0],
|
||||
[0, 0, 1, 0],
|
||||
[0, 0, 1, 0],
|
||||
],
|
||||
[
|
||||
[0, 0, 0, 0],
|
||||
[0, 0, 0, 0],
|
||||
[1, 1, 1, 1],
|
||||
[0, 0, 0, 0],
|
||||
],
|
||||
[
|
||||
[0, 1, 0, 0],
|
||||
[0, 1, 0, 0],
|
||||
[0, 1, 0, 0],
|
||||
[0, 1, 0, 0],
|
||||
],
|
||||
];
|
||||
}
|
||||
// eslint-disable-next-line class-methods-use-this
|
||||
getShapes(): Array<ShapeType> {
|
||||
return [
|
||||
[
|
||||
[0, 0, 0, 0],
|
||||
[1, 1, 1, 1],
|
||||
[0, 0, 0, 0],
|
||||
[0, 0, 0, 0],
|
||||
],
|
||||
[
|
||||
[0, 0, 1, 0],
|
||||
[0, 0, 1, 0],
|
||||
[0, 0, 1, 0],
|
||||
[0, 0, 1, 0],
|
||||
],
|
||||
[
|
||||
[0, 0, 0, 0],
|
||||
[0, 0, 0, 0],
|
||||
[1, 1, 1, 1],
|
||||
[0, 0, 0, 0],
|
||||
],
|
||||
[
|
||||
[0, 1, 0, 0],
|
||||
[0, 1, 0, 0],
|
||||
[0, 1, 0, 0],
|
||||
[0, 1, 0, 0],
|
||||
],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,41 +1,42 @@
|
|||
// @flow
|
||||
|
||||
import BaseShape from "./BaseShape";
|
||||
import type {CustomTheme} from "../../../managers/ThemeManager";
|
||||
import BaseShape from './BaseShape';
|
||||
import type {CustomThemeType} from '../../../managers/ThemeManager';
|
||||
import type {ShapeType} from './BaseShape';
|
||||
|
||||
export default class ShapeJ extends BaseShape {
|
||||
constructor(theme: CustomThemeType) {
|
||||
super(theme);
|
||||
this.position.x = 3;
|
||||
}
|
||||
|
||||
constructor(theme: CustomTheme) {
|
||||
super(theme);
|
||||
this.position.x = 3;
|
||||
}
|
||||
getColor(): string {
|
||||
return this.theme.colors.tetrisJ;
|
||||
}
|
||||
|
||||
getColor(): string {
|
||||
return this.theme.colors.tetrisJ;
|
||||
}
|
||||
|
||||
getShapes() {
|
||||
return [
|
||||
[
|
||||
[1, 0, 0],
|
||||
[1, 1, 1],
|
||||
[0, 0, 0],
|
||||
],
|
||||
[
|
||||
[0, 1, 1],
|
||||
[0, 1, 0],
|
||||
[0, 1, 0],
|
||||
],
|
||||
[
|
||||
[0, 0, 0],
|
||||
[1, 1, 1],
|
||||
[0, 0, 1],
|
||||
],
|
||||
[
|
||||
[0, 1, 0],
|
||||
[0, 1, 0],
|
||||
[1, 1, 0],
|
||||
],
|
||||
];
|
||||
}
|
||||
// eslint-disable-next-line class-methods-use-this
|
||||
getShapes(): Array<ShapeType> {
|
||||
return [
|
||||
[
|
||||
[1, 0, 0],
|
||||
[1, 1, 1],
|
||||
[0, 0, 0],
|
||||
],
|
||||
[
|
||||
[0, 1, 1],
|
||||
[0, 1, 0],
|
||||
[0, 1, 0],
|
||||
],
|
||||
[
|
||||
[0, 0, 0],
|
||||
[1, 1, 1],
|
||||
[0, 0, 1],
|
||||
],
|
||||
[
|
||||
[0, 1, 0],
|
||||
[0, 1, 0],
|
||||
[1, 1, 0],
|
||||
],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,41 +1,42 @@
|
|||
// @flow
|
||||
|
||||
import BaseShape from "./BaseShape";
|
||||
import type {CustomTheme} from "../../../managers/ThemeManager";
|
||||
import BaseShape from './BaseShape';
|
||||
import type {CustomThemeType} from '../../../managers/ThemeManager';
|
||||
import type {ShapeType} from './BaseShape';
|
||||
|
||||
export default class ShapeL extends BaseShape {
|
||||
constructor(theme: CustomThemeType) {
|
||||
super(theme);
|
||||
this.position.x = 3;
|
||||
}
|
||||
|
||||
constructor(theme: CustomTheme) {
|
||||
super(theme);
|
||||
this.position.x = 3;
|
||||
}
|
||||
getColor(): string {
|
||||
return this.theme.colors.tetrisL;
|
||||
}
|
||||
|
||||
getColor(): string {
|
||||
return this.theme.colors.tetrisL;
|
||||
}
|
||||
|
||||
getShapes() {
|
||||
return [
|
||||
[
|
||||
[0, 0, 1],
|
||||
[1, 1, 1],
|
||||
[0, 0, 0],
|
||||
],
|
||||
[
|
||||
[0, 1, 0],
|
||||
[0, 1, 0],
|
||||
[0, 1, 1],
|
||||
],
|
||||
[
|
||||
[0, 0, 0],
|
||||
[1, 1, 1],
|
||||
[1, 0, 0],
|
||||
],
|
||||
[
|
||||
[1, 1, 0],
|
||||
[0, 1, 0],
|
||||
[0, 1, 0],
|
||||
],
|
||||
];
|
||||
}
|
||||
// eslint-disable-next-line class-methods-use-this
|
||||
getShapes(): Array<ShapeType> {
|
||||
return [
|
||||
[
|
||||
[0, 0, 1],
|
||||
[1, 1, 1],
|
||||
[0, 0, 0],
|
||||
],
|
||||
[
|
||||
[0, 1, 0],
|
||||
[0, 1, 0],
|
||||
[0, 1, 1],
|
||||
],
|
||||
[
|
||||
[0, 0, 0],
|
||||
[1, 1, 1],
|
||||
[1, 0, 0],
|
||||
],
|
||||
[
|
||||
[1, 1, 0],
|
||||
[0, 1, 0],
|
||||
[0, 1, 0],
|
||||
],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,37 +1,38 @@
|
|||
// @flow
|
||||
|
||||
import BaseShape from "./BaseShape";
|
||||
import type {CustomTheme} from "../../../managers/ThemeManager";
|
||||
import BaseShape from './BaseShape';
|
||||
import type {CustomThemeType} from '../../../managers/ThemeManager';
|
||||
import type {ShapeType} from './BaseShape';
|
||||
|
||||
export default class ShapeO extends BaseShape {
|
||||
constructor(theme: CustomThemeType) {
|
||||
super(theme);
|
||||
this.position.x = 4;
|
||||
}
|
||||
|
||||
constructor(theme: CustomTheme) {
|
||||
super(theme);
|
||||
this.position.x = 4;
|
||||
}
|
||||
getColor(): string {
|
||||
return this.theme.colors.tetrisO;
|
||||
}
|
||||
|
||||
getColor(): string {
|
||||
return this.theme.colors.tetrisO;
|
||||
}
|
||||
|
||||
getShapes() {
|
||||
return [
|
||||
[
|
||||
[1, 1],
|
||||
[1, 1],
|
||||
],
|
||||
[
|
||||
[1, 1],
|
||||
[1, 1],
|
||||
],
|
||||
[
|
||||
[1, 1],
|
||||
[1, 1],
|
||||
],
|
||||
[
|
||||
[1, 1],
|
||||
[1, 1],
|
||||
],
|
||||
];
|
||||
}
|
||||
// eslint-disable-next-line class-methods-use-this
|
||||
getShapes(): Array<ShapeType> {
|
||||
return [
|
||||
[
|
||||
[1, 1],
|
||||
[1, 1],
|
||||
],
|
||||
[
|
||||
[1, 1],
|
||||
[1, 1],
|
||||
],
|
||||
[
|
||||
[1, 1],
|
||||
[1, 1],
|
||||
],
|
||||
[
|
||||
[1, 1],
|
||||
[1, 1],
|
||||
],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,41 +1,42 @@
|
|||
// @flow
|
||||
|
||||
import BaseShape from "./BaseShape";
|
||||
import type {CustomTheme} from "../../../managers/ThemeManager";
|
||||
import BaseShape from './BaseShape';
|
||||
import type {CustomThemeType} from '../../../managers/ThemeManager';
|
||||
import type {ShapeType} from './BaseShape';
|
||||
|
||||
export default class ShapeS extends BaseShape {
|
||||
constructor(theme: CustomThemeType) {
|
||||
super(theme);
|
||||
this.position.x = 3;
|
||||
}
|
||||
|
||||
constructor(theme: CustomTheme) {
|
||||
super(theme);
|
||||
this.position.x = 3;
|
||||
}
|
||||
getColor(): string {
|
||||
return this.theme.colors.tetrisS;
|
||||
}
|
||||
|
||||
getColor(): string {
|
||||
return this.theme.colors.tetrisS;
|
||||
}
|
||||
|
||||
getShapes() {
|
||||
return [
|
||||
[
|
||||
[0, 1, 1],
|
||||
[1, 1, 0],
|
||||
[0, 0, 0],
|
||||
],
|
||||
[
|
||||
[0, 1, 0],
|
||||
[0, 1, 1],
|
||||
[0, 0, 1],
|
||||
],
|
||||
[
|
||||
[0, 0, 0],
|
||||
[0, 1, 1],
|
||||
[1, 1, 0],
|
||||
],
|
||||
[
|
||||
[1, 0, 0],
|
||||
[1, 1, 0],
|
||||
[0, 1, 0],
|
||||
],
|
||||
];
|
||||
}
|
||||
// eslint-disable-next-line class-methods-use-this
|
||||
getShapes(): Array<ShapeType> {
|
||||
return [
|
||||
[
|
||||
[0, 1, 1],
|
||||
[1, 1, 0],
|
||||
[0, 0, 0],
|
||||
],
|
||||
[
|
||||
[0, 1, 0],
|
||||
[0, 1, 1],
|
||||
[0, 0, 1],
|
||||
],
|
||||
[
|
||||
[0, 0, 0],
|
||||
[0, 1, 1],
|
||||
[1, 1, 0],
|
||||
],
|
||||
[
|
||||
[1, 0, 0],
|
||||
[1, 1, 0],
|
||||
[0, 1, 0],
|
||||
],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,41 +1,42 @@
|
|||
// @flow
|
||||
|
||||
import BaseShape from "./BaseShape";
|
||||
import type {CustomTheme} from "../../../managers/ThemeManager";
|
||||
import BaseShape from './BaseShape';
|
||||
import type {CustomThemeType} from '../../../managers/ThemeManager';
|
||||
import type {ShapeType} from './BaseShape';
|
||||
|
||||
export default class ShapeT extends BaseShape {
|
||||
constructor(theme: CustomThemeType) {
|
||||
super(theme);
|
||||
this.position.x = 3;
|
||||
}
|
||||
|
||||
constructor(theme: CustomTheme) {
|
||||
super(theme);
|
||||
this.position.x = 3;
|
||||
}
|
||||
getColor(): string {
|
||||
return this.theme.colors.tetrisT;
|
||||
}
|
||||
|
||||
getColor(): string {
|
||||
return this.theme.colors.tetrisT;
|
||||
}
|
||||
|
||||
getShapes() {
|
||||
return [
|
||||
[
|
||||
[0, 1, 0],
|
||||
[1, 1, 1],
|
||||
[0, 0, 0],
|
||||
],
|
||||
[
|
||||
[0, 1, 0],
|
||||
[0, 1, 1],
|
||||
[0, 1, 0],
|
||||
],
|
||||
[
|
||||
[0, 0, 0],
|
||||
[1, 1, 1],
|
||||
[0, 1, 0],
|
||||
],
|
||||
[
|
||||
[0, 1, 0],
|
||||
[1, 1, 0],
|
||||
[0, 1, 0],
|
||||
],
|
||||
];
|
||||
}
|
||||
// eslint-disable-next-line class-methods-use-this
|
||||
getShapes(): Array<ShapeType> {
|
||||
return [
|
||||
[
|
||||
[0, 1, 0],
|
||||
[1, 1, 1],
|
||||
[0, 0, 0],
|
||||
],
|
||||
[
|
||||
[0, 1, 0],
|
||||
[0, 1, 1],
|
||||
[0, 1, 0],
|
||||
],
|
||||
[
|
||||
[0, 0, 0],
|
||||
[1, 1, 1],
|
||||
[0, 1, 0],
|
||||
],
|
||||
[
|
||||
[0, 1, 0],
|
||||
[1, 1, 0],
|
||||
[0, 1, 0],
|
||||
],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,41 +1,42 @@
|
|||
// @flow
|
||||
|
||||
import BaseShape from "./BaseShape";
|
||||
import type {CustomTheme} from "../../../managers/ThemeManager";
|
||||
import BaseShape from './BaseShape';
|
||||
import type {CustomThemeType} from '../../../managers/ThemeManager';
|
||||
import type {ShapeType} from './BaseShape';
|
||||
|
||||
export default class ShapeZ extends BaseShape {
|
||||
constructor(theme: CustomThemeType) {
|
||||
super(theme);
|
||||
this.position.x = 3;
|
||||
}
|
||||
|
||||
constructor(theme: CustomTheme) {
|
||||
super(theme);
|
||||
this.position.x = 3;
|
||||
}
|
||||
getColor(): string {
|
||||
return this.theme.colors.tetrisZ;
|
||||
}
|
||||
|
||||
getColor(): string {
|
||||
return this.theme.colors.tetrisZ;
|
||||
}
|
||||
|
||||
getShapes() {
|
||||
return [
|
||||
[
|
||||
[1, 1, 0],
|
||||
[0, 1, 1],
|
||||
[0, 0, 0],
|
||||
],
|
||||
[
|
||||
[0, 0, 1],
|
||||
[0, 1, 1],
|
||||
[0, 1, 0],
|
||||
],
|
||||
[
|
||||
[0, 0, 0],
|
||||
[1, 1, 0],
|
||||
[0, 1, 1],
|
||||
],
|
||||
[
|
||||
[0, 1, 0],
|
||||
[1, 1, 0],
|
||||
[1, 0, 0],
|
||||
],
|
||||
];
|
||||
}
|
||||
// eslint-disable-next-line class-methods-use-this
|
||||
getShapes(): Array<ShapeType> {
|
||||
return [
|
||||
[
|
||||
[1, 1, 0],
|
||||
[0, 1, 1],
|
||||
[0, 0, 0],
|
||||
],
|
||||
[
|
||||
[0, 0, 1],
|
||||
[0, 1, 1],
|
||||
[0, 1, 0],
|
||||
],
|
||||
[
|
||||
[0, 0, 0],
|
||||
[1, 1, 0],
|
||||
[0, 1, 1],
|
||||
],
|
||||
[
|
||||
[0, 1, 0],
|
||||
[1, 1, 0],
|
||||
[1, 0, 0],
|
||||
],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue