Compare commits

...

18 commits

Author SHA1 Message Date
c86281cbd2 Change name 2020-08-05 21:09:37 +02:00
4cc9c61d72 Disable lint for test files 2020-08-05 21:09:04 +02:00
1e81b2cd7b Improve remaining files to match linter 2020-08-05 20:58:28 +02:00
cbe3777957 Improve Game files to match linter 2020-08-05 20:24:08 +02:00
569e659779 Improve utils files to match linter 2020-08-05 18:52:18 +02:00
fcbc70956b Improve Services screen components to match linter 2020-08-05 18:39:44 +02:00
3ce23726c2 Improve Planning screen components to match linter 2020-08-05 15:04:41 +02:00
a3299c19f7 Improve Settings screen components to match linter 2020-08-05 13:51:14 +02:00
0a64f5fcd7 Improve Amicale screen components to match linter 2020-08-05 11:54:13 +02:00
483970c9a8 Improve about components to match linter 2020-08-05 00:37:51 +02:00
3e4f2f4ac1 Improve navigators to match linter 2020-08-05 00:16:05 +02:00
7107a8eadf Improve constants to match linter 2020-08-05 00:06:05 +02:00
7ac62b99f4 Improve constants to match linter 2020-08-04 23:51:32 +02:00
aa992d20b2 Improve tab components to match linter 2020-08-04 23:49:18 +02:00
0117b25cd8 Improve basic screen components to match linter 2020-08-04 21:49:19 +02:00
4db4516296 Improve override components to match linter 2020-08-04 21:24:43 +02:00
7b94afadcc Improve Mascot components to match linter 2020-08-04 19:26:25 +02:00
1cc0802c12 Improve Proxiwash components to match linter 2020-08-04 18:53:10 +02:00
105 changed files with 10349 additions and 9360 deletions

4
App.js
View file

@ -10,7 +10,7 @@ import {OverflowMenuProvider} from 'react-navigation-header-buttons';
import LocaleManager from './src/managers/LocaleManager'; import LocaleManager from './src/managers/LocaleManager';
import AsyncStorageManager from './src/managers/AsyncStorageManager'; import AsyncStorageManager from './src/managers/AsyncStorageManager';
import CustomIntroSlider from './src/components/Overrides/CustomIntroSlider'; import CustomIntroSlider from './src/components/Overrides/CustomIntroSlider';
import type {CustomTheme} from './src/managers/ThemeManager'; import type {CustomThemeType} from './src/managers/ThemeManager';
import ThemeManager from './src/managers/ThemeManager'; import ThemeManager from './src/managers/ThemeManager';
import MainNavigator from './src/navigation/MainNavigator'; import MainNavigator from './src/navigation/MainNavigator';
import AprilFoolsManager from './src/managers/AprilFoolsManager'; import AprilFoolsManager from './src/managers/AprilFoolsManager';
@ -35,7 +35,7 @@ type StateType = {
showIntro: boolean, showIntro: boolean,
showUpdate: boolean, showUpdate: boolean,
showAprilFools: boolean, showAprilFools: boolean,
currentTheme: CustomTheme | null, currentTheme: CustomThemeType | null,
}; };
export default class App extends React.Component<null, StateType> { export default class App extends React.Component<null, StateType> {

View file

@ -1,10 +1,12 @@
jest.mock('react-native-keychain'); /* eslint-disable */
import React from 'react'; import React from 'react';
import ConnectionManager from "../../src/managers/ConnectionManager"; import ConnectionManager from '../../src/managers/ConnectionManager';
import {ERROR_TYPE} from "../../src/utils/WebData"; 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(); const c = ConnectionManager.getInstance();
@ -13,132 +15,124 @@ afterEach(() => {
}); });
test('isLoggedIn yes', () => { test('isLoggedIn yes', () => {
jest.spyOn(ConnectionManager.prototype, 'getToken').mockImplementationOnce(() => { jest
.spyOn(ConnectionManager.prototype, 'getToken')
.mockImplementationOnce(() => {
return 'token'; return 'token';
}); });
return expect(c.isLoggedIn()).toBe(true); return expect(c.isLoggedIn()).toBe(true);
}); });
test('isLoggedIn no', () => { test('isLoggedIn no', () => {
jest.spyOn(ConnectionManager.prototype, 'getToken').mockImplementationOnce(() => { jest
.spyOn(ConnectionManager.prototype, 'getToken')
.mockImplementationOnce(() => {
return null; return null;
}); });
return expect(c.isLoggedIn()).toBe(false); return expect(c.isLoggedIn()).toBe(false);
}); });
test("isConnectionResponseValid", () => { test('connect bad credentials', () => {
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(() => { jest.spyOn(global, 'fetch').mockImplementationOnce(() => {
return Promise.resolve({ return Promise.resolve({
json: () => { json: () => {
return { return {
error: ERROR_TYPE.BAD_CREDENTIALS, error: ERROR_TYPE.BAD_CREDENTIALS,
data: {} data: {},
}; };
}, },
})
}); });
return expect(c.connect('email', 'password')) });
.rejects.toBe(ERROR_TYPE.BAD_CREDENTIALS); return expect(c.connect('email', 'password')).rejects.toBe(
ERROR_TYPE.BAD_CREDENTIALS,
);
}); });
test("connect good credentials", () => { test('connect good credentials', () => {
jest.spyOn(global, 'fetch').mockImplementationOnce(() => { jest.spyOn(global, 'fetch').mockImplementationOnce(() => {
return Promise.resolve({ return Promise.resolve({
json: () => { json: () => {
return { return {
error: ERROR_TYPE.SUCCESS, error: ERROR_TYPE.SUCCESS,
data: {token: 'token'} data: {token: 'token'},
}; };
}, },
})
}); });
jest.spyOn(ConnectionManager.prototype, 'saveLogin').mockImplementationOnce(() => { });
jest
.spyOn(ConnectionManager.prototype, 'saveLogin')
.mockImplementationOnce(() => {
return Promise.resolve(true); return Promise.resolve(true);
}); });
return expect(c.connect('email', 'password')).resolves.toBeTruthy(); return expect(c.connect('email', 'password')).resolves.toBeTruthy();
}); });
test("connect good credentials no consent", () => { test('connect good credentials no consent', () => {
jest.spyOn(global, 'fetch').mockImplementationOnce(() => { jest.spyOn(global, 'fetch').mockImplementationOnce(() => {
return Promise.resolve({ return Promise.resolve({
json: () => { json: () => {
return { return {
error: ERROR_TYPE.NO_CONSENT, error: ERROR_TYPE.NO_CONSENT,
data: {} data: {},
}; };
}, },
})
}); });
return expect(c.connect('email', 'password')) });
.rejects.toBe(ERROR_TYPE.NO_CONSENT); return expect(c.connect('email', 'password')).rejects.toBe(
ERROR_TYPE.NO_CONSENT,
);
}); });
test("connect good credentials, fail save token", () => { test('connect good credentials, fail save token', () => {
jest.spyOn(global, 'fetch').mockImplementationOnce(() => { jest.spyOn(global, 'fetch').mockImplementationOnce(() => {
return Promise.resolve({ return Promise.resolve({
json: () => { json: () => {
return { return {
error: ERROR_TYPE.SUCCESS, error: ERROR_TYPE.SUCCESS,
data: {token: 'token'} data: {token: 'token'},
}; };
}, },
})
}); });
jest.spyOn(ConnectionManager.prototype, 'saveLogin').mockImplementationOnce(() => { });
jest
.spyOn(ConnectionManager.prototype, 'saveLogin')
.mockImplementationOnce(() => {
return Promise.reject(false); return Promise.reject(false);
}); });
return expect(c.connect('email', 'password')).rejects.toBe(ERROR_TYPE.UNKNOWN); return expect(c.connect('email', 'password')).rejects.toBe(
ERROR_TYPE.UNKNOWN,
);
}); });
test("connect connection error", () => { test('connect connection error', () => {
jest.spyOn(global, 'fetch').mockImplementationOnce(() => { jest.spyOn(global, 'fetch').mockImplementationOnce(() => {
return Promise.reject(); return Promise.reject();
}); });
return expect(c.connect('email', 'password')) return expect(c.connect('email', 'password')).rejects.toBe(
.rejects.toBe(ERROR_TYPE.CONNECTION_ERROR); ERROR_TYPE.CONNECTION_ERROR,
);
}); });
test("connect bogus response 1", () => { test('connect bogus response 1', () => {
jest.spyOn(global, 'fetch').mockImplementationOnce(() => { jest.spyOn(global, 'fetch').mockImplementationOnce(() => {
return Promise.resolve({ return Promise.resolve({
json: () => { json: () => {
return { return {
thing: true, thing: true,
wrong: '', wrong: '',
} };
}, },
})
}); });
return expect(c.connect('email', 'password')) });
.rejects.toBe(ERROR_TYPE.CONNECTION_ERROR); return expect(c.connect('email', 'password')).rejects.toBe(
ERROR_TYPE.CONNECTION_ERROR,
);
}); });
test('authenticatedRequest success', () => {
test("authenticatedRequest success", () => { jest
jest.spyOn(ConnectionManager.prototype, 'getToken').mockImplementationOnce(() => { .spyOn(ConnectionManager.prototype, 'getToken')
.mockImplementationOnce(() => {
return 'token'; return 'token';
}); });
jest.spyOn(global, 'fetch').mockImplementationOnce(() => { jest.spyOn(global, 'fetch').mockImplementationOnce(() => {
@ -146,17 +140,20 @@ test("authenticatedRequest success", () => {
json: () => { json: () => {
return { return {
error: ERROR_TYPE.SUCCESS, error: ERROR_TYPE.SUCCESS,
data: {coucou: 'toi'} data: {coucou: 'toi'},
}; };
}, },
})
}); });
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'),
).resolves.toStrictEqual({coucou: 'toi'});
}); });
test("authenticatedRequest error wrong token", () => { test('authenticatedRequest error wrong token', () => {
jest.spyOn(ConnectionManager.prototype, 'getToken').mockImplementationOnce(() => { jest
.spyOn(ConnectionManager.prototype, 'getToken')
.mockImplementationOnce(() => {
return 'token'; return 'token';
}); });
jest.spyOn(global, 'fetch').mockImplementationOnce(() => { jest.spyOn(global, 'fetch').mockImplementationOnce(() => {
@ -164,17 +161,20 @@ test("authenticatedRequest error wrong token", () => {
json: () => { json: () => {
return { return {
error: ERROR_TYPE.BAD_TOKEN, error: ERROR_TYPE.BAD_TOKEN,
data: {} data: {},
}; };
}, },
})
}); });
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.BAD_TOKEN);
}); });
test("authenticatedRequest error bogus response", () => { test('authenticatedRequest error bogus response', () => {
jest.spyOn(ConnectionManager.prototype, 'getToken').mockImplementationOnce(() => { jest
.spyOn(ConnectionManager.prototype, 'getToken')
.mockImplementationOnce(() => {
return 'token'; return 'token';
}); });
jest.spyOn(global, 'fetch').mockImplementationOnce(() => { jest.spyOn(global, 'fetch').mockImplementationOnce(() => {
@ -184,27 +184,34 @@ test("authenticatedRequest error bogus response", () => {
error: ERROR_TYPE.SUCCESS, error: ERROR_TYPE.SUCCESS,
}; };
}, },
})
}); });
return expect(c.authenticatedRequest('https://www.amicale-insat.fr/api/token/check')) });
.rejects.toBe(ERROR_TYPE.CONNECTION_ERROR); return expect(
c.authenticatedRequest('https://www.amicale-insat.fr/api/token/check'),
).rejects.toBe(ERROR_TYPE.CONNECTION_ERROR);
}); });
test("authenticatedRequest connection error", () => { test('authenticatedRequest connection error', () => {
jest.spyOn(ConnectionManager.prototype, 'getToken').mockImplementationOnce(() => { jest
.spyOn(ConnectionManager.prototype, 'getToken')
.mockImplementationOnce(() => {
return 'token'; return 'token';
}); });
jest.spyOn(global, 'fetch').mockImplementationOnce(() => { jest.spyOn(global, 'fetch').mockImplementationOnce(() => {
return Promise.reject() return Promise.reject();
}); });
return expect(c.authenticatedRequest('https://www.amicale-insat.fr/api/token/check')) return expect(
.rejects.toBe(ERROR_TYPE.CONNECTION_ERROR); c.authenticatedRequest('https://www.amicale-insat.fr/api/token/check'),
).rejects.toBe(ERROR_TYPE.CONNECTION_ERROR);
}); });
test("authenticatedRequest error no token", () => { test('authenticatedRequest error no token', () => {
jest.spyOn(ConnectionManager.prototype, 'getToken').mockImplementationOnce(() => { jest
.spyOn(ConnectionManager.prototype, 'getToken')
.mockImplementationOnce(() => {
return null; return null;
}); });
return expect(c.authenticatedRequest('https://www.amicale-insat.fr/api/token/check')) return expect(
.rejects.toBe(ERROR_TYPE.UNKNOWN); c.authenticatedRequest('https://www.amicale-insat.fr/api/token/check'),
).rejects.toBe(ERROR_TYPE.UNKNOWN);
}); });

View file

@ -1,319 +1,345 @@
/* eslint-disable */
import React from 'react'; import React from 'react';
import * as EquipmentBooking from "../../src/utils/EquipmentBooking"; import * as EquipmentBooking from '../../src/utils/EquipmentBooking';
import i18n from "i18n-js"; import i18n from 'i18n-js';
test('getISODate', () => { test('getISODate', () => {
let date = new Date("2020-03-05 12:00"); let date = new Date('2020-03-05 12:00');
expect(EquipmentBooking.getISODate(date)).toBe("2020-03-05"); expect(EquipmentBooking.getISODate(date)).toBe('2020-03-05');
date = new Date("2020-03-05"); date = new Date('2020-03-05');
expect(EquipmentBooking.getISODate(date)).toBe("2020-03-05"); expect(EquipmentBooking.getISODate(date)).toBe('2020-03-05');
date = new Date("2020-03-05 00:00"); // Treated as local time date = new Date('2020-03-05 00:00'); // Treated as local time
expect(EquipmentBooking.getISODate(date)).toBe("2020-03-04"); // Treated as UTC expect(EquipmentBooking.getISODate(date)).toBe('2020-03-04'); // Treated as UTC
}); });
test('getCurrentDay', () => { test('getCurrentDay', () => {
jest.spyOn(Date, 'now') jest
.mockImplementation(() => .spyOn(Date, 'now')
new Date('2020-01-14 14:50:35').getTime() .mockImplementation(() => new Date('2020-01-14 14:50:35').getTime());
expect(EquipmentBooking.getCurrentDay().getTime()).toBe(
new Date('2020-01-14').getTime(),
); );
expect(EquipmentBooking.getCurrentDay().getTime()).toBe(new Date("2020-01-14").getTime());
}); });
test('isEquipmentAvailable', () => { test('isEquipmentAvailable', () => {
jest.spyOn(Date, 'now') jest
.mockImplementation(() => .spyOn(Date, 'now')
new Date('2020-07-09').getTime() .mockImplementation(() => new Date('2020-07-09').getTime());
);
let testDevice = { let testDevice = {
id: 1, id: 1,
name: "Petit barbecue", name: 'Petit barbecue',
caution: 100, caution: 100,
booked_at: [{begin: "2020-07-07", end: "2020-07-10"}] booked_at: [{begin: '2020-07-07', end: '2020-07-10'}],
}; };
expect(EquipmentBooking.isEquipmentAvailable(testDevice)).toBeFalse(); expect(EquipmentBooking.isEquipmentAvailable(testDevice)).toBeFalse();
testDevice.booked_at = [{begin: "2020-07-07", end: "2020-07-09"}]; testDevice.booked_at = [{begin: '2020-07-07', end: '2020-07-09'}];
expect(EquipmentBooking.isEquipmentAvailable(testDevice)).toBeFalse(); expect(EquipmentBooking.isEquipmentAvailable(testDevice)).toBeFalse();
testDevice.booked_at = [{begin: "2020-07-09", end: "2020-07-10"}]; testDevice.booked_at = [{begin: '2020-07-09', end: '2020-07-10'}];
expect(EquipmentBooking.isEquipmentAvailable(testDevice)).toBeFalse(); expect(EquipmentBooking.isEquipmentAvailable(testDevice)).toBeFalse();
testDevice.booked_at = [ testDevice.booked_at = [
{begin: "2020-07-07", end: "2020-07-8"}, {begin: '2020-07-07', end: '2020-07-8'},
{begin: "2020-07-10", end: "2020-07-12"}, {begin: '2020-07-10', end: '2020-07-12'},
]; ];
expect(EquipmentBooking.isEquipmentAvailable(testDevice)).toBeTrue(); expect(EquipmentBooking.isEquipmentAvailable(testDevice)).toBeTrue();
}); });
test('getFirstEquipmentAvailability', () => { test('getFirstEquipmentAvailability', () => {
jest.spyOn(Date, 'now') jest
.mockImplementation(() => .spyOn(Date, 'now')
new Date('2020-07-09').getTime() .mockImplementation(() => new Date('2020-07-09').getTime());
);
let testDevice = { let testDevice = {
id: 1, id: 1,
name: "Petit barbecue", name: 'Petit barbecue',
caution: 100, caution: 100,
booked_at: [{begin: "2020-07-07", end: "2020-07-10"}] booked_at: [{begin: '2020-07-07', end: '2020-07-10'}],
}; };
expect(EquipmentBooking.getFirstEquipmentAvailability(testDevice).getTime()).toBe(new Date("2020-07-11").getTime()); expect(
testDevice.booked_at = [{begin: "2020-07-07", end: "2020-07-09"}]; EquipmentBooking.getFirstEquipmentAvailability(testDevice).getTime(),
expect(EquipmentBooking.getFirstEquipmentAvailability(testDevice).getTime()).toBe(new Date("2020-07-10").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 = [ testDevice.booked_at = [
{begin: "2020-07-07", end: "2020-07-09"}, {begin: '2020-07-07', end: '2020-07-09'},
{begin: "2020-07-10", end: "2020-07-16"}, {begin: '2020-07-10', end: '2020-07-16'},
]; ];
expect(EquipmentBooking.getFirstEquipmentAvailability(testDevice).getTime()).toBe(new Date("2020-07-17").getTime()); expect(
EquipmentBooking.getFirstEquipmentAvailability(testDevice).getTime(),
).toBe(new Date('2020-07-17').getTime());
testDevice.booked_at = [ testDevice.booked_at = [
{begin: "2020-07-07", end: "2020-07-09"}, {begin: '2020-07-07', end: '2020-07-09'},
{begin: "2020-07-10", end: "2020-07-12"}, {begin: '2020-07-10', end: '2020-07-12'},
{begin: "2020-07-14", end: "2020-07-16"}, {begin: '2020-07-14', end: '2020-07-16'},
]; ];
expect(EquipmentBooking.getFirstEquipmentAvailability(testDevice).getTime()).toBe(new Date("2020-07-13").getTime()); expect(
EquipmentBooking.getFirstEquipmentAvailability(testDevice).getTime(),
).toBe(new Date('2020-07-13').getTime());
}); });
test('getRelativeDateString', () => { test('getRelativeDateString', () => {
jest.spyOn(Date, 'now') jest
.mockImplementation(() => .spyOn(Date, 'now')
new Date('2020-07-09').getTime() .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',
); );
jest.spyOn(i18n, 't') expect(EquipmentBooking.getRelativeDateString(new Date('2020-07-10'))).toBe(
.mockImplementation((translationString: string) => { '3',
const prefix = "screens.equipment."; );
if (translationString === prefix + "otherYear") expect(EquipmentBooking.getRelativeDateString(new Date('2020-07-11'))).toBe(
return "0"; '2',
else if (translationString === prefix + "otherMonth") );
return "1"; expect(EquipmentBooking.getRelativeDateString(new Date('2020-07-30'))).toBe(
else if (translationString === prefix + "thisMonth") '2',
return "2"; );
else if (translationString === prefix + "tomorrow") expect(EquipmentBooking.getRelativeDateString(new Date('2020-08-30'))).toBe(
return "3"; '1',
else if (translationString === prefix + "today") );
return "4"; expect(EquipmentBooking.getRelativeDateString(new Date('2020-11-10'))).toBe(
else '1',
return null; );
} expect(EquipmentBooking.getRelativeDateString(new Date('2021-11-10'))).toBe(
'0',
); );
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', () => { test('getValidRange', () => {
let testDevice = { let testDevice = {
id: 1, id: 1,
name: "Petit barbecue", name: 'Petit barbecue',
caution: 100, caution: 100,
booked_at: [{begin: "2020-07-07", end: "2020-07-10"}] booked_at: [{begin: '2020-07-07', end: '2020-07-10'}],
}; };
let start = new Date("2020-07-11"); let start = new Date('2020-07-11');
let end = new Date("2020-07-15"); let end = new Date('2020-07-15');
let result = [ let result = [
"2020-07-11", '2020-07-11',
"2020-07-12", '2020-07-12',
"2020-07-13", '2020-07-13',
"2020-07-14", '2020-07-14',
"2020-07-15", '2020-07-15',
]; ];
expect(EquipmentBooking.getValidRange(start, end, testDevice)).toStrictEqual(result); expect(EquipmentBooking.getValidRange(start, end, testDevice)).toStrictEqual(
result,
);
testDevice.booked_at = [ testDevice.booked_at = [
{begin: "2020-07-07", end: "2020-07-10"}, {begin: '2020-07-07', end: '2020-07-10'},
{begin: "2020-07-13", end: "2020-07-15"}, {begin: '2020-07-13', end: '2020-07-15'},
]; ];
result = [ result = ['2020-07-11', '2020-07-12'];
"2020-07-11", expect(EquipmentBooking.getValidRange(start, end, testDevice)).toStrictEqual(
"2020-07-12", result,
]; );
expect(EquipmentBooking.getValidRange(start, end, testDevice)).toStrictEqual(result);
testDevice.booked_at = [{begin: "2020-07-12", end: "2020-07-13"}]; testDevice.booked_at = [{begin: '2020-07-12', end: '2020-07-13'}];
result = ["2020-07-11"]; result = ['2020-07-11'];
expect(EquipmentBooking.getValidRange(start, end, testDevice)).toStrictEqual(result); expect(EquipmentBooking.getValidRange(start, end, testDevice)).toStrictEqual(
testDevice.booked_at = [{begin: "2020-07-07", end: "2020-07-12"},]; result,
result = [ );
"2020-07-13", testDevice.booked_at = [{begin: '2020-07-07', end: '2020-07-12'}];
"2020-07-14", result = ['2020-07-13', '2020-07-14', '2020-07-15'];
"2020-07-15", expect(EquipmentBooking.getValidRange(end, start, testDevice)).toStrictEqual(
]; result,
expect(EquipmentBooking.getValidRange(end, start, testDevice)).toStrictEqual(result); );
start = new Date("2020-07-14"); start = new Date('2020-07-14');
end = new Date("2020-07-14"); end = new Date('2020-07-14');
result = [ result = ['2020-07-14'];
"2020-07-14", expect(
]; EquipmentBooking.getValidRange(start, start, testDevice),
expect(EquipmentBooking.getValidRange(start, start, testDevice)).toStrictEqual(result); ).toStrictEqual(result);
expect(EquipmentBooking.getValidRange(end, start, testDevice)).toStrictEqual(result); expect(EquipmentBooking.getValidRange(end, start, testDevice)).toStrictEqual(
expect(EquipmentBooking.getValidRange(start, end, null)).toStrictEqual(result); result,
);
expect(EquipmentBooking.getValidRange(start, end, null)).toStrictEqual(
result,
);
start = new Date("2020-07-14"); start = new Date('2020-07-14');
end = new Date("2020-07-17"); end = new Date('2020-07-17');
result = [ result = ['2020-07-14', '2020-07-15', '2020-07-16', '2020-07-17'];
"2020-07-14", expect(EquipmentBooking.getValidRange(start, end, null)).toStrictEqual(
"2020-07-15", result,
"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"}]; testDevice.booked_at = [{begin: '2020-07-17', end: '2020-07-17'}];
result = [ result = ['2020-07-14', '2020-07-15', '2020-07-16'];
"2020-07-14", expect(EquipmentBooking.getValidRange(start, end, testDevice)).toStrictEqual(
"2020-07-15", result,
"2020-07-16", );
];
expect(EquipmentBooking.getValidRange(start, end, testDevice)).toStrictEqual(result);
testDevice.booked_at = [ testDevice.booked_at = [
{begin: "2020-07-12", end: "2020-07-13"}, {begin: '2020-07-12', end: '2020-07-13'},
{begin: "2020-07-15", end: "2020-07-20"}, {begin: '2020-07-15', end: '2020-07-20'},
]; ];
start = new Date("2020-07-11"); start = new Date('2020-07-11');
end = new Date("2020-07-23"); end = new Date('2020-07-23');
result = [ result = ['2020-07-21', '2020-07-22', '2020-07-23'];
"2020-07-21", expect(EquipmentBooking.getValidRange(end, start, testDevice)).toStrictEqual(
"2020-07-22", result,
"2020-07-23", );
];
expect(EquipmentBooking.getValidRange(end, start, testDevice)).toStrictEqual(result);
}); });
test('generateMarkedDates', () => { test('generateMarkedDates', () => {
let theme = { let theme = {
colors: { colors: {
primary: "primary", primary: 'primary',
danger: "primary", danger: 'primary',
textDisabled: "primary", textDisabled: 'primary',
} },
} };
let testDevice = { let testDevice = {
id: 1, id: 1,
name: "Petit barbecue", name: 'Petit barbecue',
caution: 100, caution: 100,
booked_at: [{begin: "2020-07-07", end: "2020-07-10"}] booked_at: [{begin: '2020-07-07', end: '2020-07-10'}],
}; };
let start = new Date("2020-07-11"); let start = new Date('2020-07-11');
let end = new Date("2020-07-13"); let end = new Date('2020-07-13');
let range = EquipmentBooking.getValidRange(start, end, testDevice); let range = EquipmentBooking.getValidRange(start, end, testDevice);
let result = { let result = {
"2020-07-11": { '2020-07-11': {
startingDay: true, startingDay: true,
endingDay: false, endingDay: false,
color: theme.colors.primary color: theme.colors.primary,
}, },
"2020-07-12": { '2020-07-12': {
startingDay: false, startingDay: false,
endingDay: false, endingDay: false,
color: theme.colors.danger color: theme.colors.danger,
}, },
"2020-07-13": { '2020-07-13': {
startingDay: false, startingDay: false,
endingDay: true, endingDay: true,
color: theme.colors.primary color: theme.colors.primary,
}, },
}; };
expect(EquipmentBooking.generateMarkedDates(true, theme, range)).toStrictEqual(result); expect(
EquipmentBooking.generateMarkedDates(true, theme, range),
).toStrictEqual(result);
result = { result = {
"2020-07-11": { '2020-07-11': {
startingDay: true, startingDay: true,
endingDay: false, endingDay: false,
color: theme.colors.textDisabled color: theme.colors.textDisabled,
}, },
"2020-07-12": { '2020-07-12': {
startingDay: false, startingDay: false,
endingDay: false, endingDay: false,
color: theme.colors.textDisabled color: theme.colors.textDisabled,
}, },
"2020-07-13": { '2020-07-13': {
startingDay: false, startingDay: false,
endingDay: true, endingDay: true,
color: theme.colors.textDisabled color: theme.colors.textDisabled,
}, },
}; };
expect(EquipmentBooking.generateMarkedDates(false, theme, range)).toStrictEqual(result); expect(
EquipmentBooking.generateMarkedDates(false, theme, range),
).toStrictEqual(result);
result = { result = {
"2020-07-11": { '2020-07-11': {
startingDay: true, startingDay: true,
endingDay: false, endingDay: false,
color: theme.colors.textDisabled color: theme.colors.textDisabled,
}, },
"2020-07-12": { '2020-07-12': {
startingDay: false, startingDay: false,
endingDay: false, endingDay: false,
color: theme.colors.textDisabled color: theme.colors.textDisabled,
}, },
"2020-07-13": { '2020-07-13': {
startingDay: false, startingDay: false,
endingDay: true, endingDay: true,
color: theme.colors.textDisabled color: theme.colors.textDisabled,
}, },
}; };
range = EquipmentBooking.getValidRange(end, start, testDevice); range = EquipmentBooking.getValidRange(end, start, testDevice);
expect(EquipmentBooking.generateMarkedDates(false, theme, range)).toStrictEqual(result); expect(
EquipmentBooking.generateMarkedDates(false, theme, range),
).toStrictEqual(result);
testDevice.booked_at = [{begin: "2020-07-13", end: "2020-07-15"},]; testDevice.booked_at = [{begin: '2020-07-13', end: '2020-07-15'}];
result = { result = {
"2020-07-11": { '2020-07-11': {
startingDay: true, startingDay: true,
endingDay: false, endingDay: false,
color: theme.colors.primary color: theme.colors.primary,
}, },
"2020-07-12": { '2020-07-12': {
startingDay: false, startingDay: false,
endingDay: true, endingDay: true,
color: theme.colors.primary color: theme.colors.primary,
}, },
}; };
range = EquipmentBooking.getValidRange(start, end, testDevice); range = EquipmentBooking.getValidRange(start, end, testDevice);
expect(EquipmentBooking.generateMarkedDates(true, theme, range)).toStrictEqual(result); expect(
EquipmentBooking.generateMarkedDates(true, theme, range),
).toStrictEqual(result);
testDevice.booked_at = [{begin: "2020-07-12", end: "2020-07-13"},]; testDevice.booked_at = [{begin: '2020-07-12', end: '2020-07-13'}];
result = { result = {
"2020-07-11": { '2020-07-11': {
startingDay: true, startingDay: true,
endingDay: true, endingDay: true,
color: theme.colors.primary color: theme.colors.primary,
}, },
}; };
range = EquipmentBooking.getValidRange(start, end, testDevice); range = EquipmentBooking.getValidRange(start, end, testDevice);
expect(EquipmentBooking.generateMarkedDates(true, theme, range)).toStrictEqual(result); expect(
EquipmentBooking.generateMarkedDates(true, theme, range),
).toStrictEqual(result);
testDevice.booked_at = [ testDevice.booked_at = [
{begin: "2020-07-12", end: "2020-07-13"}, {begin: '2020-07-12', end: '2020-07-13'},
{begin: "2020-07-15", end: "2020-07-20"}, {begin: '2020-07-15', end: '2020-07-20'},
]; ];
start = new Date("2020-07-11"); start = new Date('2020-07-11');
end = new Date("2020-07-23"); end = new Date('2020-07-23');
result = { result = {
"2020-07-11": { '2020-07-11': {
startingDay: true, startingDay: true,
endingDay: true, endingDay: true,
color: theme.colors.primary color: theme.colors.primary,
}, },
}; };
range = EquipmentBooking.getValidRange(start, end, testDevice); range = EquipmentBooking.getValidRange(start, end, testDevice);
expect(EquipmentBooking.generateMarkedDates(true, theme, range)).toStrictEqual(result); expect(
EquipmentBooking.generateMarkedDates(true, theme, range),
).toStrictEqual(result);
result = { result = {
"2020-07-21": { '2020-07-21': {
startingDay: true, startingDay: true,
endingDay: false, endingDay: false,
color: theme.colors.primary color: theme.colors.primary,
}, },
"2020-07-22": { '2020-07-22': {
startingDay: false, startingDay: false,
endingDay: false, endingDay: false,
color: theme.colors.danger color: theme.colors.danger,
}, },
"2020-07-23": { '2020-07-23': {
startingDay: false, startingDay: false,
endingDay: true, endingDay: true,
color: theme.colors.primary color: theme.colors.primary,
}, },
}; };
range = EquipmentBooking.getValidRange(end, start, testDevice); range = EquipmentBooking.getValidRange(end, start, testDevice);
expect(EquipmentBooking.generateMarkedDates(true, theme, range)).toStrictEqual(result); expect(
EquipmentBooking.generateMarkedDates(true, theme, range),
).toStrictEqual(result);
}); });

View file

@ -1,35 +1,41 @@
/* eslint-disable */
import React from 'react'; import React from 'react';
import * as Planning from "../../src/utils/Planning"; import * as Planning from '../../src/utils/Planning';
test('isDescriptionEmpty', () => { test('isDescriptionEmpty', () => {
expect(Planning.isDescriptionEmpty("")).toBeTrue(); expect(Planning.isDescriptionEmpty('')).toBeTrue();
expect(Planning.isDescriptionEmpty(" ")).toBeTrue(); expect(Planning.isDescriptionEmpty(' ')).toBeTrue();
// noinspection CheckTagEmptyBody // noinspection CheckTagEmptyBody
expect(Planning.isDescriptionEmpty("<p></p>")).toBeTrue(); expect(Planning.isDescriptionEmpty('<p></p>')).toBeTrue();
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>')).toBeTrue();
expect(Planning.isDescriptionEmpty("<p><br></p><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><br><br></p>')).toBeTrue();
expect(Planning.isDescriptionEmpty("<p><br>")).toBeTrue(); expect(Planning.isDescriptionEmpty('<p><br>')).toBeTrue();
expect(Planning.isDescriptionEmpty(null)).toBeTrue(); expect(Planning.isDescriptionEmpty(null)).toBeTrue();
expect(Planning.isDescriptionEmpty(undefined)).toBeTrue(); expect(Planning.isDescriptionEmpty(undefined)).toBeTrue();
expect(Planning.isDescriptionEmpty("coucou")).toBeFalse(); expect(Planning.isDescriptionEmpty('coucou')).toBeFalse();
expect(Planning.isDescriptionEmpty("<p>coucou</p>")).toBeFalse(); expect(Planning.isDescriptionEmpty('<p>coucou</p>')).toBeFalse();
}); });
test('isEventDateStringFormatValid', () => { test('isEventDateStringFormatValid', () => {
expect(Planning.isEventDateStringFormatValid("2020-03-21 09:00")).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')).toBeTrue();
expect(Planning.isEventDateStringFormatValid("3214-64-12 01:16:00")).toBeFalse(); expect(
expect(Planning.isEventDateStringFormatValid("3214-64-12 1:16")).toBeFalse(); Planning.isEventDateStringFormatValid('3214-64-12 01:16:00'),
expect(Planning.isEventDateStringFormatValid("3214-f4-12 01:16")).toBeFalse(); ).toBeFalse();
expect(Planning.isEventDateStringFormatValid("sqdd 09:00")).toBeFalse(); expect(Planning.isEventDateStringFormatValid('3214-64-12 1:16')).toBeFalse();
expect(Planning.isEventDateStringFormatValid("2020-03-21")).toBeFalse(); expect(Planning.isEventDateStringFormatValid('3214-f4-12 01:16')).toBeFalse();
expect(Planning.isEventDateStringFormatValid("2020-03-21 truc")).toBeFalse(); expect(Planning.isEventDateStringFormatValid('sqdd 09:00')).toBeFalse();
expect(Planning.isEventDateStringFormatValid("3214-64-12 1:16:65")).toBeFalse(); expect(Planning.isEventDateStringFormatValid('2020-03-21')).toBeFalse();
expect(Planning.isEventDateStringFormatValid("garbage")).toBeFalse(); expect(Planning.isEventDateStringFormatValid('2020-03-21 truc')).toBeFalse();
expect(Planning.isEventDateStringFormatValid("")).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(undefined)).toBeFalse();
expect(Planning.isEventDateStringFormatValid(null)).toBeFalse(); expect(Planning.isEventDateStringFormatValid(null)).toBeFalse();
}); });
@ -37,136 +43,144 @@ test('isEventDateStringFormatValid', () => {
test('stringToDate', () => { test('stringToDate', () => {
let testDate = new Date(); let testDate = new Date();
expect(Planning.stringToDate(undefined)).toBeNull(); expect(Planning.stringToDate(undefined)).toBeNull();
expect(Planning.stringToDate("")).toBeNull(); expect(Planning.stringToDate('')).toBeNull();
expect(Planning.stringToDate("garbage")).toBeNull(); expect(Planning.stringToDate('garbage')).toBeNull();
expect(Planning.stringToDate("2020-03-21")).toBeNull(); expect(Planning.stringToDate('2020-03-21')).toBeNull();
expect(Planning.stringToDate("09:00:00")).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();
expect(Planning.stringToDate("2020-03-21 09:g0:")).toBeNull(); expect(Planning.stringToDate('2020-03-21 09:g0:')).toBeNull();
testDate.setFullYear(2020, 2, 21); testDate.setFullYear(2020, 2, 21);
testDate.setHours(9, 0, 0, 0); testDate.setHours(9, 0, 0, 0);
expect(Planning.stringToDate("2020-03-21 09:00")).toEqual(testDate); expect(Planning.stringToDate('2020-03-21 09:00')).toEqual(testDate);
testDate.setFullYear(2020, 0, 31); testDate.setFullYear(2020, 0, 31);
testDate.setHours(18, 30, 0, 0); testDate.setHours(18, 30, 0, 0);
expect(Planning.stringToDate("2020-01-31 18:30")).toEqual(testDate); expect(Planning.stringToDate('2020-01-31 18:30')).toEqual(testDate);
testDate.setFullYear(2020, 50, 50); testDate.setFullYear(2020, 50, 50);
testDate.setHours(65, 65, 0, 0); testDate.setHours(65, 65, 0, 0);
expect(Planning.stringToDate("2020-51-50 65:65")).toEqual(testDate); expect(Planning.stringToDate('2020-51-50 65:65')).toEqual(testDate);
}); });
test('getFormattedEventTime', () => { test('getFormattedEventTime', () => {
expect(Planning.getFormattedEventTime(null, null)) expect(Planning.getFormattedEventTime(null, null)).toBe('/ - /');
.toBe('/ - /'); expect(Planning.getFormattedEventTime(undefined, undefined)).toBe('/ - /');
expect(Planning.getFormattedEventTime(undefined, undefined)) expect(Planning.getFormattedEventTime('20:30', '23:00')).toBe('/ - /');
.toBe('/ - /'); expect(Planning.getFormattedEventTime('2020-03-30', '2020-03-31')).toBe(
expect(Planning.getFormattedEventTime("20:30", "23:00")) '/ - /',
.toBe('/ - /'); );
expect(Planning.getFormattedEventTime("2020-03-30", "2020-03-31"))
.toBe('/ - /');
expect(
expect(Planning.getFormattedEventTime("2020-03-21 09:00", "2020-03-21 09:00")) Planning.getFormattedEventTime('2020-03-21 09:00', '2020-03-21 09:00'),
.toBe('09:00'); ).toBe('09:00');
expect(Planning.getFormattedEventTime("2020-03-21 09:00", "2020-03-22 17:00")) expect(
.toBe('09:00 - 23:59'); Planning.getFormattedEventTime('2020-03-21 09:00', '2020-03-22 17:00'),
expect(Planning.getFormattedEventTime("2020-03-30 20:30", "2020-03-30 23:00")) ).toBe('09:00 - 23:59');
.toBe('20:30 - 23:00'); expect(
Planning.getFormattedEventTime('2020-03-30 20:30', '2020-03-30 23:00'),
).toBe('20:30 - 23:00');
}); });
test('getDateOnlyString', () => { test('getDateOnlyString', () => {
expect(Planning.getDateOnlyString("2020-03-21 09:00")).toBe("2020-03-21"); 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-15 09:00')).toBe('2021-12-15');
expect(Planning.getDateOnlyString("2021-12-o5 09:00")).toBeNull(); expect(Planning.getDateOnlyString('2021-12-o5 09:00')).toBeNull();
expect(Planning.getDateOnlyString("2021-12-15 09:")).toBeNull(); expect(Planning.getDateOnlyString('2021-12-15 09:')).toBeNull();
expect(Planning.getDateOnlyString("2021-12-15")).toBeNull(); expect(Planning.getDateOnlyString('2021-12-15')).toBeNull();
expect(Planning.getDateOnlyString("garbage")).toBeNull(); expect(Planning.getDateOnlyString('garbage')).toBeNull();
}); });
test('isEventBefore', () => { test('isEventBefore', () => {
expect(Planning.isEventBefore( expect(
"2020-03-21 09:00", "2020-03-21 10:00")).toBeTrue(); Planning.isEventBefore('2020-03-21 09:00', '2020-03-21 10:00'),
expect(Planning.isEventBefore( ).toBeTrue();
"2020-03-21 10:00", "2020-03-21 10:15")).toBeTrue(); expect(
expect(Planning.isEventBefore( Planning.isEventBefore('2020-03-21 10:00', '2020-03-21 10:15'),
"2020-03-21 10:15", "2021-03-21 10:15")).toBeTrue(); ).toBeTrue();
expect(Planning.isEventBefore( expect(
"2020-03-21 10:15", "2020-05-21 10:15")).toBeTrue(); Planning.isEventBefore('2020-03-21 10:15', '2021-03-21 10:15'),
expect(Planning.isEventBefore( ).toBeTrue();
"2020-03-21 10:15", "2020-03-30 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( expect(
"2020-03-21 10:00", "2020-03-21 10:00")).toBeFalse(); Planning.isEventBefore('2020-03-21 10:00', '2020-03-21 10:00'),
expect(Planning.isEventBefore( ).toBeFalse();
"2020-03-21 10:00", "2020-03-21 09:00")).toBeFalse(); expect(
expect(Planning.isEventBefore( Planning.isEventBefore('2020-03-21 10:00', '2020-03-21 09:00'),
"2020-03-21 10:15", "2020-03-21 10:00")).toBeFalse(); ).toBeFalse();
expect(Planning.isEventBefore( expect(
"2021-03-21 10:15", "2020-03-21 10:15")).toBeFalse(); Planning.isEventBefore('2020-03-21 10:15', '2020-03-21 10:00'),
expect(Planning.isEventBefore( ).toBeFalse();
"2020-05-21 10:15", "2020-03-21 10:15")).toBeFalse(); expect(
expect(Planning.isEventBefore( Planning.isEventBefore('2021-03-21 10:15', '2020-03-21 10:15'),
"2020-03-30 10:15", "2020-03-21 10:15")).toBeFalse(); ).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( expect(Planning.isEventBefore('garbage', '2020-03-21 10:15')).toBeFalse();
"garbage", "2020-03-21 10:15")).toBeFalse(); expect(Planning.isEventBefore(undefined, undefined)).toBeFalse();
expect(Planning.isEventBefore(
undefined, undefined)).toBeFalse();
}); });
test('dateToString', () => { test('dateToString', () => {
let testDate = new Date(); let testDate = new Date();
testDate.setFullYear(2020, 2, 21); testDate.setFullYear(2020, 2, 21);
testDate.setHours(9, 0, 0, 0); testDate.setHours(9, 0, 0, 0);
expect(Planning.dateToString(testDate)).toBe("2020-03-21 09:00"); expect(Planning.dateToString(testDate)).toBe('2020-03-21 09:00');
testDate.setFullYear(2021, 0, 12); testDate.setFullYear(2021, 0, 12);
testDate.setHours(9, 10, 0, 0); testDate.setHours(9, 10, 0, 0);
expect(Planning.dateToString(testDate)).toBe("2021-01-12 09:10"); expect(Planning.dateToString(testDate)).toBe('2021-01-12 09:10');
testDate.setFullYear(2022, 11, 31); testDate.setFullYear(2022, 11, 31);
testDate.setHours(9, 10, 15, 0); testDate.setHours(9, 10, 15, 0);
expect(Planning.dateToString(testDate)).toBe("2022-12-31 09:10"); expect(Planning.dateToString(testDate)).toBe('2022-12-31 09:10');
}); });
test('generateEmptyCalendar', () => { test('generateEmptyCalendar', () => {
jest.spyOn(Date, 'now') jest
.mockImplementation(() => .spyOn(Date, 'now')
new Date('2020-01-14T00:00:00.000Z').getTime() .mockImplementation(() => new Date('2020-01-14T00:00:00.000Z').getTime());
);
let calendar = Planning.generateEmptyCalendar(1); let calendar = Planning.generateEmptyCalendar(1);
expect(calendar).toHaveProperty("2020-01-14"); expect(calendar).toHaveProperty('2020-01-14');
expect(calendar).toHaveProperty("2020-01-20"); expect(calendar).toHaveProperty('2020-01-20');
expect(calendar).toHaveProperty("2020-02-10"); expect(calendar).toHaveProperty('2020-02-10');
expect(Object.keys(calendar).length).toBe(32); expect(Object.keys(calendar).length).toBe(32);
calendar = Planning.generateEmptyCalendar(3); calendar = Planning.generateEmptyCalendar(3);
expect(calendar).toHaveProperty("2020-01-14"); expect(calendar).toHaveProperty('2020-01-14');
expect(calendar).toHaveProperty("2020-01-20"); expect(calendar).toHaveProperty('2020-01-20');
expect(calendar).toHaveProperty("2020-02-10"); expect(calendar).toHaveProperty('2020-02-10');
expect(calendar).toHaveProperty("2020-02-14"); expect(calendar).toHaveProperty('2020-02-14');
expect(calendar).toHaveProperty("2020-03-20"); expect(calendar).toHaveProperty('2020-03-20');
expect(calendar).toHaveProperty("2020-04-12"); expect(calendar).toHaveProperty('2020-04-12');
expect(Object.keys(calendar).length).toBe(92); expect(Object.keys(calendar).length).toBe(92);
}); });
test('pushEventInOrder', () => { test('pushEventInOrder', () => {
let eventArray = []; let eventArray = [];
let event1 = {date_begin: "2020-01-14 09:15"}; let event1 = {date_begin: '2020-01-14 09:15'};
Planning.pushEventInOrder(eventArray, event1); Planning.pushEventInOrder(eventArray, event1);
expect(eventArray.length).toBe(1); expect(eventArray.length).toBe(1);
expect(eventArray[0]).toBe(event1); expect(eventArray[0]).toBe(event1);
let event2 = {date_begin: "2020-01-14 10:15"}; let event2 = {date_begin: '2020-01-14 10:15'};
Planning.pushEventInOrder(eventArray, event2); Planning.pushEventInOrder(eventArray, event2);
expect(eventArray.length).toBe(2); expect(eventArray.length).toBe(2);
expect(eventArray[0]).toBe(event1); expect(eventArray[0]).toBe(event1);
expect(eventArray[1]).toBe(event2); expect(eventArray[1]).toBe(event2);
let event3 = {date_begin: "2020-01-14 10:15", title: "garbage"}; let event3 = {date_begin: '2020-01-14 10:15', title: 'garbage'};
Planning.pushEventInOrder(eventArray, event3); Planning.pushEventInOrder(eventArray, event3);
expect(eventArray.length).toBe(3); expect(eventArray.length).toBe(3);
expect(eventArray[0]).toBe(event1); expect(eventArray[0]).toBe(event1);
expect(eventArray[1]).toBe(event2); expect(eventArray[1]).toBe(event2);
expect(eventArray[2]).toBe(event3); expect(eventArray[2]).toBe(event3);
let event4 = {date_begin: "2020-01-13 09:00"}; let event4 = {date_begin: '2020-01-13 09:00'};
Planning.pushEventInOrder(eventArray, event4); Planning.pushEventInOrder(eventArray, event4);
expect(eventArray.length).toBe(4); expect(eventArray.length).toBe(4);
expect(eventArray[0]).toBe(event4); expect(eventArray[0]).toBe(event4);
@ -176,31 +190,29 @@ test('pushEventInOrder', () => {
}); });
test('generateEventAgenda', () => { test('generateEventAgenda', () => {
jest.spyOn(Date, 'now') jest
.mockImplementation(() => .spyOn(Date, 'now')
new Date('2020-01-14T00:00:00.000Z').getTime() .mockImplementation(() => new Date('2020-01-14T00:00:00.000Z').getTime());
);
let eventList = [ let eventList = [
{date_begin: "2020-01-14 09:15"}, {date_begin: '2020-01-14 09:15'},
{date_begin: "2020-02-01 09:15"}, {date_begin: '2020-02-01 09:15'},
{date_begin: "2020-01-15 09:15"}, {date_begin: '2020-01-15 09:15'},
{date_begin: "2020-02-01 09:30"}, {date_begin: '2020-02-01 09:30'},
{date_begin: "2020-02-01 08:30"}, {date_begin: '2020-02-01 08:30'},
]; ];
const calendar = Planning.generateEventAgenda(eventList, 2); const calendar = Planning.generateEventAgenda(eventList, 2);
expect(calendar["2020-01-14"].length).toBe(1); expect(calendar['2020-01-14'].length).toBe(1);
expect(calendar["2020-01-14"][0]).toBe(eventList[0]); expect(calendar['2020-01-14'][0]).toBe(eventList[0]);
expect(calendar["2020-01-15"].length).toBe(1); expect(calendar['2020-01-15'].length).toBe(1);
expect(calendar["2020-01-15"][0]).toBe(eventList[2]); expect(calendar['2020-01-15'][0]).toBe(eventList[2]);
expect(calendar["2020-02-01"].length).toBe(3); expect(calendar['2020-02-01'].length).toBe(3);
expect(calendar["2020-02-01"][0]).toBe(eventList[4]); expect(calendar['2020-02-01'][0]).toBe(eventList[4]);
expect(calendar["2020-02-01"][1]).toBe(eventList[1]); expect(calendar['2020-02-01'][1]).toBe(eventList[1]);
expect(calendar["2020-02-01"][2]).toBe(eventList[3]); expect(calendar['2020-02-01'][2]).toBe(eventList[3]);
}); });
test('getCurrentDateString', () => { test('getCurrentDateString', () => {
jest.spyOn(Date, 'now') jest.spyOn(Date, 'now').mockImplementation(() => {
.mockImplementation(() => {
let date = new Date(); let date = new Date();
date.setFullYear(2020, 0, 14); date.setFullYear(2020, 0, 14);
date.setHours(15, 30, 54, 65); date.setHours(15, 30, 54, 65);

View file

@ -1,142 +1,167 @@
/* eslint-disable */
import React from 'react'; import React from 'react';
import {getCleanedMachineWatched, getMachineEndDate, getMachineOfId, isMachineWatched} from "../../src/utils/Proxiwash"; import {
getCleanedMachineWatched,
getMachineEndDate,
getMachineOfId,
isMachineWatched,
} from '../../src/utils/Proxiwash';
test('getMachineEndDate', () => { test('getMachineEndDate', () => {
jest.spyOn(Date, 'now') jest
.mockImplementation(() => .spyOn(Date, 'now')
new Date('2020-01-14T15:00:00.000Z').getTime() .mockImplementation(() => new Date('2020-01-14T15:00:00.000Z').getTime());
);
let expectDate = new Date('2020-01-14T15:00:00.000Z'); let expectDate = new Date('2020-01-14T15:00:00.000Z');
expectDate.setHours(23); expectDate.setHours(23);
expectDate.setMinutes(10); expectDate.setMinutes(10);
expect(getMachineEndDate({endTime: "23:10"}).getTime()).toBe(expectDate.getTime()); expect(getMachineEndDate({endTime: '23:10'}).getTime()).toBe(
expectDate.getTime(),
);
expectDate.setHours(16); expectDate.setHours(16);
expectDate.setMinutes(30); expectDate.setMinutes(30);
expect(getMachineEndDate({endTime: "16:30"}).getTime()).toBe(expectDate.getTime()); expect(getMachineEndDate({endTime: '16:30'}).getTime()).toBe(
expectDate.getTime(),
expect(getMachineEndDate({endTime: "15:30"})).toBeNull();
expect(getMachineEndDate({endTime: "13:10"})).toBeNull();
jest.spyOn(Date, 'now')
.mockImplementation(() =>
new Date('2020-01-14T23:00:00.000Z').getTime()
); );
expect(getMachineEndDate({endTime: '15:30'})).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 = new Date('2020-01-14T23:00:00.000Z');
expectDate.setHours(0); expectDate.setHours(0);
expectDate.setMinutes(30); expectDate.setMinutes(30);
expect(getMachineEndDate({endTime: "00:30"}).getTime()).toBe(expectDate.getTime()); expect(getMachineEndDate({endTime: '00:30'}).getTime()).toBe(
expectDate.getTime(),
);
}); });
test('isMachineWatched', () => { test('isMachineWatched', () => {
let machineList = [ let machineList = [
{ {
number: "0", number: '0',
endTime: "23:30", endTime: '23:30',
}, },
{ {
number: "1", number: '1',
endTime: "20:30", endTime: '20:30',
}, },
]; ];
expect(isMachineWatched({number: "0", endTime: "23:30"}, machineList)).toBeTrue(); expect(
expect(isMachineWatched({number: "1", endTime: "20:30"}, machineList)).toBeTrue(); isMachineWatched({number: '0', endTime: '23:30'}, machineList),
expect(isMachineWatched({number: "3", endTime: "20:30"}, machineList)).toBeFalse(); ).toBeTrue();
expect(isMachineWatched({number: "1", endTime: "23:30"}, machineList)).toBeFalse(); 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', () => { test('getMachineOfId', () => {
let machineList = [ let machineList = [
{ {
number: "0", number: '0',
}, },
{ {
number: "1", number: '1',
}, },
]; ];
expect(getMachineOfId("0", machineList)).toStrictEqual({number: "0"}); expect(getMachineOfId('0', machineList)).toStrictEqual({number: '0'});
expect(getMachineOfId("1", machineList)).toStrictEqual({number: "1"}); expect(getMachineOfId('1', machineList)).toStrictEqual({number: '1'});
expect(getMachineOfId("3", machineList)).toBeNull(); expect(getMachineOfId('3', machineList)).toBeNull();
}); });
test('getCleanedMachineWatched', () => { test('getCleanedMachineWatched', () => {
let machineList = [ let machineList = [
{ {
number: "0", number: '0',
endTime: "23:30", endTime: '23:30',
}, },
{ {
number: "1", number: '1',
endTime: "20:30", endTime: '20:30',
}, },
{ {
number: "2", number: '2',
endTime: "", endTime: '',
}, },
]; ];
let watchList = [ let watchList = [
{ {
number: "0", number: '0',
endTime: "23:30", endTime: '23:30',
}, },
{ {
number: "1", number: '1',
endTime: "20:30", endTime: '20:30',
}, },
{ {
number: "2", number: '2',
endTime: "", endTime: '',
}, },
]; ];
let cleanedList = watchList; let cleanedList = watchList;
expect(getCleanedMachineWatched(watchList, machineList)).toStrictEqual(cleanedList); expect(getCleanedMachineWatched(watchList, machineList)).toStrictEqual(
cleanedList,
);
watchList = [ watchList = [
{ {
number: "0", number: '0',
endTime: "23:30", endTime: '23:30',
}, },
{ {
number: "1", number: '1',
endTime: "20:30", endTime: '20:30',
}, },
{ {
number: "2", number: '2',
endTime: "15:30", endTime: '15:30',
}, },
]; ];
cleanedList = [ cleanedList = [
{ {
number: "0", number: '0',
endTime: "23:30", endTime: '23:30',
}, },
{ {
number: "1", number: '1',
endTime: "20:30", endTime: '20:30',
}, },
]; ];
expect(getCleanedMachineWatched(watchList, machineList)).toStrictEqual(cleanedList); expect(getCleanedMachineWatched(watchList, machineList)).toStrictEqual(
cleanedList,
);
watchList = [ watchList = [
{ {
number: "0", number: '0',
endTime: "23:30", endTime: '23:30',
}, },
{ {
number: "1", number: '1',
endTime: "20:31", endTime: '20:31',
}, },
{ {
number: "3", number: '3',
endTime: "15:30", endTime: '15:30',
}, },
]; ];
cleanedList = [ cleanedList = [
{ {
number: "0", number: '0',
endTime: "23:30", endTime: '23:30',
}, },
]; ];
expect(getCleanedMachineWatched(watchList, machineList)).toStrictEqual(cleanedList); expect(getCleanedMachineWatched(watchList, machineList)).toStrictEqual(
cleanedList,
);
}); });

View file

@ -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();
});

View 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();
});

View file

@ -6,4 +6,5 @@ import {AppRegistry} from 'react-native';
import App from './App'; import App from './App';
import {name as appName} from './app.json'; import {name as appName} from './app.json';
// eslint-disable-next-line flowtype/require-return-type
AppRegistry.registerComponent(appName, () => App); AppRegistry.registerComponent(appName, () => App);

View file

@ -7,6 +7,7 @@
module.exports = { module.exports = {
transformer: { transformer: {
// eslint-disable-next-line flowtype/require-return-type
getTransformOptions: async () => ({ getTransformOptions: async () => ({
transform: { transform: {
experimentalImportSupport: false, experimentalImportSupport: false,

View file

@ -4,10 +4,10 @@ import * as React from 'react';
import {View} from 'react-native'; 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 i18n from 'i18n-js';
import type {CustomTheme} from '../../../managers/ThemeManager'; import type {CustomThemeType} from '../../../managers/ThemeManager';
type PropsType = { type PropsType = {
theme: CustomTheme, theme: CustomThemeType,
}; };
class VoteNotAvailable extends React.Component<PropsType> { class VoteNotAvailable extends React.Component<PropsType> {

View file

@ -12,12 +12,12 @@ import {
import {FlatList, StyleSheet} from 'react-native'; import {FlatList, StyleSheet} from 'react-native';
import i18n from 'i18n-js'; import i18n from 'i18n-js';
import type {VoteTeamType} from '../../../screens/Amicale/VoteScreen'; import type {VoteTeamType} from '../../../screens/Amicale/VoteScreen';
import type {CustomTheme} from '../../../managers/ThemeManager'; import type {CustomThemeType} from '../../../managers/ThemeManager';
type PropsType = { type PropsType = {
teams: Array<VoteTeamType>, teams: Array<VoteTeamType>,
dateEnd: string, dateEnd: string,
theme: CustomTheme, theme: CustomThemeType,
}; };
const styles = StyleSheet.create({ const styles = StyleSheet.create({

View file

@ -9,14 +9,14 @@ import {
} from 'react-native-paper'; } from 'react-native-paper';
import {StyleSheet} from 'react-native'; import {StyleSheet} from 'react-native';
import i18n from 'i18n-js'; import i18n from 'i18n-js';
import type {CustomTheme} from '../../../managers/ThemeManager'; import type {CustomThemeType} from '../../../managers/ThemeManager';
type PropsType = { type PropsType = {
startDate: string | null, startDate: string | null,
justVoted: boolean, justVoted: boolean,
hasVoted: boolean, hasVoted: boolean,
isVoteRunning: boolean, isVoteRunning: boolean,
theme: CustomTheme, theme: CustomThemeType,
}; };
const styles = StyleSheet.create({ const styles = StyleSheet.create({

View file

@ -5,10 +5,10 @@ import {View} from 'react-native';
import {List, withTheme} from 'react-native-paper'; import {List, withTheme} from 'react-native-paper';
import Collapsible from 'react-native-collapsible'; import Collapsible from 'react-native-collapsible';
import * as Animatable from 'react-native-animatable'; import * as Animatable from 'react-native-animatable';
import type {CustomTheme} from '../../managers/ThemeManager'; import type {CustomThemeType} from '../../managers/ThemeManager';
type PropsType = { type PropsType = {
theme: CustomTheme, theme: CustomThemeType,
title: string, title: string,
subtitle?: string, subtitle?: string,
left?: () => React.Node, left?: () => React.Node,

View file

@ -7,13 +7,14 @@ import * as Animatable from 'react-native-animatable';
import {StackNavigationProp} from '@react-navigation/stack'; import {StackNavigationProp} from '@react-navigation/stack';
import AutoHideHandler from '../../utils/AutoHideHandler'; import AutoHideHandler from '../../utils/AutoHideHandler';
import CustomTabBar from '../Tabbar/CustomTabBar'; import CustomTabBar from '../Tabbar/CustomTabBar';
import type {CustomTheme} from '../../managers/ThemeManager'; import type {CustomThemeType} from '../../managers/ThemeManager';
import type {OnScrollType} from '../../utils/AutoHideHandler';
const AnimatedFAB = Animatable.createAnimatableComponent(FAB); const AnimatedFAB = Animatable.createAnimatableComponent(FAB);
type PropsType = { type PropsType = {
navigation: StackNavigationProp, navigation: StackNavigationProp,
theme: CustomTheme, theme: CustomThemeType,
onPress: (action: string, data?: string) => void, onPress: (action: string, data?: string) => void,
seekAttention: boolean, seekAttention: boolean,
}; };
@ -94,7 +95,7 @@ class AnimatedBottomBar extends React.Component<PropsType, StateType> {
} }
}; };
onScroll = (event: SyntheticEvent<EventTarget>) => { onScroll = (event: OnScrollType) => {
this.hideHandler.onScroll(event); this.hideHandler.onScroll(event);
}; };

View file

@ -2,7 +2,7 @@
import * as React from 'react'; import * as React from 'react';
import {Collapsible} from 'react-navigation-collapsible'; import {Collapsible} from 'react-navigation-collapsible';
import {withCollapsible} from '../../utils/withCollapsible'; import withCollapsible from '../../utils/withCollapsible';
import CustomTabBar from '../Tabbar/CustomTabBar'; import CustomTabBar from '../Tabbar/CustomTabBar';
export type CollapsibleComponentPropsType = { export type CollapsibleComponentPropsType = {

View file

@ -5,11 +5,11 @@ import {List, withTheme} from 'react-native-paper';
import {View} from 'react-native'; import {View} from 'react-native';
import i18n from 'i18n-js'; import i18n from 'i18n-js';
import {StackNavigationProp} from '@react-navigation/stack'; import {StackNavigationProp} from '@react-navigation/stack';
import type {CustomTheme} from '../../managers/ThemeManager'; import type {CustomThemeType} from '../../managers/ThemeManager';
type PropsType = { type PropsType = {
navigation: StackNavigationProp, navigation: StackNavigationProp,
theme: CustomTheme, theme: CustomThemeType,
}; };
class ActionsDashBoardItem extends React.Component<PropsType> { class ActionsDashBoardItem extends React.Component<PropsType> {

View file

@ -10,12 +10,12 @@ import {
} from 'react-native-paper'; } from 'react-native-paper';
import {StyleSheet, View} from 'react-native'; import {StyleSheet, View} from 'react-native';
import i18n from 'i18n-js'; import i18n from 'i18n-js';
import type {CustomTheme} from '../../managers/ThemeManager'; import type {CustomThemeType} from '../../managers/ThemeManager';
type PropsType = { type PropsType = {
eventNumber: number, eventNumber: number,
clickAction: () => void, clickAction: () => void,
theme: CustomTheme, theme: CustomThemeType,
children?: React.Node, children?: React.Node,
}; };

View file

@ -4,13 +4,13 @@ import * as React from 'react';
import {Badge, TouchableRipple, withTheme} from 'react-native-paper'; import {Badge, TouchableRipple, withTheme} from 'react-native-paper';
import {Dimensions, Image, View} from 'react-native'; import {Dimensions, Image, View} from 'react-native';
import * as Animatable from 'react-native-animatable'; import * as Animatable from 'react-native-animatable';
import type {CustomTheme} from '../../managers/ThemeManager'; import type {CustomThemeType} from '../../managers/ThemeManager';
type PropsType = { type PropsType = {
image: string | null, image: string | null,
onPress: () => void | null, onPress: () => void | null,
badgeCount: number | null, badgeCount: number | null,
theme: CustomTheme, theme: CustomThemeType,
}; };
const AnimatableBadge = Animatable.createAnimatableComponent(Badge); const AnimatableBadge = Animatable.createAnimatableComponent(Badge);

View file

@ -7,14 +7,14 @@ import type {
ClubCategoryType, ClubCategoryType,
ClubType, ClubType,
} from '../../../screens/Amicale/Clubs/ClubListScreen'; } from '../../../screens/Amicale/Clubs/ClubListScreen';
import type {CustomTheme} from '../../../managers/ThemeManager'; import type {CustomThemeType} from '../../../managers/ThemeManager';
type PropsType = { type PropsType = {
onPress: () => void, onPress: () => void,
categoryTranslator: (id: number) => ClubCategoryType, categoryTranslator: (id: number) => ClubCategoryType,
item: ClubType, item: ClubType,
height: number, height: number,
theme: CustomTheme, theme: CustomThemeType,
}; };
class ClubListItem extends React.Component<PropsType> { class ClubListItem extends React.Component<PropsType> {

View file

@ -10,13 +10,13 @@ import type {
ServiceCategoryType, ServiceCategoryType,
ServiceItemType, ServiceItemType,
} from '../../../managers/ServicesManager'; } from '../../../managers/ServicesManager';
import type {CustomTheme} from '../../../managers/ThemeManager'; import type {CustomThemeType} from '../../../managers/ThemeManager';
type PropsType = { type PropsType = {
item: ServiceCategoryType, item: ServiceCategoryType,
activeDashboard: Array<string>, activeDashboard: Array<string>,
onPress: (service: ServiceItemType) => void, onPress: (service: ServiceItemType) => void,
theme: CustomTheme, theme: CustomThemeType,
}; };
const LIST_ITEM_HEIGHT = 64; const LIST_ITEM_HEIGHT = 64;

View file

@ -3,7 +3,7 @@
import * as React from 'react'; import * as React from 'react';
import {Image} from 'react-native'; import {Image} from 'react-native';
import {List, withTheme} from 'react-native-paper'; import {List, withTheme} from 'react-native-paper';
import type {CustomTheme} from '../../../managers/ThemeManager'; import type {CustomThemeType} from '../../../managers/ThemeManager';
import type {ServiceItemType} from '../../../managers/ServicesManager'; import type {ServiceItemType} from '../../../managers/ServicesManager';
type PropsType = { type PropsType = {
@ -11,7 +11,7 @@ type PropsType = {
isActive: boolean, isActive: boolean,
height: number, height: number,
onPress: () => void, onPress: () => void,
theme: CustomTheme, theme: CustomThemeType,
}; };
class DashboardEditItem extends React.Component<PropsType> { class DashboardEditItem extends React.Component<PropsType> {

View file

@ -3,13 +3,13 @@
import * as React from 'react'; import * as React from 'react';
import {TouchableRipple, withTheme} from 'react-native-paper'; import {TouchableRipple, withTheme} from 'react-native-paper';
import {Dimensions, Image, View} from 'react-native'; import {Dimensions, Image, View} from 'react-native';
import type {CustomTheme} from '../../../managers/ThemeManager'; import type {CustomThemeType} from '../../../managers/ThemeManager';
type PropsType = { type PropsType = {
image: string, image: string,
isActive: boolean, isActive: boolean,
onPress: () => void, onPress: () => void,
theme: CustomTheme, theme: CustomThemeType,
}; };
/** /**

View file

@ -4,7 +4,7 @@ import * as React from 'react';
import {Avatar, List, withTheme} from 'react-native-paper'; import {Avatar, List, withTheme} from 'react-native-paper';
import i18n from 'i18n-js'; import i18n from 'i18n-js';
import {StackNavigationProp} from '@react-navigation/stack'; import {StackNavigationProp} from '@react-navigation/stack';
import type {CustomTheme} from '../../../managers/ThemeManager'; import type {CustomThemeType} from '../../../managers/ThemeManager';
import type {DeviceType} from '../../../screens/Amicale/Equipment/EquipmentListScreen'; import type {DeviceType} from '../../../screens/Amicale/Equipment/EquipmentListScreen';
import { import {
getFirstEquipmentAvailability, getFirstEquipmentAvailability,
@ -17,7 +17,7 @@ type PropsType = {
userDeviceRentDates: [string, string], userDeviceRentDates: [string, string],
item: DeviceType, item: DeviceType,
height: number, height: number,
theme: CustomTheme, theme: CustomThemeType,
}; };
class EquipmentListItem extends React.Component<PropsType> { class EquipmentListItem extends React.Component<PropsType> {

View file

@ -10,7 +10,7 @@ import type {
PlanexGroupType, PlanexGroupType,
PlanexGroupCategoryType, PlanexGroupCategoryType,
} from '../../../screens/Planex/GroupSelectionScreen'; } from '../../../screens/Planex/GroupSelectionScreen';
import type {CustomTheme} from '../../../managers/ThemeManager'; import type {CustomThemeType} from '../../../managers/ThemeManager';
type PropsType = { type PropsType = {
item: PlanexGroupCategoryType, item: PlanexGroupCategoryType,
@ -19,7 +19,7 @@ type PropsType = {
currentSearchString: string, currentSearchString: string,
favoriteNumber: number, favoriteNumber: number,
height: number, height: number,
theme: CustomTheme, theme: CustomThemeType,
}; };
const LIST_ITEM_HEIGHT = 64; const LIST_ITEM_HEIGHT = 64;

View file

@ -2,11 +2,11 @@
import * as React from 'react'; import * as React from 'react';
import {IconButton, List, withTheme} from 'react-native-paper'; import {IconButton, List, withTheme} from 'react-native-paper';
import type {CustomTheme} from '../../../managers/ThemeManager'; import type {CustomThemeType} from '../../../managers/ThemeManager';
import type {PlanexGroupType} from '../../../screens/Planex/GroupSelectionScreen'; import type {PlanexGroupType} from '../../../screens/Planex/GroupSelectionScreen';
type PropsType = { type PropsType = {
theme: CustomTheme, theme: CustomThemeType,
onPress: () => void, onPress: () => void,
onStarPress: () => void, onStarPress: () => void,
item: PlanexGroupType, item: PlanexGroupType,

View file

@ -1,188 +1,46 @@
import * as React from 'react'; // @flow
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";
type Props = { import * as React from 'react';
item: Machine, import {
theme: CustomTheme, Avatar,
onPress: Function, 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,
) => void,
isWatched: boolean, isWatched: boolean,
isDryer: boolean, isDryer: boolean,
height: number, height: number,
} };
const AnimatedIcon = Animatable.createAnimatableComponent(Avatar.Icon); const AnimatedIcon = Animatable.createAnimatableComponent(Avatar.Icon);
/**
* Component used to display a proxiwash item, showing machine progression and state
*/
class ProxiwashListItem extends React.Component<Props> {
stateColors: Object;
stateStrings: Object;
title: string;
constructor(props) {
super(props);
this.stateColors = {};
this.stateStrings = {};
this.updateStateStrings();
let displayNumber = props.item.number;
if (AprilFoolsManager.getInstance().isAprilFoolsEnabled())
displayNumber = AprilFoolsManager.getProxiwashMachineDisplayNumber(parseInt(props.item.number));
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);
}
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');
}
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;
}
onListItemPress = () => this.props.onPress(this.title, this.props.item, this.props.isDryer);
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;
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>)}
/>
</Surface>
);
}
}
const styles = StyleSheet.create({ const styles = StyleSheet.create({
container: { container: {
margin: 5, margin: 5,
justifyContent: 'center', justifyContent: 'center',
elevation: 1 elevation: 1,
}, },
icon: { icon: {
backgroundColor: 'transparent' backgroundColor: 'transparent',
}, },
progressBar: { progressBar: {
position: 'absolute', position: 'absolute',
@ -191,4 +49,188 @@ const styles = StyleSheet.create({
}, },
}); });
/**
* Component used to display a proxiwash item, showing machine progression and state
*/
class ProxiwashListItem extends React.Component<PropsType> {
stateColors: {[key: string]: string};
stateStrings: {[key: string]: string};
title: string;
constructor(props: PropsType) {
super(props);
this.stateColors = {};
this.stateStrings = {};
this.updateStateStrings();
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 += `${displayNumber}`;
}
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
);
}
onListItemPress = () => {
const {props} = this;
props.onPress(this.title, props.item, props.isDryer);
};
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',
);
}
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(): 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={(): 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}
/>
</View>
</View>
)}
/>
</Surface>
);
}
}
export default withTheme(ProxiwashListItem); export default withTheme(ProxiwashListItem);

View file

@ -1,56 +1,17 @@
// @flow
import * as React from 'react'; import * as React from 'react';
import {Avatar, Text, withTheme} from 'react-native-paper'; import {Avatar, Text, withTheme} from 'react-native-paper';
import {StyleSheet, View} from "react-native"; import {StyleSheet, View} from 'react-native';
import i18n from "i18n-js"; import i18n from 'i18n-js';
import type {CustomThemeType} from '../../../managers/ThemeManager';
type Props = { type PropsType = {
theme: CustomThemeType,
title: string, title: string,
isDryer: boolean, isDryer: boolean,
nbAvailable: number, nbAvailable: number,
} };
/**
* Component used to display a proxiwash item, showing machine progression and state
*/
class ProxiwashListItem extends React.Component<Props> {
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>
);
}
}
const styles = StyleSheet.create({ const styles = StyleSheet.create({
container: { container: {
@ -61,12 +22,51 @@ const styles = StyleSheet.create({
marginTop: 20, marginTop: 20,
}, },
icon: { icon: {
backgroundColor: 'transparent' backgroundColor: 'transparent',
}, },
text: { text: {
fontSize: 20, fontSize: 20,
fontWeight: 'bold', fontWeight: 'bold',
} },
}); });
/**
* Component used to display a proxiwash item, showing machine progression and state
*/
class ProxiwashListItem extends React.Component<PropsType> {
shouldComponentUpdate(nextProps: PropsType): boolean {
const {props} = this;
return (
nextProps.theme.dark !== props.theme.dark ||
nextProps.nbAvailable !== props.nbAvailable
);
}
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>
);
}
}
export default withTheme(ProxiwashListItem); export default withTheme(ProxiwashListItem);

View file

@ -1,35 +1,35 @@
// @flow // @flow
import * as React from 'react'; import * as React from 'react';
import * as Animatable from "react-native-animatable"; import * as Animatable from 'react-native-animatable';
import {Image, TouchableWithoutFeedback, View} from "react-native"; import {Image, TouchableWithoutFeedback, View} from 'react-native';
import type {ViewStyle} from "react-native/Libraries/StyleSheet/StyleSheet"; import type {ViewStyle} from 'react-native/Libraries/StyleSheet/StyleSheet';
type Props = { export type AnimatableViewRefType = {current: null | Animatable.View};
style?: ViewStyle,
emotion: number,
animated: boolean,
entryAnimation: Animatable.AnimatableProperties | null,
loopAnimation: Animatable.AnimatableProperties | null,
onPress?: (viewRef: AnimatableViewRef) => null,
onLongPress?: (viewRef: AnimatableViewRef) => null,
}
type State = { 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, 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_IMAGE = require("../../../assets/mascot/mascot.png"); const MASCOT_EYES_GIRLY = require('../../../assets/mascot/mascot_eyes_girly.png');
const MASCOT_EYES_NORMAL = require("../../../assets/mascot/mascot_eyes_normal.png"); const MASCOT_EYES_CUTE = require('../../../assets/mascot/mascot_eyes_cute.png');
const MASCOT_EYES_GIRLY = require("../../../assets/mascot/mascot_eyes_girly.png"); const MASCOT_EYES_WINK = require('../../../assets/mascot/mascot_eyes_wink.png');
const MASCOT_EYES_CUTE = require("../../../assets/mascot/mascot_eyes_cute.png"); const MASCOT_EYES_HEART = require('../../../assets/mascot/mascot_eyes_heart.png');
const MASCOT_EYES_WINK = require("../../../assets/mascot/mascot_eyes_wink.png"); const MASCOT_EYES_ANGRY = require('../../../assets/mascot/mascot_eyes_angry.png');
const MASCOT_EYES_HEART = require("../../../assets/mascot/mascot_eyes_heart.png"); const MASCOT_GLASSES = require('../../../assets/mascot/mascot_glasses.png');
const MASCOT_EYES_ANGRY = require("../../../assets/mascot/mascot_eyes_angry.png"); const MASCOT_SUNGLASSES = require('../../../assets/mascot/mascot_sunglasses.png');
const MASCOT_GLASSES = require("../../../assets/mascot/mascot_glasses.png");
const MASCOT_SUNGLASSES = require("../../../assets/mascot/mascot_sunglasses.png");
export const EYE_STYLE = { export const EYE_STYLE = {
NORMAL: 0, NORMAL: 0,
@ -38,12 +38,12 @@ export const EYE_STYLE = {
WINK: 4, WINK: 4,
HEART: 5, HEART: 5,
ANGRY: 6, ANGRY: 6,
} };
const GLASSES_STYLE = { const GLASSES_STYLE = {
NORMAL: 0, NORMAL: 0,
COOl: 1 COOl: 1,
} };
export const MASCOT_STYLE = { export const MASCOT_STYLE = {
NORMAL: 0, NORMAL: 0,
@ -58,40 +58,40 @@ export const MASCOT_STYLE = {
RANDOM: 999, RANDOM: 999,
}; };
class Mascot extends React.Component<PropsType, StateType> {
class Mascot extends React.Component<Props, State> {
static defaultProps = { static defaultProps = {
emotion: MASCOT_STYLE.NORMAL,
animated: false, animated: false,
style: null,
entryAnimation: { entryAnimation: {
useNativeDriver: true, useNativeDriver: true,
animation: "rubberBand", animation: 'rubberBand',
duration: 2000, duration: 2000,
}, },
loopAnimation: { loopAnimation: {
useNativeDriver: true, useNativeDriver: true,
animation: "swing", animation: 'swing',
duration: 2000, duration: 2000,
iterationDelay: 250, iterationDelay: 250,
iterationCount: "infinite", iterationCount: 'infinite',
}, },
clickAnimation: { onPress: null,
useNativeDriver: true, onLongPress: null,
animation: "rubberBand", };
duration: 2000,
},
}
viewRef: AnimatableViewRef; viewRef: AnimatableViewRefType;
eyeList: { [key: number]: number | string };
glassesList: { [key: number]: number | string };
onPress: (viewRef: AnimatableViewRef) => null; eyeList: {[key: number]: number | string};
onLongPress: (viewRef: AnimatableViewRef) => null;
glassesList: {[key: number]: number | string};
onPress: (viewRef: AnimatableViewRefType) => void;
onLongPress: (viewRef: AnimatableViewRefType) => void;
initialEmotion: number; initialEmotion: number;
constructor(props: Props) { constructor(props: PropsType) {
super(props); super(props);
this.viewRef = React.createRef(); this.viewRef = React.createRef();
this.eyeList = {}; this.eyeList = {};
@ -106,87 +106,94 @@ class Mascot extends React.Component<Props, State> {
this.glassesList[GLASSES_STYLE.NORMAL] = MASCOT_GLASSES; this.glassesList[GLASSES_STYLE.NORMAL] = MASCOT_GLASSES;
this.glassesList[GLASSES_STYLE.COOl] = MASCOT_SUNGLASSES; this.glassesList[GLASSES_STYLE.COOl] = MASCOT_SUNGLASSES;
this.initialEmotion = this.props.emotion; this.initialEmotion =
props.emotion != null ? props.emotion : Mascot.defaultProps.emotion;
if (this.initialEmotion === MASCOT_STYLE.RANDOM) if (this.initialEmotion === MASCOT_STYLE.RANDOM)
this.initialEmotion = Math.floor(Math.random() * MASCOT_STYLE.ANGRY) + 1; this.initialEmotion = Math.floor(Math.random() * MASCOT_STYLE.ANGRY) + 1;
this.state = { this.state = {
currentEmotion: this.initialEmotion currentEmotion: this.initialEmotion,
} };
if (this.props.onPress == null) { if (props.onPress == null) {
this.onPress = (viewRef: AnimatableViewRef) => { this.onPress = (viewRef: AnimatableViewRefType) => {
let ref = viewRef.current; const ref = viewRef.current;
if (ref != null) { if (ref != null) {
this.setState({currentEmotion: MASCOT_STYLE.LOVE}); this.setState({currentEmotion: MASCOT_STYLE.LOVE});
ref.rubberBand(1500).then(() => { ref.rubberBand(1500).then(() => {
this.setState({currentEmotion: this.initialEmotion}); this.setState({currentEmotion: this.initialEmotion});
}); });
} }
return null; };
} } else this.onPress = props.onPress;
} else
this.onPress = this.props.onPress;
if (this.props.onLongPress == null) { if (props.onLongPress == null) {
this.onLongPress = (viewRef: AnimatableViewRef) => { this.onLongPress = (viewRef: AnimatableViewRefType) => {
let ref = viewRef.current; const ref = viewRef.current;
if (ref != null) { if (ref != null) {
this.setState({currentEmotion: MASCOT_STYLE.ANGRY}); this.setState({currentEmotion: MASCOT_STYLE.ANGRY});
ref.tada(1000).then(() => { ref.tada(1000).then(() => {
this.setState({currentEmotion: this.initialEmotion}); this.setState({currentEmotion: this.initialEmotion});
}); });
} }
return null; };
} } else this.onLongPress = props.onLongPress;
} else
this.onLongPress = this.props.onLongPress;
} }
getGlasses(style: number) { getGlasses(style: number): React.Node {
const glasses = this.glassesList[style]; const glasses = this.glassesList[style];
return <Image return (
key={"glasses"} <Image
source={glasses != null ? glasses : this.glassesList[GLASSES_STYLE.NORMAL]} key="glasses"
source={
glasses != null ? glasses : this.glassesList[GLASSES_STYLE.NORMAL]
}
style={{ style={{
position: "absolute", position: 'absolute',
top: "15%", top: '15%',
left: 0, left: 0,
width: "100%", width: '100%',
height: "100%", height: '100%',
}} }}
/> />
);
} }
getEye(style: number, isRight: boolean, rotation: string="0deg") { getEye(
style: number,
isRight: boolean,
rotation: string = '0deg',
): React.Node {
const eye = this.eyeList[style]; const eye = this.eyeList[style];
return <Image return (
key={isRight ? "right" : "left"} <Image
key={isRight ? 'right' : 'left'}
source={eye != null ? eye : this.eyeList[EYE_STYLE.NORMAL]} source={eye != null ? eye : this.eyeList[EYE_STYLE.NORMAL]}
style={{ style={{
position: "absolute", position: 'absolute',
top: "15%", top: '15%',
left: isRight ? "-11%" : "11%", left: isRight ? '-11%' : '11%',
width: "100%", width: '100%',
height: "100%", height: '100%',
transform: [{rotateY: rotation}] transform: [{rotateY: rotation}],
}} }}
/> />
);
} }
getEyes(emotion: number) { getEyes(emotion: number): React.Node {
let final = []; const final = [];
final.push(<View final.push(
key={"container"} <View
key="container"
style={{ style={{
position: "absolute", position: 'absolute',
width: "100%", width: '100%',
height: "100%", height: '100%',
}}/>); }}
/>,
);
if (emotion === MASCOT_STYLE.CUTE) { if (emotion === MASCOT_STYLE.CUTE) {
final.push(this.getEye(EYE_STYLE.CUTE, true)); final.push(this.getEye(EYE_STYLE.CUTE, true));
final.push(this.getEye(EYE_STYLE.CUTE, false)); final.push(this.getEye(EYE_STYLE.CUTE, false));
@ -204,7 +211,7 @@ class Mascot extends React.Component<Props, State> {
final.push(this.getEye(EYE_STYLE.HEART, false)); final.push(this.getEye(EYE_STYLE.HEART, false));
} else if (emotion === MASCOT_STYLE.ANGRY) { } else if (emotion === MASCOT_STYLE.ANGRY) {
final.push(this.getEye(EYE_STYLE.ANGRY, true)); final.push(this.getEye(EYE_STYLE.ANGRY, true));
final.push(this.getEye(EYE_STYLE.ANGRY, false, "180deg")); final.push(this.getEye(EYE_STYLE.ANGRY, false, '180deg'));
} else if (emotion === MASCOT_STYLE.COOL) { } else if (emotion === MASCOT_STYLE.COOL) {
final.push(this.getGlasses(GLASSES_STYLE.COOl)); final.push(this.getGlasses(GLASSES_STYLE.COOl));
} else { } else {
@ -212,42 +219,45 @@ class Mascot extends React.Component<Props, State> {
final.push(this.getEye(EYE_STYLE.NORMAL, false)); final.push(this.getEye(EYE_STYLE.NORMAL, false));
} }
if (emotion === MASCOT_STYLE.INTELLO) { // Needs to have normal eyes behind the glasses if (emotion === MASCOT_STYLE.INTELLO) {
// Needs to have normal eyes behind the glasses
final.push(this.getGlasses(GLASSES_STYLE.NORMAL)); final.push(this.getGlasses(GLASSES_STYLE.NORMAL));
} }
final.push(<View key={"container2"}/>); final.push(<View key="container2" />);
return final; return final;
} }
render() { render(): React.Node {
const entryAnimation = this.props.animated ? this.props.entryAnimation : null; const {props, state} = this;
const loopAnimation = this.props.animated ? this.props.loopAnimation : null; const entryAnimation = props.animated ? props.entryAnimation : null;
const loopAnimation = props.animated ? props.loopAnimation : null;
return ( return (
<Animatable.View <Animatable.View
style={{ style={{
aspectRatio: 1, aspectRatio: 1,
...this.props.style ...props.style,
}} }}
{...entryAnimation} // eslint-disable-next-line react/jsx-props-no-spreading
> {...entryAnimation}>
<TouchableWithoutFeedback <TouchableWithoutFeedback
onPress={() => this.onPress(this.viewRef)} onPress={() => {
onLongPress={() => this.onLongPress(this.viewRef)} this.onPress(this.viewRef);
> }}
onLongPress={() => {
this.onLongPress(this.viewRef);
}}>
<Animatable.View ref={this.viewRef}>
<Animatable.View <Animatable.View
ref={this.viewRef} // eslint-disable-next-line react/jsx-props-no-spreading
> {...loopAnimation}>
<Animatable.View
{...loopAnimation}
>
<Image <Image
source={MASCOT_IMAGE} source={MASCOT_IMAGE}
style={{ style={{
width: "100%", width: '100%',
height:"100%", height: '100%',
}} }}
/> />
{this.getEyes(this.state.currentEmotion)} {this.getEyes(state.currentEmotion)}
</Animatable.View> </Animatable.View>
</Animatable.View> </Animatable.View>
</TouchableWithoutFeedback> </TouchableWithoutFeedback>

View file

@ -1,16 +1,29 @@
// @flow // @flow
import * as React from 'react'; import * as React from 'react';
import {Avatar, Button, Card, Paragraph, Portal, withTheme} from 'react-native-paper'; import {
import Mascot from "./Mascot"; Avatar,
import * as Animatable from "react-native-animatable"; Button,
import {BackHandler, Dimensions, ScrollView, TouchableWithoutFeedback, View} from "react-native"; Card,
import type {CustomTheme} from "../../managers/ThemeManager"; Paragraph,
import SpeechArrow from "./SpeechArrow"; Portal,
import AsyncStorageManager from "../../managers/AsyncStorageManager"; 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 = { type PropsType = {
theme: CustomTheme, theme: CustomThemeType,
icon: string, icon: string,
title: string, title: string,
message: string, message: string,
@ -26,28 +39,34 @@ type Props = {
icon: string | null, icon: string | null,
color: string | null, color: string | null,
onPress?: () => void, onPress?: () => void,
} },
}, },
emotion: number, emotion: number,
visible?: boolean, visible?: boolean,
prefKey?: string, prefKey?: string,
} };
type State = { type StateType = {
shouldRenderDialog: boolean, // Used to stop rendering after hide animation shouldRenderDialog: boolean, // Used to stop rendering after hide animation
dialogVisible: boolean, dialogVisible: boolean,
} };
/** /**
* Component used to display a popup with the mascot. * 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; mascotSize: number;
windowWidth: number; windowWidth: number;
windowHeight: number; windowHeight: number;
constructor(props: Props) { constructor(props: PropsType) {
super(props); super(props);
this.windowWidth = Dimensions.get('window').width; this.windowWidth = Dimensions.get('window').width;
@ -55,13 +74,13 @@ class MascotPopup extends React.Component<Props, State> {
this.mascotSize = Dimensions.get('window').height / 6; this.mascotSize = Dimensions.get('window').height / 6;
if (this.props.visible != null) { if (props.visible != null) {
this.state = { this.state = {
shouldRenderDialog: this.props.visible, shouldRenderDialog: props.visible,
dialogVisible: this.props.visible, dialogVisible: props.visible,
}; };
} else if (this.props.prefKey != null) { } else if (props.prefKey != null) {
const visible = AsyncStorageManager.getBool(this.props.prefKey); const visible = AsyncStorageManager.getBool(props.prefKey);
this.state = { this.state = {
shouldRenderDialog: visible, shouldRenderDialog: visible,
dialogVisible: visible, dialogVisible: visible,
@ -72,90 +91,92 @@ class MascotPopup extends React.Component<Props, State> {
dialogVisible: false, dialogVisible: false,
}; };
} }
} }
onAnimationEnd = () => { componentDidMount(): * {
this.setState({ BackHandler.addEventListener(
shouldRenderDialog: false, 'hardwareBackPress',
}) this.onBackButtonPressAndroid,
);
} }
shouldComponentUpdate(nextProps: Props, nextState: State): boolean { shouldComponentUpdate(nextProps: PropsType, nextState: StateType): boolean {
const {props, state} = this;
if (nextProps.visible) { if (nextProps.visible) {
this.state.shouldRenderDialog = true; this.state.shouldRenderDialog = true;
this.state.dialogVisible = true; this.state.dialogVisible = true;
} else if (nextProps.visible !== this.props.visible } else if (
|| (!nextState.dialogVisible && nextState.dialogVisible !== this.state.dialogVisible)) { nextProps.visible !== props.visible ||
(!nextState.dialogVisible &&
nextState.dialogVisible !== state.dialogVisible)
) {
this.state.dialogVisible = false; this.state.dialogVisible = false;
setTimeout(this.onAnimationEnd, 300); setTimeout(this.onAnimationEnd, 300);
} }
return true; return true;
} }
componentDidMount(): * { onAnimationEnd = () => {
BackHandler.addEventListener( this.setState({
'hardwareBackPress', shouldRenderDialog: false,
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() { 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;
};
getSpeechBubble(): React.Node {
const {state, props} = this;
return ( return (
<Animatable.View <Animatable.View
style={{ style={{
marginLeft: "10%", marginLeft: '10%',
marginRight: "10%", marginRight: '10%',
}} }}
useNativeDriver={true} useNativeDriver
animation={this.state.dialogVisible ? "bounceInLeft" : "bounceOutLeft"} animation={state.dialogVisible ? 'bounceInLeft' : 'bounceOutLeft'}
duration={this.state.dialogVisible ? 1000 : 300} duration={state.dialogVisible ? 1000 : 300}>
>
<SpeechArrow <SpeechArrow
style={{marginLeft: this.mascotSize / 3}} style={{marginLeft: this.mascotSize / 3}}
size={20} size={20}
color={this.props.theme.colors.mascotMessageArrow} color={props.theme.colors.mascotMessageArrow}
/> />
<Card style={{ <Card
borderColor: this.props.theme.colors.mascotMessageArrow, style={{
borderColor: props.theme.colors.mascotMessageArrow,
borderWidth: 4, borderWidth: 4,
borderRadius: 10, borderRadius: 10,
}}> }}>
<Card.Title <Card.Title
title={this.props.title} title={props.title}
left={this.props.icon != null ? left={
(props) => <Avatar.Icon props.icon != null
{...props} ? (): React.Node => (
<Avatar.Icon
size={48} size={48}
style={{backgroundColor: "transparent"}} style={{backgroundColor: 'transparent'}}
color={this.props.theme.colors.primary} color={props.theme.colors.primary}
icon={this.props.icon} icon={props.icon}
/> />
)
: null} : null
}
/> />
<Card.Content
<Card.Content style={{ style={{
maxHeight: this.windowHeight / 3 maxHeight: this.windowHeight / 3,
}}> }}>
<ScrollView> <ScrollView>
<Paragraph style={{marginBottom: 10}}> <Paragraph style={{marginBottom: 10}}>{props.message}</Paragraph>
{this.props.message}
</Paragraph>
</ScrollView> </ScrollView>
</Card.Content> </Card.Content>
@ -167,116 +188,124 @@ class MascotPopup extends React.Component<Props, State> {
); );
} }
getMascot() { getMascot(): React.Node {
const {props, state} = this;
return ( return (
<Animatable.View <Animatable.View
useNativeDriver={true} useNativeDriver
animation={this.state.dialogVisible ? "bounceInLeft" : "bounceOutLeft"} animation={state.dialogVisible ? 'bounceInLeft' : 'bounceOutLeft'}
duration={this.state.dialogVisible ? 1500 : 200} duration={state.dialogVisible ? 1500 : 200}>
>
<Mascot <Mascot
style={{width: this.mascotSize}} style={{width: this.mascotSize}}
animated={true} animated
emotion={this.props.emotion} emotion={props.emotion}
/> />
</Animatable.View> </Animatable.View>
); );
} }
getButtons() { getButtons(): React.Node {
const action = this.props.buttons.action; const {props} = this;
const cancel = this.props.buttons.cancel; const {action} = props.buttons;
const {cancel} = props.buttons;
return ( return (
<View style={{ <View
marginLeft: "auto", style={{
marginRight: "auto", marginLeft: 'auto',
marginTop: "auto", marginRight: 'auto',
marginBottom: "auto", marginTop: 'auto',
marginBottom: 'auto',
}}> }}>
{action != null {action != null ? (
? <Button <Button
style={{ style={{
marginLeft: 'auto', marginLeft: 'auto',
marginRight: 'auto', marginRight: 'auto',
marginBottom: 10, marginBottom: 10,
}} }}
mode={"contained"} mode="contained"
icon={action.icon} icon={action.icon}
color={action.color} color={action.color}
onPress={() => this.onDismiss(action.onPress)} onPress={() => {
> this.onDismiss(action.onPress);
}}>
{action.message} {action.message}
</Button> </Button>
: null} ) : null}
{cancel != null {cancel != null ? (
? <Button <Button
style={{ style={{
marginLeft: 'auto', marginLeft: 'auto',
marginRight: 'auto', marginRight: 'auto',
}} }}
mode={"contained"} mode="contained"
icon={cancel.icon} icon={cancel.icon}
color={cancel.color} color={cancel.color}
onPress={() => this.onDismiss(cancel.onPress)} onPress={() => {
> this.onDismiss(cancel.onPress);
}}>
{cancel.message} {cancel.message}
</Button> </Button>
: null} ) : null}
</View> </View>
); );
} }
getBackground() { getBackground(): React.Node {
const {props, state} = this;
return ( return (
<TouchableWithoutFeedback onPress={() => this.onDismiss(this.props.buttons.cancel.onPress)}> <TouchableWithoutFeedback
onPress={() => {
this.onDismiss(props.buttons.cancel.onPress);
}}>
<Animatable.View <Animatable.View
style={{ style={{
position: "absolute", position: 'absolute',
backgroundColor: "rgba(0,0,0,0.7)", backgroundColor: 'rgba(0,0,0,0.7)',
width: "100%", width: '100%',
height: "100%", height: '100%',
}} }}
useNativeDriver={true} useNativeDriver
animation={this.state.dialogVisible ? "fadeIn" : "fadeOut"} animation={state.dialogVisible ? 'fadeIn' : 'fadeOut'}
duration={this.state.dialogVisible ? 300 : 300} duration={state.dialogVisible ? 300 : 300}
/> />
</TouchableWithoutFeedback> </TouchableWithoutFeedback>
); );
} }
onDismiss = (callback?: ()=> void) => { onDismiss = (callback?: () => void) => {
if (this.props.prefKey != null) { const {prefKey} = this.props;
AsyncStorageManager.set(this.props.prefKey, false); if (prefKey != null) {
AsyncStorageManager.set(prefKey, false);
this.setState({dialogVisible: false}); this.setState({dialogVisible: false});
} }
if (callback != null) if (callback != null) callback();
callback(); };
}
render() { render(): React.Node {
if (this.state.shouldRenderDialog) { const {shouldRenderDialog} = this.state;
if (shouldRenderDialog) {
return ( return (
<Portal> <Portal>
{this.getBackground()} {this.getBackground()}
<View style={{ <View
marginTop: "auto", style={{
marginBottom: "auto", marginTop: 'auto',
marginBottom: 'auto',
}}> }}>
<View style={{ <View
style={{
marginTop: -80, marginTop: -80,
width: "100%" width: '100%',
}}> }}>
{this.getMascot()} {this.getMascot()}
{this.getSpeechBubble()} {this.getSpeechBubble()}
</View> </View>
</View> </View>
</Portal> </Portal>
); );
} else }
return null; return null;
} }
} }

View file

@ -1,32 +1,42 @@
// @flow // @flow
import * as React from 'react'; import * as React from 'react';
import {View} from "react-native"; import {View} from 'react-native';
import type {ViewStyle} from "react-native/Libraries/StyleSheet/StyleSheet"; import type {ViewStyle} from 'react-native/Libraries/StyleSheet/StyleSheet';
type Props = { type PropsType = {
style?: ViewStyle, style?: ViewStyle | null,
size: number, size: number,
color: string, color: string,
} };
export default class SpeechArrow extends React.Component<Props> { export default class SpeechArrow extends React.Component<PropsType> {
static defaultProps = {
style: null,
};
render() { shouldComponentUpdate(): boolean {
return false;
}
render(): React.Node {
const {props} = this;
return ( return (
<View style={this.props.style}> <View style={props.style}>
<View style={{ <View
style={{
width: 0, width: 0,
height: 0, height: 0,
borderLeftWidth: 0, borderLeftWidth: 0,
borderRightWidth: this.props.size, borderRightWidth: props.size,
borderBottomWidth: this.props.size, borderBottomWidth: props.size,
borderStyle: 'solid', borderStyle: 'solid',
backgroundColor: 'transparent', backgroundColor: 'transparent',
borderLeftColor: 'transparent', borderLeftColor: 'transparent',
borderRightColor: 'transparent', borderRightColor: 'transparent',
borderBottomColor: this.props.color, borderBottomColor: props.color,
}}/> }}
/>
</View> </View>
); );
} }

View file

@ -1,58 +1,61 @@
import * as React from 'react'; // @flow
import {View} from "react-native";
import {withTheme} from 'react-native-paper';
import {Agenda} from "react-native-calendars";
type Props = { import * as React from 'react';
theme: Object, 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 * Abstraction layer for Agenda component, using custom configuration
*/ */
class CustomAgenda extends React.Component<Props> { class CustomAgenda extends React.Component<PropsType> {
getAgenda(): React.Node {
getAgenda() { const {props} = this;
return <Agenda return (
{...this.props} <Agenda
ref={this.props.onRef} // eslint-disable-next-line react/jsx-props-no-spreading
{...props}
ref={props.onRef}
theme={{ theme={{
backgroundColor: this.props.theme.colors.agendaBackgroundColor, backgroundColor: props.theme.colors.agendaBackgroundColor,
calendarBackground: this.props.theme.colors.background, calendarBackground: props.theme.colors.background,
textSectionTitleColor: this.props.theme.colors.agendaDayTextColor, textSectionTitleColor: props.theme.colors.agendaDayTextColor,
selectedDayBackgroundColor: this.props.theme.colors.primary, selectedDayBackgroundColor: props.theme.colors.primary,
selectedDayTextColor: '#ffffff', selectedDayTextColor: '#ffffff',
todayTextColor: this.props.theme.colors.primary, todayTextColor: props.theme.colors.primary,
dayTextColor: this.props.theme.colors.text, dayTextColor: props.theme.colors.text,
textDisabledColor: this.props.theme.colors.agendaDayTextColor, textDisabledColor: props.theme.colors.agendaDayTextColor,
dotColor: this.props.theme.colors.primary, dotColor: props.theme.colors.primary,
selectedDotColor: '#ffffff', selectedDotColor: '#ffffff',
arrowColor: 'orange', arrowColor: 'orange',
monthTextColor: this.props.theme.colors.primary, monthTextColor: props.theme.colors.primary,
indicatorColor: this.props.theme.colors.primary, indicatorColor: props.theme.colors.primary,
textDayFontWeight: '300', textDayFontWeight: '300',
textMonthFontWeight: 'bold', textMonthFontWeight: 'bold',
textDayHeaderFontWeight: '300', textDayHeaderFontWeight: '300',
textDayFontSize: 16, textDayFontSize: 16,
textMonthFontSize: 16, textMonthFontSize: 16,
textDayHeaderFontSize: 16, textDayHeaderFontSize: 16,
agendaDayTextColor: this.props.theme.colors.agendaDayTextColor, agendaDayTextColor: props.theme.colors.agendaDayTextColor,
agendaDayNumColor: this.props.theme.colors.agendaDayTextColor, agendaDayNumColor: props.theme.colors.agendaDayTextColor,
agendaTodayColor: this.props.theme.colors.primary, agendaTodayColor: props.theme.colors.primary,
agendaKnobColor: this.props.theme.colors.primary, agendaKnobColor: props.theme.colors.primary,
}} }}
/>; />
);
} }
render() { render(): React.Node {
const {props} = this;
// Completely recreate the component on theme change to force theme reload // Completely recreate the component on theme change to force theme reload
if (this.props.theme.dark) if (props.theme.dark)
return ( return <View style={{flex: 1}}>{this.getAgenda()}</View>;
<View style={{flex: 1}}>
{this.getAgenda()}
</View>
);
else
return this.getAgenda(); return this.getAgenda();
} }
} }

View file

@ -1,46 +1,57 @@
/* eslint-disable flowtype/require-parameter-type */
// @flow
import * as React from 'react'; import * as React from 'react';
import {Text, withTheme} from 'react-native-paper'; import {Text, withTheme} from 'react-native-paper';
import HTML from "react-native-render-html"; import HTML from 'react-native-render-html';
import {Linking} from "react-native"; import {Linking} from 'react-native';
import type {CustomThemeType} from '../../managers/ThemeManager';
type Props = { type PropsType = {
theme: Object, theme: CustomThemeType,
html: string, html: string,
} };
/** /**
* Abstraction layer for Agenda component, using custom configuration * Abstraction layer for Agenda component, using custom configuration
*/ */
class CustomHTML extends React.Component<Props> { class CustomHTML extends React.Component<PropsType> {
openWebLink = (event: {...}, link: string) => {
openWebLink = (event, link) => { Linking.openURL(link);
Linking.openURL(link).catch((err) => console.error('Error opening link', err));
}; };
getBasicText = (htmlAttribs, children, convertedCSSStyles, passProps) => { getBasicText = (
htmlAttribs,
children,
convertedCSSStyles,
passProps,
): React.Node => {
// eslint-disable-next-line react/jsx-props-no-spreading
return <Text {...passProps}>{children}</Text>; return <Text {...passProps}>{children}</Text>;
}; };
getListBullet = (htmlAttribs, children, convertedCSSStyles, passProps) => { getListBullet = (): React.Node => {
return ( return <Text>- </Text>;
<Text>- </Text>
);
}; };
render() { render(): React.Node {
const {props} = this;
// Surround description with p to allow text styling if the description is not html // Surround description with p to allow text styling if the description is not html
return <HTML return (
html={"<p>" + this.props.html + "</p>"} <HTML
html={`<p>${props.html}</p>`}
renderers={{ renderers={{
p: this.getBasicText, p: this.getBasicText,
li: this.getBasicText, li: this.getBasicText,
}} }}
listsPrefixesRenderers={{ listsPrefixesRenderers={{
ul: this.getListBullet ul: this.getListBullet,
}} }}
ignoredTags={['img']} ignoredTags={['img']}
ignoredStyles={['color', 'background-color']} ignoredStyles={['color', 'background-color']}
onLinkPress={this.openWebLink}/>; onLinkPress={this.openWebLink}
/>
);
} }
} }

View file

@ -1,27 +1,39 @@
// @flow // @flow
import * as React from 'react'; 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 {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 <HeaderButton
// eslint-disable-next-line react/jsx-props-no-spreading
{...props} {...props}
IconComponent={MaterialCommunityIcons} IconComponent={MaterialCommunityIcons}
iconSize={26} iconSize={26}
color={props.color != null ? props.color : props.theme.colors.text} color={color != null ? color : theme.colors.text}
/>; />
);
};
const MaterialHeaderButtons = (props: Object) => { const MaterialHeaderButtons = (props: {...}): React.Node => {
return ( return (
// $FlowFixMe
<HeaderButtons <HeaderButtons
// eslint-disable-next-line react/jsx-props-no-spreading
{...props} {...props}
HeaderButtonComponent={withTheme(MaterialHeaderButton)} HeaderButtonComponent={withTheme(MaterialHeaderButton)}
/> />
); );
}; };
export default withTheme(MaterialHeaderButtons); export default MaterialHeaderButtons;
export {Item} from 'react-navigation-header-buttons'; export {Item} from 'react-navigation-header-buttons';

View file

@ -1,390 +1,37 @@
// @flow // @flow
import * as React from 'react'; import * as React from 'react';
import {Platform, StatusBar, StyleSheet, View} from "react-native"; import {Platform, StatusBar, StyleSheet, View} from 'react-native';
import type {MaterialCommunityIconsGlyphs} from "react-native-vector-icons/MaterialCommunityIcons"; import type {MaterialCommunityIconsGlyphs} from 'react-native-vector-icons/MaterialCommunityIcons';
import MaterialCommunityIcons from "react-native-vector-icons/MaterialCommunityIcons"; import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons';
import i18n from 'i18n-js'; import i18n from 'i18n-js';
import AppIntroSlider from "react-native-app-intro-slider"; import AppIntroSlider from 'react-native-app-intro-slider';
import Update from "../../constants/Update";
import ThemeManager from "../../managers/ThemeManager";
import LinearGradient from 'react-native-linear-gradient'; import LinearGradient from 'react-native-linear-gradient';
import Mascot, {MASCOT_STYLE} from "../Mascot/Mascot"; import * as Animatable from 'react-native-animatable';
import * as Animatable from "react-native-animatable"; import {Card} from 'react-native-paper';
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 = { type PropsType = {
onDone: Function, onDone: () => void,
isUpdate: boolean, isUpdate: boolean,
isAprilFools: boolean, isAprilFools: boolean,
}; };
type State = { type StateType = {
currentSlide: number, currentSlide: number,
} };
type Slide = { type IntroSlideType = {
key: string, key: string,
title: string, title: string,
text: string, text: string,
view: () => React.Node, view: () => React.Node,
mascotStyle: number, mascotStyle: number,
colors: [string, string] colors: [string, string],
}; };
/**
* Class used to create intro slides
*/
export default class CustomIntroSlider extends React.Component<Props, State> {
state = {
currentSlide: 0,
}
sliderRef: { current: null | AppIntroSlider };
introSlides: Array<Slide>;
updateSlides: Array<Slide>;
aprilFoolsSlides: Array<Slide>;
currentSlides: Array<Slide>;
/**
* 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],
},
);
}
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});
};
onSkip = () => {
this.setStatusBarColor(this.currentSlides[this.currentSlides.length - 1].colors[0]);
if (this.sliderRef.current != null)
this.sliderRef.current.goToSlide(this.currentSlides.length - 1);
}
onDone = () => {
this.setStatusBarColor(ThemeManager.getCurrentTheme().colors.surface);
this.props.onDone();
}
renderNextButton = () => {
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>
)
}
renderDoneButton = () => {
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() {
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}
renderItem={this.getIntroRenderItem}
renderNextButton={this.renderNextButton}
renderDoneButton={this.renderDoneButton}
onDone={this.onDone}
onSlideChange={this.onSlideChange}
onSkip={this.onSkip}
/>
);
}
}
const styles = StyleSheet.create({ const styles = StyleSheet.create({
mainContent: { mainContent: {
paddingBottom: 100, paddingBottom: 100,
@ -409,3 +56,348 @@ const styles = StyleSheet.create({
marginLeft: 'auto', marginLeft: 'auto',
}, },
}); });
/**
* Class used to create intro slides
*/
export default class CustomIntroSlider extends React.Component<
PropsType,
StateType,
> {
sliderRef: {current: null | AppIntroSlider};
introSlides: Array<IntroSlideType>;
updateSlides: Array<IntroSlideType>;
aprilFoolsSlides: Array<IntroSlideType>;
currentSlides: Array<IntroSlideType>;
/**
* Generates intro slides
*/
constructor() {
super();
this.state = {
currentSlide: 0,
};
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],
});
}
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={{
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 = (): 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>
);
};
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>
);
};
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}
/>
);
}
}

View file

@ -2,9 +2,10 @@
import * as React from 'react'; import * as React from 'react';
import {withTheme} from 'react-native-paper'; import {withTheme} from 'react-native-paper';
import {Modalize} from "react-native-modalize"; import {Modalize} from 'react-native-modalize';
import {View} from "react-native-animatable"; import {View} from 'react-native-animatable';
import CustomTabBar from "../Tabbar/CustomTabBar"; import CustomTabBar from '../Tabbar/CustomTabBar';
import type {CustomThemeType} from '../../managers/ThemeManager';
/** /**
* Abstraction layer for Modalize component, using custom configuration * 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. * @param props Props to pass to the element. Must specify an onRef prop to get an Modalize ref.
* @return {*} * @return {*}
*/ */
function CustomModal(props) { function CustomModal(props: {
const {colors} = props.theme; theme: CustomThemeType,
onRef: (re: Modalize) => void,
children?: React.Node,
}): React.Node {
const {theme, onRef, children} = props;
return ( return (
<Modalize <Modalize
ref={props.onRef} ref={onRef}
adjustToContentHeight adjustToContentHeight
handlePosition={'inside'} handlePosition="inside"
modalStyle={{backgroundColor: colors.card}} modalStyle={{backgroundColor: theme.colors.card}}
handleStyle={{backgroundColor: colors.primary}} handleStyle={{backgroundColor: theme.colors.primary}}>
> <View
<View style={{ style={{
paddingBottom: CustomTabBar.TAB_BAR_HEIGHT paddingBottom: CustomTabBar.TAB_BAR_HEIGHT,
}}> }}>
{props.children} {children}
</View> </View>
</Modalize> </Modalize>
); );
} }
export default withTheme(CustomModal); CustomModal.defaultProps = {children: null};
export default withTheme(CustomModal);

View file

@ -2,19 +2,19 @@
import * as React from 'react'; import * as React from 'react';
import {Text, withTheme} from 'react-native-paper'; import {Text, withTheme} from 'react-native-paper';
import {View} from "react-native-animatable"; import {View} from 'react-native-animatable';
import type {CustomTheme} from "../../managers/ThemeManager"; import Slider, {SliderProps} from '@react-native-community/slider';
import Slider, {SliderProps} from "@react-native-community/slider"; import type {CustomThemeType} from '../../managers/ThemeManager';
type Props = { type PropsType = {
theme: CustomTheme, theme: CustomThemeType,
valueSuffix: string, valueSuffix?: string,
...SliderProps ...SliderProps,
} };
type State = { type StateType = {
currentValue: number, currentValue: number,
} };
/** /**
* Abstraction layer for Modalize component, using custom configuration * 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. * @param props Props to pass to the element. Must specify an onRef prop to get an Modalize ref.
* @return {*} * @return {*}
*/ */
class CustomSlider extends React.Component<Props, State> { class CustomSlider extends React.Component<PropsType, StateType> {
static defaultProps = { static defaultProps = {
valueSuffix: "", valueSuffix: '',
} };
state = { constructor(props: PropsType) {
currentValue: this.props.value, super(props);
this.state = {
currentValue: props.value,
};
} }
onValueChange = (value: number) => { onValueChange = (value: number) => {
const {props} = this;
this.setState({currentValue: value}); this.setState({currentValue: value});
if (this.props.onValueChange != null) if (props.onValueChange != null) props.onValueChange(value);
this.props.onValueChange(value); };
}
render() { render(): React.Node {
const {props, state} = this;
return ( return (
<View style={{flex: 1, flexDirection: 'row'}}> <View style={{flex: 1, flexDirection: 'row'}}>
<Text style={{marginHorizontal: 10, marginTop: 'auto', marginBottom: 'auto'}}> <Text
{this.state.currentValue}min style={{
marginHorizontal: 10,
marginTop: 'auto',
marginBottom: 'auto',
}}>
{state.currentValue}min
</Text> </Text>
<Slider <Slider
{...this.props} // eslint-disable-next-line react/jsx-props-no-spreading
{...props}
onValueChange={this.onValueChange} onValueChange={this.onValueChange}
/> />
</View> </View>
); );
} }
} }
export default withTheme(CustomSlider); export default withTheme(CustomSlider);

View file

@ -3,6 +3,7 @@
import * as React from 'react'; import * as React from 'react';
import {View} from 'react-native'; import {View} from 'react-native';
import {ActivityIndicator, withTheme} from 'react-native-paper'; import {ActivityIndicator, withTheme} from 'react-native-paper';
import type {CustomThemeType} from '../../managers/ThemeManager';
/** /**
* Component used to display a header button * Component used to display a header button
@ -10,26 +11,27 @@ import {ActivityIndicator, withTheme} from 'react-native-paper';
* @param props Props to pass to the component * @param props Props to pass to the component
* @return {*} * @return {*}
*/ */
function BasicLoadingScreen(props) { function BasicLoadingScreen(props: {
const {colors} = props.theme; theme: CustomThemeType,
let position = undefined; isAbsolute: boolean,
if (props.isAbsolute !== undefined && props.isAbsolute) }): React.Node {
position = 'absolute'; const {theme, isAbsolute} = props;
const {colors} = theme;
let position;
if (isAbsolute != null && isAbsolute) position = 'absolute';
return ( return (
<View style={{ <View
style={{
backgroundColor: colors.background, backgroundColor: colors.background,
position: position, position,
top: 0, top: 0,
right: 0, right: 0,
width: '100%', width: '100%',
height: '100%', height: '100%',
justifyContent: 'center', justifyContent: 'center',
}}> }}>
<ActivityIndicator <ActivityIndicator animating size="large" color={colors.primary} />
animating={true}
size={'large'}
color={colors.primary}/>
</View> </View>
); );
} }

View file

@ -2,167 +2,24 @@
import * as React from 'react'; import * as React from 'react';
import {Button, Subheading, withTheme} from 'react-native-paper'; import {Button, Subheading, withTheme} from 'react-native-paper';
import {StyleSheet, View} from "react-native"; import {StyleSheet, View} from 'react-native';
import MaterialCommunityIcons from "react-native-vector-icons/MaterialCommunityIcons"; import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons';
import i18n from 'i18n-js'; import i18n from 'i18n-js';
import {ERROR_TYPE} from "../../utils/WebData";
import * as Animatable from 'react-native-animatable'; 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 = { type PropsType = {
navigation: Object, navigation: StackNavigationProp,
route: Object, theme: CustomThemeType,
errorCode: number, route: {name: string},
onRefresh: Function, onRefresh?: () => void,
icon: string, errorCode?: number,
message: string, icon?: string,
showRetryButton: boolean, 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>
);
}
}
const styles = StyleSheet.create({ const styles = StyleSheet.create({
outer: { outer: {
@ -175,18 +32,162 @@ const styles = StyleSheet.create({
iconContainer: { iconContainer: {
marginLeft: 'auto', marginLeft: 'auto',
marginRight: 'auto', marginRight: 'auto',
marginBottom: 20 marginBottom: 20,
}, },
subheading: { subheading: {
textAlign: 'center', textAlign: 'center',
paddingHorizontal: 20 paddingHorizontal: 20,
}, },
button: { button: {
marginTop: 10, marginTop: 10,
marginLeft: 'auto', marginLeft: 'auto',
marginRight: '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); export default withTheme(ErrorView);

View file

@ -9,7 +9,7 @@ import {Collapsible} from 'react-navigation-collapsible';
import {StackNavigationProp} from '@react-navigation/stack'; import {StackNavigationProp} from '@react-navigation/stack';
import ErrorView from './ErrorView'; import ErrorView from './ErrorView';
import BasicLoadingScreen from './BasicLoadingScreen'; import BasicLoadingScreen from './BasicLoadingScreen';
import {withCollapsible} from '../../utils/withCollapsible'; import withCollapsible from '../../utils/withCollapsible';
import CustomTabBar from '../Tabbar/CustomTabBar'; import CustomTabBar from '../Tabbar/CustomTabBar';
import {ERROR_TYPE, readData} from '../../utils/WebData'; import {ERROR_TYPE, readData} from '../../utils/WebData';
import CollapsibleSectionList from '../Collapsible/CollapsibleSectionList'; import CollapsibleSectionList from '../Collapsible/CollapsibleSectionList';

View file

@ -1,47 +1,50 @@
// @flow // @flow
import * as React from 'react'; import * as React from 'react';
import WebView from "react-native-webview"; import WebView from 'react-native-webview';
import BasicLoadingScreen from "./BasicLoadingScreen"; import {
import ErrorView from "./ErrorView"; Divider,
import {ERROR_TYPE} from "../../utils/WebData"; HiddenItem,
import MaterialHeaderButtons, {Item} from '../Overrides/CustomHeaderButton'; OverflowMenu,
import {Divider, HiddenItem, OverflowMenu} from "react-navigation-header-buttons"; } from 'react-navigation-header-buttons';
import i18n from 'i18n-js'; import i18n from 'i18n-js';
import {Animated, BackHandler, Linking} from "react-native"; import {Animated, BackHandler, Linking} from 'react-native';
import {withCollapsible} from "../../utils/withCollapsible"; import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons';
import MaterialCommunityIcons from "react-native-vector-icons/MaterialCommunityIcons"; import {withTheme} from 'react-native-paper';
import {withTheme} from "react-native-paper"; import {StackNavigationProp} from '@react-navigation/stack';
import type {CustomTheme} from "../../managers/ThemeManager"; import {Collapsible} from 'react-navigation-collapsible';
import {StackNavigationProp} from "@react-navigation/stack"; import type {CustomThemeType} from '../../managers/ThemeManager';
import {Collapsible} from "react-navigation-collapsible"; 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 = { type PropsType = {
navigation: StackNavigationProp, navigation: StackNavigationProp,
theme: CustomTheme, theme: CustomThemeType,
url: string, url: string,
customJS: string,
customPaddingFunction: null | (padding: number) => string,
collapsibleStack: Collapsible, collapsibleStack: Collapsible,
onMessage: Function, onMessage: (event: {nativeEvent: {data: string}}) => void,
onScroll: Function, onScroll: (event: SyntheticEvent<EventTarget>) => void,
showAdvancedControls: boolean, customJS?: string,
} customPaddingFunction?: null | ((padding: number) => string),
showAdvancedControls?: boolean,
};
const AnimatedWebView = Animated.createAnimatedComponent(WebView); const AnimatedWebView = Animated.createAnimatedComponent(WebView);
/** /**
* Class defining a webview screen. * Class defining a webview screen.
*/ */
class WebViewScreen extends React.PureComponent<Props> { class WebViewScreen extends React.PureComponent<PropsType> {
static defaultProps = { static defaultProps = {
customJS: '', customJS: '',
showAdvancedControls: true, showAdvancedControls: true,
customPaddingFunction: null, customPaddingFunction: null,
}; };
webviewRef: { current: null | WebView }; webviewRef: {current: null | WebView};
canGoBack: boolean; canGoBack: boolean;
@ -55,27 +58,24 @@ class WebViewScreen extends React.PureComponent<Props> {
* Creates header buttons and listens to events after mounting * Creates header buttons and listens to events after mounting
*/ */
componentDidMount() { componentDidMount() {
this.props.navigation.setOptions({ const {props} = this;
headerRight: this.props.showAdvancedControls props.navigation.setOptions({
headerRight: props.showAdvancedControls
? this.getAdvancedButtons ? this.getAdvancedButtons
: this.getBasicButton, : this.getBasicButton,
}); });
this.props.navigation.addListener( props.navigation.addListener('focus', () => {
'focus',
() =>
BackHandler.addEventListener( BackHandler.addEventListener(
'hardwareBackPress', 'hardwareBackPress',
this.onBackButtonPressAndroid this.onBackButtonPressAndroid,
)
); );
this.props.navigation.addListener( });
'blur', props.navigation.addListener('blur', () => {
() =>
BackHandler.removeEventListener( BackHandler.removeEventListener(
'hardwareBackPress', 'hardwareBackPress',
this.onBackButtonPressAndroid this.onBackButtonPressAndroid,
)
); );
});
} }
/** /**
@ -83,7 +83,7 @@ class WebViewScreen extends React.PureComponent<Props> {
* *
* @returns {boolean} * @returns {boolean}
*/ */
onBackButtonPressAndroid = () => { onBackButtonPressAndroid = (): boolean => {
if (this.canGoBack) { if (this.canGoBack) {
this.onGoBackClicked(); this.onGoBackClicked();
return true; return true;
@ -96,17 +96,19 @@ class WebViewScreen extends React.PureComponent<Props> {
* *
* @return {*} * @return {*}
*/ */
getBasicButton = () => { getBasicButton = (): React.Node => {
return ( return (
<MaterialHeaderButtons> <MaterialHeaderButtons>
<Item <Item
title="refresh" title="refresh"
iconName="refresh" iconName="refresh"
onPress={this.onRefreshClicked}/> onPress={this.onRefreshClicked}
/>
<Item <Item
title={i18n.t("general.openInBrowser")} title={i18n.t('general.openInBrowser')}
iconName="open-in-new" iconName="open-in-new"
onPress={this.onOpenClicked}/> onPress={this.onOpenClicked}
/>
</MaterialHeaderButtons> </MaterialHeaderButtons>
); );
}; };
@ -117,7 +119,8 @@ class WebViewScreen extends React.PureComponent<Props> {
* *
* @returns {*} * @returns {*}
*/ */
getAdvancedButtons = () => { getAdvancedButtons = (): React.Node => {
const {props} = this;
return ( return (
<MaterialHeaderButtons> <MaterialHeaderButtons>
<Item <Item
@ -131,40 +134,74 @@ class WebViewScreen extends React.PureComponent<Props> {
<MaterialCommunityIcons <MaterialCommunityIcons
name="dots-vertical" name="dots-vertical"
size={26} size={26}
color={this.props.theme.colors.text} color={props.theme.colors.text}
/>} />
> }>
<HiddenItem <HiddenItem
title={i18n.t("general.goBack")} title={i18n.t('general.goBack')}
onPress={this.onGoBackClicked}/> onPress={this.onGoBackClicked}
/>
<HiddenItem <HiddenItem
title={i18n.t("general.goForward")} title={i18n.t('general.goForward')}
onPress={this.onGoForwardClicked}/> onPress={this.onGoForwardClicked}
<Divider/> />
<Divider />
<HiddenItem <HiddenItem
title={i18n.t("general.openInBrowser")} title={i18n.t('general.openInBrowser')}
onPress={this.onOpenClicked}/> onPress={this.onOpenClicked}
/>
</OverflowMenu> </OverflowMenu>
</MaterialHeaderButtons> </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. * Callback to use when refresh button is clicked. Reloads the webview.
*/ */
onRefreshClicked = () => { onRefreshClicked = () => {
if (this.webviewRef.current != null) if (this.webviewRef.current != null) this.webviewRef.current.reload();
this.webviewRef.current.reload(); };
}
onGoBackClicked = () => { onGoBackClicked = () => {
if (this.webviewRef.current != null) if (this.webviewRef.current != null) this.webviewRef.current.goBack();
this.webviewRef.current.goBack(); };
}
onGoForwardClicked = () => { onGoForwardClicked = () => {
if (this.webviewRef.current != null) if (this.webviewRef.current != null) this.webviewRef.current.goForward();
this.webviewRef.current.goForward(); };
}
onOpenClicked = () => Linking.openURL(this.props.url); 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 * Injects the given javascript string into the web page
@ -174,55 +211,32 @@ class WebViewScreen extends React.PureComponent<Props> {
injectJavaScript = (script: string) => { injectJavaScript = (script: string) => {
if (this.webviewRef.current != null) if (this.webviewRef.current != null)
this.webviewRef.current.injectJavaScript(script); this.webviewRef.current.injectJavaScript(script);
} };
/** render(): React.Node {
* Gets the loading indicator const {props} = this;
* const {containerPaddingTop, onScrollWithListener} = props.collapsibleStack;
* @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 ( return (
<AnimatedWebView <AnimatedWebView
ref={this.webviewRef} ref={this.webviewRef}
source={{uri: this.props.url}} source={{uri: props.url}}
startInLoadingState={true} startInLoadingState
injectedJavaScript={this.props.customJS} injectedJavaScript={props.customJS}
javaScriptEnabled={true} javaScriptEnabled
renderLoading={this.getRenderLoading} renderLoading={this.getRenderLoading}
renderError={() => <ErrorView renderError={(): React.Node => (
<ErrorView
errorCode={ERROR_TYPE.CONNECTION_ERROR} errorCode={ERROR_TYPE.CONNECTION_ERROR}
onRefresh={this.onRefreshClicked} onRefresh={this.onRefreshClicked}
/>} />
onNavigationStateChange={navState => { )}
onNavigationStateChange={(navState: {canGoBack: boolean}) => {
this.canGoBack = navState.canGoBack; this.canGoBack = navState.canGoBack;
}} }}
onMessage={this.props.onMessage} onMessage={props.onMessage}
onLoad={() => this.injectJavaScript(this.getJavascriptPadding(containerPaddingTop))} onLoad={() => {
this.injectJavaScript(this.getJavascriptPadding(containerPaddingTop));
}}
// Animations // Animations
onScroll={onScrollWithListener(this.onScroll)} onScroll={onScrollWithListener(this.onScroll)}
/> />

View file

@ -2,23 +2,44 @@
import * as React from 'react'; import * as React from 'react';
import {withTheme} from 'react-native-paper'; import {withTheme} from 'react-native-paper';
import TabIcon from "./TabIcon"; import Animated from 'react-native-reanimated';
import TabHomeIcon from "./TabHomeIcon"; import {Collapsible} from 'react-navigation-collapsible';
import {Animated} from 'react-native'; import {StackNavigationProp} from '@react-navigation/stack';
import {Collapsible} from "react-navigation-collapsible"; import TabIcon from './TabIcon';
import TabHomeIcon from './TabHomeIcon';
import type {CustomThemeType} from '../../managers/ThemeManager';
type Props = { type RouteType = {
state: Object, name: string,
descriptors: Object, key: string,
navigation: Object, params: {collapsible: Collapsible},
theme: Object, state: {
collapsibleStack: Object, index: number,
} routes: Array<RouteType>,
},
};
type State = { type PropsType = {
translateY: AnimatedValue, state: {
barSynced: boolean, index: number,
} routes: Array<RouteType>,
},
descriptors: {
[key: string]: {
options: {
tabBarLabel: string,
title: string,
},
},
},
navigation: StackNavigationProp,
theme: CustomThemeType,
};
type StateType = {
// eslint-disable-next-line flowtype/no-weak-types
translateY: any,
};
const TAB_ICONS = { const TAB_ICONS = {
proxiwash: 'tshirt-crew', proxiwash: 'tshirt-crew',
@ -27,29 +48,15 @@ const TAB_ICONS = {
planex: 'clock', planex: 'clock',
}; };
class CustomTabBar extends React.Component<Props, State> { class CustomTabBar extends React.Component<PropsType, StateType> {
static TAB_BAR_HEIGHT = 48; static TAB_BAR_HEIGHT = 48;
state = { constructor() {
super();
this.state = {
translateY: new Animated.Value(0), translateY: new Animated.Value(0),
}
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
});
}
}
}; };
}
/** /**
* Navigates to the given route if it is different from the current one * Navigates to the given route if it is different from the current one
@ -58,14 +65,15 @@ class CustomTabBar extends React.Component<Props, State> {
* @param currentIndex The current route index * @param currentIndex The current route index
* @param destIndex The destination route index * @param destIndex The destination route index
*/ */
onItemPress(route: Object, currentIndex: number, destIndex: number) { onItemPress(route: RouteType, currentIndex: number, destIndex: number) {
const event = this.props.navigation.emit({ const {navigation} = this.props;
const event = navigation.emit({
type: 'tabPress', type: 'tabPress',
target: route.key, target: route.key,
canPreventDefault: true, canPreventDefault: true,
}); });
if (currentIndex !== destIndex && !event.defaultPrevented) if (currentIndex !== destIndex && !event.defaultPrevented)
this.props.navigation.navigate(route.name); navigation.navigate(route.name);
} }
/** /**
@ -73,16 +81,25 @@ class CustomTabBar extends React.Component<Props, State> {
* *
* @param route * @param route
*/ */
onItemLongPress(route: Object) { onItemLongPress(route: RouteType) {
const event = this.props.navigation.emit({ const {navigation} = this.props;
const event = navigation.emit({
type: 'tabLongPress', type: 'tabLongPress',
target: route.key, target: route.key,
canPreventDefault: true, canPreventDefault: true,
}); });
if (route.name === "home" && !event.defaultPrevented) if (route.name === 'home' && !event.defaultPrevented)
this.props.navigation.navigate('game-start'); 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 * Gets an icon for the given route if it is not the home one as it uses a custom button
* *
@ -90,22 +107,13 @@ class CustomTabBar extends React.Component<Props, State> {
* @param focused * @param focused
* @returns {null} * @returns {null}
*/ */
tabBarIcon = (route, focused) => { getTabBarIcon = (route: RouteType, focused: boolean): React.Node => {
let icon = TAB_ICONS[route.name]; let icon = TAB_ICONS[route.name];
icon = focused ? icon : icon + ('-outline'); icon = focused ? icon : `${icon}-outline`;
if (route.name !== "home") if (route.name !== 'home') return icon;
return icon;
else
return null; 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. * Gets a tab icon render.
* If the given route is focused, it syncs the tab bar and header bar animations together * If the given route is focused, it syncs the tab bar and header bar animations together
@ -114,49 +122,79 @@ class CustomTabBar extends React.Component<Props, State> {
* @param index The index of the current route * @param index The index of the current route
* @returns {*} * @returns {*}
*/ */
renderIcon = (route, index) => { getRenderIcon = (route: RouteType, index: number): React.Node => {
const state = this.props.state; const {props} = this;
const {options} = this.props.descriptors[route.key]; const {state} = props;
const label = const {options} = props.descriptors[route.key];
options.tabBarLabel != null let label;
? options.tabBarLabel if (options.tabBarLabel != null) label = options.tabBarLabel;
: options.title != null else if (options.title != null) label = options.title;
? options.title else label = route.name;
: route.name;
const onPress = () => this.onItemPress(route, state.index, index); const onPress = () => {
const onLongPress = () => this.onItemLongPress(route); this.onItemPress(route, state.index, index);
};
const onLongPress = () => {
this.onItemLongPress(route);
};
const isFocused = state.index === index; const isFocused = state.index === index;
const color = isFocused ? this.props.theme.colors.primary : this.props.theme.colors.tabIcon; const color = isFocused
if (route.name !== "home") { ? props.theme.colors.primary
return <TabIcon : props.theme.colors.tabIcon;
if (route.name !== 'home') {
return (
<TabIcon
onPress={onPress} onPress={onPress}
onLongPress={onLongPress} onLongPress={onLongPress}
icon={this.tabBarIcon(route, isFocused)} icon={this.getTabBarIcon(route, isFocused)}
color={color} color={color}
label={label} label={label}
focused={isFocused} focused={isFocused}
extraData={state.index > index} extraData={state.index > index}
key={route.key} key={route.key}
/> />
} else );
return <TabHomeIcon }
return (
<TabHomeIcon
onPress={onPress} onPress={onPress}
onLongPress={onLongPress} onLongPress={onLongPress}
focused={isFocused} focused={isFocused}
key={route.key} key={route.key}
tabBarHeight={CustomTabBar.TAB_BAR_HEIGHT} tabBarHeight={CustomTabBar.TAB_BAR_HEIGHT}
/> />
);
}; };
getIcons() { getIcons(): React.Node {
return this.props.state.routes.map(this.renderIcon); const {props} = this;
return props.state.routes.map(this.getRenderIcon);
} }
render() { syncTabBar = (route: RouteType, index: number) => {
this.props.navigation.addListener('state', this.onRouteChange); 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
});
}
}
};
render(): React.Node {
const {props, state} = this;
props.navigation.addListener('state', this.onRouteChange);
const icons = this.getIcons(); const icons = this.getIcons();
// $FlowFixMe
return ( return (
<Animated.View <Animated.View
useNativeDriver useNativeDriver
@ -167,10 +205,9 @@ class CustomTabBar extends React.Component<Props, State> {
position: 'absolute', position: 'absolute',
bottom: 0, bottom: 0,
left: 0, left: 0,
backgroundColor: this.props.theme.colors.surface, backgroundColor: props.theme.colors.surface,
transform: [{translateY: this.state.translateY}], transform: [{translateY: state.translateY}],
}} }}>
>
{icons} {icons}
</Animated.View> </Animated.View>
); );

View file

@ -1,70 +1,95 @@
// @flow // @flow
import * as React from 'react'; 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 {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 = { type PropsType = {
focused: boolean, focused: boolean,
onPress: Function, onPress: () => void,
onLongPress: Function, onLongPress: () => void,
theme: Object, theme: CustomThemeType,
tabBarHeight: number, tabBarHeight: number,
} };
const AnimatedFAB = Animatable.createAnimatableComponent(FAB); const AnimatedFAB = Animatable.createAnimatableComponent(FAB);
/** /**
* Abstraction layer for Agenda component, using custom configuration * Abstraction layer for Agenda component, using custom configuration
*/ */
class TabHomeIcon extends React.Component<Props> { class TabHomeIcon extends React.Component<PropsType> {
constructor(props: PropsType) {
focusedIcon = require('../../../assets/tab-icon.png');
unFocusedIcon = require('../../../assets/tab-icon-outline.png');
constructor(props) {
super(props); super(props);
Animatable.initializeRegistryWithDefinitions({ Animatable.initializeRegistryWithDefinitions({
fabFocusIn: { fabFocusIn: {
"0": { '0': {
scale: 1, translateY: 0 scale: 1,
translateY: 0,
}, },
"0.9": { '0.9': {
scale: 1.2, translateY: -9 scale: 1.2,
translateY: -9,
}, },
"1": { '1': {
scale: 1.1, translateY: -7 scale: 1.1,
translateY: -7,
}, },
}, },
fabFocusOut: { fabFocusOut: {
"0": { '0': {
scale: 1.1, translateY: -6 scale: 1.1,
translateY: -6,
},
'1': {
scale: 1,
translateY: 0,
}, },
"1": {
scale: 1, translateY: 0
}, },
}
}); });
} }
iconRender = ({size, color}) => shouldComponentUpdate(nextProps: PropsType): boolean {
this.props.focused const {focused} = this.props;
? <Image return nextProps.focused !== focused;
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 { getIconRender = ({
const props = this.props; 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 ( return (
<View <View
style={{ style={{
@ -74,33 +99,35 @@ class TabHomeIcon extends React.Component<Props> {
<TouchableRipple <TouchableRipple
onPress={props.onPress} onPress={props.onPress}
onLongPress={props.onLongPress} onLongPress={props.onLongPress}
borderless={true} borderless
rippleColor={Platform.OS === 'android' ? this.props.theme.colors.primary : 'transparent'} rippleColor={
Platform.OS === 'android'
? props.theme.colors.primary
: 'transparent'
}
style={{ style={{
position: 'absolute', position: 'absolute',
bottom: 0, bottom: 0,
left: 0, left: 0,
width: '100%', width: '100%',
height: this.props.tabBarHeight + 30, height: props.tabBarHeight + 30,
marginBottom: -15, marginBottom: -15,
}} }}>
>
<AnimatedFAB <AnimatedFAB
duration={200} duration={200}
easing={"ease-out"} easing="ease-out"
animation={props.focused ? "fabFocusIn" : "fabFocusOut"} animation={props.focused ? 'fabFocusIn' : 'fabFocusOut'}
icon={this.iconRender} icon={this.getIconRender}
style={{ style={{
marginTop: 15, marginTop: 15,
marginLeft: 'auto', marginLeft: 'auto',
marginRight: 'auto' marginRight: 'auto',
}}/> }}
/>
</TouchableRipple> </TouchableRipple>
</View> </View>
); );
} }
} }
export default withTheme(TabHomeIcon); export default withTheme(TabHomeIcon);

View file

@ -1,53 +1,57 @@
// @flow // @flow
import * as React from 'react'; import * as React from 'react';
import {View} from "react-native"; import {View} from 'react-native';
import {TouchableRipple, withTheme} from 'react-native-paper'; import {TouchableRipple, withTheme} from 'react-native-paper';
import type {MaterialCommunityIconsGlyphs} from "react-native-vector-icons/MaterialCommunityIcons"; import type {MaterialCommunityIconsGlyphs} from 'react-native-vector-icons/MaterialCommunityIcons';
import MaterialCommunityIcons from "react-native-vector-icons/MaterialCommunityIcons"; import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons';
import * as Animatable from "react-native-animatable"; import * as Animatable from 'react-native-animatable';
import type {CustomThemeType} from '../../managers/ThemeManager';
type Props = { type PropsType = {
focused: boolean, focused: boolean,
color: string, color: string,
label: string, label: string,
icon: MaterialCommunityIconsGlyphs, icon: MaterialCommunityIconsGlyphs,
onPress: Function, onPress: () => void,
onLongPress: Function, onLongPress: () => void,
theme: Object, theme: CustomThemeType,
extraData: any, extraData: null | boolean | number | string,
} };
/** /**
* Abstraction layer for Agenda component, using custom configuration * 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) { constructor(props: PropsType) {
super(props); super(props);
Animatable.initializeRegistryWithDefinitions({ Animatable.initializeRegistryWithDefinitions({
focusIn: { focusIn: {
"0": { '0': {
scale: 1, translateY: 0 scale: 1,
translateY: 0,
}, },
"0.9": { '0.9': {
scale: 1.3, translateY: 7 scale: 1.3,
translateY: 7,
}, },
"1": { '1': {
scale: 1.2, translateY: 6 scale: 1.2,
translateY: 6,
}, },
}, },
focusOut: { focusOut: {
"0": { '0': {
scale: 1.2, translateY: 6 scale: 1.2,
translateY: 6,
},
'1': {
scale: 1,
translateY: 0,
}, },
"1": {
scale: 1, translateY: 0
}, },
}
}); });
this.firstRender = true; this.firstRender = true;
} }
@ -56,32 +60,33 @@ class TabIcon extends React.Component<Props> {
this.firstRender = false; this.firstRender = false;
} }
shouldComponentUpdate(nextProps: Props): boolean { shouldComponentUpdate(nextProps: PropsType): boolean {
return (nextProps.focused !== this.props.focused) const {props} = this;
|| (nextProps.theme.dark !== this.props.theme.dark) return (
|| (nextProps.extraData !== this.props.extraData); nextProps.focused !== props.focused ||
nextProps.theme.dark !== props.theme.dark ||
nextProps.extraData !== props.extraData
);
} }
render(): React$Node { render(): React.Node {
const props = this.props; const {props} = this;
return ( return (
<TouchableRipple <TouchableRipple
onPress={props.onPress} onPress={props.onPress}
onLongPress={props.onLongPress} onLongPress={props.onLongPress}
borderless={true} borderless
rippleColor={this.props.theme.colors.primary} rippleColor={props.theme.colors.primary}
style={{ style={{
flex: 1, flex: 1,
justifyContent: 'center', justifyContent: 'center',
}} }}>
>
<View> <View>
<Animatable.View <Animatable.View
duration={200} duration={200}
easing={"ease-out"} easing="ease-out"
animation={props.focused ? "focusIn" : "focusOut"} animation={props.focused ? 'focusIn' : 'focusOut'}
useNativeDriver useNativeDriver>
>
<MaterialCommunityIcons <MaterialCommunityIcons
name={props.icon} name={props.icon}
color={props.color} color={props.color}
@ -93,16 +98,14 @@ class TabIcon extends React.Component<Props> {
/> />
</Animatable.View> </Animatable.View>
<Animatable.Text <Animatable.Text
animation={props.focused ? "fadeOutDown" : "fadeIn"} animation={props.focused ? 'fadeOutDown' : 'fadeIn'}
useNativeDriver useNativeDriver
style={{ style={{
color: props.color, color: props.color,
marginLeft: 'auto', marginLeft: 'auto',
marginRight: 'auto', marginRight: 'auto',
fontSize: 10, fontSize: 10,
}} }}>
>
{props.label} {props.label}
</Animatable.Text> </Animatable.Text>
</View> </View>

View file

@ -1,13 +1,13 @@
export default { export default {
websites: { websites: {
AMICALE: "https://www.amicale-insat.fr/", AMICALE: 'https://www.amicale-insat.fr/',
AVAILABLE_ROOMS: "http://planex.insa-toulouse.fr/salles.php", AVAILABLE_ROOMS: 'http://planex.insa-toulouse.fr/salles.php',
BIB: "https://bibbox.insa-toulouse.fr/", BIB: 'https://bibbox.insa-toulouse.fr/',
BLUEMIND: "https://etud-mel.insa-toulouse.fr/webmail/", BLUEMIND: 'https://etud-mel.insa-toulouse.fr/webmail/',
ELUS_ETUDIANTS: "https://etud.insa-toulouse.fr/~eeinsat/", ELUS_ETUDIANTS: 'https://etud.insa-toulouse.fr/~eeinsat/',
ENT: "https://ent.insa-toulouse.fr/", ENT: 'https://ent.insa-toulouse.fr/',
INSA_ACCOUNT: "https://moncompte.insa-toulouse.fr/", INSA_ACCOUNT: 'https://moncompte.insa-toulouse.fr/',
TUTOR_INSA: "https://www.etud.insa-toulouse.fr/~tutorinsa/", TUTOR_INSA: 'https://www.etud.insa-toulouse.fr/~tutorinsa/',
WIKETUD: "https://wiki.etud.insa-toulouse.fr/", WIKETUD: 'https://wiki.etud.insa-toulouse.fr/',
}, },
} };

View file

@ -1,12 +1,12 @@
export default { export default {
machineStates: { machineStates: {
"AVAILABLE": 0, AVAILABLE: 0,
"RUNNING": 1, RUNNING: 1,
"RUNNING_NOT_STARTED": 2, RUNNING_NOT_STARTED: 2,
"FINISHED": 3, FINISHED: 3,
"UNAVAILABLE": 4, UNAVAILABLE: 4,
"ERROR": 5, ERROR: 5,
"UNKNOWN": 6, UNKNOWN: 6,
}, },
stateIcons: { stateIcons: {
0: 'radiobox-blank', 0: 'radiobox-blank',
@ -16,5 +16,5 @@ export default {
4: 'alert-octagram-outline', 4: 'alert-octagram-outline',
5: 'alert', 5: 'alert',
6: 'help-circle-outline', 6: 'help-circle-outline',
} },
}; };

View file

@ -1,6 +1,6 @@
// @flow // @flow
import i18n from "i18n-js"; import i18n from 'i18n-js';
/** /**
* Singleton used to manage update slides. * Singleton used to manage update slides.
@ -14,28 +14,26 @@ import i18n from "i18n-js";
* </ul> * </ul>
*/ */
export default class Update { export default class Update {
// Increment the number to show the update slide // Increment the number to show the update slide
static number = 6; static number = 6;
// Change the number of slides to display // Change the number of slides to display
static slidesNumber = 4; static slidesNumber = 4;
// Change the icons to be displayed on the update slide // Change the icons to be displayed on the update slide
static iconList = [ static iconList = ['star', 'clock', 'qrcode-scan', 'account'];
'star',
'clock',
'qrcode-scan',
'account',
];
static colorsList = [ static colorsList = [
['#e01928', '#be1522'], ['#e01928', '#be1522'],
['#7c33ec', '#5e11d1'], ['#7c33ec', '#5e11d1'],
['#337aec', '#114ed1'], ['#337aec', '#114ed1'],
['#e01928', '#be1522'], ['#e01928', '#be1522'],
] ];
static instance: Update | null = null; static instance: Update | null = null;
titleList: Array<string>; titleList: Array<string>;
descriptionList: Array<string>; descriptionList: Array<string>;
/** /**
@ -44,9 +42,9 @@ export default class Update {
constructor() { constructor() {
this.titleList = []; this.titleList = [];
this.descriptionList = []; this.descriptionList = [];
for (let i = 0; i < Update.slidesNumber; i++) { for (let i = 0; i < Update.slidesNumber; i += 1) {
this.titleList.push(i18n.t('intro.updateSlide' + i + '.title')) this.titleList.push(i18n.t(`intro.updateSlide${i}.title`));
this.descriptionList.push(i18n.t('intro.updateSlide' + i + '.text')) this.descriptionList.push(i18n.t(`intro.updateSlide${i}.text`));
} }
} }
@ -56,9 +54,7 @@ export default class Update {
* @returns {Update} * @returns {Update}
*/ */
static getInstance(): Update { static getInstance(): Update {
return Update.instance === null ? if (Update.instance == null) Update.instance = new Update();
Update.instance = new Update() : return Update.instance;
Update.instance;
} }
}
};

View file

@ -1,33 +1,36 @@
// @flow // @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 * Singleton class used to manage april fools
*/ */
export default class AprilFoolsManager { export default class AprilFoolsManager {
static instance: AprilFoolsManager | null = null; static instance: AprilFoolsManager | null = null;
static fakeMachineNumber = [ static fakeMachineNumber = [
"", '',
"cos(ln(1))", 'cos(ln(1))',
"0,5⁻¹", '0,5⁻¹',
"567/189", '567/189',
"√2×√8", '√2×√8',
"√50×sin(9π/4)", '√50×sin(9π/4)',
"⌈π+e⌉", '⌈π+e⌉',
"div(rot(B))+7", 'div(rot(B))+7',
"4×cosh(0)+4", '4×cosh(0)+4',
"8-(-i)²", '8-(-i)²',
"|5√2+5√2i|", '|5√2+5√2i|',
"1×10¹+1×10⁰", '1×10¹+1×10⁰',
"Re(√192e^(iπ/6))", 'Re(√192e^(iπ/6))',
]; ];
aprilFoolsEnabled: boolean; aprilFoolsEnabled: boolean;
constructor() { constructor() {
let today = new Date(); const today = new Date();
this.aprilFoolsEnabled = (today.getDate() === 1 && today.getMonth() === 3); this.aprilFoolsEnabled = today.getDate() === 1 && today.getMonth() === 3;
} }
/** /**
@ -35,9 +38,9 @@ export default class AprilFoolsManager {
* @returns {ThemeManager} * @returns {ThemeManager}
*/ */
static getInstance(): AprilFoolsManager { static getInstance(): AprilFoolsManager {
return AprilFoolsManager.instance === null ? if (AprilFoolsManager.instance == null)
AprilFoolsManager.instance = new AprilFoolsManager() : AprilFoolsManager.instance = new AprilFoolsManager();
AprilFoolsManager.instance; return AprilFoolsManager.instance;
} }
/** /**
@ -46,12 +49,14 @@ export default class AprilFoolsManager {
* @param menu * @param menu
* @returns {Object} * @returns {Object}
*/ */
static getFakeMenuItem(menu: Array<{dishes: Array<{name: string}>}>) { static getFakeMenuItem(
menu[1]["dishes"].splice(4, 0, {name: "Coq au vin"}); menu: Array<RuFoodCategoryType>,
menu[1]["dishes"].splice(2, 0, {name: "Bat'Soupe"}); ): Array<RuFoodCategoryType> {
menu[1]["dishes"].splice(1, 0, {name: "Pave de loup"}); menu[1].dishes.splice(4, 0, {name: 'Coq au vin'});
menu[1]["dishes"].splice(0, 0, {name: "Béranger à point"}); menu[1].dishes.splice(2, 0, {name: "Bat'Soupe"});
menu[1]["dishes"].splice(0, 0, {name: "Pieds d'Arnaud"}); 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; return menu;
} }
@ -60,9 +65,11 @@ export default class AprilFoolsManager {
* *
* @param dryers * @param dryers
*/ */
static getNewProxiwashDryerOrderedList(dryers: Array<Machine> | null) { static getNewProxiwashDryerOrderedList(
dryers: Array<ProxiwashMachineType> | null,
) {
if (dryers != null) { if (dryers != null) {
let second = dryers[1]; const second = dryers[1];
dryers.splice(1, 1); dryers.splice(1, 1);
dryers.push(second); dryers.push(second);
} }
@ -73,12 +80,14 @@ export default class AprilFoolsManager {
* *
* @param washers * @param washers
*/ */
static getNewProxiwashWasherOrderedList(washers: Array<Machine> | null) { static getNewProxiwashWasherOrderedList(
washers: Array<ProxiwashMachineType> | null,
) {
if (washers != null) { if (washers != null) {
let first = washers[0]; const first = washers[0];
let second = washers[1]; const second = washers[1];
let fifth = washers[4]; const fifth = washers[4];
let ninth = washers[8]; const ninth = washers[8];
washers.splice(8, 1, second); washers.splice(8, 1, second);
washers.splice(4, 1, ninth); washers.splice(4, 1, ninth);
washers.splice(1, 1, first); washers.splice(1, 1, first);
@ -92,7 +101,7 @@ export default class AprilFoolsManager {
* @param number * @param number
* @returns {string} * @returns {string}
*/ */
static getProxiwashMachineDisplayNumber(number: number) { static getProxiwashMachineDisplayNumber(number: number): string {
return AprilFoolsManager.fakeMachineNumber[number]; return AprilFoolsManager.fakeMachineNumber[number];
} }
@ -102,7 +111,7 @@ export default class AprilFoolsManager {
* @param currentTheme * @param currentTheme
* @returns {{colors: {textDisabled: string, agendaDayTextColor: string, surface: string, background: string, dividerBackground: string, accent: string, agendaBackgroundColor: string, tabIcon: string, card: string, primary: string}}} * @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) { static getAprilFoolsTheme(currentTheme: CustomThemeType): CustomThemeType {
return { return {
...currentTheme, ...currentTheme,
colors: { colors: {
@ -110,9 +119,9 @@ export default class AprilFoolsManager {
primary: '#00be45', primary: '#00be45',
accent: '#00be45', accent: '#00be45',
background: '#d02eee', background: '#d02eee',
tabIcon: "#380d43", tabIcon: '#380d43',
card: "#eed639", card: '#eed639',
surface: "#eed639", surface: '#eed639',
dividerBackground: '#c72ce4', dividerBackground: '#c72ce4',
textDisabled: '#b9b9b9', textDisabled: '#b9b9b9',
@ -123,8 +132,7 @@ export default class AprilFoolsManager {
}; };
} }
isAprilFoolsEnabled() { isAprilFoolsEnabled(): boolean {
return this.aprilFoolsEnabled; return this.aprilFoolsEnabled;
} }
}
};

View file

@ -1,7 +1,7 @@
// @flow // @flow
import AsyncStorage from '@react-native-community/async-storage'; import AsyncStorage from '@react-native-community/async-storage';
import {SERVICES_KEY} from "./ServicesManager"; import {SERVICES_KEY} from './ServicesManager';
/** /**
* Singleton used to manage preferences. * Singleton used to manage preferences.
@ -10,7 +10,6 @@ import {SERVICES_KEY} from "./ServicesManager";
*/ */
export default class AsyncStorageManager { export default class AsyncStorageManager {
static instance: AsyncStorageManager | null = null; static instance: AsyncStorageManager | null = null;
static PREFERENCES = { static PREFERENCES = {
@ -108,7 +107,7 @@ export default class AsyncStorageManager {
key: 'gameScores', key: 'gameScores',
default: '[]', default: '[]',
}, },
} };
#currentPreferences: {[key: string]: string}; #currentPreferences: {[key: string]: string};
@ -121,9 +120,66 @@ export default class AsyncStorageManager {
* @returns {AsyncStorageManager} * @returns {AsyncStorageManager}
*/ */
static getInstance(): AsyncStorageManager { static getInstance(): AsyncStorageManager {
return AsyncStorageManager.instance === null ? if (AsyncStorageManager.instance == null)
AsyncStorageManager.instance = new AsyncStorageManager() : AsyncStorageManager.instance = new AsyncStorageManager();
AsyncStorageManager.instance; 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));
} }
/** /**
@ -133,21 +189,20 @@ export default class AsyncStorageManager {
* @return {Promise<void>} * @return {Promise<void>}
*/ */
async loadPreferences() { async loadPreferences() {
let prefKeys = []; const prefKeys = [];
// Get all available keys // Get all available keys
for (let key in AsyncStorageManager.PREFERENCES) { Object.keys(AsyncStorageManager.PREFERENCES).forEach((key: string) => {
prefKeys.push(key); prefKeys.push(key);
} });
// Get corresponding values // Get corresponding values
let resultArray: Array<Array<string>> = await AsyncStorage.multiGet(prefKeys); const resultArray = await AsyncStorage.multiGet(prefKeys);
// Save those values for later use // Save those values for later use
for (let i = 0; i < resultArray.length; i++) { resultArray.forEach((item: [string, string | null]) => {
let key: string = resultArray[i][0]; const key = item[0];
let val: string | null = resultArray[i][1]; let val = item[1];
if (val === null) if (val === null) val = AsyncStorageManager.PREFERENCES[key].default;
val = AsyncStorageManager.PREFERENCES[key].default;
this.#currentPreferences[key] = val; this.#currentPreferences[key] = val;
} });
} }
/** /**
@ -157,15 +212,17 @@ export default class AsyncStorageManager {
* @param key * @param key
* @param value * @param value
*/ */
setPreference(key: string, value: any) { setPreference(
key: string,
// eslint-disable-next-line flowtype/no-weak-types
value: number | string | boolean | {...} | Array<any>,
) {
if (AsyncStorageManager.PREFERENCES[key] != null) { if (AsyncStorageManager.PREFERENCES[key] != null) {
let convertedValue = ""; let convertedValue;
if (typeof value === "string") if (typeof value === 'string') convertedValue = value;
convertedValue = value; else if (typeof value === 'boolean' || typeof value === 'number')
else if (typeof value === "boolean" || typeof value === "number")
convertedValue = value.toString(); convertedValue = value.toString();
else else convertedValue = JSON.stringify(value);
convertedValue = JSON.stringify(value);
this.#currentPreferences[key] = convertedValue; this.#currentPreferences[key] = convertedValue;
AsyncStorage.setItem(key, convertedValue); AsyncStorage.setItem(key, convertedValue);
} }
@ -178,59 +235,7 @@ export default class AsyncStorageManager {
* @param key * @param key
* @returns {string|null} * @returns {string|null}
*/ */
getPreference(key: string) { getPreference(key: string): string | null {
return this.#currentPreferences[key]; 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));
}
} }

View file

@ -10,29 +10,30 @@ export default class DateManager {
static instance: DateManager | null = null; static instance: DateManager | null = null;
daysOfWeek = []; daysOfWeek = [];
monthsOfYear = []; monthsOfYear = [];
constructor() { constructor() {
this.daysOfWeek.push(i18n.t("date.daysOfWeek.sunday")); // 0 represents sunday 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.monday'));
this.daysOfWeek.push(i18n.t("date.daysOfWeek.tuesday")); this.daysOfWeek.push(i18n.t('date.daysOfWeek.tuesday'));
this.daysOfWeek.push(i18n.t("date.daysOfWeek.wednesday")); this.daysOfWeek.push(i18n.t('date.daysOfWeek.wednesday'));
this.daysOfWeek.push(i18n.t("date.daysOfWeek.thursday")); this.daysOfWeek.push(i18n.t('date.daysOfWeek.thursday'));
this.daysOfWeek.push(i18n.t("date.daysOfWeek.friday")); this.daysOfWeek.push(i18n.t('date.daysOfWeek.friday'));
this.daysOfWeek.push(i18n.t("date.daysOfWeek.saturday")); this.daysOfWeek.push(i18n.t('date.daysOfWeek.saturday'));
this.monthsOfYear.push(i18n.t("date.monthsOfYear.january")); this.monthsOfYear.push(i18n.t('date.monthsOfYear.january'));
this.monthsOfYear.push(i18n.t("date.monthsOfYear.february")); this.monthsOfYear.push(i18n.t('date.monthsOfYear.february'));
this.monthsOfYear.push(i18n.t("date.monthsOfYear.march")); this.monthsOfYear.push(i18n.t('date.monthsOfYear.march'));
this.monthsOfYear.push(i18n.t("date.monthsOfYear.april")); this.monthsOfYear.push(i18n.t('date.monthsOfYear.april'));
this.monthsOfYear.push(i18n.t("date.monthsOfYear.may")); this.monthsOfYear.push(i18n.t('date.monthsOfYear.may'));
this.monthsOfYear.push(i18n.t("date.monthsOfYear.june")); this.monthsOfYear.push(i18n.t('date.monthsOfYear.june'));
this.monthsOfYear.push(i18n.t("date.monthsOfYear.july")); this.monthsOfYear.push(i18n.t('date.monthsOfYear.july'));
this.monthsOfYear.push(i18n.t("date.monthsOfYear.august")); this.monthsOfYear.push(i18n.t('date.monthsOfYear.august'));
this.monthsOfYear.push(i18n.t("date.monthsOfYear.september")); this.monthsOfYear.push(i18n.t('date.monthsOfYear.september'));
this.monthsOfYear.push(i18n.t("date.monthsOfYear.october")); this.monthsOfYear.push(i18n.t('date.monthsOfYear.october'));
this.monthsOfYear.push(i18n.t("date.monthsOfYear.november")); this.monthsOfYear.push(i18n.t('date.monthsOfYear.november'));
this.monthsOfYear.push(i18n.t("date.monthsOfYear.december")); this.monthsOfYear.push(i18n.t('date.monthsOfYear.december'));
} }
/** /**
@ -40,16 +41,15 @@ export default class DateManager {
* @returns {DateManager} * @returns {DateManager}
*/ */
static getInstance(): DateManager { static getInstance(): DateManager {
return DateManager.instance === null ? if (DateManager.instance == null) DateManager.instance = new DateManager();
DateManager.instance = new DateManager() : return DateManager.instance;
DateManager.instance;
} }
static isWeekend(date: Date) { static isWeekend(date: Date): boolean {
return date.getDay() === 6 || date.getDay() === 0; return date.getDay() === 6 || date.getDay() === 0;
} }
getMonthsOfYear() { getMonthsOfYear(): Array<string> {
return this.monthsOfYear; return this.monthsOfYear;
} }
@ -59,11 +59,16 @@ export default class DateManager {
* @param dateString The date with the format YYYY-MM-DD * @param dateString The date with the format YYYY-MM-DD
* @return {string} The translated string * @return {string} The translated string
*/ */
getTranslatedDate(dateString: string) { getTranslatedDate(dateString: string): string {
let dateArray = dateString.split('-'); const dateArray = dateString.split('-');
let date = new Date(); const date = new Date();
date.setFullYear(parseInt(dateArray[0]), parseInt(dateArray[1]) - 1, parseInt(dateArray[2])); date.setFullYear(
return this.daysOfWeek[date.getDay()] + " " + date.getDate() + " " + this.monthsOfYear[date.getMonth()] + " " + date.getFullYear(); 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()}`;
} }
} }

View file

@ -1,22 +1,24 @@
// @flow // @flow
import i18n from 'i18n-js'; 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'; import fr from '../../locales/fr.json';
/** /**
* Static class used to manage locales * Static class used to manage locales
*/ */
export default class LocaleManager { export default class LocaleManager {
/** /**
* Initialize translations using language files * Initialize translations using language files
*/ */
static initTranslations() { static initTranslations() {
i18n.fallbacks = true; i18n.fallbacks = true;
i18n.translations = {fr, en}; i18n.translations = {fr, en};
i18n.locale = RNLocalize.findBestAvailableLanguage(["en", "fr"]).languageTag; i18n.locale = RNLocalize.findBestAvailableLanguage([
'en',
'fr',
]).languageTag;
} }
} }

View file

@ -1,13 +1,13 @@
// @flow // @flow
import AsyncStorageManager from "./AsyncStorageManager";
import {DarkTheme, DefaultTheme} from 'react-native-paper'; import {DarkTheme, DefaultTheme} from 'react-native-paper';
import AprilFoolsManager from "./AprilFoolsManager";
import {Appearance} from 'react-native-appearance'; import {Appearance} from 'react-native-appearance';
import AsyncStorageManager from './AsyncStorageManager';
import AprilFoolsManager from './AprilFoolsManager';
const colorScheme = Appearance.getColorScheme(); const colorScheme = Appearance.getColorScheme();
export type CustomTheme = { export type CustomThemeType = {
...DefaultTheme, ...DefaultTheme,
colors: { colors: {
primary: string, primary: string,
@ -63,15 +63,15 @@ export type CustomTheme = {
// Mascot Popup // Mascot Popup
mascotMessageArrow: string, mascotMessageArrow: string,
}, },
} };
/** /**
* Singleton class used to manage themes * Singleton class used to manage themes
*/ */
export default class ThemeManager { export default class ThemeManager {
static instance: ThemeManager | null = null; static instance: ThemeManager | null = null;
updateThemeCallback: Function;
updateThemeCallback: null | (() => void);
constructor() { constructor() {
this.updateThemeCallback = null; this.updateThemeCallback = null;
@ -80,25 +80,25 @@ export default class ThemeManager {
/** /**
* Gets the light theme * Gets the light theme
* *
* @return {CustomTheme} Object containing theme variables * @return {CustomThemeType} Object containing theme variables
* */ * */
static getWhiteTheme(): CustomTheme { static getWhiteTheme(): CustomThemeType {
return { return {
...DefaultTheme, ...DefaultTheme,
colors: { colors: {
...DefaultTheme.colors, ...DefaultTheme.colors,
primary: '#be1522', primary: '#be1522',
accent: '#be1522', accent: '#be1522',
tabIcon: "#929292", tabIcon: '#929292',
card: "#fff", card: '#fff',
dividerBackground: '#e2e2e2', dividerBackground: '#e2e2e2',
ripple: "rgba(0,0,0,0.2)", ripple: 'rgba(0,0,0,0.2)',
textDisabled: '#c1c1c1', textDisabled: '#c1c1c1',
icon: '#5d5d5d', icon: '#5d5d5d',
subtitle: '#707070', subtitle: '#707070',
success: "#5cb85c", success: '#5cb85c',
warning: "#f0ad4e", warning: '#f0ad4e',
danger: "#d9534f", danger: '#d9534f',
cc: 'dst', cc: 'dst',
// Calendar/Agenda // Calendar/Agenda
@ -106,14 +106,14 @@ export default class ThemeManager {
agendaDayTextColor: '#636363', agendaDayTextColor: '#636363',
// PROXIWASH // PROXIWASH
proxiwashFinishedColor: "#a5dc9d", proxiwashFinishedColor: '#a5dc9d',
proxiwashReadyColor: "transparent", proxiwashReadyColor: 'transparent',
proxiwashRunningColor: "#a0ceff", proxiwashRunningColor: '#a0ceff',
proxiwashRunningNotStartedColor: "#c9e0ff", proxiwashRunningNotStartedColor: '#c9e0ff',
proxiwashRunningBgColor: "#c7e3ff", proxiwashRunningBgColor: '#c7e3ff',
proxiwashBrokenColor: "#ffa8a2", proxiwashBrokenColor: '#ffa8a2',
proxiwashErrorColor: "#ffa8a2", proxiwashErrorColor: '#ffa8a2',
proxiwashUnknownColor: "#b6b6b6", proxiwashUnknownColor: '#b6b6b6',
// Screens // Screens
planningColor: '#d9b10a', planningColor: '#d9b10a',
@ -133,12 +133,12 @@ export default class ThemeManager {
tetrisJ: '#2a67e3', tetrisJ: '#2a67e3',
tetrisL: '#da742d', tetrisL: '#da742d',
gameGold: "#ffd610", gameGold: '#ffd610',
gameSilver: "#7b7b7b", gameSilver: '#7b7b7b',
gameBronze: "#a15218", gameBronze: '#a15218',
// Mascot Popup // Mascot Popup
mascotMessageArrow: "#dedede", mascotMessageArrow: '#dedede',
}, },
}; };
} }
@ -146,40 +146,40 @@ export default class ThemeManager {
/** /**
* Gets the dark theme * Gets the dark theme
* *
* @return {CustomTheme} Object containing theme variables * @return {CustomThemeType} Object containing theme variables
* */ * */
static getDarkTheme(): CustomTheme { static getDarkTheme(): CustomThemeType {
return { return {
...DarkTheme, ...DarkTheme,
colors: { colors: {
...DarkTheme.colors, ...DarkTheme.colors,
primary: '#be1522', primary: '#be1522',
accent: '#be1522', accent: '#be1522',
tabBackground: "#181818", tabBackground: '#181818',
tabIcon: "#6d6d6d", tabIcon: '#6d6d6d',
card: "rgb(18,18,18)", card: 'rgb(18,18,18)',
dividerBackground: '#222222', dividerBackground: '#222222',
ripple: "rgba(255,255,255,0.2)", ripple: 'rgba(255,255,255,0.2)',
textDisabled: '#5b5b5b', textDisabled: '#5b5b5b',
icon: '#b3b3b3', icon: '#b3b3b3',
subtitle: '#aaaaaa', subtitle: '#aaaaaa',
success: "#5cb85c", success: '#5cb85c',
warning: "#f0ad4e", warning: '#f0ad4e',
danger: "#d9534f", danger: '#d9534f',
// Calendar/Agenda // Calendar/Agenda
agendaBackgroundColor: '#171717', agendaBackgroundColor: '#171717',
agendaDayTextColor: '#6d6d6d', agendaDayTextColor: '#6d6d6d',
// PROXIWASH // PROXIWASH
proxiwashFinishedColor: "#31682c", proxiwashFinishedColor: '#31682c',
proxiwashReadyColor: "transparent", proxiwashReadyColor: 'transparent',
proxiwashRunningColor: "#213c79", proxiwashRunningColor: '#213c79',
proxiwashRunningNotStartedColor: "#1e263e", proxiwashRunningNotStartedColor: '#1e263e',
proxiwashRunningBgColor: "#1a2033", proxiwashRunningBgColor: '#1a2033',
proxiwashBrokenColor: "#7e2e2f", proxiwashBrokenColor: '#7e2e2f',
proxiwashErrorColor: "#7e2e2f", proxiwashErrorColor: '#7e2e2f',
proxiwashUnknownColor: "#535353", proxiwashUnknownColor: '#535353',
// Screens // Screens
planningColor: '#d99e09', planningColor: '#d99e09',
@ -199,12 +199,12 @@ export default class ThemeManager {
tetrisJ: '#0f37b9', tetrisJ: '#0f37b9',
tetrisL: '#b96226', tetrisL: '#b96226',
gameGold: "#ffd610", gameGold: '#ffd610',
gameSilver: "#7b7b7b", gameSilver: '#7b7b7b',
gameBronze: "#a15218", gameBronze: '#a15218',
// Mascot Popup // Mascot Popup
mascotMessageArrow: "#323232", mascotMessageArrow: '#323232',
}, },
}; };
} }
@ -215,9 +215,9 @@ export default class ThemeManager {
* @returns {ThemeManager} * @returns {ThemeManager}
*/ */
static getInstance(): ThemeManager { static getInstance(): ThemeManager {
return ThemeManager.instance === null ? if (ThemeManager.instance == null)
ThemeManager.instance = new ThemeManager() : ThemeManager.instance = new ThemeManager();
ThemeManager.instance; return ThemeManager.instance;
} }
/** /**
@ -228,34 +228,39 @@ export default class ThemeManager {
* @returns {boolean} Night mode state * @returns {boolean} Night mode state
*/ */
static getNightMode(): boolean { static getNightMode(): boolean {
return (AsyncStorageManager.getBool(AsyncStorageManager.PREFERENCES.nightMode.key) && return (
(!AsyncStorageManager.getBool(AsyncStorageManager.PREFERENCES.nightModeFollowSystem.key) (AsyncStorageManager.getBool(
|| colorScheme === 'no-preference')) || AsyncStorageManager.PREFERENCES.nightMode.key,
(AsyncStorageManager.getBool(AsyncStorageManager.PREFERENCES.nightModeFollowSystem.key) ) &&
&& colorScheme === 'dark'); (!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 * Get the current theme based on night mode and events
* *
* @returns {CustomTheme} The current theme * @returns {CustomThemeType} The current theme
*/ */
static getCurrentTheme(): CustomTheme { static getCurrentTheme(): CustomThemeType {
if (AprilFoolsManager.getInstance().isAprilFoolsEnabled()) if (AprilFoolsManager.getInstance().isAprilFoolsEnabled())
return AprilFoolsManager.getAprilFoolsTheme(ThemeManager.getWhiteTheme()); return AprilFoolsManager.getAprilFoolsTheme(ThemeManager.getWhiteTheme());
else return ThemeManager.getBaseTheme();
return ThemeManager.getBaseTheme()
} }
/** /**
* Get the theme based on night mode * Get the theme based on night mode
* *
* @return {CustomTheme} The theme * @return {CustomThemeType} The theme
*/ */
static getBaseTheme(): CustomTheme { static getBaseTheme(): CustomThemeType {
if (ThemeManager.getNightMode()) if (ThemeManager.getNightMode()) return ThemeManager.getDarkTheme();
return ThemeManager.getDarkTheme();
else
return ThemeManager.getWhiteTheme(); return ThemeManager.getWhiteTheme();
} }
@ -274,9 +279,10 @@ export default class ThemeManager {
* @param isNightMode True to enable night mode, false to disable * @param isNightMode True to enable night mode, false to disable
*/ */
setNightMode(isNightMode: boolean) { setNightMode(isNightMode: boolean) {
AsyncStorageManager.set(AsyncStorageManager.PREFERENCES.nightMode.key, isNightMode); AsyncStorageManager.set(
if (this.updateThemeCallback != null) AsyncStorageManager.PREFERENCES.nightMode.key,
this.updateThemeCallback(); isNightMode,
);
if (this.updateThemeCallback != null) this.updateThemeCallback();
} }
}
};

View file

@ -1,35 +1,41 @@
// @flow // @flow
import * as React from 'react'; 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 SettingsScreen from '../screens/Other/Settings/SettingsScreen';
import AboutScreen from '../screens/About/AboutScreen'; import AboutScreen from '../screens/About/AboutScreen';
import AboutDependenciesScreen from '../screens/About/AboutDependenciesScreen'; import AboutDependenciesScreen from '../screens/About/AboutDependenciesScreen';
import DebugScreen from '../screens/About/DebugScreen'; import DebugScreen from '../screens/About/DebugScreen';
import {createStackNavigator, TransitionPresets} from "@react-navigation/stack"; import TabNavigator from './TabNavigator';
import i18n from "i18n-js"; import GameMainScreen from '../screens/Game/screens/GameMainScreen';
import TabNavigator from "./TabNavigator"; import VoteScreen from '../screens/Amicale/VoteScreen';
import GameMainScreen from "../screens/Game/screens/GameMainScreen"; import LoginScreen from '../screens/Amicale/LoginScreen';
import VoteScreen from "../screens/Amicale/VoteScreen"; import SelfMenuScreen from '../screens/Services/SelfMenuScreen';
import LoginScreen from "../screens/Amicale/LoginScreen"; import ProximoMainScreen from '../screens/Services/Proximo/ProximoMainScreen';
import {Platform} from "react-native"; import ProximoListScreen from '../screens/Services/Proximo/ProximoListScreen';
import SelfMenuScreen from "../screens/Services/SelfMenuScreen"; import ProximoAboutScreen from '../screens/Services/Proximo/ProximoAboutScreen';
import ProximoMainScreen from "../screens/Services/Proximo/ProximoMainScreen"; import ProfileScreen from '../screens/Amicale/ProfileScreen';
import ProximoListScreen from "../screens/Services/Proximo/ProximoListScreen"; import ClubListScreen from '../screens/Amicale/Clubs/ClubListScreen';
import ProximoAboutScreen from "../screens/Services/Proximo/ProximoAboutScreen"; import ClubAboutScreen from '../screens/Amicale/Clubs/ClubAboutScreen';
import ProfileScreen from "../screens/Amicale/ProfileScreen"; import ClubDisplayScreen from '../screens/Amicale/Clubs/ClubDisplayScreen';
import ClubListScreen from "../screens/Amicale/Clubs/ClubListScreen"; import {
import ClubAboutScreen from "../screens/Amicale/Clubs/ClubAboutScreen"; createScreenCollapsibleStack,
import ClubDisplayScreen from "../screens/Amicale/Clubs/ClubDisplayScreen"; getWebsiteStack,
import {createScreenCollapsibleStack, getWebsiteStack} from "../utils/CollapsibleUtils"; } from '../utils/CollapsibleUtils';
import BugReportScreen from "../screens/Other/FeedbackScreen"; import BugReportScreen from '../screens/Other/FeedbackScreen';
import WebsiteScreen from "../screens/Services/WebsiteScreen"; import WebsiteScreen from '../screens/Services/WebsiteScreen';
import EquipmentScreen from "../screens/Amicale/Equipment/EquipmentListScreen"; import EquipmentScreen from '../screens/Amicale/Equipment/EquipmentListScreen';
import EquipmentLendScreen from "../screens/Amicale/Equipment/EquipmentRentScreen"; import EquipmentLendScreen from '../screens/Amicale/Equipment/EquipmentRentScreen';
import EquipmentConfirmScreen from "../screens/Amicale/Equipment/EquipmentConfirmScreen"; import EquipmentConfirmScreen from '../screens/Amicale/Equipment/EquipmentConfirmScreen';
import DashboardEditScreen from "../screens/Other/Settings/DashboardEditScreen"; import DashboardEditScreen from '../screens/Other/Settings/DashboardEditScreen';
import GameStartScreen from "../screens/Game/screens/GameStartScreen"; import GameStartScreen from '../screens/Game/screens/GameStartScreen';
const modalTransition = Platform.OS === 'ios' ? TransitionPresets.ModalPresentationIOS : TransitionPresets.ModalSlideFromBottomIOS; const modalTransition =
Platform.OS === 'ios'
? TransitionPresets.ModalPresentationIOS
: TransitionPresets.ModalSlideFromBottomIOS;
const defaultScreenOptions = { const defaultScreenOptions = {
gestureEnabled: true, gestureEnabled: true,
@ -37,91 +43,100 @@ const defaultScreenOptions = {
...TransitionPresets.SlideFromRightIOS, ...TransitionPresets.SlideFromRightIOS,
}; };
const MainStack = createStackNavigator(); const MainStack = createStackNavigator();
function MainStackComponent(props: { createTabNavigator: () => React.Node }) { function MainStackComponent(props: {
createTabNavigator: () => React.Node,
}): React.Node {
const {createTabNavigator} = props;
return ( return (
<MainStack.Navigator <MainStack.Navigator
initialRouteName={'main'} initialRouteName="main"
headerMode={'screen'} headerMode="screen"
screenOptions={defaultScreenOptions} screenOptions={defaultScreenOptions}>
>
<MainStack.Screen <MainStack.Screen
name="main" name="main"
component={props.createTabNavigator} component={createTabNavigator}
options={{ options={{
headerShown: false, headerShown: false,
title: i18n.t('screens.home.title'), title: i18n.t('screens.home.title'),
}} }}
/> />
{createScreenCollapsibleStack( {createScreenCollapsibleStack(
"settings", 'settings',
MainStack, MainStack,
SettingsScreen, SettingsScreen,
i18n.t('screens.settings.title'))} i18n.t('screens.settings.title'),
)}
{createScreenCollapsibleStack( {createScreenCollapsibleStack(
"dashboard-edit", 'dashboard-edit',
MainStack, MainStack,
DashboardEditScreen, DashboardEditScreen,
i18n.t('screens.settings.dashboardEdit.title'))} i18n.t('screens.settings.dashboardEdit.title'),
)}
{createScreenCollapsibleStack( {createScreenCollapsibleStack(
"about", 'about',
MainStack, MainStack,
AboutScreen, AboutScreen,
i18n.t('screens.about.title'))} i18n.t('screens.about.title'),
)}
{createScreenCollapsibleStack( {createScreenCollapsibleStack(
"dependencies", 'dependencies',
MainStack, MainStack,
AboutDependenciesScreen, AboutDependenciesScreen,
i18n.t('screens.about.libs'))} i18n.t('screens.about.libs'),
)}
{createScreenCollapsibleStack( {createScreenCollapsibleStack(
"debug", 'debug',
MainStack, MainStack,
DebugScreen, DebugScreen,
i18n.t('screens.about.debug'))} i18n.t('screens.about.debug'),
)}
{createScreenCollapsibleStack( {createScreenCollapsibleStack(
"game-start", 'game-start',
MainStack, MainStack,
GameStartScreen, GameStartScreen,
i18n.t('screens.game.title'))} i18n.t('screens.game.title'),
)}
<MainStack.Screen <MainStack.Screen
name="game-main" name="game-main"
component={GameMainScreen} component={GameMainScreen}
options={{ options={{
title: i18n.t("screens.game.title"), title: i18n.t('screens.game.title'),
}} }}
/> />
{createScreenCollapsibleStack( {createScreenCollapsibleStack(
"login", 'login',
MainStack, MainStack,
LoginScreen, LoginScreen,
i18n.t('screens.login.title'), i18n.t('screens.login.title'),
true, true,
{headerTintColor: "#fff"}, {headerTintColor: '#fff'},
'transparent')} 'transparent',
{getWebsiteStack("website", MainStack, WebsiteScreen, "")} )}
{getWebsiteStack('website', MainStack, WebsiteScreen, '')}
{createScreenCollapsibleStack( {createScreenCollapsibleStack(
"self-menu", 'self-menu',
MainStack, MainStack,
SelfMenuScreen, SelfMenuScreen,
i18n.t('screens.menu.title'))} i18n.t('screens.menu.title'),
)}
{createScreenCollapsibleStack( {createScreenCollapsibleStack(
"proximo", 'proximo',
MainStack, MainStack,
ProximoMainScreen, ProximoMainScreen,
i18n.t('screens.proximo.title'))} i18n.t('screens.proximo.title'),
)}
{createScreenCollapsibleStack( {createScreenCollapsibleStack(
"proximo-list", 'proximo-list',
MainStack, MainStack,
ProximoListScreen, ProximoListScreen,
i18n.t('screens.proximo.articleList'), i18n.t('screens.proximo.articleList'),
)} )}
{createScreenCollapsibleStack( {createScreenCollapsibleStack(
"proximo-about", 'proximo-about',
MainStack, MainStack,
ProximoAboutScreen, ProximoAboutScreen,
i18n.t('screens.proximo.title'), i18n.t('screens.proximo.title'),
@ -130,75 +145,87 @@ function MainStackComponent(props: { createTabNavigator: () => React.Node }) {
)} )}
{createScreenCollapsibleStack( {createScreenCollapsibleStack(
"profile", 'profile',
MainStack, MainStack,
ProfileScreen, ProfileScreen,
i18n.t('screens.profile.title'))} i18n.t('screens.profile.title'),
)}
{createScreenCollapsibleStack( {createScreenCollapsibleStack(
"club-list", 'club-list',
MainStack, MainStack,
ClubListScreen, ClubListScreen,
i18n.t('screens.clubs.title'))} i18n.t('screens.clubs.title'),
)}
{createScreenCollapsibleStack( {createScreenCollapsibleStack(
"club-information", 'club-information',
MainStack, MainStack,
ClubDisplayScreen, ClubDisplayScreen,
i18n.t('screens.clubs.details'), i18n.t('screens.clubs.details'),
true, true,
{...modalTransition})} {...modalTransition},
)}
{createScreenCollapsibleStack( {createScreenCollapsibleStack(
"club-about", 'club-about',
MainStack, MainStack,
ClubAboutScreen, ClubAboutScreen,
i18n.t('screens.clubs.title'), i18n.t('screens.clubs.title'),
true, true,
{...modalTransition})} {...modalTransition},
)}
{createScreenCollapsibleStack( {createScreenCollapsibleStack(
"equipment-list", 'equipment-list',
MainStack, MainStack,
EquipmentScreen, EquipmentScreen,
i18n.t('screens.equipment.title'))} i18n.t('screens.equipment.title'),
)}
{createScreenCollapsibleStack( {createScreenCollapsibleStack(
"equipment-rent", 'equipment-rent',
MainStack, MainStack,
EquipmentLendScreen, EquipmentLendScreen,
i18n.t('screens.equipment.book'))} i18n.t('screens.equipment.book'),
)}
{createScreenCollapsibleStack( {createScreenCollapsibleStack(
"equipment-confirm", 'equipment-confirm',
MainStack, MainStack,
EquipmentConfirmScreen, EquipmentConfirmScreen,
i18n.t('screens.equipment.confirm'))} i18n.t('screens.equipment.confirm'),
)}
{createScreenCollapsibleStack( {createScreenCollapsibleStack(
"vote", 'vote',
MainStack, MainStack,
VoteScreen, VoteScreen,
i18n.t('screens.vote.title'))} i18n.t('screens.vote.title'),
)}
{createScreenCollapsibleStack( {createScreenCollapsibleStack(
"feedback", 'feedback',
MainStack, MainStack,
BugReportScreen, BugReportScreen,
i18n.t('screens.feedback.title'))} i18n.t('screens.feedback.title'),
)}
</MainStack.Navigator> </MainStack.Navigator>
); );
} }
type Props = { type PropsType = {
defaultHomeRoute: string | null, defaultHomeRoute: string | null,
defaultHomeData: { [key: string]: any } // eslint-disable-next-line flowtype/no-weak-types
} defaultHomeData: {[key: string]: string},
};
export default class MainNavigator extends React.Component<Props> {
export default class MainNavigator extends React.Component<PropsType> {
createTabNavigator: () => React.Node; createTabNavigator: () => React.Node;
constructor(props: Props) { constructor(props: PropsType) {
super(props); super(props);
this.createTabNavigator = () => <TabNavigator {...props}/> this.createTabNavigator = (): React.Node => (
} <TabNavigator
defaultHomeRoute={props.defaultHomeRoute}
render() { defaultHomeData={props.defaultHomeData}
return ( />
<MainStackComponent createTabNavigator={this.createTabNavigator}/>
); );
} }
render(): React.Node {
return <MainStackComponent createTabNavigator={this.createTabNavigator} />;
}
} }

View file

@ -1,32 +1,39 @@
// @flow
import * as React from 'react'; import * as React from 'react';
import {createStackNavigator, TransitionPresets} from '@react-navigation/stack'; 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 HomeScreen from '../screens/Home/HomeScreen';
import PlanningScreen from '../screens/Planning/PlanningScreen'; import PlanningScreen from '../screens/Planning/PlanningScreen';
import PlanningDisplayScreen from '../screens/Planning/PlanningDisplayScreen'; import PlanningDisplayScreen from '../screens/Planning/PlanningDisplayScreen';
import ProxiwashScreen from '../screens/Proxiwash/ProxiwashScreen'; import ProxiwashScreen from '../screens/Proxiwash/ProxiwashScreen';
import ProxiwashAboutScreen from '../screens/Proxiwash/ProxiwashAboutScreen'; import ProxiwashAboutScreen from '../screens/Proxiwash/ProxiwashAboutScreen';
import PlanexScreen from '../screens/Planex/PlanexScreen'; import PlanexScreen from '../screens/Planex/PlanexScreen';
import AsyncStorageManager from "../managers/AsyncStorageManager"; import AsyncStorageManager from '../managers/AsyncStorageManager';
import {Title, useTheme} from 'react-native-paper'; import ClubDisplayScreen from '../screens/Amicale/Clubs/ClubDisplayScreen';
import {Platform} from 'react-native'; import ScannerScreen from '../screens/Home/ScannerScreen';
import i18n from "i18n-js"; import FeedItemScreen from '../screens/Home/FeedItemScreen';
import ClubDisplayScreen from "../screens/Amicale/Clubs/ClubDisplayScreen"; import GroupSelectionScreen from '../screens/Planex/GroupSelectionScreen';
import ScannerScreen from "../screens/Home/ScannerScreen"; import CustomTabBar from '../components/Tabbar/CustomTabBar';
import FeedItemScreen from "../screens/Home/FeedItemScreen"; import WebsitesHomeScreen from '../screens/Services/ServicesScreen';
import {createCollapsibleStack} from "react-navigation-collapsible"; import ServicesSectionScreen from '../screens/Services/ServicesSectionScreen';
import GroupSelectionScreen from "../screens/Planex/GroupSelectionScreen"; import AmicaleContactScreen from '../screens/Amicale/AmicaleContactScreen';
import CustomTabBar from "../components/Tabbar/CustomTabBar"; import {
import WebsitesHomeScreen from "../screens/Services/ServicesScreen"; createScreenCollapsibleStack,
import ServicesSectionScreen from "../screens/Services/ServicesSectionScreen"; getWebsiteStack,
import AmicaleContactScreen from "../screens/Amicale/AmicaleContactScreen"; } from '../utils/CollapsibleUtils';
import {createScreenCollapsibleStack, getWebsiteStack} from "../utils/CollapsibleUtils"; import Mascot, {MASCOT_STYLE} from '../components/Mascot/Mascot';
import {View} from "react-native-animatable";
import Mascot, {MASCOT_STYLE} from "../components/Mascot/Mascot";
const modalTransition = Platform.OS === 'ios' ? TransitionPresets.ModalPresentationIOS : TransitionPresets.ModalSlideFromBottomIOS;
const modalTransition =
Platform.OS === 'ios'
? TransitionPresets.ModalPresentationIOS
: TransitionPresets.ModalSlideFromBottomIOS;
const defaultScreenOptions = { const defaultScreenOptions = {
gestureEnabled: true, gestureEnabled: true,
@ -34,94 +41,98 @@ const defaultScreenOptions = {
...modalTransition, ...modalTransition,
}; };
const ServicesStack = createStackNavigator(); const ServicesStack = createStackNavigator();
function ServicesStackComponent() { function ServicesStackComponent(): React.Node {
return ( return (
<ServicesStack.Navigator <ServicesStack.Navigator
initialRouteName="index" initialRouteName="index"
headerMode={"screen"} headerMode="screen"
screenOptions={defaultScreenOptions} screenOptions={defaultScreenOptions}>
>
{createScreenCollapsibleStack( {createScreenCollapsibleStack(
"index", 'index',
ServicesStack, ServicesStack,
WebsitesHomeScreen, WebsitesHomeScreen,
i18n.t('screens.services.title'))} i18n.t('screens.services.title'),
)}
{createScreenCollapsibleStack( {createScreenCollapsibleStack(
"services-section", 'services-section',
ServicesStack, ServicesStack,
ServicesSectionScreen, ServicesSectionScreen,
"SECTION")} 'SECTION',
)}
{createScreenCollapsibleStack( {createScreenCollapsibleStack(
"amicale-contact", 'amicale-contact',
ServicesStack, ServicesStack,
AmicaleContactScreen, AmicaleContactScreen,
i18n.t('screens.amicaleAbout.title'))} i18n.t('screens.amicaleAbout.title'),
)}
</ServicesStack.Navigator> </ServicesStack.Navigator>
); );
} }
const ProxiwashStack = createStackNavigator(); const ProxiwashStack = createStackNavigator();
function ProxiwashStackComponent() { function ProxiwashStackComponent(): React.Node {
return ( return (
<ProxiwashStack.Navigator <ProxiwashStack.Navigator
initialRouteName="index" initialRouteName="index"
headerMode={"screen"} headerMode="screen"
screenOptions={defaultScreenOptions} screenOptions={defaultScreenOptions}>
>
{createScreenCollapsibleStack( {createScreenCollapsibleStack(
"index", 'index',
ProxiwashStack, ProxiwashStack,
ProxiwashScreen, ProxiwashScreen,
i18n.t('screens.proxiwash.title'))} i18n.t('screens.proxiwash.title'),
)}
{createScreenCollapsibleStack( {createScreenCollapsibleStack(
"proxiwash-about", 'proxiwash-about',
ProxiwashStack, ProxiwashStack,
ProxiwashAboutScreen, ProxiwashAboutScreen,
i18n.t('screens.proxiwash.title'))} i18n.t('screens.proxiwash.title'),
)}
</ProxiwashStack.Navigator> </ProxiwashStack.Navigator>
); );
} }
const PlanningStack = createStackNavigator(); const PlanningStack = createStackNavigator();
function PlanningStackComponent() { function PlanningStackComponent(): React.Node {
return ( return (
<PlanningStack.Navigator <PlanningStack.Navigator
initialRouteName="index" initialRouteName="index"
headerMode={"screen"} headerMode="screen"
screenOptions={defaultScreenOptions} screenOptions={defaultScreenOptions}>
>
<PlanningStack.Screen <PlanningStack.Screen
name="index" name="index"
component={PlanningScreen} component={PlanningScreen}
options={{title: i18n.t('screens.planning.title'),}} options={{title: i18n.t('screens.planning.title')}}
/> />
{createScreenCollapsibleStack( {createScreenCollapsibleStack(
"planning-information", 'planning-information',
PlanningStack, PlanningStack,
PlanningDisplayScreen, PlanningDisplayScreen,
i18n.t('screens.planning.eventDetails'))} i18n.t('screens.planning.eventDetails'),
)}
</PlanningStack.Navigator> </PlanningStack.Navigator>
); );
} }
const HomeStack = createStackNavigator(); const HomeStack = createStackNavigator();
function HomeStackComponent(initialRoute: string | null, defaultData: { [key: string]: any }) { function HomeStackComponent(
let params = undefined; initialRoute: string | null,
defaultData: {[key: string]: string},
): React.Node {
let params;
if (initialRoute != null) if (initialRoute != null)
params = {data: defaultData, nextScreen: initialRoute, shouldOpen: true}; params = {data: defaultData, nextScreen: initialRoute, shouldOpen: true};
const {colors} = useTheme(); const {colors} = useTheme();
return ( return (
<HomeStack.Navigator <HomeStack.Navigator
initialRouteName={"index"} initialRouteName="index"
headerMode={"screen"} headerMode="screen"
screenOptions={defaultScreenOptions} screenOptions={defaultScreenOptions}>
>
{createCollapsibleStack( {createCollapsibleStack(
<HomeStack.Screen <HomeStack.Screen
name="index" name="index"
@ -131,113 +142,123 @@ function HomeStackComponent(initialRoute: string | null, defaultData: { [key: st
headerStyle: { headerStyle: {
backgroundColor: colors.surface, backgroundColor: colors.surface,
}, },
headerTitle: () => headerTitle: (): React.Node => (
<View style={{flexDirection: "row"}}> <View style={{flexDirection: 'row'}}>
<Mascot <Mascot
style={{ style={{
width: 50 width: 50,
}} }}
emotion={MASCOT_STYLE.RANDOM} emotion={MASCOT_STYLE.RANDOM}
animated={true} animated
entryAnimation={{ entryAnimation={{
animation: "bounceIn", animation: 'bounceIn',
duration: 1000 duration: 1000,
}} }}
loopAnimation={{ loopAnimation={{
animation: "pulse", animation: 'pulse',
duration: 2000, duration: 2000,
iterationCount: "infinite" iterationCount: 'infinite',
}} }}
/> />
<Title style={{ <Title
style={{
marginLeft: 10, marginLeft: 10,
marginTop: "auto", marginTop: 'auto',
marginBottom: "auto", marginBottom: 'auto',
}}>{i18n.t('screens.home.title')}</Title> }}>
{i18n.t('screens.home.title')}
</Title>
</View> </View>
),
}} }}
initialParams={params} initialParams={params}
/>, />,
{ {
collapsedColor: colors.surface, collapsedColor: colors.surface,
useNativeDriver: true, useNativeDriver: true,
} },
)} )}
<HomeStack.Screen <HomeStack.Screen
name="scanner" name="scanner"
component={ScannerScreen} component={ScannerScreen}
options={{title: i18n.t('screens.scanner.title'),}} options={{title: i18n.t('screens.scanner.title')}}
/> />
{createScreenCollapsibleStack( {createScreenCollapsibleStack(
"club-information", 'club-information',
HomeStack, HomeStack,
ClubDisplayScreen, ClubDisplayScreen,
i18n.t('screens.clubs.details'))} i18n.t('screens.clubs.details'),
)}
{createScreenCollapsibleStack( {createScreenCollapsibleStack(
"feed-information", 'feed-information',
HomeStack, HomeStack,
FeedItemScreen, FeedItemScreen,
i18n.t('screens.home.feed'))} i18n.t('screens.home.feed'),
)}
{createScreenCollapsibleStack( {createScreenCollapsibleStack(
"planning-information", 'planning-information',
HomeStack, HomeStack,
PlanningDisplayScreen, PlanningDisplayScreen,
i18n.t('screens.planning.eventDetails'))} i18n.t('screens.planning.eventDetails'),
)}
</HomeStack.Navigator> </HomeStack.Navigator>
); );
} }
const PlanexStack = createStackNavigator(); const PlanexStack = createStackNavigator();
function PlanexStackComponent() { function PlanexStackComponent(): React.Node {
return ( return (
<PlanexStack.Navigator <PlanexStack.Navigator
initialRouteName="index" initialRouteName="index"
headerMode={"screen"} headerMode="screen"
screenOptions={defaultScreenOptions} screenOptions={defaultScreenOptions}>
>
{getWebsiteStack( {getWebsiteStack(
"index", 'index',
PlanexStack, PlanexStack,
PlanexScreen, PlanexScreen,
i18n.t("screens.planex.title"))} i18n.t('screens.planex.title'),
)}
{createScreenCollapsibleStack( {createScreenCollapsibleStack(
"group-select", 'group-select',
PlanexStack, PlanexStack,
GroupSelectionScreen, GroupSelectionScreen,
"")} '',
)}
</PlanexStack.Navigator> </PlanexStack.Navigator>
); );
} }
const Tab = createBottomTabNavigator(); const Tab = createBottomTabNavigator();
type Props = { type PropsType = {
defaultHomeRoute: string | null, defaultHomeRoute: string | null,
defaultHomeData: { [key: string]: any } defaultHomeData: {[key: string]: string},
} };
export default class TabNavigator extends React.Component<Props> { export default class TabNavigator extends React.Component<PropsType> {
createHomeStackComponent: () => React.Node;
createHomeStackComponent: () => HomeStackComponent;
defaultRoute: string; defaultRoute: string;
constructor(props) { constructor(props: PropsType) {
super(props); super(props);
if (props.defaultHomeRoute != null) if (props.defaultHomeRoute != null) this.defaultRoute = 'home';
this.defaultRoute = 'home';
else else
this.defaultRoute = AsyncStorageManager.getString(AsyncStorageManager.PREFERENCES.defaultStartScreen.key).toLowerCase(); this.defaultRoute = AsyncStorageManager.getString(
this.createHomeStackComponent = () => HomeStackComponent(props.defaultHomeRoute, props.defaultHomeData); AsyncStorageManager.PREFERENCES.defaultStartScreen.key,
).toLowerCase();
this.createHomeStackComponent = (): React.Node =>
HomeStackComponent(props.defaultHomeRoute, props.defaultHomeData);
} }
render() { render(): React.Node {
return ( return (
<Tab.Navigator <Tab.Navigator
initialRouteName={this.defaultRoute} initialRouteName={this.defaultRoute}
tabBar={props => <CustomTabBar {...props} />} // eslint-disable-next-line react/jsx-props-no-spreading
> tabBar={(props: {...}): React.Node => <CustomTabBar {...props} />}>
<Tab.Screen <Tab.Screen
name="services" name="services"
option option
@ -263,7 +284,7 @@ export default class TabNavigator extends React.Component<Props> {
<Tab.Screen <Tab.Screen
name="planex" name="planex"
component={PlanexStackComponent} component={PlanexStackComponent}
options={{title: i18n.t("screens.planex.title")}} options={{title: i18n.t('screens.planex.title')}}
/> />
</Tab.Navigator> </Tab.Navigator>
); );

View file

@ -1,73 +1,75 @@
// @flow // @flow
import * as React from 'react'; import * as React from 'react';
import packageJson from '../../../package';
import {List} from 'react-native-paper'; import {List} from 'react-native-paper';
import {StackNavigationProp} from "@react-navigation/stack"; import {View} from 'react-native-animatable';
import CollapsibleFlatList from "../../components/Collapsible/CollapsibleFlatList"; import CollapsibleFlatList from '../../components/Collapsible/CollapsibleFlatList';
import {View} from "react-native-animatable"; import packageJson from '../../../package.json';
type listItem = { type ListItemType = {
name: string, name: string,
version: string version: string,
}; };
/** /**
* Generates the dependencies list from the raw json * Generates the dependencies list from the raw json
* *
* @param object The raw json * @param object The raw json
* @return {Array<listItem>} * @return {Array<ListItemType>}
*/ */
function generateListFromObject(object: { [key: string]: string }): Array<listItem> { function generateListFromObject(object: {
let list = []; [key: string]: string,
let keys = Object.keys(object); }): Array<ListItemType> {
let values = Object.values(object); const list = [];
for (let i = 0; i < keys.length; i++) { const keys = Object.keys(object);
list.push({name: keys[i], version: values[i]}); keys.forEach((key: string) => {
} list.push({name: key, version: object[key]});
//$FlowFixMe });
return list; return list;
} }
type Props = {
navigation: StackNavigationProp,
}
const LIST_ITEM_HEIGHT = 64; const LIST_ITEM_HEIGHT = 64;
/** /**
* Class defining a screen showing the list of libraries used by the app, taken from package.json * 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() { constructor() {
super(); super();
this.data = generateListFromObject(packageJson.dependencies); this.data = generateListFromObject(packageJson.dependencies);
} }
keyExtractor = (item: listItem) => item.name; keyExtractor = (item: ListItemType): string => item.name;
renderItem = ({item}: { item: listItem }) => getRenderItem = ({item}: {item: ListItemType}): React.Node => (
<List.Item <List.Item
title={item.name} title={item.name}
description={item.version.replace('^', '').replace('~', '')} description={item.version.replace('^', '').replace('~', '')}
style={{height: LIST_ITEM_HEIGHT}} style={{height: LIST_ITEM_HEIGHT}}
/>; />
);
itemLayout = (data: any, index: number) => ({length: LIST_ITEM_HEIGHT, offset: LIST_ITEM_HEIGHT * index, index}); getItemLayout = (
data: ListItemType,
index: number,
): {length: number, offset: number, index: number} => ({
length: LIST_ITEM_HEIGHT,
offset: LIST_ITEM_HEIGHT * index,
index,
});
render() { render(): React.Node {
return ( return (
<View> <View>
<CollapsibleFlatList <CollapsibleFlatList
data={this.data} data={this.data}
keyExtractor={this.keyExtractor} keyExtractor={this.keyExtractor}
renderItem={this.renderItem} renderItem={this.getRenderItem}
// Performance props, see https://reactnative.dev/docs/optimizing-flatlist-configuration // Performance props, see https://reactnative.dev/docs/optimizing-flatlist-configuration
removeClippedSubviews={true} removeClippedSubviews
getItemLayout={this.itemLayout} getItemLayout={this.getItemLayout}
/> />
</View> </View>
); );

View file

@ -1,43 +1,50 @@
// @flow // @flow
import * as React from 'react'; import * as React from 'react';
import {FlatList, Linking, Platform, View} from 'react-native'; import {FlatList, Linking, Platform} from 'react-native';
import i18n from "i18n-js"; import i18n from 'i18n-js';
import {Avatar, Card, List, Title, withTheme} from 'react-native-paper'; import {Avatar, Card, List, Title, withTheme} from 'react-native-paper';
import packageJson from "../../../package.json"; import {StackNavigationProp} from '@react-navigation/stack';
import {StackNavigationProp} from "@react-navigation/stack"; import packageJson from '../../../package.json';
import CollapsibleFlatList from "../../components/Collapsible/CollapsibleFlatList"; import CollapsibleFlatList from '../../components/Collapsible/CollapsibleFlatList';
import APP_LOGO from '../../../assets/android.icon.png';
type ListItem = { type ListItemType = {
onPressCallback: () => void, onPressCallback: () => void,
icon: string, icon: string,
text: string, text: string,
showChevron: boolean showChevron: boolean,
}; };
const links = { const links = {
appstore: 'https://apps.apple.com/us/app/campus-amicale-insat/id1477722148', appstore: 'https://apps.apple.com/us/app/campus-amicale-insat/id1477722148',
playstore: 'https://play.google.com/store/apps/details?id=fr.amicaleinsat.application', playstore:
git: 'https://git.etud.insa-toulouse.fr/vergnet/application-amicale/src/branch/master/README.md', 'https://play.google.com/store/apps/details?id=fr.amicaleinsat.application',
changelog: 'https://git.etud.insa-toulouse.fr/vergnet/application-amicale/src/branch/master/Changelog.md', git:
license: 'https://git.etud.insa-toulouse.fr/vergnet/application-amicale/src/branch/master/LICENSE', 'https://git.etud.insa-toulouse.fr/vergnet/application-amicale/src/branch/master/README.md',
authorMail: "mailto:vergnet@etud.insa-toulouse.fr?" + changelog:
"subject=" + 'https://git.etud.insa-toulouse.fr/vergnet/application-amicale/src/branch/master/Changelog.md',
"Application Amicale INSA Toulouse" + license:
"&body=" + 'https://git.etud.insa-toulouse.fr/vergnet/application-amicale/src/branch/master/LICENSE',
"Coucou !\n\n", 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/', authorLinkedin: 'https://www.linkedin.com/in/arnaud-vergnet-434ba5179/',
yohanMail: "mailto:ysimard@etud.insa-toulouse.fr?" + yohanMail:
"subject=" + 'mailto:ysimard@etud.insa-toulouse.fr?' +
"Application Amicale INSA Toulouse" + 'subject=' +
"&body=" + 'Application Amicale INSA Toulouse' +
"Coucou !\n\n", '&body=' +
'Coucou !\n\n',
yohanLinkedin: 'https://www.linkedin.com/in/yohan-simard', yohanLinkedin: 'https://www.linkedin.com/in/yohan-simard',
react: 'https://facebook.github.io/react-native/', react: 'https://facebook.github.io/react-native/',
meme: "https://www.youtube.com/watch?v=dQw4w9WgXcQ" meme: 'https://www.youtube.com/watch?v=dQw4w9WgXcQ',
}; };
type Props = { type PropsType = {
navigation: StackNavigationProp, navigation: StackNavigationProp,
}; };
@ -45,113 +52,145 @@ type Props = {
* Opens a link in the device's browser * Opens a link in the device's browser
* @param link The link to open * @param link The link to open
*/ */
function openWebLink(link) { function openWebLink(link: string) {
Linking.openURL(link).catch((err) => console.error('Error opening link', err)); Linking.openURL(link);
} }
/** /**
* Class defining an about screen. This screen shows the user information about the app and it's author. * 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 * Data to be displayed in the app card
*/ */
appData = [ appData = [
{ {
onPressCallback: () => openWebLink(Platform.OS === "ios" ? links.appstore : links.playstore), onPressCallback: () => {
icon: Platform.OS === "ios" ? 'apple' : 'google-play', openWebLink(Platform.OS === 'ios' ? links.appstore : links.playstore);
text: Platform.OS === "ios" ? i18n.t('screens.about.appstore') : i18n.t('screens.about.playstore'), },
showChevron: true 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"), onPressCallback: () => {
const {navigation} = this.props;
navigation.navigate('feedback');
},
icon: 'bug', icon: 'bug',
text: i18n.t("screens.feedback.homeButtonTitle"), text: i18n.t('screens.feedback.homeButtonTitle'),
showChevron: true showChevron: true,
}, },
{ {
onPressCallback: () => openWebLink(links.git), onPressCallback: () => {
openWebLink(links.git);
},
icon: 'git', icon: 'git',
text: 'Git', text: 'Git',
showChevron: true showChevron: true,
}, },
{ {
onPressCallback: () => openWebLink(links.changelog), onPressCallback: () => {
openWebLink(links.changelog);
},
icon: 'refresh', icon: 'refresh',
text: i18n.t('screens.about.changelog'), text: i18n.t('screens.about.changelog'),
showChevron: true showChevron: true,
}, },
{ {
onPressCallback: () => openWebLink(links.license), onPressCallback: () => {
openWebLink(links.license);
},
icon: 'file-document', icon: 'file-document',
text: i18n.t('screens.about.license'), text: i18n.t('screens.about.license'),
showChevron: true showChevron: true,
}, },
]; ];
/** /**
* Data to be displayed in the author card * Data to be displayed in the author card
*/ */
authorData = [ authorData = [
{ {
onPressCallback: () => openWebLink(links.meme), onPressCallback: () => {
openWebLink(links.meme);
},
icon: 'account-circle', icon: 'account-circle',
text: 'Arnaud VERGNET', text: 'Arnaud VERGNET',
showChevron: false showChevron: false,
}, },
{ {
onPressCallback: () => openWebLink(links.authorMail), onPressCallback: () => {
openWebLink(links.authorMail);
},
icon: 'email', icon: 'email',
text: i18n.t('screens.about.authorMail'), text: i18n.t('screens.about.authorMail'),
showChevron: true showChevron: true,
}, },
{ {
onPressCallback: () => openWebLink(links.authorLinkedin), onPressCallback: () => {
openWebLink(links.authorLinkedin);
},
icon: 'linkedin', icon: 'linkedin',
text: 'Linkedin', text: 'Linkedin',
showChevron: true showChevron: true,
}, },
]; ];
/** /**
* Data to be displayed in the additional developer card * Data to be displayed in the additional developer card
*/ */
additionalDevData = [ additionalDevData = [
{ {
onPressCallback: () => console.log('Meme this'), onPressCallback: () => {},
icon: 'account', icon: 'account',
text: 'Yohan SIMARD', text: 'Yohan SIMARD',
showChevron: false showChevron: false,
}, },
{ {
onPressCallback: () => openWebLink(links.yohanMail), onPressCallback: () => {
openWebLink(links.yohanMail);
},
icon: 'email', icon: 'email',
text: i18n.t('screens.about.authorMail'), text: i18n.t('screens.about.authorMail'),
showChevron: true showChevron: true,
}, },
{ {
onPressCallback: () => openWebLink(links.yohanLinkedin), onPressCallback: () => {
openWebLink(links.yohanLinkedin);
},
icon: 'linkedin', icon: 'linkedin',
text: 'Linkedin', text: 'Linkedin',
showChevron: true showChevron: true,
}, },
]; ];
/** /**
* Data to be displayed in the technologies card * Data to be displayed in the technologies card
*/ */
technoData = [ technoData = [
{ {
onPressCallback: () => openWebLink(links.react), onPressCallback: () => {
openWebLink(links.react);
},
icon: 'react', icon: 'react',
text: i18n.t('screens.about.reactNative'), text: i18n.t('screens.about.reactNative'),
showChevron: true showChevron: true,
}, },
{ {
onPressCallback: () => this.props.navigation.navigate('dependencies'), onPressCallback: () => {
const {navigation} = this.props;
navigation.navigate('dependencies');
},
icon: 'developer-board', icon: 'developer-board',
text: i18n.t('screens.about.libs'), text: i18n.t('screens.about.libs'),
showChevron: true showChevron: true,
}, },
]; ];
/** /**
* Order of information cards * Order of information cards
*/ */
@ -167,44 +206,25 @@ class AboutScreen extends React.Component<Props> {
}, },
]; ];
/**
* Gets the app icon
*
* @param props
* @return {*}
*/
getAppIcon(props) {
return (
<Avatar.Image
{...props}
source={require('../../../assets/android.icon.png')}
style={{backgroundColor: 'transparent'}}
/>
);
}
/**
* 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 the app card showing information and links about the app. * Gets the app card showing information and links about the app.
* *
* @return {*} * @return {*}
*/ */
getAppCard() { getAppCard(): React.Node {
return ( return (
<Card style={{marginBottom: 10}}> <Card style={{marginBottom: 10}}>
<Card.Title <Card.Title
title={"Campus"} title="Campus"
subtitle={packageJson.version} subtitle={packageJson.version}
left={this.getAppIcon}/> left={({size}: {size: number}): React.Node => (
<Avatar.Image
size={size}
source={APP_LOGO}
style={{backgroundColor: 'transparent'}}
/>
)}
/>
<Card.Content> <Card.Content>
<FlatList <FlatList
data={this.appData} data={this.appData}
@ -221,25 +241,28 @@ class AboutScreen extends React.Component<Props> {
* *
* @return {*} * @return {*}
*/ */
getTeamCard() { getTeamCard(): React.Node {
return ( return (
<Card style={{marginBottom: 10}}> <Card style={{marginBottom: 10}}>
<Card.Title <Card.Title
title={i18n.t('screens.about.team')} title={i18n.t('screens.about.team')}
left={(props) => <Avatar.Icon {...props} icon={'account-multiple'}/>}/> left={({size, color}: {size: number, color: string}): React.Node => (
<Avatar.Icon size={size} color={color} icon="account-multiple" />
)}
/>
<Card.Content> <Card.Content>
<Title>{i18n.t('screens.about.author')}</Title> <Title>{i18n.t('screens.about.author')}</Title>
<FlatList <FlatList
data={this.authorData} data={this.authorData}
keyExtractor={this.keyExtractor} keyExtractor={this.keyExtractor}
listKey={"1"} listKey="1"
renderItem={this.getCardItem} renderItem={this.getCardItem}
/> />
<Title>{i18n.t('screens.about.additionalDev')}</Title> <Title>{i18n.t('screens.about.additionalDev')}</Title>
<FlatList <FlatList
data={this.additionalDevData} data={this.additionalDevData}
keyExtractor={this.keyExtractor} keyExtractor={this.keyExtractor}
listKey={"2"} listKey="2"
renderItem={this.getCardItem} renderItem={this.getCardItem}
/> />
</Card.Content> </Card.Content>
@ -252,7 +275,7 @@ class AboutScreen extends React.Component<Props> {
* *
* @return {*} * @return {*}
*/ */
getTechnoCard() { getTechnoCard(): React.Node {
return ( return (
<Card style={{marginBottom: 10}}> <Card style={{marginBottom: 10}}>
<Card.Content> <Card.Content>
@ -273,10 +296,14 @@ class AboutScreen extends React.Component<Props> {
* @param props * @param props
* @return {*} * @return {*}
*/ */
getChevronIcon(props) { static getChevronIcon({
return ( size,
<List.Icon {...props} icon={'chevron-right'}/> color,
); }: {
size: number,
color: string,
}): React.Node {
return <List.Icon size={size} color={color} icon="chevron-right" />;
} }
/** /**
@ -286,10 +313,11 @@ class AboutScreen extends React.Component<Props> {
* @param props * @param props
* @return {*} * @return {*}
*/ */
getItemIcon(item: ListItem, props) { static getItemIcon(
return ( item: ListItemType,
<List.Icon {...props} icon={item.icon}/> {size, color}: {size: number, color: string},
); ): React.Node {
return <List.Icon size={size} color={color} icon={item.icon} />;
} }
/** /**
@ -297,18 +325,19 @@ class AboutScreen extends React.Component<Props> {
* *
* @returns {*} * @returns {*}
*/ */
getCardItem = ({item}: { item: ListItem }) => { getCardItem = ({item}: {item: ListItemType}): React.Node => {
const getItemIcon = this.getItemIcon.bind(this, item); const getItemIcon = (props: {size: number, color: string}): React.Node =>
AboutScreen.getItemIcon(item, props);
if (item.showChevron) { if (item.showChevron) {
return ( return (
<List.Item <List.Item
title={item.text} title={item.text}
left={getItemIcon} left={getItemIcon}
right={this.getChevronIcon} right={AboutScreen.getChevronIcon}
onPress={item.onPressCallback} onPress={item.onPressCallback}
/> />
); );
} else { }
return ( return (
<List.Item <List.Item
title={item.text} title={item.text}
@ -316,7 +345,6 @@ class AboutScreen extends React.Component<Props> {
onPress={item.onPressCallback} onPress={item.onPressCallback}
/> />
); );
}
}; };
/** /**
@ -325,7 +353,7 @@ class AboutScreen extends React.Component<Props> {
* @param item The item to show * @param item The item to show
* @return {*} * @return {*}
*/ */
getMainCard = ({item}: { item: { id: string } }) => { getMainCard = ({item}: {item: {id: string}}): React.Node => {
switch (item.id) { switch (item.id) {
case 'app': case 'app':
return this.getAppCard(); return this.getAppCard();
@ -333,11 +361,20 @@ class AboutScreen extends React.Component<Props> {
return this.getTeamCard(); return this.getTeamCard();
case 'techno': case 'techno':
return this.getTechnoCard(); return this.getTechnoCard();
default:
return null;
} }
return <View/>;
}; };
render() { /**
* 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;
render(): React.Node {
return ( return (
<CollapsibleFlatList <CollapsibleFlatList
style={{padding: 5}} style={{padding: 5}}

View file

@ -1,38 +1,43 @@
// @flow // @flow
import * as React from 'react'; import * as React from 'react';
import {View} from "react-native"; import {View} from 'react-native';
import AsyncStorageManager from "../../managers/AsyncStorageManager"; import {
import CustomModal from "../../components/Overrides/CustomModal"; Button,
import {Button, List, Subheading, TextInput, Title, withTheme} from 'react-native-paper'; List,
import {StackNavigationProp} from "@react-navigation/stack"; Subheading,
import {Modalize} from "react-native-modalize"; TextInput,
import type {CustomTheme} from "../../managers/ThemeManager"; Title,
import CollapsibleFlatList from "../../components/Collapsible/CollapsibleFlatList"; 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 = { type PreferenceItemType = {
key: string, key: string,
default: string, default: string,
current: string, current: string,
}
type Props = {
navigation: StackNavigationProp,
theme: CustomTheme
}; };
type State = { type PropsType = {
modalCurrentDisplayItem: PreferenceItem, theme: CustomThemeType,
currentPreferences: Array<PreferenceItem>, };
}
type StateType = {
modalCurrentDisplayItem: PreferenceItemType,
currentPreferences: Array<PreferenceItemType>,
};
/** /**
* Class defining the Debug screen. * Class defining the Debug screen.
* This screen allows the user to get and modify information on the app/device. * 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;
/** /**
@ -40,87 +45,126 @@ class DebugScreen extends React.Component<Props, State> {
* *
* @param props * @param props
*/ */
constructor(props) { constructor(props: PropsType) {
super(props); super(props);
this.modalInputValue = ""; this.modalInputValue = '';
let currentPreferences : Array<PreferenceItem> = []; const currentPreferences: Array<PreferenceItemType> = [];
Object.values(AsyncStorageManager.PREFERENCES).map((object: any) => { // eslint-disable-next-line flowtype/no-weak-types
let newObject: PreferenceItem = {...object}; Object.values(AsyncStorageManager.PREFERENCES).forEach((object: any) => {
const newObject: PreferenceItemType = {...object};
newObject.current = AsyncStorageManager.getString(newObject.key); newObject.current = AsyncStorageManager.getString(newObject.key);
currentPreferences.push(newObject); currentPreferences.push(newObject);
}); });
this.state = { this.state = {
modalCurrentDisplayItem: {}, modalCurrentDisplayItem: {},
currentPreferences: 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 * Gets the edit modal content
* *
* @return {*} * @return {*}
*/ */
getModalContent() { getModalContent(): React.Node {
const {props, state} = this;
return ( return (
<View style={{ <View
style={{
flex: 1, flex: 1,
padding: 20 padding: 20,
}}> }}>
<Title>{this.state.modalCurrentDisplayItem.key}</Title> <Title>{state.modalCurrentDisplayItem.key}</Title>
<Subheading>Default: {this.state.modalCurrentDisplayItem.default}</Subheading> <Subheading>
<Subheading>Current: {this.state.modalCurrentDisplayItem.current}</Subheading> Default: {state.modalCurrentDisplayItem.default}
</Subheading>
<Subheading>
Current: {state.modalCurrentDisplayItem.current}
</Subheading>
<TextInput <TextInput
label='New Value' label="New Value"
onChangeText={(text) => this.modalInputValue = text} onChangeText={(text: string) => {
this.modalInputValue = text;
}}
/> />
<View style={{ <View
style={{
flexDirection: 'row', flexDirection: 'row',
marginTop: 10, marginTop: 10,
}}> }}>
<Button <Button
mode="contained" mode="contained"
dark={true} dark
color={this.props.theme.colors.success} color={props.theme.colors.success}
onPress={() => this.saveNewPrefs(this.state.modalCurrentDisplayItem.key, this.modalInputValue)}> onPress={() => {
this.saveNewPrefs(
state.modalCurrentDisplayItem.key,
this.modalInputValue,
);
}}>
Save new value Save new value
</Button> </Button>
<Button <Button
mode="contained" mode="contained"
dark={true} dark
color={this.props.theme.colors.danger} color={props.theme.colors.danger}
onPress={() => this.saveNewPrefs(this.state.modalCurrentDisplayItem.key, this.state.modalCurrentDisplayItem.default)}> onPress={() => {
this.saveNewPrefs(
state.modalCurrentDisplayItem.key,
state.modalCurrentDisplayItem.default,
);
}}>
Reset to default Reset to default
</Button> </Button>
</View> </View>
</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 * Finds the index of the given key in the preferences array
* *
* @param key THe key to find the index of * @param key THe key to find the index of
* @returns {number} * @returns {number}
*/ */
findIndexOfKey(key: string) { findIndexOfKey(key: string): number {
const {currentPreferences} = this.state;
let index = -1; let index = -1;
for (let i = 0; i < this.state.currentPreferences.length; i++) { for (let i = 0; i < currentPreferences.length; i += 1) {
if (this.state.currentPreferences[i].key === key) { if (currentPreferences[i].key === key) {
index = i; index = i;
break; break;
} }
@ -135,8 +179,10 @@ class DebugScreen extends React.Component<Props, State> {
* @param value The pref value * @param value The pref value
*/ */
saveNewPrefs(key: string, value: string) { saveNewPrefs(key: string, value: string) {
this.setState((prevState) => { this.setState((prevState: StateType): {
let currentPreferences = [...prevState.currentPreferences]; currentPreferences: Array<PreferenceItemType>,
} => {
const currentPreferences = [...prevState.currentPreferences];
currentPreferences[this.findIndexOfKey(key)].current = value; currentPreferences[this.findIndexOfKey(key)].current = value;
return {currentPreferences}; return {currentPreferences};
}); });
@ -144,36 +190,18 @@ class DebugScreen extends React.Component<Props, State> {
this.modalRef.close(); this.modalRef.close();
} }
/** render(): React.Node {
* Callback used when receiving the modal ref const {state} = this;
*
* @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)}
/>
);
};
render() {
return ( return (
<View> <View>
<CustomModal onRef={this.onModalRef}> <CustomModal onRef={this.onModalRef}>
{this.getModalContent()} {this.getModalContent()}
</CustomModal> </CustomModal>
{/*$FlowFixMe*/} {/* $FlowFixMe */}
<CollapsibleFlatList <CollapsibleFlatList
data={this.state.currentPreferences} data={state.currentPreferences}
extraData={this.state.currentPreferences} extraData={state.currentPreferences}
renderItem={this.renderItem} renderItem={this.getRenderItem}
/> />
</View> </View>
); );

View file

@ -4,121 +4,141 @@ import * as React from 'react';
import {FlatList, Image, Linking, View} from 'react-native'; import {FlatList, Image, Linking, View} from 'react-native';
import {Card, List, Text, withTheme} from 'react-native-paper'; import {Card, List, Text, withTheme} from 'react-native-paper';
import i18n from 'i18n-js'; import i18n from 'i18n-js';
import type {MaterialCommunityIconsGlyphs} from "react-native-vector-icons/MaterialCommunityIcons"; import type {MaterialCommunityIconsGlyphs} from 'react-native-vector-icons/MaterialCommunityIcons';
import CollapsibleFlatList from "../../components/Collapsible/CollapsibleFlatList"; import CollapsibleFlatList from '../../components/Collapsible/CollapsibleFlatList';
import AMICALE_LOGO from '../../../assets/amicale.png';
type Props = { type DatasetItemType = {
};
type DatasetItem = {
name: string, name: string,
email: string, email: string,
icon: MaterialCommunityIconsGlyphs, icon: MaterialCommunityIconsGlyphs,
} };
/** /**
* Class defining a planning event information page. * Class defining a planning event information page.
*/ */
class AmicaleContactScreen extends React.Component<Props> { class AmicaleContactScreen extends React.Component<null> {
// Dataset containing information about contacts // Dataset containing information about contacts
CONTACT_DATASET: Array<DatasetItem>; CONTACT_DATASET: Array<DatasetItemType>;
constructor(props: Props) { constructor() {
super(props); super();
this.CONTACT_DATASET = [ this.CONTACT_DATASET = [
{ {
name: i18n.t("screens.amicaleAbout.roles.interSchools"), name: i18n.t('screens.amicaleAbout.roles.interSchools'),
email: "inter.ecoles@amicale-insat.fr", email: 'inter.ecoles@amicale-insat.fr',
icon: "share-variant" icon: 'share-variant',
}, },
{ {
name: i18n.t("screens.amicaleAbout.roles.culture"), name: i18n.t('screens.amicaleAbout.roles.culture'),
email: "culture@amicale-insat.fr", email: 'culture@amicale-insat.fr',
icon: "book" icon: 'book',
}, },
{ {
name: i18n.t("screens.amicaleAbout.roles.animation"), name: i18n.t('screens.amicaleAbout.roles.animation'),
email: "animation@amicale-insat.fr", email: 'animation@amicale-insat.fr',
icon: "emoticon" icon: 'emoticon',
}, },
{ {
name: i18n.t("screens.amicaleAbout.roles.clubs"), name: i18n.t('screens.amicaleAbout.roles.clubs'),
email: "clubs@amicale-insat.fr", email: 'clubs@amicale-insat.fr',
icon: "account-group" icon: 'account-group',
}, },
{ {
name: i18n.t("screens.amicaleAbout.roles.event"), name: i18n.t('screens.amicaleAbout.roles.event'),
email: "evenements@amicale-insat.fr", email: 'evenements@amicale-insat.fr',
icon: "calendar-range" icon: 'calendar-range',
}, },
{ {
name: i18n.t("screens.amicaleAbout.roles.tech"), name: i18n.t('screens.amicaleAbout.roles.tech'),
email: "technique@amicale-insat.fr", email: 'technique@amicale-insat.fr',
icon: "cog" icon: 'cog',
}, },
{ {
name: i18n.t("screens.amicaleAbout.roles.communication"), name: i18n.t('screens.amicaleAbout.roles.communication'),
email: "amicale@amicale-insat.fr", email: 'amicale@amicale-insat.fr',
icon: "comment-account" icon: 'comment-account',
}, },
{ {
name: i18n.t("screens.amicaleAbout.roles.intraSchools"), name: i18n.t('screens.amicaleAbout.roles.intraSchools'),
email: "intra.ecoles@amicale-insat.fr", email: 'intra.ecoles@amicale-insat.fr',
icon: "school" icon: 'school',
}, },
{ {
name: i18n.t("screens.amicaleAbout.roles.publicRelations"), name: i18n.t('screens.amicaleAbout.roles.publicRelations'),
email: "rp@amicale-insat.fr", email: 'rp@amicale-insat.fr',
icon: "account-tie" icon: 'account-tie',
}, },
]; ];
} }
keyExtractor = (item: DatasetItem) => item.email; keyExtractor = (item: DatasetItemType): string => item.email;
getChevronIcon = (props) => <List.Icon {...props} icon={'chevron-right'}/>; getChevronIcon = ({
size,
color,
}: {
size: number,
color: string,
}): React.Node => (
<List.Icon size={size} color={color} icon="chevron-right" />
);
renderItem = ({item}: { item: DatasetItem }) => { getRenderItem = ({item}: {item: DatasetItemType}): React.Node => {
const onPress = () => Linking.openURL('mailto:' + item.email); const onPress = () => {
return <List.Item Linking.openURL(`mailto:${item.email}`);
};
return (
<List.Item
title={item.name} title={item.name}
description={item.email} description={item.email}
left={(props) => <List.Icon {...props} icon={item.icon}/>} left={({size, color}: {size: number, color: string}): React.Node => (
<List.Icon size={size} color={color} icon={item.icon} />
)}
right={this.getChevronIcon} right={this.getChevronIcon}
onPress={onPress} onPress={onPress}
/> />
);
}; };
getScreen = () => { getScreen = (): React.Node => {
return ( return (
<View> <View>
<View style={{ <View
style={{
width: '100%', width: '100%',
height: 100, height: 100,
marginTop: 20, marginTop: 20,
marginBottom: 20, marginBottom: 20,
justifyContent: 'center', justifyContent: 'center',
alignItems: 'center' alignItems: 'center',
}}> }}>
<Image <Image
source={require('../../../assets/amicale.png')} source={AMICALE_LOGO}
style={{flex: 1, resizeMode: "contain"}} style={{flex: 1, resizeMode: 'contain'}}
resizeMode="contain"/> resizeMode="contain"
/>
</View> </View>
<Card style={{margin: 5}}> <Card style={{margin: 5}}>
<Card.Title <Card.Title
title={i18n.t("screens.amicaleAbout.title")} title={i18n.t('screens.amicaleAbout.title')}
subtitle={i18n.t("screens.amicaleAbout.subtitle")} subtitle={i18n.t('screens.amicaleAbout.subtitle')}
left={props => <List.Icon {...props} icon={'information'}/>} left={({
size,
color,
}: {
size: number,
color: string,
}): React.Node => (
<List.Icon size={size} color={color} icon="information" />
)}
/> />
<Card.Content> <Card.Content>
<Text>{i18n.t("screens.amicaleAbout.message")}</Text> <Text>{i18n.t('screens.amicaleAbout.message')}</Text>
{/*$FlowFixMe*/}
<FlatList <FlatList
data={this.CONTACT_DATASET} data={this.CONTACT_DATASET}
keyExtractor={this.keyExtractor} keyExtractor={this.keyExtractor}
renderItem={this.renderItem} renderItem={this.getRenderItem}
/> />
</Card.Content> </Card.Content>
</Card> </Card>
@ -126,12 +146,12 @@ class AmicaleContactScreen extends React.Component<Props> {
); );
}; };
render() { render(): React.Node {
return ( return (
<CollapsibleFlatList <CollapsibleFlatList
data={[{key: "1"}]} data={[{key: '1'}]}
renderItem={this.getScreen} renderItem={this.getScreen}
hasTab={true} hasTab
/> />
); );
} }

View file

@ -17,7 +17,7 @@ import AuthenticatedScreen from '../../../components/Amicale/AuthenticatedScreen
import CustomHTML from '../../../components/Overrides/CustomHTML'; import CustomHTML from '../../../components/Overrides/CustomHTML';
import CustomTabBar from '../../../components/Tabbar/CustomTabBar'; import CustomTabBar from '../../../components/Tabbar/CustomTabBar';
import type {ClubCategoryType, ClubType} from './ClubListScreen'; import type {ClubCategoryType, ClubType} from './ClubListScreen';
import type {CustomTheme} from '../../../managers/ThemeManager'; import type {CustomThemeType} from '../../../managers/ThemeManager';
import {ERROR_TYPE} from '../../../utils/WebData'; import {ERROR_TYPE} from '../../../utils/WebData';
import CollapsibleScrollView from '../../../components/Collapsible/CollapsibleScrollView'; import CollapsibleScrollView from '../../../components/Collapsible/CollapsibleScrollView';
import type {ApiGenericDataType} from '../../../utils/WebData'; import type {ApiGenericDataType} from '../../../utils/WebData';
@ -32,7 +32,7 @@ type PropsType = {
}, },
... ...
}, },
theme: CustomTheme, theme: CustomThemeType,
}; };
const AMICALE_MAIL = 'clubs@amicale-insat.fr'; const AMICALE_MAIL = 'clubs@amicale-insat.fr';

View file

@ -11,7 +11,7 @@ import {
} from 'react-native-paper'; } from 'react-native-paper';
import {View} from 'react-native'; import {View} from 'react-native';
import i18n from 'i18n-js'; import i18n from 'i18n-js';
import type {CustomTheme} from '../../../managers/ThemeManager'; import type {CustomThemeType} from '../../../managers/ThemeManager';
import type {DeviceType} from './EquipmentListScreen'; import type {DeviceType} from './EquipmentListScreen';
import {getRelativeDateString} from '../../../utils/EquipmentBooking'; import {getRelativeDateString} from '../../../utils/EquipmentBooking';
import CollapsibleScrollView from '../../../components/Collapsible/CollapsibleScrollView'; import CollapsibleScrollView from '../../../components/Collapsible/CollapsibleScrollView';
@ -23,7 +23,7 @@ type PropsType = {
dates: [string, string], dates: [string, string],
}, },
}, },
theme: CustomTheme, theme: CustomThemeType,
}; };
class EquipmentConfirmScreen extends React.Component<PropsType> { class EquipmentConfirmScreen extends React.Component<PropsType> {

View file

@ -15,7 +15,7 @@ import * as Animatable from 'react-native-animatable';
import i18n from 'i18n-js'; import i18n from 'i18n-js';
import {CalendarList} from 'react-native-calendars'; import {CalendarList} from 'react-native-calendars';
import type {DeviceType} from './EquipmentListScreen'; import type {DeviceType} from './EquipmentListScreen';
import type {CustomTheme} from '../../../managers/ThemeManager'; import type {CustomThemeType} from '../../../managers/ThemeManager';
import LoadingConfirmDialog from '../../../components/Dialogs/LoadingConfirmDialog'; import LoadingConfirmDialog from '../../../components/Dialogs/LoadingConfirmDialog';
import ErrorDialog from '../../../components/Dialogs/ErrorDialog'; import ErrorDialog from '../../../components/Dialogs/ErrorDialog';
import { import {
@ -36,7 +36,7 @@ type PropsType = {
item?: DeviceType, item?: DeviceType,
}, },
}, },
theme: CustomTheme, theme: CustomThemeType,
}; };
export type MarkedDatesObjectType = { export type MarkedDatesObjectType = {

View file

@ -1,27 +1,33 @@
// @flow // @flow
import * as React from 'react'; import * as React from 'react';
import {Image, KeyboardAvoidingView, StyleSheet, View} from "react-native"; import {Image, KeyboardAvoidingView, StyleSheet, View} from 'react-native';
import {Button, Card, HelperText, TextInput, withTheme} from 'react-native-paper'; import {
import ConnectionManager from "../../managers/ConnectionManager"; Button,
Card,
HelperText,
TextInput,
withTheme,
} from 'react-native-paper';
import i18n from 'i18n-js'; import i18n from 'i18n-js';
import ErrorDialog from "../../components/Dialogs/ErrorDialog"; import {StackNavigationProp} from '@react-navigation/stack';
import type {CustomTheme} from "../../managers/ThemeManager"; import LinearGradient from 'react-native-linear-gradient';
import AsyncStorageManager from "../../managers/AsyncStorageManager"; import ConnectionManager from '../../managers/ConnectionManager';
import {StackNavigationProp} from "@react-navigation/stack"; import ErrorDialog from '../../components/Dialogs/ErrorDialog';
import AvailableWebsites from "../../constants/AvailableWebsites"; import type {CustomThemeType} from '../../managers/ThemeManager';
import {MASCOT_STYLE} from "../../components/Mascot/Mascot"; import AsyncStorageManager from '../../managers/AsyncStorageManager';
import MascotPopup from "../../components/Mascot/MascotPopup"; import AvailableWebsites from '../../constants/AvailableWebsites';
import LinearGradient from "react-native-linear-gradient"; import {MASCOT_STYLE} from '../../components/Mascot/Mascot';
import CollapsibleScrollView from "../../components/Collapsible/CollapsibleScrollView"; import MascotPopup from '../../components/Mascot/MascotPopup';
import CollapsibleScrollView from '../../components/Collapsible/CollapsibleScrollView';
type Props = { type PropsType = {
navigation: StackNavigationProp, navigation: StackNavigationProp,
route: { params: { nextScreen: string } }, route: {params: {nextScreen: string}},
theme: CustomTheme theme: CustomThemeType,
} };
type State = { type StateType = {
email: string, email: string,
password: string, password: string,
isEmailValidated: boolean, isEmailValidated: boolean,
@ -30,17 +36,53 @@ type State = {
dialogVisible: boolean, dialogVisible: boolean,
dialogError: number, dialogError: number,
mascotDialogVisible: boolean, mascotDialogVisible: boolean,
} };
const ICON_AMICALE = require('../../../assets/amicale.png'); 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 = /^.+@.+\..+$/; const emailRegex = /^.+@.+\..+$/;
class LoginScreen extends React.Component<Props, State> { const styles = StyleSheet.create({
container: {
flex: 1,
},
card: {
marginTop: 'auto',
marginBottom: 'auto',
},
header: {
fontSize: 36,
marginBottom: 48,
},
textInput: {},
btnContainer: {
marginTop: 5,
marginBottom: 10,
},
});
state = { 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: '', email: '',
password: '', password: '',
isEmailValidated: false, isEmailValidated: false,
@ -48,139 +90,27 @@ class LoginScreen extends React.Component<Props, State> {
loading: false, loading: false,
dialogVisible: false, dialogVisible: false,
dialogError: 0, dialogError: 0,
mascotDialogVisible: AsyncStorageManager.getBool(AsyncStorageManager.PREFERENCES.loginShowBanner.key), 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 = () => { onScreenFocus = () => {
this.handleNavigationParams(); 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 * Navigates to the Amicale website screen with the reset password link as navigation parameters
*/ */
onResetPasswordClick = () => this.props.navigation.navigate("website", { onResetPasswordClick = () => {
const {navigation} = this.props;
navigation.navigate('website', {
host: AvailableWebsites.websites.AMICALE, host: AvailableWebsites.websites.AMICALE,
path: RESET_PASSWORD_PATH, path: RESET_PASSWORD_PATH,
title: i18n.t('screens.websites.amicale') 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. * Called when the user input changes in the email or password field.
@ -211,7 +141,7 @@ class LoginScreen extends React.Component<Props, State> {
onEmailSubmit = () => { onEmailSubmit = () => {
if (this.passwordInputRef.current != null) if (this.passwordInputRef.current != null)
this.passwordInputRef.current.focus(); this.passwordInputRef.current.focus();
} };
/** /**
* Called when the user clicks on login or finishes to type his password. * Called when the user clicks on login or finishes to type his password.
@ -221,9 +151,11 @@ class LoginScreen extends React.Component<Props, State> {
* *
*/ */
onSubmit = () => { onSubmit = () => {
const {email, password} = this.state;
if (this.shouldEnableLogin()) { if (this.shouldEnableLogin()) {
this.setState({loading: true}); this.setState({loading: true});
ConnectionManager.getInstance().connect(this.state.email, this.state.password) ConnectionManager.getInstance()
.connect(email, password)
.then(this.handleSuccess) .then(this.handleSuccess)
.catch(this.showErrorDialog) .catch(this.showErrorDialog)
.finally(() => { .finally(() => {
@ -237,53 +169,48 @@ class LoginScreen extends React.Component<Props, State> {
* *
* @returns {*} * @returns {*}
*/ */
getFormInput() { getFormInput(): React.Node {
const {email, password} = this.state;
return ( return (
<View> <View>
<TextInput <TextInput
label={i18n.t("screens.login.email")} label={i18n.t('screens.login.email')}
mode='outlined' mode="outlined"
value={this.state.email} value={email}
onChangeText={this.onEmailChange} onChangeText={this.onEmailChange}
onBlur={this.validateEmail} onBlur={this.validateEmail}
onSubmitEditing={this.onEmailSubmit} onSubmitEditing={this.onEmailSubmit}
error={this.shouldShowEmailError()} error={this.shouldShowEmailError()}
textContentType={'emailAddress'} textContentType="emailAddress"
autoCapitalize={'none'} autoCapitalize="none"
autoCompleteType={'email'} autoCompleteType="email"
autoCorrect={false} autoCorrect={false}
keyboardType={'email-address'} keyboardType="email-address"
returnKeyType={'next'} returnKeyType="next"
secureTextEntry={false} secureTextEntry={false}
/> />
<HelperText <HelperText type="error" visible={this.shouldShowEmailError()}>
type="error" {i18n.t('screens.login.emailError')}
visible={this.shouldShowEmailError()}
>
{i18n.t("screens.login.emailError")}
</HelperText> </HelperText>
<TextInput <TextInput
ref={this.passwordInputRef} ref={this.passwordInputRef}
label={i18n.t("screens.login.password")} label={i18n.t('screens.login.password')}
mode='outlined' mode="outlined"
value={this.state.password} value={password}
onChangeText={this.onPasswordChange} onChangeText={this.onPasswordChange}
onBlur={this.validatePassword} onBlur={this.validatePassword}
onSubmitEditing={this.onSubmit} onSubmitEditing={this.onSubmit}
error={this.shouldShowPasswordError()} error={this.shouldShowPasswordError()}
textContentType={'password'} textContentType="password"
autoCapitalize={'none'} autoCapitalize="none"
autoCompleteType={'password'} autoCompleteType="password"
autoCorrect={false} autoCorrect={false}
keyboardType={'default'} keyboardType="default"
returnKeyType={'done'} returnKeyType="done"
secureTextEntry={true} secureTextEntry
/> />
<HelperText <HelperText type="error" visible={this.shouldShowPasswordError()}>
type="error" {i18n.t('screens.login.passwordError')}
visible={this.shouldShowPasswordError()}
>
{i18n.t("screens.login.passwordError")}
</HelperText> </HelperText>
</View> </View>
); );
@ -293,43 +220,45 @@ class LoginScreen extends React.Component<Props, State> {
* Gets the card containing the input form * Gets the card containing the input form
* @returns {*} * @returns {*}
*/ */
getMainCard() { getMainCard(): React.Node {
const {props, state} = this;
return ( return (
<View style={styles.card}> <View style={styles.card}>
<Card.Title <Card.Title
title={i18n.t("screens.login.title")} title={i18n.t('screens.login.title')}
titleStyle={{color: "#fff"}} titleStyle={{color: '#fff'}}
subtitle={i18n.t("screens.login.subtitle")} subtitle={i18n.t('screens.login.subtitle')}
subtitleStyle={{color: "#fff"}} subtitleStyle={{color: '#fff'}}
left={(props) => <Image left={({size}: {size: number}): React.Node => (
{...props} <Image
source={ICON_AMICALE} source={ICON_AMICALE}
style={{ style={{
width: props.size, width: size,
height: props.size, height: size,
}}/>} }}
/>
)}
/> />
<Card.Content> <Card.Content>
{this.getFormInput()} {this.getFormInput()}
<Card.Actions style={{flexWrap: "wrap"}}> <Card.Actions style={{flexWrap: 'wrap'}}>
<Button <Button
icon="lock-question" icon="lock-question"
mode="contained" mode="contained"
onPress={this.onResetPasswordClick} onPress={this.onResetPasswordClick}
color={this.props.theme.colors.warning} color={props.theme.colors.warning}
style={{marginRight: 'auto', marginBottom: 20}}> style={{marginRight: 'auto', marginBottom: 20}}>
{i18n.t("screens.login.resetPassword")} {i18n.t('screens.login.resetPassword')}
</Button> </Button>
<Button <Button
icon="send" icon="send"
mode="contained" mode="contained"
disabled={!this.shouldEnableLogin()} disabled={!this.shouldEnableLogin()}
loading={this.state.loading} loading={state.loading}
onPress={this.onSubmit} onPress={this.onSubmit}
style={{marginLeft: 'auto'}}> style={{marginLeft: 'auto'}}>
{i18n.t("screens.login.title")} {i18n.t('screens.login.title')}
</Button> </Button>
</Card.Actions> </Card.Actions>
<Card.Actions> <Card.Actions>
<Button <Button
@ -340,7 +269,7 @@ class LoginScreen extends React.Component<Props, State> {
marginLeft: 'auto', marginLeft: 'auto',
marginRight: 'auto', marginRight: 'auto',
}}> }}>
{i18n.t("screens.login.mascotDialog.title")} {i18n.t('screens.login.mascotDialog.title')}
</Button> </Button>
</Card.Actions> </Card.Actions>
</Card.Content> </Card.Content>
@ -348,45 +277,164 @@ class LoginScreen extends React.Component<Props, State> {
); );
} }
render() { /**
* 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 ( return (
<LinearGradient <LinearGradient
style={{ style={{
height: "100%" height: '100%',
}} }}
colors={['#9e0d18', '#530209']} colors={['#9e0d18', '#530209']}
start={{x: 0, y: 0.1}} start={{x: 0, y: 0.1}}
end={{x: 0.1, y: 1}}> end={{x: 0.1, y: 1}}>
<KeyboardAvoidingView <KeyboardAvoidingView
behavior={"height"} behavior="height"
contentContainerStyle={styles.container} contentContainerStyle={styles.container}
style={styles.container} style={styles.container}
enabled enabled
keyboardVerticalOffset={100} keyboardVerticalOffset={100}>
>
<CollapsibleScrollView> <CollapsibleScrollView>
<View style={{height: "100%"}}> <View style={{height: '100%'}}>{this.getMainCard()}</View>
{this.getMainCard()}
</View>
<MascotPopup <MascotPopup
visible={this.state.mascotDialogVisible} visible={mascotDialogVisible}
title={i18n.t("screens.login.mascotDialog.title")} title={i18n.t('screens.login.mascotDialog.title')}
message={i18n.t("screens.login.mascotDialog.message")} message={i18n.t('screens.login.mascotDialog.message')}
icon={"help"} icon="help"
buttons={{ buttons={{
action: null, action: null,
cancel: { cancel: {
message: i18n.t("screens.login.mascotDialog.button"), message: i18n.t('screens.login.mascotDialog.button'),
icon: "check", icon: 'check',
onPress: this.hideMascotDialog, onPress: this.hideMascotDialog,
} },
}} }}
emotion={MASCOT_STYLE.NORMAL} emotion={MASCOT_STYLE.NORMAL}
/> />
<ErrorDialog <ErrorDialog
visible={this.state.dialogVisible} visible={dialogVisible}
onDismiss={this.hideErrorDialog} onDismiss={this.hideErrorDialog}
errorCode={this.state.dialogError} errorCode={dialogError}
/> />
</CollapsibleScrollView> </CollapsibleScrollView>
</KeyboardAvoidingView> </KeyboardAvoidingView>
@ -395,23 +443,4 @@ class LoginScreen extends React.Component<Props, State> {
} }
} }
const styles = StyleSheet.create({
container: {
flex: 1,
},
card: {
marginTop: 'auto',
marginBottom: 'auto',
},
header: {
fontSize: 36,
marginBottom: 48
},
textInput: {},
btnContainer: {
marginTop: 5,
marginBottom: 10,
}
});
export default withTheme(LoginScreen); export default withTheme(LoginScreen);

View file

@ -1,31 +1,47 @@
// @flow // @flow
import * as React from 'react'; import * as React from 'react';
import {FlatList, StyleSheet, View} from "react-native"; import {FlatList, StyleSheet, View} from 'react-native';
import {Avatar, Button, Card, Divider, List, Paragraph, withTheme} from 'react-native-paper'; import {
import AuthenticatedScreen from "../../components/Amicale/AuthenticatedScreen"; Avatar,
Button,
Card,
Divider,
List,
Paragraph,
withTheme,
} from 'react-native-paper';
import i18n from 'i18n-js'; import i18n from 'i18n-js';
import LogoutDialog from "../../components/Amicale/LogoutDialog"; import {StackNavigationProp} from '@react-navigation/stack';
import MaterialHeaderButtons, {Item} from "../../components/Overrides/CustomHeaderButton"; import AuthenticatedScreen from '../../components/Amicale/AuthenticatedScreen';
import type {cardList} from "../../components/Lists/CardList/CardList"; import LogoutDialog from '../../components/Amicale/LogoutDialog';
import CardList from "../../components/Lists/CardList/CardList"; import MaterialHeaderButtons, {
import {StackNavigationProp} from "@react-navigation/stack"; Item,
import type {CustomTheme} from "../../managers/ThemeManager"; } from '../../components/Overrides/CustomHeaderButton';
import AvailableWebsites from "../../constants/AvailableWebsites"; import CardList from '../../components/Lists/CardList/CardList';
import Mascot, {MASCOT_STYLE} from "../../components/Mascot/Mascot"; import type {CustomThemeType} from '../../managers/ThemeManager';
import ServicesManager, {SERVICES_KEY} from "../../managers/ServicesManager"; import AvailableWebsites from '../../constants/AvailableWebsites';
import CollapsibleFlatList from "../../components/Collapsible/CollapsibleFlatList"; 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 = { type PropsType = {
navigation: StackNavigationProp, navigation: StackNavigationProp,
theme: CustomTheme, theme: CustomThemeType,
} };
type State = { type StateType = {
dialogVisible: boolean, dialogVisible: boolean,
} };
type ProfileData = { type ClubType = {
id: number,
name: string,
is_manager: boolean,
};
type ProfileDataType = {
first_name: string, first_name: string,
last_name: string, last_name: string,
email: string, email: string,
@ -34,55 +50,59 @@ type ProfileData = {
branch: string, branch: string,
link: string, link: string,
validity: boolean, validity: boolean,
clubs: Array<Club>, clubs: Array<ClubType>,
} };
type Club = {
id: number,
name: string,
is_manager: boolean,
}
class ProfileScreen extends React.Component<Props, State> { const styles = StyleSheet.create({
card: {
margin: 10,
},
icon: {
backgroundColor: 'transparent',
},
editButton: {
marginLeft: 'auto',
},
});
state = { class ProfileScreen extends React.Component<PropsType, StateType> {
dialogVisible: false, data: ProfileDataType;
};
data: ProfileData; flatListData: Array<{id: string}>;
flatListData: Array<{ id: string }>; amicaleDataset: Array<ServiceItemType>;
amicaleDataset: cardList;
constructor(props: Props) { constructor(props: PropsType) {
super(props); super(props);
this.flatListData = [ this.flatListData = [{id: '0'}, {id: '1'}, {id: '2'}, {id: '3'}];
{id: '0'},
{id: '1'},
{id: '2'},
{id: '3'},
]
const services = new ServicesManager(props.navigation); const services = new ServicesManager(props.navigation);
this.amicaleDataset = services.getAmicaleServices([SERVICES_KEY.PROFILE]); this.amicaleDataset = services.getAmicaleServices([SERVICES_KEY.PROFILE]);
this.state = {
dialogVisible: false,
};
} }
componentDidMount() { componentDidMount() {
this.props.navigation.setOptions({ const {navigation} = this.props;
navigation.setOptions({
headerRight: this.getHeaderButton, headerRight: this.getHeaderButton,
}); });
} }
showDisconnectDialog = () => this.setState({dialogVisible: true});
hideDisconnectDialog = () => this.setState({dialogVisible: false});
/** /**
* Gets the logout header button * Gets the logout header button
* *
* @returns {*} * @returns {*}
*/ */
getHeaderButton = () => <MaterialHeaderButtons> getHeaderButton = (): React.Node => (
<Item title="logout" iconName="logout" onPress={this.showDisconnectDialog}/> <MaterialHeaderButtons>
</MaterialHeaderButtons>; <Item
title="logout"
iconName="logout"
onPress={this.showDisconnectDialog}
/>
</MaterialHeaderButtons>
);
/** /**
* Gets the main screen component with the fetched data * Gets the main screen component with the fetched data
@ -90,10 +110,12 @@ class ProfileScreen extends React.Component<Props, State> {
* @param data The data fetched from the server * @param data The data fetched from the server
* @returns {*} * @returns {*}
*/ */
getScreen = (data: Array<{ [key: string]: any } | null>) => { getScreen = (data: Array<ProfileDataType | null>): React.Node => {
if (data[0] != null) { const {dialogVisible} = this.state;
this.data = data[0]; const {navigation} = this.props;
} // eslint-disable-next-line prefer-destructuring
if (data[0] != null) this.data = data[0];
return ( return (
<View style={{flex: 1}}> <View style={{flex: 1}}>
<CollapsibleFlatList <CollapsibleFlatList
@ -101,15 +123,15 @@ class ProfileScreen extends React.Component<Props, State> {
data={this.flatListData} data={this.flatListData}
/> />
<LogoutDialog <LogoutDialog
{...this.props} navigation={navigation}
visible={this.state.dialogVisible} visible={dialogVisible}
onDismiss={this.hideDisconnectDialog} onDismiss={this.hideDisconnectDialog}
/> />
</View> </View>
) );
}; };
getRenderItem = ({item}: { item: { id: string } }) => { getRenderItem = ({item}: {item: {id: string}}): React.Node => {
switch (item.id) { switch (item.id) {
case '0': case '0':
return this.getWelcomeCard(); return this.getWelcomeCard();
@ -127,13 +149,8 @@ class ProfileScreen extends React.Component<Props, State> {
* *
* @returns {*} * @returns {*}
*/ */
getServicesList() { getServicesList(): React.Node {
return ( return <CardList dataset={this.amicaleDataset} isHorizontal />;
<CardList
dataset={this.amicaleDataset}
isHorizontal={true}
/>
);
} }
/** /**
@ -141,42 +158,44 @@ class ProfileScreen extends React.Component<Props, State> {
* *
* @returns {*} * @returns {*}
*/ */
getWelcomeCard() { getWelcomeCard(): React.Node {
const {navigation} = this.props;
return ( return (
<Card style={styles.card}> <Card style={styles.card}>
<Card.Title <Card.Title
title={i18n.t("screens.profile.welcomeTitle", {name: this.data.first_name})} title={i18n.t('screens.profile.welcomeTitle', {
left={() => name: this.data.first_name,
})}
left={(): React.Node => (
<Mascot <Mascot
style={{ style={{
width: 60 width: 60,
}} }}
emotion={MASCOT_STYLE.COOL} emotion={MASCOT_STYLE.COOL}
animated={true} animated
entryAnimation={{ entryAnimation={{
animation: "bounceIn", animation: 'bounceIn',
duration: 1000 duration: 1000,
}} }}
/>} />
)}
titleStyle={{marginLeft: 10}} titleStyle={{marginLeft: 10}}
/> />
<Card.Content> <Card.Content>
<Divider/> <Divider />
<Paragraph> <Paragraph>{i18n.t('screens.profile.welcomeDescription')}</Paragraph>
{i18n.t("screens.profile.welcomeDescription")}
</Paragraph>
{this.getServicesList()} {this.getServicesList()}
<Paragraph> <Paragraph>{i18n.t('screens.profile.welcomeFeedback')}</Paragraph>
{i18n.t("screens.profile.welcomeFeedback")} <Divider />
</Paragraph>
<Divider/>
<Card.Actions> <Card.Actions>
<Button <Button
icon="bug" icon="bug"
mode="contained" mode="contained"
onPress={() => this.props.navigation.navigate('feedback')} onPress={() => {
navigation.navigate('feedback');
}}
style={styles.editButton}> style={styles.editButton}>
{i18n.t("screens.feedback.homeButtonTitle")} {i18n.t('screens.feedback.homeButtonTitle')}
</Button> </Button>
</Card.Actions> </Card.Actions>
</Card.Content> </Card.Content>
@ -184,16 +203,6 @@ class ProfileScreen extends React.Component<Props, State> {
); );
} }
/**
* 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. * Gets the given field value.
* If the field does not have a value, returns a placeholder text * If the field does not have a value, returns a placeholder text
@ -201,10 +210,8 @@ class ProfileScreen extends React.Component<Props, State> {
* @param field The field to get the value from * @param field The field to get the value from
* @return {*} * @return {*}
*/ */
getFieldValue(field: ?string) { static getFieldValue(field: ?string): string {
return this.isFieldAvailable(field) return field != null ? field : i18n.t('screens.profile.noData');
? field
: i18n.t("screens.profile.noData");
} }
/** /**
@ -214,18 +221,21 @@ class ProfileScreen extends React.Component<Props, State> {
* @param icon The icon to use * @param icon The icon to use
* @return {*} * @return {*}
*/ */
getPersonalListItem(field: ?string, icon: string) { getPersonalListItem(field: ?string, icon: string): React.Node {
let title = this.isFieldAvailable(field) ? this.getFieldValue(field) : ':('; const {theme} = this.props;
let subtitle = this.isFieldAvailable(field) ? '' : this.getFieldValue(field); const title = field != null ? ProfileScreen.getFieldValue(field) : ':(';
const subtitle = field != null ? '' : ProfileScreen.getFieldValue(field);
return ( return (
<List.Item <List.Item
title={title} title={title}
description={subtitle} description={subtitle}
left={props => <List.Icon left={({size}: {size: number}): React.Node => (
{...props} <List.Icon
size={size}
icon={icon} icon={icon}
color={this.isFieldAvailable(field) ? undefined : this.props.theme.colors.textDisabled} color={field != null ? null : theme.colors.textDisabled}
/>} />
)}
/> />
); );
} }
@ -235,40 +245,47 @@ class ProfileScreen extends React.Component<Props, State> {
* *
* @return {*} * @return {*}
*/ */
getPersonalCard() { getPersonalCard(): React.Node {
const {theme, navigation} = this.props;
return ( return (
<Card style={styles.card}> <Card style={styles.card}>
<Card.Title <Card.Title
title={this.data.first_name + ' ' + this.data.last_name} title={`${this.data.first_name} ${this.data.last_name}`}
subtitle={this.data.email} subtitle={this.data.email}
left={(props) => <Avatar.Icon left={({size}: {size: number}): React.Node => (
{...props} <Avatar.Icon
size={size}
icon="account" icon="account"
color={this.props.theme.colors.primary} color={theme.colors.primary}
style={styles.icon} style={styles.icon}
/>} />
)}
/> />
<Card.Content> <Card.Content>
<Divider/> <Divider />
<List.Section> <List.Section>
<List.Subheader>{i18n.t("screens.profile.personalInformation")}</List.Subheader> <List.Subheader>
{this.getPersonalListItem(this.data.birthday, "cake-variant")} {i18n.t('screens.profile.personalInformation')}
{this.getPersonalListItem(this.data.phone, "phone")} </List.Subheader>
{this.getPersonalListItem(this.data.email, "email")} {this.getPersonalListItem(this.data.birthday, 'cake-variant')}
{this.getPersonalListItem(this.data.branch, "school")} {this.getPersonalListItem(this.data.phone, 'phone')}
{this.getPersonalListItem(this.data.email, 'email')}
{this.getPersonalListItem(this.data.branch, 'school')}
</List.Section> </List.Section>
<Divider/> <Divider />
<Card.Actions> <Card.Actions>
<Button <Button
icon="account-edit" icon="account-edit"
mode="contained" mode="contained"
onPress={() => this.props.navigation.navigate("website", { onPress={() => {
navigation.navigate('website', {
host: AvailableWebsites.websites.AMICALE, host: AvailableWebsites.websites.AMICALE,
path: this.data.link, path: this.data.link,
title: i18n.t('screens.websites.amicale') title: i18n.t('screens.websites.amicale'),
})} });
}}
style={styles.editButton}> style={styles.editButton}>
{i18n.t("screens.profile.editInformation")} {i18n.t('screens.profile.editInformation')}
</Button> </Button>
</Card.Actions> </Card.Actions>
</Card.Content> </Card.Content>
@ -281,21 +298,24 @@ class ProfileScreen extends React.Component<Props, State> {
* *
* @return {*} * @return {*}
*/ */
getClubCard() { getClubCard(): React.Node {
const {theme} = this.props;
return ( return (
<Card style={styles.card}> <Card style={styles.card}>
<Card.Title <Card.Title
title={i18n.t("screens.profile.clubs")} title={i18n.t('screens.profile.clubs')}
subtitle={i18n.t("screens.profile.clubsSubtitle")} subtitle={i18n.t('screens.profile.clubsSubtitle')}
left={(props) => <Avatar.Icon left={({size}: {size: number}): React.Node => (
{...props} <Avatar.Icon
size={size}
icon="account-group" icon="account-group"
color={this.props.theme.colors.primary} color={theme.colors.primary}
style={styles.icon} style={styles.icon}
/>} />
)}
/> />
<Card.Content> <Card.Content>
<Divider/> <Divider />
{this.getClubList(this.data.clubs)} {this.getClubList(this.data.clubs)}
</Card.Content> </Card.Content>
</Card> </Card>
@ -307,18 +327,21 @@ class ProfileScreen extends React.Component<Props, State> {
* *
* @return {*} * @return {*}
*/ */
getMembershipCar() { getMembershipCar(): React.Node {
const {theme} = this.props;
return ( return (
<Card style={styles.card}> <Card style={styles.card}>
<Card.Title <Card.Title
title={i18n.t("screens.profile.membership")} title={i18n.t('screens.profile.membership')}
subtitle={i18n.t("screens.profile.membershipSubtitle")} subtitle={i18n.t('screens.profile.membershipSubtitle')}
left={(props) => <Avatar.Icon left={({size}: {size: number}): React.Node => (
{...props} <Avatar.Icon
size={size}
icon="credit-card" icon="credit-card"
color={this.props.theme.colors.primary} color={theme.colors.primary}
style={styles.icon} style={styles.icon}
/>} />
)}
/> />
<Card.Content> <Card.Content>
<List.Section> <List.Section>
@ -334,81 +357,106 @@ class ProfileScreen extends React.Component<Props, State> {
* *
* @return {*} * @return {*}
*/ */
getMembershipItem(state: boolean) { getMembershipItem(state: boolean): React.Node {
const {theme} = this.props;
return ( return (
<List.Item <List.Item
title={state ? i18n.t("screens.profile.membershipPayed") : i18n.t("screens.profile.membershipNotPayed")} title={
left={props => <List.Icon state
{...props} ? i18n.t('screens.profile.membershipPayed')
color={state ? this.props.theme.colors.success : this.props.theme.colors.danger} : 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'} 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 * Gets a list item for the club list
* *
* @param item The club to render * @param item The club to render
* @return {*} * @return {*}
*/ */
clubListItem = ({item}: { item: Club }) => { getClubListItem = ({item}: {item: ClubType}): React.Node => {
const onPress = () => this.openClubDetailsScreen(item.id); const {theme} = this.props;
let description = i18n.t("screens.profile.isMember"); const onPress = () => {
let icon = (props) => <List.Icon {...props} icon="chevron-right"/>; 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) { if (item.is_manager) {
description = i18n.t("screens.profile.isManager"); description = i18n.t('screens.profile.isManager');
icon = (props) => <List.Icon {...props} icon="star" color={this.props.theme.colors.primary}/>; icon = ({size}: {size: number}): React.Node => (
<List.Icon size={size} icon="star" color={theme.colors.primary} />
);
} }
return <List.Item return (
<List.Item
title={item.name} title={item.name}
description={description} description={description}
left={icon} left={icon}
onPress={onPress} 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 * Renders the list of clubs the user is part of
* *
* @param list The club list * @param list The club list
* @return {*} * @return {*}
*/ */
getClubList(list: Array<Club>) { getClubList(list: Array<ClubType>): React.Node {
list.sort(this.sortClubList); list.sort(this.sortClubList);
return ( return (
//$FlowFixMe
<FlatList <FlatList
renderItem={this.clubListItem} renderItem={this.getClubListItem}
keyExtractor={this.clubKeyExtractor} keyExtractor={this.clubKeyExtractor}
data={list} data={list}
/> />
); );
} }
render() { 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 ( return (
<AuthenticatedScreen <AuthenticatedScreen
{...this.props} navigation={navigation}
requests={[ requests={[
{ {
link: 'user/profile', link: 'user/profile',
params: {}, params: {},
mandatory: true, mandatory: true,
} },
]} ]}
renderFunction={this.getScreen} renderFunction={this.getScreen}
/> />
@ -416,17 +464,4 @@ class ProfileScreen extends React.Component<Props, State> {
} }
} }
const styles = StyleSheet.create({
card: {
margin: 10,
},
icon: {
backgroundColor: 'transparent'
},
editButton: {
marginLeft: 'auto'
}
});
export default withTheme(ProfileScreen); export default withTheme(ProfileScreen);

View file

@ -1,13 +1,13 @@
// @flow // @flow
import type {CustomTheme} from "../../../managers/ThemeManager"; import type {CustomThemeType} from '../../../managers/ThemeManager';
export type Coordinates = { export type CoordinatesType = {
x: number, x: number,
y: number, y: number,
} };
type Shape = Array<Array<number>>; export type ShapeType = Array<Array<number>>;
/** /**
* Abstract class used to represent a BaseShape. * Abstract class used to represent a BaseShape.
@ -15,16 +15,18 @@ type Shape = Array<Array<number>>;
* and in methods to implement * and in methods to implement
*/ */
export default class BaseShape { export default class BaseShape {
#currentShape: ShapeType;
#currentShape: Shape;
#rotation: number; #rotation: number;
position: Coordinates;
theme: CustomTheme; position: CoordinatesType;
theme: CustomThemeType;
/** /**
* Prevent instantiation if classname is BaseShape to force class to be abstract * Prevent instantiation if classname is BaseShape to force class to be abstract
*/ */
constructor(theme: CustomTheme) { constructor(theme: CustomThemeType) {
if (this.constructor === BaseShape) if (this.constructor === BaseShape)
throw new Error("Abstract class can't be instantiated"); throw new Error("Abstract class can't be instantiated");
this.theme = theme; this.theme = theme;
@ -37,6 +39,7 @@ export default class BaseShape {
* Gets this shape's color. * Gets this shape's color.
* Must be implemented by child class * Must be implemented by child class
*/ */
// eslint-disable-next-line class-methods-use-this
getColor(): string { getColor(): string {
throw new Error("Method 'getColor()' must be implemented"); throw new Error("Method 'getColor()' must be implemented");
} }
@ -47,14 +50,15 @@ export default class BaseShape {
* *
* Used by tests to read private fields * Used by tests to read private fields
*/ */
getShapes(): Array<Shape> { // eslint-disable-next-line class-methods-use-this
getShapes(): Array<ShapeType> {
throw new Error("Method 'getShapes()' must be implemented"); throw new Error("Method 'getShapes()' must be implemented");
} }
/** /**
* Gets this object's current shape. * Gets this object's current shape.
*/ */
getCurrentShape(): Shape { getCurrentShape(): ShapeType {
return this.#currentShape; return this.#currentShape;
} }
@ -63,17 +67,20 @@ export default class BaseShape {
* This will return an array of coordinates representing the positions of the cells used by this object. * 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? * @param isAbsolute Should we take into account the current position of the object?
* @return {Array<Coordinates>} This object cells coordinates * @return {Array<CoordinatesType>} This object cells coordinates
*/ */
getCellsCoordinates(isAbsolute: boolean): Array<Coordinates> { getCellsCoordinates(isAbsolute: boolean): Array<CoordinatesType> {
let coordinates = []; const coordinates = [];
for (let row = 0; row < this.#currentShape.length; row++) { for (let row = 0; row < this.#currentShape.length; row += 1) {
for (let col = 0; col < this.#currentShape[row].length; col++) { for (let col = 0; col < this.#currentShape[row].length; col += 1) {
if (this.#currentShape[row][col] === 1) if (this.#currentShape[row][col] === 1) {
if (isAbsolute) if (isAbsolute) {
coordinates.push({x: this.position.x + col, y: this.position.y + row}); coordinates.push({
else x: this.position.x + col,
coordinates.push({x: col, y: row}); y: this.position.y + row,
});
} else coordinates.push({x: col, y: row});
}
} }
} }
return coordinates; return coordinates;
@ -85,14 +92,10 @@ export default class BaseShape {
* @param isForward Should we rotate clockwise? * @param isForward Should we rotate clockwise?
*/ */
rotate(isForward: boolean) { rotate(isForward: boolean) {
if (isForward) if (isForward) this.#rotation += 1;
this.#rotation++; else this.#rotation -= 1;
else if (this.#rotation > 3) this.#rotation = 0;
this.#rotation--; else if (this.#rotation < 0) this.#rotation = 3;
if (this.#rotation > 3)
this.#rotation = 0;
else if (this.#rotation < 0)
this.#rotation = 3;
this.#currentShape = this.getShapes()[this.#rotation]; this.#currentShape = this.getShapes()[this.#rotation];
} }
@ -106,5 +109,4 @@ export default class BaseShape {
this.position.x += x; this.position.x += x;
this.position.y += y; this.position.y += y;
} }
} }

View file

@ -1,11 +1,11 @@
// @flow // @flow
import BaseShape from "./BaseShape"; import BaseShape from './BaseShape';
import type {CustomTheme} from "../../../managers/ThemeManager"; import type {CustomThemeType} from '../../../managers/ThemeManager';
import type {ShapeType} from './BaseShape';
export default class ShapeI extends BaseShape { export default class ShapeI extends BaseShape {
constructor(theme: CustomThemeType) {
constructor(theme: CustomTheme) {
super(theme); super(theme);
this.position.x = 3; this.position.x = 3;
} }
@ -14,7 +14,8 @@ export default class ShapeI extends BaseShape {
return this.theme.colors.tetrisI; return this.theme.colors.tetrisI;
} }
getShapes() { // eslint-disable-next-line class-methods-use-this
getShapes(): Array<ShapeType> {
return [ return [
[ [
[0, 0, 0, 0], [0, 0, 0, 0],

View file

@ -1,11 +1,11 @@
// @flow // @flow
import BaseShape from "./BaseShape"; import BaseShape from './BaseShape';
import type {CustomTheme} from "../../../managers/ThemeManager"; import type {CustomThemeType} from '../../../managers/ThemeManager';
import type {ShapeType} from './BaseShape';
export default class ShapeJ extends BaseShape { export default class ShapeJ extends BaseShape {
constructor(theme: CustomThemeType) {
constructor(theme: CustomTheme) {
super(theme); super(theme);
this.position.x = 3; this.position.x = 3;
} }
@ -14,7 +14,8 @@ export default class ShapeJ extends BaseShape {
return this.theme.colors.tetrisJ; return this.theme.colors.tetrisJ;
} }
getShapes() { // eslint-disable-next-line class-methods-use-this
getShapes(): Array<ShapeType> {
return [ return [
[ [
[1, 0, 0], [1, 0, 0],

View file

@ -1,11 +1,11 @@
// @flow // @flow
import BaseShape from "./BaseShape"; import BaseShape from './BaseShape';
import type {CustomTheme} from "../../../managers/ThemeManager"; import type {CustomThemeType} from '../../../managers/ThemeManager';
import type {ShapeType} from './BaseShape';
export default class ShapeL extends BaseShape { export default class ShapeL extends BaseShape {
constructor(theme: CustomThemeType) {
constructor(theme: CustomTheme) {
super(theme); super(theme);
this.position.x = 3; this.position.x = 3;
} }
@ -14,7 +14,8 @@ export default class ShapeL extends BaseShape {
return this.theme.colors.tetrisL; return this.theme.colors.tetrisL;
} }
getShapes() { // eslint-disable-next-line class-methods-use-this
getShapes(): Array<ShapeType> {
return [ return [
[ [
[0, 0, 1], [0, 0, 1],

View file

@ -1,11 +1,11 @@
// @flow // @flow
import BaseShape from "./BaseShape"; import BaseShape from './BaseShape';
import type {CustomTheme} from "../../../managers/ThemeManager"; import type {CustomThemeType} from '../../../managers/ThemeManager';
import type {ShapeType} from './BaseShape';
export default class ShapeO extends BaseShape { export default class ShapeO extends BaseShape {
constructor(theme: CustomThemeType) {
constructor(theme: CustomTheme) {
super(theme); super(theme);
this.position.x = 4; this.position.x = 4;
} }
@ -14,7 +14,8 @@ export default class ShapeO extends BaseShape {
return this.theme.colors.tetrisO; return this.theme.colors.tetrisO;
} }
getShapes() { // eslint-disable-next-line class-methods-use-this
getShapes(): Array<ShapeType> {
return [ return [
[ [
[1, 1], [1, 1],

View file

@ -1,11 +1,11 @@
// @flow // @flow
import BaseShape from "./BaseShape"; import BaseShape from './BaseShape';
import type {CustomTheme} from "../../../managers/ThemeManager"; import type {CustomThemeType} from '../../../managers/ThemeManager';
import type {ShapeType} from './BaseShape';
export default class ShapeS extends BaseShape { export default class ShapeS extends BaseShape {
constructor(theme: CustomThemeType) {
constructor(theme: CustomTheme) {
super(theme); super(theme);
this.position.x = 3; this.position.x = 3;
} }
@ -14,7 +14,8 @@ export default class ShapeS extends BaseShape {
return this.theme.colors.tetrisS; return this.theme.colors.tetrisS;
} }
getShapes() { // eslint-disable-next-line class-methods-use-this
getShapes(): Array<ShapeType> {
return [ return [
[ [
[0, 1, 1], [0, 1, 1],

View file

@ -1,11 +1,11 @@
// @flow // @flow
import BaseShape from "./BaseShape"; import BaseShape from './BaseShape';
import type {CustomTheme} from "../../../managers/ThemeManager"; import type {CustomThemeType} from '../../../managers/ThemeManager';
import type {ShapeType} from './BaseShape';
export default class ShapeT extends BaseShape { export default class ShapeT extends BaseShape {
constructor(theme: CustomThemeType) {
constructor(theme: CustomTheme) {
super(theme); super(theme);
this.position.x = 3; this.position.x = 3;
} }
@ -14,7 +14,8 @@ export default class ShapeT extends BaseShape {
return this.theme.colors.tetrisT; return this.theme.colors.tetrisT;
} }
getShapes() { // eslint-disable-next-line class-methods-use-this
getShapes(): Array<ShapeType> {
return [ return [
[ [
[0, 1, 0], [0, 1, 0],

View file

@ -1,11 +1,11 @@
// @flow // @flow
import BaseShape from "./BaseShape"; import BaseShape from './BaseShape';
import type {CustomTheme} from "../../../managers/ThemeManager"; import type {CustomThemeType} from '../../../managers/ThemeManager';
import type {ShapeType} from './BaseShape';
export default class ShapeZ extends BaseShape { export default class ShapeZ extends BaseShape {
constructor(theme: CustomThemeType) {
constructor(theme: CustomTheme) {
super(theme); super(theme);
this.position.x = 3; this.position.x = 3;
} }
@ -14,7 +14,8 @@ export default class ShapeZ extends BaseShape {
return this.theme.colors.tetrisZ; return this.theme.colors.tetrisZ;
} }
getShapes() { // eslint-disable-next-line class-methods-use-this
getShapes(): Array<ShapeType> {
return [ return [
[ [
[1, 1, 0], [1, 1, 0],

View file

@ -1,19 +1,20 @@
/* eslint-disable */
import React from 'react'; import React from 'react';
import GridManager from "../logic/GridManager"; import GridManager from '../logic/GridManager';
import ScoreManager from "../logic/ScoreManager"; import ScoreManager from '../logic/ScoreManager';
import Piece from "../logic/Piece"; import Piece from '../logic/Piece';
let colors = { let colors = {
tetrisBackground: "#000002" tetrisBackground: '#000002',
}; };
jest.mock("../ScoreManager"); jest.mock('../ScoreManager');
afterAll(() => { afterAll(() => {
jest.restoreAllMocks(); jest.restoreAllMocks();
}); });
test('getEmptyLine', () => { test('getEmptyLine', () => {
let g = new GridManager(2, 2, colors); let g = new GridManager(2, 2, colors);
expect(g.getEmptyLine(2)).toStrictEqual([ expect(g.getEmptyLine(2)).toStrictEqual([
@ -89,9 +90,11 @@ test('clearLines', () => {
test('freezeTetromino', () => { test('freezeTetromino', () => {
let g = new GridManager(2, 2, colors); let g = new GridManager(2, 2, colors);
let spy1 = jest.spyOn(GridManager.prototype, 'getLinesToClear') let spy1 = jest
.spyOn(GridManager.prototype, 'getLinesToClear')
.mockImplementation(() => {}); .mockImplementation(() => {});
let spy2 = jest.spyOn(GridManager.prototype, 'clearLines') let spy2 = jest
.spyOn(GridManager.prototype, 'clearLines')
.mockImplementation(() => {}); .mockImplementation(() => {});
g.freezeTetromino(new Piece({}), null); g.freezeTetromino(new Piece({}), null);

View file

@ -1,17 +1,22 @@
/* eslint-disable */
import React from 'react'; import React from 'react';
import Piece from "../logic/Piece"; import Piece from '../logic/Piece';
import ShapeI from "../Shapes/ShapeI"; import ShapeI from '../Shapes/ShapeI';
let colors = { let colors = {
tetrisI: "#000001", tetrisI: '#000001',
tetrisBackground: "#000002" tetrisBackground: '#000002',
}; };
jest.mock("../Shapes/ShapeI"); jest.mock('../Shapes/ShapeI');
beforeAll(() => { beforeAll(() => {
jest.spyOn(Piece.prototype, 'getRandomShape') jest
.mockImplementation((colors: Object) => {return new ShapeI(colors);}); .spyOn(Piece.prototype, 'getRandomShape')
.mockImplementation((colors: Object) => {
return new ShapeI(colors);
});
}); });
afterAll(() => { afterAll(() => {
@ -21,8 +26,11 @@ afterAll(() => {
test('isPositionValid', () => { test('isPositionValid', () => {
let x = 0; let x = 0;
let y = 0; let y = 0;
let spy = jest.spyOn(ShapeI.prototype, 'getCellsCoordinates') let spy = jest
.mockImplementation(() => {return [{x: x, y: y}];}); .spyOn(ShapeI.prototype, 'getCellsCoordinates')
.mockImplementation(() => {
return [{x: x, y: y}];
});
let grid = [ let grid = [
[{isEmpty: true}, {isEmpty: true}], [{isEmpty: true}, {isEmpty: true}],
[{isEmpty: true}, {isEmpty: false}], [{isEmpty: true}, {isEmpty: false}],
@ -31,19 +39,26 @@ test('isPositionValid', () => {
let p = new Piece(colors); let p = new Piece(colors);
expect(p.isPositionValid(grid, size, size)).toBeTrue(); expect(p.isPositionValid(grid, size, size)).toBeTrue();
x = 1; y = 0; x = 1;
y = 0;
expect(p.isPositionValid(grid, size, size)).toBeTrue(); expect(p.isPositionValid(grid, size, size)).toBeTrue();
x = 0; y = 1; x = 0;
y = 1;
expect(p.isPositionValid(grid, size, size)).toBeTrue(); expect(p.isPositionValid(grid, size, size)).toBeTrue();
x = 1; y = 1; x = 1;
y = 1;
expect(p.isPositionValid(grid, size, size)).toBeFalse(); expect(p.isPositionValid(grid, size, size)).toBeFalse();
x = 2; y = 0; x = 2;
y = 0;
expect(p.isPositionValid(grid, size, size)).toBeFalse(); expect(p.isPositionValid(grid, size, size)).toBeFalse();
x = -1; y = 0; x = -1;
y = 0;
expect(p.isPositionValid(grid, size, size)).toBeFalse(); expect(p.isPositionValid(grid, size, size)).toBeFalse();
x = 0; y = 2; x = 0;
y = 2;
expect(p.isPositionValid(grid, size, size)).toBeFalse(); expect(p.isPositionValid(grid, size, size)).toBeFalse();
x = 0; y = -1; x = 0;
y = -1;
expect(p.isPositionValid(grid, size, size)).toBeFalse(); expect(p.isPositionValid(grid, size, size)).toBeFalse();
spy.mockRestore(); spy.mockRestore();
@ -53,12 +68,15 @@ test('tryMove', () => {
let p = new Piece(colors); let p = new Piece(colors);
const callbackMock = jest.fn(); const callbackMock = jest.fn();
let isValid = true; let isValid = true;
let spy1 = jest.spyOn(Piece.prototype, 'isPositionValid') let spy1 = jest
.mockImplementation(() => {return isValid;}); .spyOn(Piece.prototype, 'isPositionValid')
let spy2 = jest.spyOn(Piece.prototype, 'removeFromGrid') .mockImplementation(() => {
.mockImplementation(() => {}); return isValid;
let spy3 = jest.spyOn(Piece.prototype, 'toGrid') });
let spy2 = jest
.spyOn(Piece.prototype, 'removeFromGrid')
.mockImplementation(() => {}); .mockImplementation(() => {});
let spy3 = jest.spyOn(Piece.prototype, 'toGrid').mockImplementation(() => {});
expect(p.tryMove(-1, 0, null, null, null, callbackMock)).toBeTrue(); expect(p.tryMove(-1, 0, null, null, null, callbackMock)).toBeTrue();
isValid = false; isValid = false;
@ -82,16 +100,19 @@ test('tryMove', () => {
test('tryRotate', () => { test('tryRotate', () => {
let p = new Piece(colors); let p = new Piece(colors);
let isValid = true; let isValid = true;
let spy1 = jest.spyOn(Piece.prototype, 'isPositionValid') let spy1 = jest
.mockImplementation(() => {return isValid;}); .spyOn(Piece.prototype, 'isPositionValid')
let spy2 = jest.spyOn(Piece.prototype, 'removeFromGrid') .mockImplementation(() => {
.mockImplementation(() => {}); return isValid;
let spy3 = jest.spyOn(Piece.prototype, 'toGrid') });
let spy2 = jest
.spyOn(Piece.prototype, 'removeFromGrid')
.mockImplementation(() => {}); .mockImplementation(() => {});
let spy3 = jest.spyOn(Piece.prototype, 'toGrid').mockImplementation(() => {});
expect(p.tryRotate( null, null, null)).toBeTrue(); expect(p.tryRotate(null, null, null)).toBeTrue();
isValid = false; isValid = false;
expect(p.tryRotate( null, null, null)).toBeFalse(); expect(p.tryRotate(null, null, null)).toBeFalse();
expect(spy2).toBeCalledTimes(2); expect(spy2).toBeCalledTimes(2);
expect(spy3).toBeCalledTimes(2); expect(spy3).toBeCalledTimes(2);
@ -101,14 +122,17 @@ test('tryRotate', () => {
spy3.mockRestore(); spy3.mockRestore();
}); });
test('toGrid', () => { test('toGrid', () => {
let x = 0; let x = 0;
let y = 0; let y = 0;
let spy1 = jest.spyOn(ShapeI.prototype, 'getCellsCoordinates') let spy1 = jest
.mockImplementation(() => {return [{x: x, y: y}];}); .spyOn(ShapeI.prototype, 'getCellsCoordinates')
let spy2 = jest.spyOn(ShapeI.prototype, 'getColor') .mockImplementation(() => {
.mockImplementation(() => {return colors.tetrisI;}); return [{x: x, y: y}];
});
let spy2 = jest.spyOn(ShapeI.prototype, 'getColor').mockImplementation(() => {
return colors.tetrisI;
});
let grid = [ let grid = [
[{isEmpty: true}, {isEmpty: true}], [{isEmpty: true}, {isEmpty: true}],
[{isEmpty: true}, {isEmpty: true}], [{isEmpty: true}, {isEmpty: true}],
@ -141,11 +165,18 @@ test('removeFromGrid', () => {
{color: colors.tetrisBackground, isEmpty: true}, {color: colors.tetrisBackground, isEmpty: true},
], ],
]; ];
let oldCoord = [{x: 0, y: 0}, {x: 1, y: 0}]; let oldCoord = [
let spy1 = jest.spyOn(ShapeI.prototype, 'getCellsCoordinates') {x: 0, y: 0},
.mockImplementation(() => {return oldCoord;}); {x: 1, y: 0},
let spy2 = jest.spyOn(ShapeI.prototype, 'getColor') ];
.mockImplementation(() => {return colors.tetrisI;}); let spy1 = jest
.spyOn(ShapeI.prototype, 'getCellsCoordinates')
.mockImplementation(() => {
return oldCoord;
});
let spy2 = jest.spyOn(ShapeI.prototype, 'getColor').mockImplementation(() => {
return colors.tetrisI;
});
let p = new Piece(colors); let p = new Piece(colors);
p.removeFromGrid(gridOld); p.removeFromGrid(gridOld);
expect(gridOld).toStrictEqual(gridNew); expect(gridOld).toStrictEqual(gridNew);

View file

@ -1,6 +1,7 @@
import React from 'react'; /* eslint-disable */
import ScoreManager from "../logic/ScoreManager";
import React from 'react';
import ScoreManager from '../logic/ScoreManager';
test('incrementScore', () => { test('incrementScore', () => {
let scoreManager = new ScoreManager(); let scoreManager = new ScoreManager();

View file

@ -1,6 +1,8 @@
/* eslint-disable */
import React from 'react'; import React from 'react';
import BaseShape from "../Shapes/BaseShape"; import BaseShape from '../Shapes/BaseShape';
import ShapeI from "../Shapes/ShapeI"; import ShapeI from '../Shapes/ShapeI';
const colors = { const colors = {
tetrisI: '#000001', tetrisI: '#000001',
@ -22,7 +24,7 @@ test('constructor', () => {
expect(T.getColor()).toBe(colors.tetrisI); expect(T.getColor()).toBe(colors.tetrisI);
}); });
test("move", () => { test('move', () => {
let T = new ShapeI(colors); let T = new ShapeI(colors);
T.move(0, 1); T.move(0, 1);
expect(T.position.x).toBe(3); expect(T.position.x).toBe(3);

View file

@ -3,19 +3,17 @@
import * as React from 'react'; import * as React from 'react';
import {View} from 'react-native'; import {View} from 'react-native';
import {withTheme} from 'react-native-paper'; import {withTheme} from 'react-native-paper';
import type {CustomTheme} from "../../../managers/ThemeManager";
export type Cell = {color: string, isEmpty: boolean, key: string}; export type CellType = {color: string, isEmpty: boolean, key: string};
type Props = { type PropsType = {
cell: Cell, cell: CellType,
theme: CustomTheme, };
}
class CellComponent extends React.PureComponent<Props> { class CellComponent extends React.PureComponent<PropsType> {
render(): React.Node {
render() { const {props} = this;
const item = this.props.cell; const item = props.cell;
return ( return (
<View <View
style={{ style={{
@ -29,8 +27,6 @@ class CellComponent extends React.PureComponent<Props> {
/> />
); );
} }
} }
export default withTheme(CellComponent); export default withTheme(CellComponent);

View file

@ -3,51 +3,50 @@
import * as React from 'react'; import * as React from 'react';
import {View} from 'react-native'; import {View} from 'react-native';
import {withTheme} from 'react-native-paper'; import {withTheme} from 'react-native-paper';
import type {Cell} from "./CellComponent"; import type {ViewStyle} from 'react-native/Libraries/StyleSheet/StyleSheet';
import CellComponent from "./CellComponent"; import type {CellType} from './CellComponent';
import type {ViewStyle} from "react-native/Libraries/StyleSheet/StyleSheet"; import CellComponent from './CellComponent';
export type Grid = Array<Array<CellComponent>>; export type GridType = Array<Array<CellComponent>>;
type Props = { type PropsType = {
grid: Array<Array<Object>>, grid: Array<Array<CellType>>,
height: number, height: number,
width: number, width: number,
style: ViewStyle, style: ViewStyle,
} };
class GridComponent extends React.Component<Props> { class GridComponent extends React.Component<PropsType> {
getRow(rowNumber: number): React.Node {
getRow(rowNumber: number) { const {grid} = this.props;
let cells = this.props.grid[rowNumber].map(this.getCellRender);
return ( return (
<View <View style={{flexDirection: 'row'}} key={rowNumber.toString()}>
style={{flexDirection: 'row',}} {grid[rowNumber].map(this.getCellRender)}
key={rowNumber.toString()}
>
{cells}
</View> </View>
); );
} }
getCellRender = (item: Cell) => { getCellRender = (item: CellType): React.Node => {
return <CellComponent cell={item} key={item.key}/>; return <CellComponent cell={item} key={item.key} />;
}; };
getGrid() { getGrid(): React.Node {
let rows = []; const {height} = this.props;
for (let i = 0; i < this.props.height; i++) { const rows = [];
for (let i = 0; i < height; i += 1) {
rows.push(this.getRow(i)); rows.push(this.getRow(i));
} }
return rows; return rows;
} }
render() { render(): React.Node {
const {style, width, height} = this.props;
return ( return (
<View style={{ <View
aspectRatio: this.props.width / this.props.height, style={{
aspectRatio: width / height,
borderRadius: 4, borderRadius: 4,
...this.props.style ...style,
}}> }}>
{this.getGrid()} {this.getGrid()}
</View> </View>

View file

@ -3,27 +3,28 @@
import * as React from 'react'; import * as React from 'react';
import {View} from 'react-native'; import {View} from 'react-native';
import {withTheme} from 'react-native-paper'; import {withTheme} from 'react-native-paper';
import type {Grid} from "./GridComponent"; import type {ViewStyle} from 'react-native/Libraries/StyleSheet/StyleSheet';
import GridComponent from "./GridComponent"; import type {GridType} from './GridComponent';
import type {ViewStyle} from "react-native/Libraries/StyleSheet/StyleSheet"; import GridComponent from './GridComponent';
type Props = { type PropsType = {
items: Array<Grid>, items: Array<GridType>,
style: ViewStyle style: ViewStyle,
} };
class Preview extends React.PureComponent<Props> { class Preview extends React.PureComponent<PropsType> {
getGrids(): React.Node {
getGrids() { const {items} = this.props;
let grids = []; const grids = [];
for (let i = 0; i < this.props.items.length; i++) { items.forEach((item: GridType, index: number) => {
grids.push(this.getGridRender(this.props.items[i], i)); grids.push(Preview.getGridRender(item, index));
} });
return grids; return grids;
} }
getGridRender(item: Grid, index: number) { static getGridRender(item: GridType, index: number): React.Node {
return <GridComponent return (
<GridComponent
width={item[0].length} width={item[0].length}
height={item.length} height={item.length}
grid={item} grid={item}
@ -33,21 +34,17 @@ class Preview extends React.PureComponent<Props> {
marginBottom: 5, marginBottom: 5,
}} }}
key={index.toString()} key={index.toString()}
/>; />
};
render() {
if (this.props.items.length > 0) {
return (
<View style={this.props.style}>
{this.getGrids()}
</View>
); );
} else
return null;
} }
render(): React.Node {
const {style, items} = this.props;
if (items.length > 0) {
return <View style={style}>{this.getGrids()}</View>;
}
return null;
}
} }
export default withTheme(Preview); export default withTheme(Preview);

View file

@ -1,243 +1,318 @@
// @flow // @flow
import Piece from "./Piece"; import Piece from './Piece';
import ScoreManager from "./ScoreManager"; import ScoreManager from './ScoreManager';
import GridManager from "./GridManager"; import GridManager from './GridManager';
import type {CustomTheme} from "../../../managers/ThemeManager"; import type {CustomThemeType} from '../../../managers/ThemeManager';
import type {GridType} from '../components/GridComponent';
export type TickCallbackType = (
score: number,
level: number,
grid: GridType,
) => void;
export type ClockCallbackType = (time: number) => void;
export type EndCallbackType = (
time: number,
score: number,
isRestart: boolean,
) => void;
export type MovementCallbackType = (grid: GridType, score?: number) => void;
export default class GameLogic { export default class GameLogic {
static levelTicks = [1000, 800, 600, 400, 300, 200, 150, 100];
static levelTicks = [ scoreManager: ScoreManager;
1000,
800,
600,
400,
300,
200,
150,
100,
];
#scoreManager: ScoreManager; gridManager: GridManager;
#gridManager: GridManager;
#height: number; height: number;
#width: number;
#gameRunning: boolean; width: number;
#gamePaused: boolean;
#gameTime: number;
#currentObject: Piece; gameRunning: boolean;
#gameTick: number; gamePaused: boolean;
#gameTickInterval: IntervalID;
#gameTimeInterval: IntervalID;
#pressInInterval: TimeoutID; gameTime: number;
#isPressedIn: boolean;
#autoRepeatActivationDelay: number;
#autoRepeatDelay: number;
#nextPieces: Array<Piece>; currentObject: Piece;
#nextPiecesCount: number;
#onTick: Function; gameTick: number;
#onClock: Function;
endCallback: Function;
#theme: CustomTheme; gameTickInterval: IntervalID;
constructor(height: number, width: number, theme: CustomTheme) { gameTimeInterval: IntervalID;
this.#height = height;
this.#width = width; pressInInterval: TimeoutID;
this.#gameRunning = false;
this.#gamePaused = false; isPressedIn: boolean;
this.#theme = theme;
this.#autoRepeatActivationDelay = 300; autoRepeatActivationDelay: number;
this.#autoRepeatDelay = 50;
this.#nextPieces = []; autoRepeatDelay: number;
this.#nextPiecesCount = 3;
this.#scoreManager = new ScoreManager(); nextPieces: Array<Piece>;
this.#gridManager = new GridManager(this.getWidth(), this.getHeight(), this.#theme);
nextPiecesCount: number;
tickCallback: TickCallbackType;
clockCallback: ClockCallbackType;
endCallback: EndCallbackType;
theme: CustomThemeType;
constructor(height: number, width: number, theme: CustomThemeType) {
this.height = height;
this.width = width;
this.gameRunning = false;
this.gamePaused = false;
this.theme = theme;
this.autoRepeatActivationDelay = 300;
this.autoRepeatDelay = 50;
this.nextPieces = [];
this.nextPiecesCount = 3;
this.scoreManager = new ScoreManager();
this.gridManager = new GridManager(
this.getWidth(),
this.getHeight(),
this.theme,
);
} }
getHeight(): number { getHeight(): number {
return this.#height; return this.height;
} }
getWidth(): number { getWidth(): number {
return this.#width; return this.width;
} }
getCurrentGrid() { getCurrentGrid(): GridType {
return this.#gridManager.getCurrentGrid(); return this.gridManager.getCurrentGrid();
}
isGameRunning(): boolean {
return this.#gameRunning;
} }
isGamePaused(): boolean { isGamePaused(): boolean {
return this.#gamePaused; return this.gamePaused;
} }
onFreeze() { onFreeze = () => {
this.#gridManager.freezeTetromino(this.#currentObject, this.#scoreManager); this.gridManager.freezeTetromino(this.currentObject, this.scoreManager);
this.createTetromino(); this.createTetromino();
} };
setNewGameTick(level: number) { setNewGameTick(level: number) {
if (level >= GameLogic.levelTicks.length) if (level >= GameLogic.levelTicks.length) return;
return; this.gameTick = GameLogic.levelTicks[level];
this.#gameTick = GameLogic.levelTicks[level]; this.stopTick();
clearInterval(this.#gameTickInterval); this.startTick();
this.#gameTickInterval = setInterval(this.#onTick, this.#gameTick);
} }
onTick(callback: Function) { startClock() {
this.#currentObject.tryMove(0, 1, this.gameTimeInterval = setInterval(() => {
this.#gridManager.getCurrentGrid(), this.getWidth(), this.getHeight(), this.onClock(this.clockCallback);
() => this.onFreeze()); }, 1000);
}
startTick() {
this.gameTickInterval = setInterval(() => {
this.onTick(this.tickCallback);
}, this.gameTick);
}
stopClock() {
clearInterval(this.gameTimeInterval);
}
stopTick() {
clearInterval(this.gameTickInterval);
}
stopGameTime() {
this.stopClock();
this.stopTick();
}
startGameTime() {
this.startClock();
this.startTick();
}
onTick(callback: TickCallbackType) {
this.currentObject.tryMove(
0,
1,
this.gridManager.getCurrentGrid(),
this.getWidth(),
this.getHeight(),
this.onFreeze,
);
callback( callback(
this.#scoreManager.getScore(), this.scoreManager.getScore(),
this.#scoreManager.getLevel(), this.scoreManager.getLevel(),
this.#gridManager.getCurrentGrid()); this.gridManager.getCurrentGrid(),
if (this.#scoreManager.canLevelUp()) );
this.setNewGameTick(this.#scoreManager.getLevel()); if (this.scoreManager.canLevelUp())
this.setNewGameTick(this.scoreManager.getLevel());
} }
onClock(callback: Function) { onClock(callback: ClockCallbackType) {
this.#gameTime++; this.gameTime += 1;
callback(this.#gameTime); callback(this.gameTime);
} }
canUseInput() { canUseInput(): boolean {
return this.#gameRunning && !this.#gamePaused return this.gameRunning && !this.gamePaused;
} }
rightPressed(callback: Function) { rightPressed(callback: MovementCallbackType) {
this.#isPressedIn = true; this.isPressedIn = true;
this.movePressedRepeat(true, callback, 1, 0); this.movePressedRepeat(true, callback, 1, 0);
} }
leftPressedIn(callback: Function) { leftPressedIn(callback: MovementCallbackType) {
this.#isPressedIn = true; this.isPressedIn = true;
this.movePressedRepeat(true, callback, -1, 0); this.movePressedRepeat(true, callback, -1, 0);
} }
downPressedIn(callback: Function) { downPressedIn(callback: MovementCallbackType) {
this.#isPressedIn = true; this.isPressedIn = true;
this.movePressedRepeat(true, callback, 0, 1); this.movePressedRepeat(true, callback, 0, 1);
} }
movePressedRepeat(isInitial: boolean, callback: Function, x: number, y: number) { movePressedRepeat(
if (!this.canUseInput() || !this.#isPressedIn) isInitial: boolean,
return; callback: MovementCallbackType,
const moved = this.#currentObject.tryMove(x, y, x: number,
this.#gridManager.getCurrentGrid(), this.getWidth(), this.getHeight(), y: number,
() => this.onFreeze()); ) {
if (!this.canUseInput() || !this.isPressedIn) return;
const moved = this.currentObject.tryMove(
x,
y,
this.gridManager.getCurrentGrid(),
this.getWidth(),
this.getHeight(),
this.onFreeze,
);
if (moved) { if (moved) {
if (y === 1) { if (y === 1) {
this.#scoreManager.incrementScore(); this.scoreManager.incrementScore();
callback(this.#gridManager.getCurrentGrid(), this.#scoreManager.getScore()); callback(
} else this.gridManager.getCurrentGrid(),
callback(this.#gridManager.getCurrentGrid()); this.scoreManager.getScore(),
);
} else callback(this.gridManager.getCurrentGrid());
} }
this.#pressInInterval = setTimeout(() => this.pressInInterval = setTimeout(
this.movePressedRepeat(false, callback, x, y), () => {
isInitial ? this.#autoRepeatActivationDelay : this.#autoRepeatDelay this.movePressedRepeat(false, callback, x, y);
},
isInitial ? this.autoRepeatActivationDelay : this.autoRepeatDelay,
); );
} }
pressedOut() { pressedOut() {
this.#isPressedIn = false; this.isPressedIn = false;
clearTimeout(this.#pressInInterval); clearTimeout(this.pressInInterval);
} }
rotatePressed(callback: Function) { rotatePressed(callback: MovementCallbackType) {
if (!this.canUseInput()) if (!this.canUseInput()) return;
return;
if (this.#currentObject.tryRotate(this.#gridManager.getCurrentGrid(), this.getWidth(), this.getHeight())) if (
callback(this.#gridManager.getCurrentGrid()); this.currentObject.tryRotate(
this.gridManager.getCurrentGrid(),
this.getWidth(),
this.getHeight(),
)
)
callback(this.gridManager.getCurrentGrid());
} }
getNextPiecesPreviews() { getNextPiecesPreviews(): Array<GridType> {
let finalArray = []; const finalArray = [];
for (let i = 0; i < this.#nextPieces.length; i++) { for (let i = 0; i < this.nextPieces.length; i += 1) {
const gridSize = this.#nextPieces[i].getCurrentShape().getCurrentShape()[0].length; const gridSize = this.nextPieces[i].getCurrentShape().getCurrentShape()[0]
finalArray.push(this.#gridManager.getEmptyGrid(gridSize, gridSize)); .length;
this.#nextPieces[i].toGrid(finalArray[i], true); finalArray.push(this.gridManager.getEmptyGrid(gridSize, gridSize));
this.nextPieces[i].toGrid(finalArray[i], true);
} }
return finalArray; return finalArray;
} }
recoverNextPiece() { recoverNextPiece() {
this.#currentObject = this.#nextPieces.shift(); this.currentObject = this.nextPieces.shift();
this.generateNextPieces(); this.generateNextPieces();
} }
generateNextPieces() { generateNextPieces() {
while (this.#nextPieces.length < this.#nextPiecesCount) { while (this.nextPieces.length < this.nextPiecesCount) {
this.#nextPieces.push(new Piece(this.#theme)); this.nextPieces.push(new Piece(this.theme));
} }
} }
createTetromino() { createTetromino() {
this.pressedOut(); this.pressedOut();
this.recoverNextPiece(); this.recoverNextPiece();
if (!this.#currentObject.isPositionValid(this.#gridManager.getCurrentGrid(), this.getWidth(), this.getHeight())) if (
!this.currentObject.isPositionValid(
this.gridManager.getCurrentGrid(),
this.getWidth(),
this.getHeight(),
)
)
this.endGame(false); this.endGame(false);
} }
togglePause() { togglePause() {
if (!this.#gameRunning) if (!this.gameRunning) return;
return; this.gamePaused = !this.gamePaused;
this.#gamePaused = !this.#gamePaused; if (this.gamePaused) this.stopGameTime();
if (this.#gamePaused) { else this.startGameTime();
clearInterval(this.#gameTickInterval);
clearInterval(this.#gameTimeInterval);
} else {
this.#gameTickInterval = setInterval(this.#onTick, this.#gameTick);
this.#gameTimeInterval = setInterval(this.#onClock, 1000);
}
}
stopGame() {
this.#gameRunning = false;
this.#gamePaused = false;
clearInterval(this.#gameTickInterval);
clearInterval(this.#gameTimeInterval);
} }
endGame(isRestart: boolean) { endGame(isRestart: boolean) {
this.stopGame(); this.gameRunning = false;
this.endCallback(this.#gameTime, this.#scoreManager.getScore(), isRestart); this.gamePaused = false;
this.stopGameTime();
this.endCallback(this.gameTime, this.scoreManager.getScore(), isRestart);
} }
startGame(tickCallback: Function, clockCallback: Function, endCallback: Function) { startGame(
if (this.#gameRunning) tickCallback: TickCallbackType,
this.endGame(true); clockCallback: ClockCallbackType,
this.#gameRunning = true; endCallback: EndCallbackType,
this.#gamePaused = false; ) {
this.#gameTime = 0; if (this.gameRunning) this.endGame(true);
this.#scoreManager = new ScoreManager(); this.gameRunning = true;
this.#gameTick = GameLogic.levelTicks[this.#scoreManager.getLevel()]; this.gamePaused = false;
this.#gridManager = new GridManager(this.getWidth(), this.getHeight(), this.#theme); this.gameTime = 0;
this.#nextPieces = []; this.scoreManager = new ScoreManager();
this.gameTick = GameLogic.levelTicks[this.scoreManager.getLevel()];
this.gridManager = new GridManager(
this.getWidth(),
this.getHeight(),
this.theme,
);
this.nextPieces = [];
this.generateNextPieces(); this.generateNextPieces();
this.createTetromino(); this.createTetromino();
tickCallback( tickCallback(
this.#scoreManager.getScore(), this.scoreManager.getScore(),
this.#scoreManager.getLevel(), this.scoreManager.getLevel(),
this.#gridManager.getCurrentGrid()); this.gridManager.getCurrentGrid(),
clockCallback(this.#gameTime); );
this.#onTick = this.onTick.bind(this, tickCallback); clockCallback(this.gameTime);
this.#onClock = this.onClock.bind(this, clockCallback); this.startTick();
this.#gameTickInterval = setInterval(this.#onTick, this.#gameTick); this.startClock();
this.#gameTimeInterval = setInterval(this.#onClock, 1000); this.tickCallback = tickCallback;
this.clockCallback = clockCallback;
this.endCallback = endCallback; this.endCallback = endCallback;
} }
} }

View file

@ -1,19 +1,19 @@
// @flow // @flow
import Piece from "./Piece"; import Piece from './Piece';
import ScoreManager from "./ScoreManager"; import ScoreManager from './ScoreManager';
import type {Coordinates} from '../Shapes/BaseShape'; import type {CoordinatesType} from '../Shapes/BaseShape';
import type {Grid} from "../components/GridComponent"; import type {GridType} from '../components/GridComponent';
import type {Cell} from "../components/CellComponent"; import type {CellType} from '../components/CellComponent';
import type {CustomTheme} from "../../../managers/ThemeManager"; import type {CustomThemeType} from '../../../managers/ThemeManager';
/** /**
* Class used to manage the game grid * Class used to manage the game grid
*/ */
export default class GridManager { export default class GridManager {
#currentGrid: GridType;
#currentGrid: Grid; #theme: CustomThemeType;
#theme: CustomTheme;
/** /**
* Initializes a grid of the given size * Initializes a grid of the given size
@ -22,7 +22,7 @@ export default class GridManager {
* @param height The grid height * @param height The grid height
* @param theme Object containing current theme * @param theme Object containing current theme
*/ */
constructor(width: number, height: number, theme: CustomTheme) { constructor(width: number, height: number, theme: CustomThemeType) {
this.#theme = theme; this.#theme = theme;
this.#currentGrid = this.getEmptyGrid(height, width); this.#currentGrid = this.getEmptyGrid(height, width);
} }
@ -30,9 +30,9 @@ export default class GridManager {
/** /**
* Get the current grid * Get the current grid
* *
* @return {Grid} The current grid * @return {GridType} The current grid
*/ */
getCurrentGrid(): Grid { getCurrentGrid(): GridType {
return this.#currentGrid; return this.#currentGrid;
} }
@ -40,11 +40,11 @@ export default class GridManager {
* Get a new empty grid line of the given size * Get a new empty grid line of the given size
* *
* @param width The line size * @param width The line size
* @return {Array<Cell>} * @return {Array<CellType>}
*/ */
getEmptyLine(width: number): Array<Cell> { getEmptyLine(width: number): Array<CellType> {
let line = []; const line = [];
for (let col = 0; col < width; col++) { for (let col = 0; col < width; col += 1) {
line.push({ line.push({
color: this.#theme.colors.tetrisBackground, color: this.#theme.colors.tetrisBackground,
isEmpty: true, isEmpty: true,
@ -59,11 +59,11 @@ export default class GridManager {
* *
* @param width The grid width * @param width The grid width
* @param height The grid height * @param height The grid height
* @return {Grid} A new empty grid * @return {GridType} A new empty grid
*/ */
getEmptyGrid(height: number, width: number): Grid { getEmptyGrid(height: number, width: number): GridType {
let grid = []; const grid = [];
for (let row = 0; row < height; row++) { for (let row = 0; row < height; row += 1) {
grid.push(this.getEmptyLine(width)); grid.push(this.getEmptyLine(width));
} }
return grid; return grid;
@ -78,7 +78,7 @@ export default class GridManager {
*/ */
clearLines(lines: Array<number>, scoreManager: ScoreManager) { clearLines(lines: Array<number>, scoreManager: ScoreManager) {
lines.sort(); lines.sort();
for (let i = 0; i < lines.length; i++) { for (let i = 0; i < lines.length; i += 1) {
this.#currentGrid.splice(lines[i], 1); this.#currentGrid.splice(lines[i], 1);
this.#currentGrid.unshift(this.getEmptyLine(this.#currentGrid[0].length)); this.#currentGrid.unshift(this.getEmptyLine(this.#currentGrid[0].length));
} }
@ -92,18 +92,17 @@ export default class GridManager {
* @param pos The piece's coordinates to check lines at * @param pos The piece's coordinates to check lines at
* @return {Array<number>} An array containing the line numbers to clear * @return {Array<number>} An array containing the line numbers to clear
*/ */
getLinesToClear(pos: Array<Coordinates>): Array<number> { getLinesToClear(pos: Array<CoordinatesType>): Array<number> {
let rows = []; const rows = [];
for (let i = 0; i < pos.length; i++) { for (let i = 0; i < pos.length; i += 1) {
let isLineFull = true; let isLineFull = true;
for (let col = 0; col < this.#currentGrid[pos[i].y].length; col++) { for (let col = 0; col < this.#currentGrid[pos[i].y].length; col += 1) {
if (this.#currentGrid[pos[i].y][col].isEmpty) { if (this.#currentGrid[pos[i].y][col].isEmpty) {
isLineFull = false; isLineFull = false;
break; break;
} }
} }
if (isLineFull && rows.indexOf(pos[i].y) === -1) if (isLineFull && rows.indexOf(pos[i].y) === -1) rows.push(pos[i].y);
rows.push(pos[i].y);
} }
return rows; return rows;
} }
@ -115,6 +114,9 @@ export default class GridManager {
* @param scoreManager A reference to the score manager * @param scoreManager A reference to the score manager
*/ */
freezeTetromino(currentObject: Piece, scoreManager: ScoreManager) { freezeTetromino(currentObject: Piece, scoreManager: ScoreManager) {
this.clearLines(this.getLinesToClear(currentObject.getCoordinates()), scoreManager); this.clearLines(
this.getLinesToClear(currentObject.getCoordinates()),
scoreManager,
);
} }
} }

View file

@ -1,14 +1,16 @@
import ShapeL from "../Shapes/ShapeL"; // @flow
import ShapeI from "../Shapes/ShapeI";
import ShapeJ from "../Shapes/ShapeJ"; import ShapeL from '../Shapes/ShapeL';
import ShapeO from "../Shapes/ShapeO"; import ShapeI from '../Shapes/ShapeI';
import ShapeS from "../Shapes/ShapeS"; import ShapeJ from '../Shapes/ShapeJ';
import ShapeT from "../Shapes/ShapeT"; import ShapeO from '../Shapes/ShapeO';
import ShapeZ from "../Shapes/ShapeZ"; import ShapeS from '../Shapes/ShapeS';
import type {Coordinates} from '../Shapes/BaseShape'; import ShapeT from '../Shapes/ShapeT';
import BaseShape from "../Shapes/BaseShape"; import ShapeZ from '../Shapes/ShapeZ';
import type {Grid} from "../components/GridComponent"; import type {CoordinatesType} from '../Shapes/BaseShape';
import type {CustomTheme} from "../../../managers/ThemeManager"; import BaseShape from '../Shapes/BaseShape';
import type {GridType} from '../components/GridComponent';
import type {CustomThemeType} from '../../../managers/ThemeManager';
/** /**
* Class used as an abstraction layer for shapes. * Class used as an abstraction layer for shapes.
@ -16,27 +18,20 @@ import type {CustomTheme} from "../../../managers/ThemeManager";
* *
*/ */
export default class Piece { export default class Piece {
shapes = [ShapeL, ShapeI, ShapeJ, ShapeO, ShapeS, ShapeT, ShapeZ];
#shapes = [ currentShape: BaseShape;
ShapeL,
ShapeI, theme: CustomThemeType;
ShapeJ,
ShapeO,
ShapeS,
ShapeT,
ShapeZ,
];
#currentShape: BaseShape;
#theme: CustomTheme;
/** /**
* Initializes this piece's color and shape * Initializes this piece's color and shape
* *
* @param theme Object containing current theme * @param theme Object containing current theme
*/ */
constructor(theme: CustomTheme) { constructor(theme: CustomThemeType) {
this.#currentShape = this.getRandomShape(theme); this.currentShape = this.getRandomShape(theme);
this.#theme = theme; this.theme = theme;
} }
/** /**
@ -44,8 +39,8 @@ export default class Piece {
* *
* @param theme Object containing current theme * @param theme Object containing current theme
*/ */
getRandomShape(theme: CustomTheme) { getRandomShape(theme: CustomThemeType): BaseShape {
return new this.#shapes[Math.floor(Math.random() * 7)](theme); return new this.shapes[Math.floor(Math.random() * 7)](theme);
} }
/** /**
@ -53,15 +48,18 @@ export default class Piece {
* *
* @param grid The grid to remove the piece from * @param grid The grid to remove the piece from
*/ */
removeFromGrid(grid: Grid) { removeFromGrid(grid: GridType) {
const pos: Array<Coordinates> = this.#currentShape.getCellsCoordinates(true); const pos: Array<CoordinatesType> = this.currentShape.getCellsCoordinates(
for (let i = 0; i < pos.length; i++) { true,
grid[pos[i].y][pos[i].x] = { );
color: this.#theme.colors.tetrisBackground, pos.forEach((coordinates: CoordinatesType) => {
// eslint-disable-next-line no-param-reassign
grid[coordinates.y][coordinates.x] = {
color: this.theme.colors.tetrisBackground,
isEmpty: true, isEmpty: true,
key: grid[pos[i].y][pos[i].x].key key: grid[coordinates.y][coordinates.x].key,
}; };
} });
} }
/** /**
@ -70,15 +68,18 @@ export default class Piece {
* @param grid The grid to add the piece to * @param grid The grid to add the piece to
* @param isPreview Should we use this piece's current position to determine the cells? * @param isPreview Should we use this piece's current position to determine the cells?
*/ */
toGrid(grid: Grid, isPreview: boolean) { toGrid(grid: GridType, isPreview: boolean) {
const pos: Array<Coordinates> = this.#currentShape.getCellsCoordinates(!isPreview); const pos: Array<CoordinatesType> = this.currentShape.getCellsCoordinates(
for (let i = 0; i < pos.length; i++) { !isPreview,
grid[pos[i].y][pos[i].x] = { );
color: this.#currentShape.getColor(), pos.forEach((coordinates: CoordinatesType) => {
// eslint-disable-next-line no-param-reassign
grid[coordinates.y][coordinates.x] = {
color: this.currentShape.getColor(),
isEmpty: false, isEmpty: false,
key: grid[pos[i].y][pos[i].x].key key: grid[coordinates.y][coordinates.x].key,
}; };
} });
} }
/** /**
@ -89,15 +90,19 @@ export default class Piece {
* @param height The grid's height * @param height The grid's height
* @return {boolean} If the position is valid * @return {boolean} If the position is valid
*/ */
isPositionValid(grid: Grid, width: number, height: number) { isPositionValid(grid: GridType, width: number, height: number): boolean {
let isValid = true; let isValid = true;
const pos: Array<Coordinates> = this.#currentShape.getCellsCoordinates(true); const pos: Array<CoordinatesType> = this.currentShape.getCellsCoordinates(
for (let i = 0; i < pos.length; i++) { true,
if (pos[i].x >= width );
|| pos[i].x < 0 for (let i = 0; i < pos.length; i += 1) {
|| pos[i].y >= height if (
|| pos[i].y < 0 pos[i].x >= width ||
|| !grid[pos[i].y][pos[i].x].isEmpty) { pos[i].x < 0 ||
pos[i].y >= height ||
pos[i].y < 0 ||
!grid[pos[i].y][pos[i].x].isEmpty
) {
isValid = false; isValid = false;
break; break;
} }
@ -116,24 +121,31 @@ export default class Piece {
* @param freezeCallback Callback to use if the piece should freeze itself * @param freezeCallback Callback to use if the piece should freeze itself
* @return {boolean} True if the move was valid, false otherwise * @return {boolean} True if the move was valid, false otherwise
*/ */
tryMove(x: number, y: number, grid: Grid, width: number, height: number, freezeCallback: () => void) { tryMove(
if (x > 1) x = 1; // Prevent moving from more than one tile x: number,
if (x < -1) x = -1; y: number,
if (y > 1) y = 1; grid: GridType,
if (y < -1) y = -1; width: number,
if (x !== 0 && y !== 0) y = 0; // Prevent diagonal movement height: number,
freezeCallback: () => void,
): boolean {
let newX = x;
let newY = y;
if (x > 1) newX = 1; // Prevent moving from more than one tile
if (x < -1) newX = -1;
if (y > 1) newY = 1;
if (y < -1) newY = -1;
if (x !== 0 && y !== 0) newY = 0; // Prevent diagonal movement
this.removeFromGrid(grid); this.removeFromGrid(grid);
this.#currentShape.move(x, y); this.currentShape.move(newX, newY);
let isValid = this.isPositionValid(grid, width, height); const isValid = this.isPositionValid(grid, width, height);
if (!isValid) if (!isValid) this.currentShape.move(-newX, -newY);
this.#currentShape.move(-x, -y);
let shouldFreeze = !isValid && y !== 0; const shouldFreeze = !isValid && newY !== 0;
this.toGrid(grid, false); this.toGrid(grid, false);
if (shouldFreeze) if (shouldFreeze) freezeCallback();
freezeCallback();
return isValid; return isValid;
} }
@ -145,11 +157,11 @@ export default class Piece {
* @param height The grid's height * @param height The grid's height
* @return {boolean} True if the rotation was valid, false otherwise * @return {boolean} True if the rotation was valid, false otherwise
*/ */
tryRotate(grid: Grid, width: number, height: number) { tryRotate(grid: GridType, width: number, height: number): boolean {
this.removeFromGrid(grid); this.removeFromGrid(grid);
this.#currentShape.rotate(true); this.currentShape.rotate(true);
if (!this.isPositionValid(grid, width, height)) { if (!this.isPositionValid(grid, width, height)) {
this.#currentShape.rotate(false); this.currentShape.rotate(false);
this.toGrid(grid, false); this.toGrid(grid, false);
return false; return false;
} }
@ -160,13 +172,13 @@ export default class Piece {
/** /**
* Gets this piece used cells coordinates * Gets this piece used cells coordinates
* *
* @return {Array<Coordinates>} An array of coordinates * @return {Array<CoordinatesType>} An array of coordinates
*/ */
getCoordinates(): Array<Coordinates> { getCoordinates(): Array<CoordinatesType> {
return this.#currentShape.getCellsCoordinates(true); return this.currentShape.getCellsCoordinates(true);
} }
getCurrentShape() { getCurrentShape(): BaseShape {
return this.#currentShape; return this.currentShape;
} }
} }

View file

@ -4,11 +4,12 @@
* Class used to manage game score * Class used to manage game score
*/ */
export default class ScoreManager { export default class ScoreManager {
#scoreLinesModifier = [40, 100, 300, 1200]; #scoreLinesModifier = [40, 100, 300, 1200];
#score: number; #score: number;
#level: number; #level: number;
#levelProgression: number; #levelProgression: number;
/** /**
@ -51,7 +52,7 @@ export default class ScoreManager {
* Increments the score by one * Increments the score by one
*/ */
incrementScore() { incrementScore() {
this.#score++; this.#score += 1;
} }
/** /**
@ -63,9 +64,9 @@ export default class ScoreManager {
* @param numberRemoved The number of lines removed at the same time * @param numberRemoved The number of lines removed at the same time
*/ */
addLinesRemovedPoints(numberRemoved: number) { addLinesRemovedPoints(numberRemoved: number) {
if (numberRemoved < 1 || numberRemoved > 4) if (numberRemoved < 1 || numberRemoved > 4) return;
return; this.#score +=
this.#score += this.#scoreLinesModifier[numberRemoved-1] * (this.#level + 1); this.#scoreLinesModifier[numberRemoved - 1] * (this.#level + 1);
switch (numberRemoved) { switch (numberRemoved) {
case 1: case 1:
this.#levelProgression += 1; this.#levelProgression += 1;
@ -79,6 +80,8 @@ export default class ScoreManager {
case 4: // Did a tetris ! case 4: // Did a tetris !
this.#levelProgression += 8; this.#levelProgression += 8;
break; break;
default:
break;
} }
} }
@ -89,13 +92,12 @@ export default class ScoreManager {
* *
* @return {boolean} True if the current level has changed * @return {boolean} True if the current level has changed
*/ */
canLevelUp() { canLevelUp(): boolean {
let canLevel = this.#levelProgression > this.#level * 5; const canLevel = this.#levelProgression > this.#level * 5;
if (canLevel){ if (canLevel) {
this.#levelProgression -= this.#level * 5; this.#levelProgression -= this.#level * 5;
this.#level++; this.#level += 1;
} }
return canLevel; return canLevel;
} }
} }

View file

@ -3,27 +3,28 @@
import * as React from 'react'; import * as React from 'react';
import {View} from 'react-native'; import {View} from 'react-native';
import {Caption, IconButton, Text, withTheme} from 'react-native-paper'; import {Caption, IconButton, Text, withTheme} from 'react-native-paper';
import MaterialCommunityIcons from "react-native-vector-icons/MaterialCommunityIcons"; import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons';
import GameLogic from "../logic/GameLogic"; import i18n from 'i18n-js';
import type {Grid} from "../components/GridComponent"; import {StackNavigationProp} from '@react-navigation/stack';
import GridComponent from "../components/GridComponent"; import GameLogic from '../logic/GameLogic';
import Preview from "../components/Preview"; import type {GridType} from '../components/GridComponent';
import i18n from "i18n-js"; import GridComponent from '../components/GridComponent';
import MaterialHeaderButtons, {Item} from "../../../components/Overrides/CustomHeaderButton"; import Preview from '../components/Preview';
import {StackNavigationProp} from "@react-navigation/stack"; import MaterialHeaderButtons, {
import type {CustomTheme} from "../../../managers/ThemeManager"; Item,
import type {OptionsDialogButton} from "../../../components/Dialogs/OptionsDialog"; } from '../../../components/Overrides/CustomHeaderButton';
import OptionsDialog from "../../../components/Dialogs/OptionsDialog"; import type {CustomThemeType} from '../../../managers/ThemeManager';
import type {OptionsDialogButtonType} from '../../../components/Dialogs/OptionsDialog';
import OptionsDialog from '../../../components/Dialogs/OptionsDialog';
type Props = { type PropsType = {
navigation: StackNavigationProp, navigation: StackNavigationProp,
route: { params: { highScore: number }, ... }, route: {params: {highScore: number}},
theme: CustomTheme, theme: CustomThemeType,
} };
type State = { type StateType = {
grid: Grid, grid: GridType,
gameRunning: boolean,
gameTime: number, gameTime: number,
gameScore: number, gameScore: number,
gameLevel: number, gameLevel: number,
@ -31,101 +32,320 @@ type State = {
dialogVisible: boolean, dialogVisible: boolean,
dialogTitle: string, dialogTitle: string,
dialogMessage: string, dialogMessage: string,
dialogButtons: Array<OptionsDialogButton>, dialogButtons: Array<OptionsDialogButtonType>,
onDialogDismiss: () => void, onDialogDismiss: () => void,
} };
class GameMainScreen extends React.Component<Props, State> { class GameMainScreen extends React.Component<PropsType, StateType> {
static getFormattedTime(seconds: number): string {
const date = new Date();
date.setHours(0);
date.setMinutes(0);
date.setSeconds(seconds);
let format;
if (date.getHours())
format = `${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`;
else if (date.getMinutes())
format = `${date.getMinutes()}:${date.getSeconds()}`;
else format = date.getSeconds().toString();
return format;
}
logic: GameLogic; logic: GameLogic;
highScore: number | null; highScore: number | null;
constructor(props) { constructor(props: PropsType) {
super(props); super(props);
this.logic = new GameLogic(20, 10, this.props.theme); this.logic = new GameLogic(20, 10, props.theme);
this.state = { this.state = {
grid: this.logic.getCurrentGrid(), grid: this.logic.getCurrentGrid(),
gameRunning: false,
gameTime: 0, gameTime: 0,
gameScore: 0, gameScore: 0,
gameLevel: 0, gameLevel: 0,
dialogVisible: false, dialogVisible: false,
dialogTitle: "", dialogTitle: '',
dialogMessage: "", dialogMessage: '',
dialogButtons: [], dialogButtons: [],
onDialogDismiss: () => { onDialogDismiss: () => {},
},
}; };
if (this.props.route.params != null) if (props.route.params != null)
this.highScore = this.props.route.params.highScore; this.highScore = props.route.params.highScore;
} }
componentDidMount() { componentDidMount() {
this.props.navigation.setOptions({ const {navigation} = this.props;
navigation.setOptions({
headerRight: this.getRightButton, headerRight: this.getRightButton,
}); });
this.startGame(); this.startGame();
} }
componentWillUnmount() { componentWillUnmount() {
this.logic.stopGame(); this.logic.endGame(false);
} }
getRightButton = () => { getRightButton = (): React.Node => {
return <MaterialHeaderButtons> return (
<Item title="pause" iconName="pause" onPress={this.togglePause}/> <MaterialHeaderButtons>
</MaterialHeaderButtons>; <Item title="pause" iconName="pause" onPress={this.togglePause} />
} </MaterialHeaderButtons>
);
};
getFormattedTime(seconds: number) { onTick = (score: number, level: number, newGrid: GridType) => {
let date = new Date();
date.setHours(0);
date.setMinutes(0);
date.setSeconds(seconds);
let format;
if (date.getHours())
format = date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds();
else if (date.getMinutes())
format = date.getMinutes() + ':' + date.getSeconds();
else
format = date.getSeconds();
return format;
}
onTick = (score: number, level: number, newGrid: Grid) => {
this.setState({ this.setState({
gameScore: score, gameScore: score,
gameLevel: level, gameLevel: level,
grid: newGrid, grid: newGrid,
}); });
} };
onClock = (time: number) => { onClock = (time: number) => {
this.setState({ this.setState({
gameTime: time, gameTime: time,
}); });
} };
updateGrid = (newGrid: Grid) => { onDialogDismiss = () => {
this.setState({ this.setState({dialogVisible: false});
grid: newGrid, };
});
}
updateGridScore = (newGrid: Grid, score: number) => { onGameEnd = (time: number, score: number, isRestart: boolean) => {
const {props, state} = this;
this.setState({ this.setState({
grid: newGrid, gameTime: time,
gameScore: score, gameScore: score,
}); });
if (!isRestart)
props.navigation.replace('game-start', {
score: state.gameScore,
level: state.gameLevel,
time: state.gameTime,
});
};
getStatusIcons(): React.Node {
const {props, state} = this;
return (
<View
style={{
flex: 1,
marginTop: 'auto',
marginBottom: 'auto',
}}>
<View
style={{
marginLeft: 'auto',
marginRight: 'auto',
}}>
<Caption
style={{
marginLeft: 'auto',
marginRight: 'auto',
marginBottom: 5,
}}>
{i18n.t('screens.game.time')}
</Caption>
<View
style={{
flexDirection: 'row',
}}>
<MaterialCommunityIcons
name="timer"
color={props.theme.colors.subtitle}
size={20}
/>
<Text
style={{
marginLeft: 5,
color: props.theme.colors.subtitle,
}}>
{GameMainScreen.getFormattedTime(state.gameTime)}
</Text>
</View>
</View>
<View
style={{
marginLeft: 'auto',
marginRight: 'auto',
marginTop: 20,
}}>
<Caption
style={{
marginLeft: 'auto',
marginRight: 'auto',
marginBottom: 5,
}}>
{i18n.t('screens.game.level')}
</Caption>
<View
style={{
flexDirection: 'row',
}}>
<MaterialCommunityIcons
name="gamepad-square"
color={props.theme.colors.text}
size={20}
/>
<Text
style={{
marginLeft: 5,
}}>
{state.gameLevel}
</Text>
</View>
</View>
</View>
);
} }
getScoreIcon(): React.Node {
const {props, state} = this;
const highScore =
this.highScore == null || state.gameScore > this.highScore
? state.gameScore
: this.highScore;
return (
<View
style={{
marginTop: 10,
marginBottom: 10,
}}>
<View
style={{
flexDirection: 'row',
marginLeft: 'auto',
marginRight: 'auto',
}}>
<Text
style={{
marginLeft: 5,
fontSize: 20,
}}>
{i18n.t('screens.game.score', {score: state.gameScore})}
</Text>
<MaterialCommunityIcons
name="star"
color={props.theme.colors.tetrisScore}
size={20}
style={{
marginTop: 'auto',
marginBottom: 'auto',
marginLeft: 5,
}}
/>
</View>
<View
style={{
flexDirection: 'row',
marginLeft: 'auto',
marginRight: 'auto',
marginTop: 5,
}}>
<Text
style={{
marginLeft: 5,
fontSize: 10,
color: props.theme.colors.textDisabled,
}}>
{i18n.t('screens.game.highScore', {score: highScore})}
</Text>
<MaterialCommunityIcons
name="star"
color={props.theme.colors.tetrisScore}
size={10}
style={{
marginTop: 'auto',
marginBottom: 'auto',
marginLeft: 5,
}}
/>
</View>
</View>
);
}
getControlButtons(): React.Node {
const {props} = this;
return (
<View
style={{
height: 80,
flexDirection: 'row',
}}>
<IconButton
icon="rotate-right-variant"
size={40}
onPress={() => {
this.logic.rotatePressed(this.updateGrid);
}}
style={{flex: 1}}
/>
<View
style={{
flexDirection: 'row',
flex: 4,
}}>
<IconButton
icon="chevron-left"
size={40}
style={{flex: 1}}
onPress={() => {
this.logic.pressedOut();
}}
onPressIn={() => {
this.logic.leftPressedIn(this.updateGrid);
}}
/>
<IconButton
icon="chevron-right"
size={40}
style={{flex: 1}}
onPress={() => {
this.logic.pressedOut();
}}
onPressIn={() => {
this.logic.rightPressed(this.updateGrid);
}}
/>
</View>
<IconButton
icon="arrow-down-bold"
size={40}
onPressIn={() => {
this.logic.downPressedIn(this.updateGridScore);
}}
onPress={() => {
this.logic.pressedOut();
}}
style={{flex: 1}}
color={props.theme.colors.tetrisScore}
/>
</View>
);
}
updateGrid = (newGrid: GridType) => {
this.setState({
grid: newGrid,
});
};
updateGridScore = (newGrid: GridType, score?: number) => {
this.setState((prevState: StateType): {
grid: GridType,
gameScore: number,
} => ({
grid: newGrid,
gameScore: score != null ? score : prevState.gameScore,
}));
};
togglePause = () => { togglePause = () => {
this.logic.togglePause(); this.logic.togglePause();
if (this.logic.isGamePaused()) if (this.logic.isGamePaused()) this.showPausePopup();
this.showPausePopup(); };
}
onDialogDismiss = () => this.setState({dialogVisible: false});
showPausePopup = () => { showPausePopup = () => {
const onDismiss = () => { const onDismiss = () => {
@ -134,228 +354,56 @@ class GameMainScreen extends React.Component<Props, State> {
}; };
this.setState({ this.setState({
dialogVisible: true, dialogVisible: true,
dialogTitle: i18n.t("screens.game.pause"), dialogTitle: i18n.t('screens.game.pause'),
dialogMessage: i18n.t("screens.game.pauseMessage"), dialogMessage: i18n.t('screens.game.pauseMessage'),
dialogButtons: [ dialogButtons: [
{ {
title: i18n.t("screens.game.restart.text"), title: i18n.t('screens.game.restart.text'),
onPress: this.showRestartConfirm onPress: this.showRestartConfirm,
}, },
{ {
title: i18n.t("screens.game.resume"), title: i18n.t('screens.game.resume'),
onPress: onDismiss onPress: onDismiss,
} },
], ],
onDialogDismiss: onDismiss, onDialogDismiss: onDismiss,
}); });
} };
showRestartConfirm = () => { showRestartConfirm = () => {
this.setState({ this.setState({
dialogVisible: true, dialogVisible: true,
dialogTitle: i18n.t("screens.game.restart.confirm"), dialogTitle: i18n.t('screens.game.restart.confirm'),
dialogMessage: i18n.t("screens.game.restart.confirmMessage"), dialogMessage: i18n.t('screens.game.restart.confirmMessage'),
dialogButtons: [ dialogButtons: [
{ {
title: i18n.t("screens.game.restart.confirmYes"), title: i18n.t('screens.game.restart.confirmYes'),
onPress: () => { onPress: () => {
this.onDialogDismiss(); this.onDialogDismiss();
this.startGame(); this.startGame();
} },
}, },
{ {
title: i18n.t("screens.game.restart.confirmNo"), title: i18n.t('screens.game.restart.confirmNo'),
onPress: this.showPausePopup onPress: this.showPausePopup,
} },
], ],
onDialogDismiss: this.showPausePopup, onDialogDismiss: this.showPausePopup,
}); });
} };
startGame = () => { startGame = () => {
this.logic.startGame(this.onTick, this.onClock, this.onGameEnd); this.logic.startGame(this.onTick, this.onClock, this.onGameEnd);
this.setState({ };
gameRunning: true,
});
}
onGameEnd = (time: number, score: number, isRestart: boolean) => { render(): React.Node {
this.setState({ const {props, state} = this;
gameTime: time,
gameScore: score,
gameRunning: false,
});
if (!isRestart)
this.props.navigation.replace(
"game-start",
{
score: this.state.gameScore,
level: this.state.gameLevel,
time: this.state.gameTime,
}
);
}
getStatusIcons() {
return (
<View style={{
flex: 1,
marginTop: "auto",
marginBottom: "auto"
}}>
<View style={{
marginLeft: 'auto',
marginRight: 'auto',
}}>
<Caption style={{
marginLeft: "auto",
marginRight: "auto",
marginBottom: 5,
}}>{i18n.t("screens.game.time")}</Caption>
<View style={{
flexDirection: "row"
}}>
<MaterialCommunityIcons
name={'timer'}
color={this.props.theme.colors.subtitle}
size={20}/>
<Text style={{
marginLeft: 5,
color: this.props.theme.colors.subtitle
}}>{this.getFormattedTime(this.state.gameTime)}</Text>
</View>
</View>
<View style={{
marginLeft: 'auto',
marginRight: 'auto',
marginTop: 20,
}}>
<Caption style={{
marginLeft: "auto",
marginRight: "auto",
marginBottom: 5,
}}>{i18n.t("screens.game.level")}</Caption>
<View style={{
flexDirection: "row"
}}>
<MaterialCommunityIcons
name={'gamepad-square'}
color={this.props.theme.colors.text}
size={20}/>
<Text style={{
marginLeft: 5
}}>{this.state.gameLevel}</Text>
</View>
</View>
</View>
);
}
getScoreIcon() {
let highScore = this.highScore == null || this.state.gameScore > this.highScore
? this.state.gameScore
: this.highScore;
return (
<View style={{
marginTop: 10,
marginBottom: 10,
}}>
<View style={{
flexDirection: "row",
marginLeft: "auto",
marginRight: "auto",
}}>
<Text style={{
marginLeft: 5,
fontSize: 20,
}}>{i18n.t("screens.game.score", {score: this.state.gameScore})}</Text>
<MaterialCommunityIcons
name={'star'}
color={this.props.theme.colors.tetrisScore}
size={20}
style={{
marginTop: "auto",
marginBottom: "auto",
marginLeft: 5
}}/>
</View>
<View style={{
flexDirection: "row",
marginLeft: "auto",
marginRight: "auto",
marginTop: 5,
}}>
<Text style={{
marginLeft: 5,
fontSize: 10,
color: this.props.theme.colors.textDisabled
}}>{i18n.t("screens.game.highScore", {score: highScore})}</Text>
<MaterialCommunityIcons
name={'star'}
color={this.props.theme.colors.tetrisScore}
size={10}
style={{
marginTop: "auto",
marginBottom: "auto",
marginLeft: 5
}}/>
</View>
</View>
);
}
getControlButtons() {
return (
<View style={{
height: 80,
flexDirection: "row"
}}>
<IconButton
icon="rotate-right-variant"
size={40}
onPress={() => this.logic.rotatePressed(this.updateGrid)}
style={{flex: 1}}
/>
<View style={{
flexDirection: 'row',
flex: 4
}}>
<IconButton
icon="chevron-left"
size={40}
style={{flex: 1}}
onPress={() => this.logic.pressedOut()}
onPressIn={() => this.logic.leftPressedIn(this.updateGrid)}
/>
<IconButton
icon="chevron-right"
size={40}
style={{flex: 1}}
onPress={() => this.logic.pressedOut()}
onPressIn={() => this.logic.rightPressed(this.updateGrid)}
/>
</View>
<IconButton
icon="arrow-down-bold"
size={40}
onPressIn={() => this.logic.downPressedIn(this.updateGridScore)}
onPress={() => this.logic.pressedOut()}
style={{flex: 1}}
color={this.props.theme.colors.tetrisScore}
/>
</View>
);
}
render() {
return ( return (
<View style={{flex: 1}}> <View style={{flex: 1}}>
<View style={{ <View
style={{
flex: 1, flex: 1,
flexDirection: "row", flexDirection: 'row',
}}> }}>
{this.getStatusIcons()} {this.getStatusIcons()}
<View style={{flex: 4}}> <View style={{flex: 4}}>
@ -363,12 +411,12 @@ class GameMainScreen extends React.Component<Props, State> {
<GridComponent <GridComponent
width={this.logic.getWidth()} width={this.logic.getWidth()}
height={this.logic.getHeight()} height={this.logic.getHeight()}
grid={this.state.grid} grid={state.grid}
style={{ style={{
backgroundColor: this.props.theme.colors.tetrisBackground, backgroundColor: props.theme.colors.tetrisBackground,
flex: 1, flex: 1,
marginLeft: "auto", marginLeft: 'auto',
marginRight: "auto", marginRight: 'auto',
}} }}
/> />
</View> </View>
@ -387,16 +435,15 @@ class GameMainScreen extends React.Component<Props, State> {
{this.getControlButtons()} {this.getControlButtons()}
<OptionsDialog <OptionsDialog
visible={this.state.dialogVisible} visible={state.dialogVisible}
title={this.state.dialogTitle} title={state.dialogTitle}
message={this.state.dialogMessage} message={state.dialogMessage}
buttons={this.state.dialogButtons} buttons={state.dialogButtons}
onDismiss={this.state.onDialogDismiss} onDismiss={state.onDialogDismiss}
/> />
</View> </View>
); );
} }
} }
export default withTheme(GameMainScreen); export default withTheme(GameMainScreen);

View file

@ -1,111 +1,105 @@
// @flow // @flow
import * as React from "react"; import * as React from 'react';
import {StackNavigationProp} from "@react-navigation/stack"; import {StackNavigationProp} from '@react-navigation/stack';
import type {CustomTheme} from "../../../managers/ThemeManager"; import {
import {Button, Card, Divider, Headline, Paragraph, Text, withTheme} from "react-native-paper"; Button,
import {View} from "react-native"; Card,
import i18n from "i18n-js"; Divider,
import Mascot, {MASCOT_STYLE} from "../../../components/Mascot/Mascot"; Headline,
import MascotPopup from "../../../components/Mascot/MascotPopup"; Paragraph,
import AsyncStorageManager from "../../../managers/AsyncStorageManager"; Text,
import type {Grid} from "../components/GridComponent"; withTheme,
import GridComponent from "../components/GridComponent"; } from 'react-native-paper';
import GridManager from "../logic/GridManager"; import {View} from 'react-native';
import Piece from "../logic/Piece"; import i18n from 'i18n-js';
import * as Animatable from "react-native-animatable"; import * as Animatable from 'react-native-animatable';
import MaterialCommunityIcons from "react-native-vector-icons/MaterialCommunityIcons"; import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons';
import LinearGradient from "react-native-linear-gradient"; import LinearGradient from 'react-native-linear-gradient';
import SpeechArrow from "../../../components/Mascot/SpeechArrow"; import type {CustomThemeType} from '../../../managers/ThemeManager';
import CollapsibleScrollView from "../../../components/Collapsible/CollapsibleScrollView"; import Mascot, {MASCOT_STYLE} from '../../../components/Mascot/Mascot';
import MascotPopup from '../../../components/Mascot/MascotPopup';
import AsyncStorageManager from '../../../managers/AsyncStorageManager';
import type {GridType} from '../components/GridComponent';
import GridComponent from '../components/GridComponent';
import GridManager from '../logic/GridManager';
import Piece from '../logic/Piece';
import SpeechArrow from '../../../components/Mascot/SpeechArrow';
import CollapsibleScrollView from '../../../components/Collapsible/CollapsibleScrollView';
type GameStats = { type GameStatsType = {
score: number, score: number,
level: number, level: number,
time: number, time: number,
} };
type Props = { type PropsType = {
navigation: StackNavigationProp, navigation: StackNavigationProp,
route: { route: {
params: GameStats params: GameStatsType,
}, },
theme: CustomTheme, theme: CustomThemeType,
} };
class GameStartScreen extends React.Component<Props> {
class GameStartScreen extends React.Component<PropsType> {
gridManager: GridManager; gridManager: GridManager;
scores: Array<number>; scores: Array<number>;
gameStats: GameStats | null; gameStats: GameStatsType | null;
isHighScore: boolean; isHighScore: boolean;
constructor(props: Props) { constructor(props: PropsType) {
super(props); super(props);
this.gridManager = new GridManager(4, 4, props.theme); this.gridManager = new GridManager(4, 4, props.theme);
this.scores = AsyncStorageManager.getObject(AsyncStorageManager.PREFERENCES.gameScores.key); this.scores = AsyncStorageManager.getObject(
this.scores.sort((a, b) => b - a); AsyncStorageManager.PREFERENCES.gameScores.key,
if (this.props.route.params != null) );
this.recoverGameScore(); this.scores.sort((a: number, b: number): number => b - a);
if (props.route.params != null) this.recoverGameScore();
} }
recoverGameScore() { getPiecesBackground(): React.Node {
this.gameStats = this.props.route.params; const {theme} = this.props;
this.isHighScore = this.scores.length === 0 || this.gameStats.score > this.scores[0]; const gridList = [];
for (let i = 0; i < 3; i++) { for (let i = 0; i < 18; i += 1) {
if (this.scores.length > i && this.gameStats.score > this.scores[i]) {
this.scores.splice(i, 0, this.gameStats.score);
break;
} else if (this.scores.length <= i) {
this.scores.push(this.gameStats.score);
break;
}
}
if (this.scores.length > 3)
this.scores.splice(3, 1);
AsyncStorageManager.set(AsyncStorageManager.PREFERENCES.gameScores.key, this.scores);
}
getPiecesBackground() {
let gridList = [];
for (let i = 0; i < 18; i++) {
gridList.push(this.gridManager.getEmptyGrid(4, 4)); gridList.push(this.gridManager.getEmptyGrid(4, 4));
const piece = new Piece(this.props.theme); const piece = new Piece(theme);
piece.toGrid(gridList[i], true); piece.toGrid(gridList[i], true);
} }
return ( return (
<View style={{ <View
position: "absolute", style={{
width: "100%", position: 'absolute',
height: "100%", width: '100%',
height: '100%',
}}> }}>
{gridList.map((item: Grid, index: number) => { {gridList.map((item: GridType, index: number): React.Node => {
const size = 10 + Math.floor(Math.random() * 30); const size = 10 + Math.floor(Math.random() * 30);
const top = Math.floor(Math.random() * 100); const top = Math.floor(Math.random() * 100);
const rot = Math.floor(Math.random() * 360); const rot = Math.floor(Math.random() * 360);
const left = (index % 6) * 20; const left = (index % 6) * 20;
const animDelay = size * 20; const animDelay = size * 20;
const animDuration = 2 * (2000 - (size * 30)); const animDuration = 2 * (2000 - size * 30);
return ( return (
<Animatable.View <Animatable.View
animation={"fadeInDownBig"} animation="fadeInDownBig"
delay={animDelay} delay={animDelay}
duration={animDuration} duration={animDuration}
key={"piece" + index.toString()} key={`piece${index.toString()}`}
style={{ style={{
width: size + "%", width: `${size}%`,
position: "absolute", position: 'absolute',
top: top + "%", top: `${top}%`,
left: left + "%", left: `${left}%`,
}} }}>
>
<GridComponent <GridComponent
width={4} width={4}
height={4} height={4}
grid={item} grid={item}
style={{ style={{
transform: [{rotateZ: rot + "deg"}], transform: [{rotateZ: `${rot}deg`}],
}} }}
/> />
</Animatable.View> </Animatable.View>
@ -115,26 +109,30 @@ class GameStartScreen extends React.Component<Props> {
); );
} }
getPostGameContent(stats: GameStats) { getPostGameContent(stats: GameStatsType): React.Node {
const {props} = this;
return ( return (
<View style={{ <View
flex: 1 style={{
flex: 1,
}}> }}>
<Mascot <Mascot
emotion={this.isHighScore ? MASCOT_STYLE.LOVE : MASCOT_STYLE.NORMAL} emotion={this.isHighScore ? MASCOT_STYLE.LOVE : MASCOT_STYLE.NORMAL}
animated={this.isHighScore} animated={this.isHighScore}
style={{ style={{
width: this.isHighScore ? "50%" : "30%", width: this.isHighScore ? '50%' : '30%',
marginLeft: this.isHighScore ? "auto" : null, marginLeft: this.isHighScore ? 'auto' : null,
marginRight: this.isHighScore ? "auto" : null, marginRight: this.isHighScore ? 'auto' : null,
}}/> }}
<SpeechArrow
style={{marginLeft: this.isHighScore ? "60%" : "20%"}}
size={20}
color={this.props.theme.colors.mascotMessageArrow}
/> />
<Card style={{ <SpeechArrow
borderColor: this.props.theme.colors.mascotMessageArrow, style={{marginLeft: this.isHighScore ? '60%' : '20%'}}
size={20}
color={props.theme.colors.mascotMessageArrow}
/>
<Card
style={{
borderColor: props.theme.colors.mascotMessageArrow,
borderWidth: 2, borderWidth: 2,
marginLeft: 20, marginLeft: 20,
marginRight: 20, marginRight: 20,
@ -142,95 +140,101 @@ class GameStartScreen extends React.Component<Props> {
<Card.Content> <Card.Content>
<Headline <Headline
style={{ style={{
textAlign: "center", textAlign: 'center',
color: this.isHighScore color: this.isHighScore
? this.props.theme.colors.gameGold ? props.theme.colors.gameGold
: this.props.theme.colors.primary : props.theme.colors.primary,
}}> }}>
{this.isHighScore {this.isHighScore
? i18n.t("screens.game.newHighScore") ? i18n.t('screens.game.newHighScore')
: i18n.t("screens.game.gameOver")} : i18n.t('screens.game.gameOver')}
</Headline> </Headline>
<Divider/> <Divider />
<View style={{ <View
flexDirection: "row", style={{
marginLeft: "auto", flexDirection: 'row',
marginRight: "auto", marginLeft: 'auto',
marginRight: 'auto',
marginTop: 10, marginTop: 10,
marginBottom: 10, marginBottom: 10,
}}> }}>
<Text style={{ <Text
style={{
fontSize: 20, fontSize: 20,
}}> }}>
{i18n.t("screens.game.score", {score: stats.score})} {i18n.t('screens.game.score', {score: stats.score})}
</Text> </Text>
<MaterialCommunityIcons <MaterialCommunityIcons
name={'star'} name="star"
color={this.props.theme.colors.tetrisScore} color={props.theme.colors.tetrisScore}
size={30} size={30}
style={{ style={{
marginLeft: 5 marginLeft: 5,
}}/> }}
/>
</View> </View>
<View style={{ <View
flexDirection: "row", style={{
marginLeft: "auto", flexDirection: 'row',
marginRight: "auto", marginLeft: 'auto',
marginRight: 'auto',
}}> }}>
<Text>{i18n.t("screens.game.level")}</Text> <Text>{i18n.t('screens.game.level')}</Text>
<MaterialCommunityIcons <MaterialCommunityIcons
style={{ style={{
marginRight: 5, marginRight: 5,
marginLeft: 5, marginLeft: 5,
}} }}
name={"gamepad-square"} name="gamepad-square"
size={20} size={20}
color={this.props.theme.colors.textDisabled} color={props.theme.colors.textDisabled}
/> />
<Text> <Text>{stats.level}</Text>
{stats.level}
</Text>
</View> </View>
<View style={{ <View
flexDirection: "row", style={{
marginLeft: "auto", flexDirection: 'row',
marginRight: "auto", marginLeft: 'auto',
marginRight: 'auto',
}}> }}>
<Text>{i18n.t("screens.game.time")}</Text> <Text>{i18n.t('screens.game.time')}</Text>
<MaterialCommunityIcons <MaterialCommunityIcons
style={{ style={{
marginRight: 5, marginRight: 5,
marginLeft: 5, marginLeft: 5,
}} }}
name={"timer"} name="timer"
size={20} size={20}
color={this.props.theme.colors.textDisabled} color={props.theme.colors.textDisabled}
/> />
<Text> <Text>{stats.time}</Text>
{stats.time}
</Text>
</View> </View>
</Card.Content> </Card.Content>
</Card> </Card>
</View> </View>
) );
} }
getWelcomeText() { getWelcomeText(): React.Node {
const {props} = this;
return ( return (
<View> <View>
<Mascot emotion={MASCOT_STYLE.COOL} style={{ <Mascot
width: "40%", emotion={MASCOT_STYLE.COOL}
marginLeft: "auto", style={{
marginRight: "auto", width: '40%',
}}/> marginLeft: 'auto',
<SpeechArrow marginRight: 'auto',
style={{marginLeft: "60%"}} }}
size={20}
color={this.props.theme.colors.mascotMessageArrow}
/> />
<Card style={{ <SpeechArrow
borderColor: this.props.theme.colors.mascotMessageArrow, style={{marginLeft: '60%'}}
size={20}
color={props.theme.colors.mascotMessageArrow}
/>
<Card
style={{
borderColor: props.theme.colors.mascotMessageArrow,
borderWidth: 2, borderWidth: 2,
marginLeft: 10, marginLeft: 10,
marginRight: 10, marginRight: 10,
@ -238,18 +242,18 @@ class GameStartScreen extends React.Component<Props> {
<Card.Content> <Card.Content>
<Headline <Headline
style={{ style={{
textAlign: "center", textAlign: 'center',
color: this.props.theme.colors.primary color: props.theme.colors.primary,
}}> }}>
{i18n.t("screens.game.welcomeTitle")} {i18n.t('screens.game.welcomeTitle')}
</Headline> </Headline>
<Divider/> <Divider />
<Paragraph <Paragraph
style={{ style={{
textAlign: "center", textAlign: 'center',
marginTop: 10, marginTop: 10,
}}> }}>
{i18n.t("screens.game.welcomeMessage")} {i18n.t('screens.game.welcomeMessage')}
</Paragraph> </Paragraph>
</Card.Content> </Card.Content>
</Card> </Card>
@ -257,93 +261,88 @@ class GameStartScreen extends React.Component<Props> {
); );
} }
getPodiumRender(place: 1 | 2 | 3, score: string) { getPodiumRender(place: 1 | 2 | 3, score: string): React.Node {
let icon = "podium-gold"; const {props} = this;
let color = this.props.theme.colors.gameGold; let icon = 'podium-gold';
let color = props.theme.colors.gameGold;
let fontSize = 20; let fontSize = 20;
let size = 70; let size = 70;
if (place === 2) { if (place === 2) {
icon = "podium-silver"; icon = 'podium-silver';
color = this.props.theme.colors.gameSilver; color = props.theme.colors.gameSilver;
fontSize = 18; fontSize = 18;
size = 60; size = 60;
} else if (place === 3) { } else if (place === 3) {
icon = "podium-bronze"; icon = 'podium-bronze';
color = this.props.theme.colors.gameBronze; color = props.theme.colors.gameBronze;
fontSize = 15; fontSize = 15;
size = 50; size = 50;
} }
return ( return (
<View style={{ <View
marginLeft: place === 2 ? 20 : "auto", style={{
marginRight: place === 3 ? 20 : "auto", marginLeft: place === 2 ? 20 : 'auto',
flexDirection: "column", marginRight: place === 3 ? 20 : 'auto',
alignItems: "center", flexDirection: 'column',
justifyContent: "flex-end", alignItems: 'center',
justifyContent: 'flex-end',
}}> }}>
{ {this.isHighScore && place === 1 ? (
this.isHighScore && place === 1
?
<Animatable.View <Animatable.View
animation={"swing"} animation="swing"
iterationCount={"infinite"} iterationCount="infinite"
duration={2000} duration={2000}
delay={1000} delay={1000}
useNativeDriver={true} useNativeDriver
style={{ style={{
position: "absolute", position: 'absolute',
top: -20 top: -20,
}} }}>
>
<Animatable.View <Animatable.View
animation={"pulse"} animation="pulse"
iterationCount={"infinite"} iterationCount="infinite"
useNativeDriver={true} useNativeDriver>
>
<MaterialCommunityIcons <MaterialCommunityIcons
name={"decagram"} name="decagram"
color={this.props.theme.colors.gameGold} color={props.theme.colors.gameGold}
size={150} size={150}
/> />
</Animatable.View> </Animatable.View>
</Animatable.View> </Animatable.View>
) : null}
: null
}
<MaterialCommunityIcons <MaterialCommunityIcons
name={icon} name={icon}
color={this.isHighScore && place === 1 ? "#fff" : color} color={this.isHighScore && place === 1 ? '#fff' : color}
size={size} size={size}
/> />
<Text style={{ <Text
textAlign: "center", style={{
fontWeight: place === 1 ? "bold" : null, textAlign: 'center',
fontSize: fontSize, fontWeight: place === 1 ? 'bold' : null,
}}>{score}</Text> fontSize,
}}>
{score}
</Text>
</View> </View>
); );
} }
getTopScoresRender() { getTopScoresRender(): React.Node {
const gold = this.scores.length > 0 const gold = this.scores.length > 0 ? this.scores[0] : '-';
? this.scores[0] const silver = this.scores.length > 1 ? this.scores[1] : '-';
: "-"; const bronze = this.scores.length > 2 ? this.scores[2] : '-';
const silver = this.scores.length > 1
? this.scores[1]
: "-";
const bronze = this.scores.length > 2
? this.scores[2]
: "-";
return ( return (
<View style={{ <View
style={{
marginBottom: 20, marginBottom: 20,
marginTop: 20 marginTop: 20,
}}> }}>
{this.getPodiumRender(1, gold.toString())} {this.getPodiumRender(1, gold.toString())}
<View style={{ <View
flexDirection: "row", style={{
marginLeft: "auto", flexDirection: 'row',
marginRight: "auto", marginLeft: 'auto',
marginRight: 'auto',
}}> }}>
{this.getPodiumRender(3, bronze.toString())} {this.getPodiumRender(3, bronze.toString())}
{this.getPodiumRender(2, silver.toString())} {this.getPodiumRender(2, silver.toString())}
@ -352,76 +351,90 @@ class GameStartScreen extends React.Component<Props> {
); );
} }
getMainContent() { getMainContent(): React.Node {
const {props} = this;
return ( return (
<View style={{flex: 1}}> <View style={{flex: 1}}>
{ {this.gameStats != null
this.gameStats != null
? this.getPostGameContent(this.gameStats) ? this.getPostGameContent(this.gameStats)
: this.getWelcomeText() : this.getWelcomeText()}
}
<Button <Button
icon={"play"} icon="play"
mode={"contained"} mode="contained"
onPress={() => this.props.navigation.replace( onPress={() => {
"game-main", props.navigation.replace('game-main', {
{ highScore: this.scores.length > 0 ? this.scores[0] : null,
highScore: this.scores.length > 0 });
? this.scores[0]
: null
}
)}
style={{
marginLeft: "auto",
marginRight: "auto",
marginTop: 10,
}} }}
> style={{
{i18n.t("screens.game.play")} marginLeft: 'auto',
marginRight: 'auto',
marginTop: 10,
}}>
{i18n.t('screens.game.play')}
</Button> </Button>
{this.getTopScoresRender()} {this.getTopScoresRender()}
</View> </View>
) );
} }
keyExtractor = (item: number) => item.toString(); keyExtractor = (item: number): string => item.toString();
render() { recoverGameScore() {
const {route} = this.props;
this.gameStats = route.params;
this.isHighScore =
this.scores.length === 0 || this.gameStats.score > this.scores[0];
for (let i = 0; i < 3; i += 1) {
if (this.scores.length > i && this.gameStats.score > this.scores[i]) {
this.scores.splice(i, 0, this.gameStats.score);
break;
} else if (this.scores.length <= i) {
this.scores.push(this.gameStats.score);
break;
}
}
if (this.scores.length > 3) this.scores.splice(3, 1);
AsyncStorageManager.set(
AsyncStorageManager.PREFERENCES.gameScores.key,
this.scores,
);
}
render(): React.Node {
const {props} = this;
return ( return (
<View style={{flex: 1}}> <View style={{flex: 1}}>
{this.getPiecesBackground()} {this.getPiecesBackground()}
<LinearGradient <LinearGradient
style={{flex: 1}} style={{flex: 1}}
colors={[ colors={[
this.props.theme.colors.background + "00", `${props.theme.colors.background}00`,
this.props.theme.colors.background props.theme.colors.background,
]} ]}
start={{x: 0, y: 0}} start={{x: 0, y: 0}}
end={{x: 0, y: 1}} end={{x: 0, y: 1}}>
>
<CollapsibleScrollView> <CollapsibleScrollView>
{this.getMainContent()} {this.getMainContent()}
<MascotPopup <MascotPopup
prefKey={AsyncStorageManager.PREFERENCES.gameStartShowBanner.key} prefKey={AsyncStorageManager.PREFERENCES.gameStartShowBanner.key}
title={i18n.t("screens.game.mascotDialog.title")} title={i18n.t('screens.game.mascotDialog.title')}
message={i18n.t("screens.game.mascotDialog.message")} message={i18n.t('screens.game.mascotDialog.message')}
icon={"gamepad-variant"} icon="gamepad-variant"
buttons={{ buttons={{
action: null, action: null,
cancel: { cancel: {
message: i18n.t("screens.game.mascotDialog.button"), message: i18n.t('screens.game.mascotDialog.button'),
icon: "check", icon: 'check',
} },
}} }}
emotion={MASCOT_STYLE.COOL} emotion={MASCOT_STYLE.COOL}
/> />
</CollapsibleScrollView> </CollapsibleScrollView>
</LinearGradient> </LinearGradient>
</View> </View>
); );
} }
} }
export default withTheme(GameStartScreen); export default withTheme(GameStartScreen);

View file

@ -19,7 +19,7 @@ import MaterialHeaderButtons, {
Item, Item,
} from '../../components/Overrides/CustomHeaderButton'; } from '../../components/Overrides/CustomHeaderButton';
import AnimatedFAB from '../../components/Animations/AnimatedFAB'; import AnimatedFAB from '../../components/Animations/AnimatedFAB';
import type {CustomTheme} from '../../managers/ThemeManager'; import type {CustomThemeType} from '../../managers/ThemeManager';
import ConnectionManager from '../../managers/ConnectionManager'; import ConnectionManager from '../../managers/ConnectionManager';
import LogoutDialog from '../../components/Amicale/LogoutDialog'; import LogoutDialog from '../../components/Amicale/LogoutDialog';
import AsyncStorageManager from '../../managers/AsyncStorageManager'; import AsyncStorageManager from '../../managers/AsyncStorageManager';
@ -78,7 +78,7 @@ type RawDashboardType = {
type PropsType = { type PropsType = {
navigation: StackNavigationProp, navigation: StackNavigationProp,
route: {params: {nextScreen: string, data: {...}}}, route: {params: {nextScreen: string, data: {...}}},
theme: CustomTheme, theme: CustomThemeType,
}; };
type StateType = { type StateType = {

View file

@ -1,14 +1,14 @@
// @flow // @flow
import * as React from 'react'; import * as React from 'react';
import {Avatar, Button, Card, Paragraph, withTheme} from "react-native-paper"; import {Avatar, Button, Card, Paragraph, withTheme} from 'react-native-paper';
import i18n from "i18n-js"; import i18n from 'i18n-js';
import {Linking} from "react-native"; import {Linking} from 'react-native';
import type {CustomTheme} from "../../managers/ThemeManager"; import type {CustomThemeType} from '../../managers/ThemeManager';
import CollapsibleScrollView from "../../components/Collapsible/CollapsibleScrollView"; import CollapsibleScrollView from '../../components/Collapsible/CollapsibleScrollView';
type Props = { type PropsType = {
theme: CustomTheme theme: CustomThemeType,
}; };
const links = { const links = {
@ -18,95 +18,118 @@ Informations sur ton système si tu sais (iOS ou Android, modèle du tel, versio
Nature du problème :\n\n\n Nature du problème :\n\n\n
Étapes pour reproduire ce pb :\n\n\n\n Étapes pour reproduire ce pb :\n\n\n\n
Stp corrige le pb, bien cordialement.`, Stp corrige le pb, bien cordialement.`,
bugsGit: 'https://git.etud.insa-toulouse.fr/vergnet/application-amicale/issues/new', bugsGit:
facebook: "https://www.facebook.com/campus.insat", 'https://git.etud.insa-toulouse.fr/vergnet/application-amicale/issues/new',
facebook: 'https://www.facebook.com/campus.insat',
feedbackMail: `mailto:app@amicale-insat.fr?subject=[FEEDBACK] Application CAMPUS feedbackMail: `mailto:app@amicale-insat.fr?subject=[FEEDBACK] Application CAMPUS
&body=Coucou Arnaud j'ai du feedback\n\n\n\nBien cordialement.`, &body=Coucou Arnaud j'ai du feedback\n\n\n\nBien cordialement.`,
feedbackGit: "https://git.etud.insa-toulouse.fr/vergnet/application-amicale/issues/new", feedbackGit:
} 'https://git.etud.insa-toulouse.fr/vergnet/application-amicale/issues/new',
};
class FeedbackScreen extends React.Component<Props> {
class FeedbackScreen extends React.Component<PropsType> {
/** /**
* Gets link buttons * Gets link buttons
* *
* @param isBug True if buttons should redirect to bug report methods * @param isBug True if buttons should redirect to bug report methods
* @returns {*} * @returns {*}
*/ */
getButtons(isBug: boolean) { static getButtons(isBug: boolean): React.Node {
return ( return (
<Card.Actions style={{ <Card.Actions
style={{
flex: 1, flex: 1,
flexWrap: 'wrap', flexWrap: 'wrap',
}}> }}>
<Button <Button
icon="email" icon="email"
mode={"contained"} mode="contained"
style={{ style={{
marginLeft: 'auto', marginLeft: 'auto',
marginTop: 5, marginTop: 5,
}} }}
onPress={() => Linking.openURL(isBug ? links.bugsMail : links.feedbackMail)}> onPress={() => {
Linking.openURL(isBug ? links.bugsMail : links.feedbackMail);
}}>
MAIL MAIL
</Button> </Button>
<Button <Button
icon="git" icon="git"
mode={"contained"} mode="contained"
color={"#609927"} color="#609927"
style={{ style={{
marginLeft: 'auto', marginLeft: 'auto',
marginTop: 5, marginTop: 5,
}} }}
onPress={() => Linking.openURL(isBug ? links.bugsGit : links.feedbackGit)}> onPress={() => {
Linking.openURL(isBug ? links.bugsGit : links.feedbackGit);
}}>
GITEA GITEA
</Button> </Button>
<Button <Button
icon="facebook" icon="facebook"
mode={"contained"} mode="contained"
color={"#2e88fe"} color="#2e88fe"
style={{ style={{
marginLeft: 'auto', marginLeft: 'auto',
marginTop: 5, marginTop: 5,
}} }}
onPress={() => Linking.openURL(links.facebook)}> onPress={() => {
Linking.openURL(links.facebook);
}}>
Facebook Facebook
</Button> </Button>
</Card.Actions> </Card.Actions>
); );
} }
render() { render(): React.Node {
const {theme} = this.props;
return ( return (
<CollapsibleScrollView style={{padding: 5}}> <CollapsibleScrollView style={{padding: 5}}>
<Card> <Card>
<Card.Title <Card.Title
title={i18n.t('screens.feedback.bugs')} title={i18n.t('screens.feedback.bugs')}
subtitle={i18n.t('screens.feedback.bugsSubtitle')} subtitle={i18n.t('screens.feedback.bugsSubtitle')}
left={(props) => <Avatar.Icon {...props} icon="bug"/>} left={({
size,
color,
}: {
size: number,
color: number,
}): React.Node => (
<Avatar.Icon size={size} color={color} icon="bug" />
)}
/> />
<Card.Content> <Card.Content>
<Paragraph> <Paragraph>{i18n.t('screens.feedback.bugsDescription')}</Paragraph>
{i18n.t('screens.feedback.bugsDescription')} <Paragraph style={{color: theme.colors.primary}}>
</Paragraph>
<Paragraph style={{color: this.props.theme.colors.primary}}>
{i18n.t('screens.feedback.contactMeans')} {i18n.t('screens.feedback.contactMeans')}
</Paragraph> </Paragraph>
</Card.Content> </Card.Content>
{this.getButtons(true)} {FeedbackScreen.getButtons(true)}
</Card> </Card>
<Card style={{marginTop: 20, marginBottom: 10}}> <Card style={{marginTop: 20, marginBottom: 10}}>
<Card.Title <Card.Title
title={i18n.t('screens.feedback.title')} title={i18n.t('screens.feedback.title')}
subtitle={i18n.t('screens.feedback.feedbackSubtitle')} subtitle={i18n.t('screens.feedback.feedbackSubtitle')}
left={(props) => <Avatar.Icon {...props} icon="comment"/>} left={({
size,
color,
}: {
size: number,
color: number,
}): React.Node => (
<Avatar.Icon size={size} color={color} icon="comment" />
)}
/> />
<Card.Content> <Card.Content>
<Paragraph> <Paragraph>
{i18n.t('screens.feedback.feedbackDescription')} {i18n.t('screens.feedback.feedbackDescription')}
</Paragraph> </Paragraph>
</Card.Content> </Card.Content>
{this.getButtons(false)} {FeedbackScreen.getButtons(false)}
</Card> </Card>
</CollapsibleScrollView> </CollapsibleScrollView>
); );

View file

@ -1,26 +1,25 @@
// @flow // @flow
import * as React from 'react'; import * as React from 'react';
import {View} from "react-native"; import {View} from 'react-native';
import type {CustomTheme} from "../../../managers/ThemeManager"; import i18n from 'i18n-js';
import ThemeManager from '../../../managers/ThemeManager';
import i18n from "i18n-js";
import AsyncStorageManager from "../../../managers/AsyncStorageManager";
import {Card, List, Switch, ToggleButton, withTheme} from 'react-native-paper'; import {Card, List, Switch, ToggleButton, withTheme} from 'react-native-paper';
import {Appearance} from "react-native-appearance"; import {Appearance} from 'react-native-appearance';
import CustomSlider from "../../../components/Overrides/CustomSlider"; import {StackNavigationProp} from '@react-navigation/stack';
import {StackNavigationProp} from "@react-navigation/stack"; import type {CustomThemeType} from '../../../managers/ThemeManager';
import CollapsibleScrollView from "../../../components/Collapsible/CollapsibleScrollView"; import ThemeManager from '../../../managers/ThemeManager';
import AsyncStorageManager from '../../../managers/AsyncStorageManager';
import CustomSlider from '../../../components/Overrides/CustomSlider';
import CollapsibleScrollView from '../../../components/Collapsible/CollapsibleScrollView';
type Props = { type PropsType = {
navigation: StackNavigationProp, navigation: StackNavigationProp,
theme: CustomTheme, theme: CustomThemeType,
}; };
type State = { type StateType = {
nightMode: boolean, nightMode: boolean,
nightModeFollowSystem: boolean, nightModeFollowSystem: boolean,
notificationReminderSelected: number,
startScreenPickerSelected: string, startScreenPickerSelected: string,
isDebugUnlocked: boolean, isDebugUnlocked: boolean,
}; };
@ -28,8 +27,7 @@ type State = {
/** /**
* Class defining the Settings screen. This screen shows controls to modify app preferences. * Class defining the Settings screen. This screen shows controls to modify app preferences.
*/ */
class SettingsScreen extends React.Component<Props, State> { class SettingsScreen extends React.Component<PropsType, StateType> {
savedNotificationReminder: number; savedNotificationReminder: number;
/** /**
@ -37,37 +35,38 @@ class SettingsScreen extends React.Component<Props, State> {
*/ */
constructor() { constructor() {
super(); super();
let notifReminder = AsyncStorageManager.getString(AsyncStorageManager.PREFERENCES.proxiwashNotifications.key); const notifReminder = AsyncStorageManager.getString(
this.savedNotificationReminder = parseInt(notifReminder); AsyncStorageManager.PREFERENCES.proxiwashNotifications.key,
if (isNaN(this.savedNotificationReminder)) );
this.savedNotificationReminder = parseInt(notifReminder, 10);
if (Number.isNaN(this.savedNotificationReminder))
this.savedNotificationReminder = 0; this.savedNotificationReminder = 0;
this.state = { this.state = {
nightMode: ThemeManager.getNightMode(), nightMode: ThemeManager.getNightMode(),
nightModeFollowSystem: AsyncStorageManager.getBool(AsyncStorageManager.PREFERENCES.nightModeFollowSystem.key) nightModeFollowSystem:
&& Appearance.getColorScheme() !== 'no-preference', AsyncStorageManager.getBool(
notificationReminderSelected: this.savedNotificationReminder, AsyncStorageManager.PREFERENCES.nightModeFollowSystem.key,
startScreenPickerSelected: AsyncStorageManager.getString(AsyncStorageManager.PREFERENCES.defaultStartScreen.key), ) && Appearance.getColorScheme() !== 'no-preference',
isDebugUnlocked: AsyncStorageManager.getBool(AsyncStorageManager.PREFERENCES.debugUnlocked.key) startScreenPickerSelected: AsyncStorageManager.getString(
AsyncStorageManager.PREFERENCES.defaultStartScreen.key,
),
isDebugUnlocked: AsyncStorageManager.getBool(
AsyncStorageManager.PREFERENCES.debugUnlocked.key,
),
}; };
} }
/**
* Unlocks debug mode and saves its state to user preferences
*/
unlockDebugMode = () => {
this.setState({isDebugUnlocked: true});
AsyncStorageManager.set(AsyncStorageManager.PREFERENCES.debugUnlocked.key, true);
}
/** /**
* Saves the value for the proxiwash reminder notification time * Saves the value for the proxiwash reminder notification time
* *
* @param value The value to store * @param value The value to store
*/ */
onProxiwashNotifPickerValueChange = (value: number) => { onProxiwashNotifPickerValueChange = (value: number) => {
this.setState({notificationReminderSelected: value}); AsyncStorageManager.set(
AsyncStorageManager.set(AsyncStorageManager.PREFERENCES.proxiwashNotifications.key, value); AsyncStorageManager.PREFERENCES.proxiwashNotifications.key,
value,
);
}; };
/** /**
@ -78,7 +77,10 @@ class SettingsScreen extends React.Component<Props, State> {
onStartScreenPickerValueChange = (value: string) => { onStartScreenPickerValueChange = (value: string) => {
if (value != null) { if (value != null) {
this.setState({startScreenPickerSelected: value}); this.setState({startScreenPickerSelected: value});
AsyncStorageManager.set(AsyncStorageManager.PREFERENCES.defaultStartScreen.key, value); AsyncStorageManager.set(
AsyncStorageManager.PREFERENCES.defaultStartScreen.key,
value,
);
} }
}; };
@ -87,7 +89,8 @@ class SettingsScreen extends React.Component<Props, State> {
* *
* @returns {React.Node} * @returns {React.Node}
*/ */
getProxiwashNotifPicker() { getProxiwashNotifPicker(): React.Node {
const {theme} = this.props;
return ( return (
<CustomSlider <CustomSlider
style={{flex: 1, marginHorizontal: 10, height: 50}} style={{flex: 1, marginHorizontal: 10, height: 50}}
@ -96,8 +99,8 @@ class SettingsScreen extends React.Component<Props, State> {
step={1} step={1}
value={this.savedNotificationReminder} value={this.savedNotificationReminder}
onValueChange={this.onProxiwashNotifPickerValueChange} onValueChange={this.onProxiwashNotifPickerValueChange}
thumbTintColor={this.props.theme.colors.primary} thumbTintColor={theme.colors.primary}
minimumTrackTintColor={this.props.theme.colors.primary} minimumTrackTintColor={theme.colors.primary}
/> />
); );
} }
@ -107,18 +110,18 @@ class SettingsScreen extends React.Component<Props, State> {
* *
* @returns {React.Node} * @returns {React.Node}
*/ */
getStartScreenPicker() { getStartScreenPicker(): React.Node {
const {startScreenPickerSelected} = this.state;
return ( return (
<ToggleButton.Row <ToggleButton.Row
onValueChange={this.onStartScreenPickerValueChange} onValueChange={this.onStartScreenPickerValueChange}
value={this.state.startScreenPickerSelected} value={startScreenPickerSelected}
style={{marginLeft: 'auto', marginRight: 'auto'}} style={{marginLeft: 'auto', marginRight: 'auto'}}>
> <ToggleButton icon="account-circle" value="services" />
<ToggleButton icon="account-circle" value="services"/> <ToggleButton icon="tshirt-crew" value="proxiwash" />
<ToggleButton icon="tshirt-crew" value="proxiwash"/> <ToggleButton icon="triangle" value="home" />
<ToggleButton icon="triangle" value="home"/> <ToggleButton icon="calendar-range" value="planning" />
<ToggleButton icon="calendar-range" value="planning"/> <ToggleButton icon="clock" value="planex" />
<ToggleButton icon="clock" value="planex"/>
</ToggleButton.Row> </ToggleButton.Row>
); );
} }
@ -127,18 +130,23 @@ class SettingsScreen extends React.Component<Props, State> {
* Toggles night mode and saves it to preferences * Toggles night mode and saves it to preferences
*/ */
onToggleNightMode = () => { onToggleNightMode = () => {
ThemeManager.getInstance().setNightMode(!this.state.nightMode); const {nightMode} = this.state;
this.setState({nightMode: !this.state.nightMode}); ThemeManager.getInstance().setNightMode(!nightMode);
this.setState({nightMode: !nightMode});
}; };
onToggleNightModeFollowSystem = () => { onToggleNightModeFollowSystem = () => {
const value = !this.state.nightModeFollowSystem; const {nightModeFollowSystem} = this.state;
const value = !nightModeFollowSystem;
this.setState({nightModeFollowSystem: value}); this.setState({nightModeFollowSystem: value});
AsyncStorageManager.set(AsyncStorageManager.PREFERENCES.nightModeFollowSystem.key, value); AsyncStorageManager.set(
AsyncStorageManager.PREFERENCES.nightModeFollowSystem.key,
value,
);
if (value) { if (value) {
const nightMode = Appearance.getColorScheme() === 'dark'; const nightMode = Appearance.getColorScheme() === 'dark';
ThemeManager.getInstance().setNightMode(nightMode); ThemeManager.getInstance().setNightMode(nightMode);
this.setState({nightMode: nightMode}); this.setState({nightMode});
} }
}; };
@ -152,81 +160,129 @@ class SettingsScreen extends React.Component<Props, State> {
* @param state The current state of the switch * @param state The current state of the switch
* @returns {React.Node} * @returns {React.Node}
*/ */
getToggleItem(onPressCallback: Function, icon: string, title: string, subtitle: string, state: boolean) { static getToggleItem(
onPressCallback: () => void,
icon: string,
title: string,
subtitle: string,
state: boolean,
): React.Node {
return ( return (
<List.Item <List.Item
title={title} title={title}
description={subtitle} description={subtitle}
left={props => <List.Icon {...props} icon={icon}/>} left={({size, color}: {size: number, color: number}): React.Node => (
right={() => <List.Icon size={size} color={color} icon={icon} />
<Switch )}
value={state} right={(): React.Node => (
onValueChange={onPressCallback} <Switch value={state} onValueChange={onPressCallback} />
/>} )}
/> />
); );
} }
getNavigateItem(route: string, icon: string, title: string, subtitle: string, onLongPress?: () => void) { getNavigateItem(
route: string,
icon: string,
title: string,
subtitle: string,
onLongPress?: () => void,
): React.Node {
const {navigation} = this.props;
return ( return (
<List.Item <List.Item
title={title} title={title}
description={subtitle} description={subtitle}
onPress={() => this.props.navigation.navigate(route)} onPress={() => {
left={props => <List.Icon {...props} icon={icon}/>} navigation.navigate(route);
right={props => <List.Icon {...props} icon={"chevron-right"}/>} }}
left={({size, color}: {size: number, color: number}): React.Node => (
<List.Icon size={size} color={color} icon={icon} />
)}
right={({size, color}: {size: number, color: number}): React.Node => (
<List.Icon size={size} color={color} icon="chevron-right" />
)}
onLongPress={onLongPress} onLongPress={onLongPress}
/> />
); );
} }
render() { /**
* Unlocks debug mode and saves its state to user preferences
*/
unlockDebugMode = () => {
this.setState({isDebugUnlocked: true});
AsyncStorageManager.set(
AsyncStorageManager.PREFERENCES.debugUnlocked.key,
true,
);
};
render(): React.Node {
const {nightModeFollowSystem, nightMode, isDebugUnlocked} = this.state;
return ( return (
<CollapsibleScrollView> <CollapsibleScrollView>
<Card style={{margin: 5}}> <Card style={{margin: 5}}>
<Card.Title title={i18n.t('screens.settings.generalCard')}/> <Card.Title title={i18n.t('screens.settings.generalCard')} />
<List.Section> <List.Section>
{Appearance.getColorScheme() !== 'no-preference' ? this.getToggleItem( {Appearance.getColorScheme() !== 'no-preference'
? SettingsScreen.getToggleItem(
this.onToggleNightModeFollowSystem, this.onToggleNightModeFollowSystem,
'theme-light-dark', 'theme-light-dark',
i18n.t('screens.settings.nightModeAuto'), i18n.t('screens.settings.nightModeAuto'),
i18n.t('screens.settings.nightModeAutoSub'), i18n.t('screens.settings.nightModeAutoSub'),
this.state.nightModeFollowSystem nightModeFollowSystem,
) : null} )
{ : null}
Appearance.getColorScheme() === 'no-preference' || !this.state.nightModeFollowSystem ? {Appearance.getColorScheme() === 'no-preference' ||
this.getToggleItem( !nightModeFollowSystem
? SettingsScreen.getToggleItem(
this.onToggleNightMode, this.onToggleNightMode,
'theme-light-dark', 'theme-light-dark',
i18n.t('screens.settings.nightMode'), i18n.t('screens.settings.nightMode'),
this.state.nightMode ? nightMode
i18n.t('screens.settings.nightModeSubOn') : ? i18n.t('screens.settings.nightModeSubOn')
i18n.t('screens.settings.nightModeSubOff'), : i18n.t('screens.settings.nightModeSubOff'),
this.state.nightMode nightMode,
) : null )
} : null}
<List.Item <List.Item
title={i18n.t('screens.settings.startScreen')} title={i18n.t('screens.settings.startScreen')}
description={i18n.t('screens.settings.startScreenSub')} description={i18n.t('screens.settings.startScreenSub')}
left={props => <List.Icon {...props} icon="power"/>} left={({
size,
color,
}: {
size: number,
color: number,
}): React.Node => (
<List.Icon size={size} color={color} icon="power" />
)}
/> />
{this.getStartScreenPicker()} {this.getStartScreenPicker()}
{this.getNavigateItem( {this.getNavigateItem(
"dashboard-edit", 'dashboard-edit',
"view-dashboard", 'view-dashboard',
i18n.t('screens.settings.dashboard'), i18n.t('screens.settings.dashboard'),
i18n.t('screens.settings.dashboardSub') i18n.t('screens.settings.dashboardSub'),
)} )}
</List.Section> </List.Section>
</Card> </Card>
<Card style={{margin: 5}}> <Card style={{margin: 5}}>
<Card.Title title="Proxiwash"/> <Card.Title title="Proxiwash" />
<List.Section> <List.Section>
<List.Item <List.Item
title={i18n.t('screens.settings.proxiwashNotifReminder')} title={i18n.t('screens.settings.proxiwashNotifReminder')}
description={i18n.t('screens.settings.proxiwashNotifReminderSub')} description={i18n.t('screens.settings.proxiwashNotifReminderSub')}
left={props => <List.Icon {...props} icon="washing-machine"/>} left={({
opened={true} size,
color,
}: {
size: number,
color: number,
}): React.Node => (
<List.Icon size={size} color={color} icon="washing-machine" />
)}
/> />
<View style={{marginLeft: 30}}> <View style={{marginLeft: 30}}>
{this.getProxiwashNotifPicker()} {this.getProxiwashNotifPicker()}
@ -234,26 +290,26 @@ class SettingsScreen extends React.Component<Props, State> {
</List.Section> </List.Section>
</Card> </Card>
<Card style={{margin: 5}}> <Card style={{margin: 5}}>
<Card.Title title={i18n.t('screens.settings.information')}/> <Card.Title title={i18n.t('screens.settings.information')} />
<List.Section> <List.Section>
{this.state.isDebugUnlocked {isDebugUnlocked
? this.getNavigateItem( ? this.getNavigateItem(
"debug", 'debug',
"bug-check", 'bug-check',
i18n.t('screens.debug.title'), i18n.t('screens.debug.title'),
"" '',
) )
: null} : null}
{this.getNavigateItem( {this.getNavigateItem(
"about", 'about',
"information", 'information',
i18n.t('screens.about.title'), i18n.t('screens.about.title'),
i18n.t('screens.about.buttonDesc'), i18n.t('screens.about.buttonDesc'),
this.unlockDebugMode, this.unlockDebugMode,
)} )}
{this.getNavigateItem( {this.getNavigateItem(
"feedback", 'feedback',
"comment-quote", 'comment-quote',
i18n.t('screens.feedback.homeButtonTitle'), i18n.t('screens.feedback.homeButtonTitle'),
i18n.t('screens.feedback.homeButtonSubtitle'), i18n.t('screens.feedback.homeButtonSubtitle'),
)} )}

View file

@ -6,7 +6,7 @@ import i18n from 'i18n-js';
import {View} from 'react-native'; import {View} from 'react-native';
import {CommonActions} from '@react-navigation/native'; import {CommonActions} from '@react-navigation/native';
import {StackNavigationProp} from '@react-navigation/stack'; import {StackNavigationProp} from '@react-navigation/stack';
import type {CustomTheme} from '../../managers/ThemeManager'; import type {CustomThemeType} from '../../managers/ThemeManager';
import ThemeManager from '../../managers/ThemeManager'; import ThemeManager from '../../managers/ThemeManager';
import WebViewScreen from '../../components/Screens/WebViewScreen'; import WebViewScreen from '../../components/Screens/WebViewScreen';
import AsyncStorageManager from '../../managers/AsyncStorageManager'; import AsyncStorageManager from '../../managers/AsyncStorageManager';
@ -22,7 +22,7 @@ import MascotPopup from '../../components/Mascot/MascotPopup';
type PropsType = { type PropsType = {
navigation: StackNavigationProp, navigation: StackNavigationProp,
route: {params: {group: PlanexGroupType}}, route: {params: {group: PlanexGroupType}},
theme: CustomTheme, theme: CustomThemeType,
}; };
type StateType = { type StateType = {

View file

@ -2,40 +2,43 @@
import * as React from 'react'; import * as React from 'react';
import {View} from 'react-native'; import {View} from 'react-native';
import {getDateOnlyString, getFormattedEventTime} from '../../utils/Planning';
import {Card, withTheme} from 'react-native-paper'; import {Card, withTheme} from 'react-native-paper';
import DateManager from "../../managers/DateManager";
import ImageModal from 'react-native-image-modal'; import ImageModal from 'react-native-image-modal';
import BasicLoadingScreen from "../../components/Screens/BasicLoadingScreen";
import {apiRequest, ERROR_TYPE} from "../../utils/WebData";
import ErrorView from "../../components/Screens/ErrorView";
import CustomHTML from "../../components/Overrides/CustomHTML";
import CustomTabBar from "../../components/Tabbar/CustomTabBar";
import i18n from 'i18n-js'; import i18n from 'i18n-js';
import {StackNavigationProp} from "@react-navigation/stack"; import {StackNavigationProp} from '@react-navigation/stack';
import type {CustomTheme} from "../../managers/ThemeManager"; import {getDateOnlyString, getFormattedEventTime} from '../../utils/Planning';
import CollapsibleScrollView from "../../components/Collapsible/CollapsibleScrollView"; import DateManager from '../../managers/DateManager';
import BasicLoadingScreen from '../../components/Screens/BasicLoadingScreen';
import {apiRequest, ERROR_TYPE} from '../../utils/WebData';
import ErrorView from '../../components/Screens/ErrorView';
import CustomHTML from '../../components/Overrides/CustomHTML';
import CustomTabBar from '../../components/Tabbar/CustomTabBar';
import type {CustomThemeType} from '../../managers/ThemeManager';
import CollapsibleScrollView from '../../components/Collapsible/CollapsibleScrollView';
import type {PlanningEventType} from '../../utils/Planning';
type Props = { type PropsType = {
navigation: StackNavigationProp, navigation: StackNavigationProp,
route: { params: { data: Object, id: number, eventId: number } }, route: {params: {data: PlanningEventType, id: number, eventId: number}},
theme: CustomTheme theme: CustomThemeType,
}; };
type State = { type StateType = {
loading: boolean loading: boolean,
}; };
const CLUB_INFO_PATH = "event/info"; const EVENT_INFO_URL = 'event/info';
/** /**
* Class defining a planning event information page. * Class defining a planning event information page.
*/ */
class PlanningDisplayScreen extends React.Component<Props, State> { class PlanningDisplayScreen extends React.Component<PropsType, StateType> {
displayData: null | PlanningEventType;
displayData: Object;
shouldFetchData: boolean; shouldFetchData: boolean;
eventId: number; eventId: number;
errorCode: number; errorCode: number;
/** /**
@ -43,11 +46,11 @@ class PlanningDisplayScreen extends React.Component<Props, State> {
* *
* @param props * @param props
*/ */
constructor(props) { constructor(props: PropsType) {
super(props); super(props);
if (this.props.route.params.data != null) { if (props.route.params.data != null) {
this.displayData = this.props.route.params.data; this.displayData = props.route.params.data;
this.eventId = this.displayData.id; this.eventId = this.displayData.id;
this.shouldFetchData = false; this.shouldFetchData = false;
this.errorCode = 0; this.errorCode = 0;
@ -56,33 +59,22 @@ class PlanningDisplayScreen extends React.Component<Props, State> {
}; };
} else { } else {
this.displayData = null; this.displayData = null;
this.eventId = this.props.route.params.eventId; this.eventId = props.route.params.eventId;
this.shouldFetchData = true; this.shouldFetchData = true;
this.errorCode = 0; this.errorCode = 0;
this.state = { this.state = {
loading: true, loading: true,
}; };
this.fetchData(); this.fetchData();
} }
} }
/**
* Fetches data for the current event id from the API
*/
fetchData = () => {
this.setState({loading: true});
apiRequest(CLUB_INFO_PATH, 'POST', {id: this.eventId})
.then(this.onFetchSuccess)
.catch(this.onFetchError);
};
/** /**
* Hides loading and saves fetched data * Hides loading and saves fetched data
* *
* @param data Received data * @param data Received data
*/ */
onFetchSuccess = (data: Object) => { onFetchSuccess = (data: PlanningEventType) => {
this.displayData = data; this.displayData = data;
this.setState({loading: false}); this.setState({loading: false});
}; };
@ -102,41 +94,46 @@ class PlanningDisplayScreen extends React.Component<Props, State> {
* *
* @returns {*} * @returns {*}
*/ */
getContent() { getContent(): React.Node {
const {theme} = this.props;
const {displayData} = this;
if (displayData == null) return null;
let subtitle = getFormattedEventTime( let subtitle = getFormattedEventTime(
this.displayData["date_begin"], this.displayData["date_end"]); displayData.date_begin,
let dateString = getDateOnlyString(this.displayData["date_begin"]); displayData.date_end,
);
const dateString = getDateOnlyString(displayData.date_begin);
if (dateString !== null) if (dateString !== null)
subtitle += ' | ' + DateManager.getInstance().getTranslatedDate(dateString); subtitle += ` | ${DateManager.getInstance().getTranslatedDate(
dateString,
)}`;
return ( return (
<CollapsibleScrollView <CollapsibleScrollView style={{paddingLeft: 5, paddingRight: 5}} hasTab>
style={{paddingLeft: 5, paddingRight: 5}} <Card.Title title={displayData.title} subtitle={subtitle} />
hasTab={true} {displayData.logo !== null ? (
>
<Card.Title
title={this.displayData.title}
subtitle={subtitle}
/>
{this.displayData.logo !== null ?
<View style={{marginLeft: 'auto', marginRight: 'auto'}}> <View style={{marginLeft: 'auto', marginRight: 'auto'}}>
<ImageModal <ImageModal
resizeMode="contain" resizeMode="contain"
imageBackgroundColor={this.props.theme.colors.background} imageBackgroundColor={theme.colors.background}
style={{ style={{
width: 300, width: 300,
height: 300, height: 300,
}} }}
source={{ source={{
uri: this.displayData.logo, uri: displayData.logo,
}} }}
/></View> />
: <View/>} </View>
) : null}
{this.displayData.description !== null ? {displayData.description !== null ? (
<Card.Content style={{paddingBottom: CustomTabBar.TAB_BAR_HEIGHT + 20}}> <Card.Content
<CustomHTML html={this.displayData.description}/> style={{paddingBottom: CustomTabBar.TAB_BAR_HEIGHT + 20}}>
<CustomHTML html={displayData.description} />
</Card.Content> </Card.Content>
: <View/>} ) : (
<View />
)}
</CollapsibleScrollView> </CollapsibleScrollView>
); );
} }
@ -146,20 +143,40 @@ class PlanningDisplayScreen extends React.Component<Props, State> {
* *
* @returns {*} * @returns {*}
*/ */
getErrorView() { getErrorView(): React.Node {
const {navigation} = this.props;
if (this.errorCode === ERROR_TYPE.BAD_INPUT) if (this.errorCode === ERROR_TYPE.BAD_INPUT)
return <ErrorView {...this.props} showRetryButton={false} message={i18n.t("screens.planning.invalidEvent")} return (
icon={"calendar-remove"}/>; <ErrorView
else navigation={navigation}
return <ErrorView {...this.props} errorCode={this.errorCode} onRefresh={this.fetchData}/>; showRetryButton={false}
message={i18n.t('screens.planning.invalidEvent')}
icon="calendar-remove"
/>
);
return (
<ErrorView
navigation={navigation}
errorCode={this.errorCode}
onRefresh={this.fetchData}
/>
);
} }
render() { /**
if (this.state.loading) * Fetches data for the current event id from the API
return <BasicLoadingScreen/>; */
else if (this.errorCode === 0) fetchData = () => {
return this.getContent(); this.setState({loading: true});
else apiRequest(EVENT_INFO_URL, 'POST', {id: this.eventId})
.then(this.onFetchSuccess)
.catch(this.onFetchError);
};
render(): React.Node {
const {loading} = this.state;
if (loading) return <BasicLoadingScreen />;
if (this.errorCode === 0) return this.getContent();
return this.getErrorView(); return this.getErrorView();
} }
} }

View file

@ -2,91 +2,120 @@
import * as React from 'react'; import * as React from 'react';
import {BackHandler, View} from 'react-native'; import {BackHandler, View} from 'react-native';
import i18n from "i18n-js"; import i18n from 'i18n-js';
import {LocaleConfig} from 'react-native-calendars'; import {Agenda, LocaleConfig} from 'react-native-calendars';
import {readData} from "../../utils/WebData"; import {Avatar, Divider, List} from 'react-native-paper';
import type {eventObject} from "../../utils/Planning"; import {StackNavigationProp} from '@react-navigation/stack';
import {readData} from '../../utils/WebData';
import type {PlanningEventType} from '../../utils/Planning';
import { import {
generateEventAgenda, generateEventAgenda,
getCurrentDateString, getCurrentDateString,
getDateOnlyString, getDateOnlyString,
getFormattedEventTime, getFormattedEventTime,
} from '../../utils/Planning'; } from '../../utils/Planning';
import {Avatar, Divider, List} from 'react-native-paper'; import CustomAgenda from '../../components/Overrides/CustomAgenda';
import CustomAgenda from "../../components/Overrides/CustomAgenda"; import {MASCOT_STYLE} from '../../components/Mascot/Mascot';
import {StackNavigationProp} from "@react-navigation/stack"; import MascotPopup from '../../components/Mascot/MascotPopup';
import {MASCOT_STYLE} from "../../components/Mascot/Mascot"; import AsyncStorageManager from '../../managers/AsyncStorageManager';
import MascotPopup from "../../components/Mascot/MascotPopup";
import AsyncStorageManager from "../../managers/AsyncStorageManager";
LocaleConfig.locales['fr'] = { LocaleConfig.locales.fr = {
monthNames: ['Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin', 'Juillet', 'Août', 'Septembre', 'Octobre', 'Novembre', 'Décembre'], monthNames: [
monthNamesShort: ['Janv.', 'Févr.', 'Mars', 'Avril', 'Mai', 'Juin', 'Juil.', 'Août', 'Sept.', 'Oct.', 'Nov.', 'Déc.'], 'Janvier',
dayNames: ['Dimanche', 'Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi'], 'Février',
'Mars',
'Avril',
'Mai',
'Juin',
'Juillet',
'Août',
'Septembre',
'Octobre',
'Novembre',
'Décembre',
],
monthNamesShort: [
'Janv.',
'Févr.',
'Mars',
'Avril',
'Mai',
'Juin',
'Juil.',
'Août',
'Sept.',
'Oct.',
'Nov.',
'Déc.',
],
dayNames: [
'Dimanche',
'Lundi',
'Mardi',
'Mercredi',
'Jeudi',
'Vendredi',
'Samedi',
],
dayNamesShort: ['Dim', 'Lun', 'Mar', 'Mer', 'Jeu', 'Ven', 'Sam'], dayNamesShort: ['Dim', 'Lun', 'Mar', 'Mer', 'Jeu', 'Ven', 'Sam'],
today: 'Aujourd\'hui' today: "Aujourd'hui",
}; };
type PropsType = {
type Props = {
navigation: StackNavigationProp, navigation: StackNavigationProp,
} };
type State = { type StateType = {
refreshing: boolean, refreshing: boolean,
agendaItems: Object, agendaItems: {[key: string]: Array<PlanningEventType>},
calendarShowing: boolean, calendarShowing: boolean,
}; };
const FETCH_URL = "https://www.amicale-insat.fr/api/event/list"; const FETCH_URL = 'https://www.amicale-insat.fr/api/event/list';
const AGENDA_MONTH_SPAN = 3; const AGENDA_MONTH_SPAN = 3;
/** /**
* Class defining the app's planning screen * Class defining the app's planning screen
*/ */
class PlanningScreen extends React.Component<Props, State> { class PlanningScreen extends React.Component<PropsType, StateType> {
agendaRef: null | Agenda;
agendaRef: Object;
lastRefresh: Date; lastRefresh: Date;
minTimeBetweenRefresh = 60; minTimeBetweenRefresh = 60;
state = { currentDate = getDateOnlyString(getCurrentDateString());
constructor(props: PropsType) {
super(props);
if (i18n.currentLocale().startsWith('fr')) {
LocaleConfig.defaultLocale = 'fr';
}
this.state = {
refreshing: false, refreshing: false,
agendaItems: {}, agendaItems: {},
calendarShowing: false, calendarShowing: false,
}; };
currentDate = getDateOnlyString(getCurrentDateString());
constructor(props: any) {
super(props);
if (i18n.currentLocale().startsWith("fr")) {
LocaleConfig.defaultLocale = 'fr';
}
} }
/** /**
* Captures focus and blur events to hook on android back button * Captures focus and blur events to hook on android back button
*/ */
componentDidMount() { componentDidMount() {
const {navigation} = this.props;
this.onRefresh(); this.onRefresh();
this.props.navigation.addListener( navigation.addListener('focus', () => {
'focus',
() =>
BackHandler.addEventListener( BackHandler.addEventListener(
'hardwareBackPress', 'hardwareBackPress',
this.onBackButtonPressAndroid this.onBackButtonPressAndroid,
)
); );
this.props.navigation.addListener( });
'blur', navigation.addListener('blur', () => {
() =>
BackHandler.removeEventListener( BackHandler.removeEventListener(
'hardwareBackPress', 'hardwareBackPress',
this.onBackButtonPressAndroid this.onBackButtonPressAndroid,
)
); );
});
} }
/** /**
@ -94,46 +123,33 @@ class PlanningScreen extends React.Component<Props, State> {
* *
* @return {boolean} * @return {boolean}
*/ */
onBackButtonPressAndroid = () => { onBackButtonPressAndroid = (): boolean => {
if (this.state.calendarShowing) { const {calendarShowing} = this.state;
if (calendarShowing && this.agendaRef != null) {
this.agendaRef.chooseDay(this.agendaRef.state.selectedDay); this.agendaRef.chooseDay(this.agendaRef.state.selectedDay);
return true; return true;
} else {
return false;
} }
return false;
}; };
/**
* Function used to check if a row has changed
*
* @param r1
* @param r2
* @return {boolean}
*/
rowHasChanged(r1: Object, r2: Object) {
return false;
// if (r1 !== undefined && r2 !== undefined)
// return r1.title !== r2.title;
// else return !(r1 === undefined && r2 === undefined);
}
/** /**
* Refreshes data and shows an animation while doing it * Refreshes data and shows an animation while doing it
*/ */
onRefresh = () => { onRefresh = () => {
let canRefresh; let canRefresh;
if (this.lastRefresh !== undefined) if (this.lastRefresh !== undefined)
canRefresh = (new Date().getTime() - this.lastRefresh.getTime()) / 1000 > this.minTimeBetweenRefresh; canRefresh =
else (new Date().getTime() - this.lastRefresh.getTime()) / 1000 >
canRefresh = true; this.minTimeBetweenRefresh;
else canRefresh = true;
if (canRefresh) { if (canRefresh) {
this.setState({refreshing: true}); this.setState({refreshing: true});
readData(FETCH_URL) readData(FETCH_URL)
.then((fetchedData) => { .then((fetchedData: Array<PlanningEventType>) => {
this.setState({ this.setState({
refreshing: false, refreshing: false,
agendaItems: generateEventAgenda(fetchedData, AGENDA_MONTH_SPAN) agendaItems: generateEventAgenda(fetchedData, AGENDA_MONTH_SPAN),
}); });
this.lastRefresh = new Date(); this.lastRefresh = new Date();
}) })
@ -150,9 +166,9 @@ class PlanningScreen extends React.Component<Props, State> {
* *
* @param ref * @param ref
*/ */
onAgendaRef = (ref: Object) => { onAgendaRef = (ref: Agenda) => {
this.agendaRef = ref; this.agendaRef = ref;
} };
/** /**
* Callback used when a button is pressed to toggle the calendar * Callback used when a button is pressed to toggle the calendar
@ -161,7 +177,7 @@ class PlanningScreen extends React.Component<Props, State> {
*/ */
onCalendarToggled = (isCalendarOpened: boolean) => { onCalendarToggled = (isCalendarOpened: boolean) => {
this.setState({calendarShowing: isCalendarOpened}); this.setState({calendarShowing: isCalendarOpened});
} };
/** /**
* Gets an event render item * Gets an event render item
@ -169,53 +185,61 @@ class PlanningScreen extends React.Component<Props, State> {
* @param item The current event to render * @param item The current event to render
* @return {*} * @return {*}
*/ */
getRenderItem = (item: eventObject) => { getRenderItem = (item: PlanningEventType): React.Node => {
const onPress = this.props.navigation.navigate.bind(this, 'planning-information', {data: item}); const {navigation} = this.props;
const onPress = () => {
navigation.navigate('planning-information', {
data: item,
});
};
if (item.logo !== null) { if (item.logo !== null) {
return ( return (
<View> <View>
<Divider/> <Divider />
<List.Item <List.Item
title={item.title} title={item.title}
description={getFormattedEventTime(item["date_begin"], item["date_end"])} description={getFormattedEventTime(item.date_begin, item.date_end)}
left={() => <Avatar.Image left={(): React.Node => (
<Avatar.Image
source={{uri: item.logo}} source={{uri: item.logo}}
style={{backgroundColor: 'transparent'}} style={{backgroundColor: 'transparent'}}
/>} />
)}
onPress={onPress} onPress={onPress}
/> />
</View> </View>
); );
} else { }
return ( return (
<View> <View>
<Divider/> <Divider />
<List.Item <List.Item
title={item.title} title={item.title}
description={getFormattedEventTime(item["date_begin"], item["date_end"])} description={getFormattedEventTime(item.date_begin, item.date_end)}
onPress={onPress} onPress={onPress}
/> />
</View> </View>
); );
} };
}
/** /**
* Gets an empty render item for an empty date * Gets an empty render item for an empty date
* *
* @return {*} * @return {*}
*/ */
getRenderEmptyDate = () => <Divider/>; getRenderEmptyDate = (): React.Node => <Divider />;
render() { render(): React.Node {
const {state, props} = this;
return ( return (
<View style={{flex: 1}}> <View style={{flex: 1}}>
<CustomAgenda <CustomAgenda
{...this.props} // eslint-disable-next-line react/jsx-props-no-spreading
{...props}
// the list of items that have to be displayed in agenda. If you want to render item as empty date // the list of items that have to be displayed in agenda. If you want to render item as empty date
// the value of date key kas to be an empty array []. If there exists no value for date key it is // the value of date key kas to be an empty array []. If there exists no value for date key it is
// considered that the date in question is not yet loaded // considered that the date in question is not yet loaded
items={this.state.agendaItems} items={state.agendaItems}
// initially selected day // initially selected day
selected={this.currentDate} selected={this.currentDate}
// Minimum date that can be selected, dates before minDate will be grayed out. Default = undefined // Minimum date that can be selected, dates before minDate will be grayed out. Default = undefined
@ -229,10 +253,9 @@ class PlanningScreen extends React.Component<Props, State> {
// callback that fires when the calendar is opened or closed // callback that fires when the calendar is opened or closed
onCalendarToggled={this.onCalendarToggled} onCalendarToggled={this.onCalendarToggled}
// Set this true while waiting for new data from a refresh // Set this true while waiting for new data from a refresh
refreshing={this.state.refreshing} refreshing={state.refreshing}
renderItem={this.getRenderItem} renderItem={this.getRenderItem}
renderEmptyDate={this.getRenderEmptyDate} renderEmptyDate={this.getRenderEmptyDate}
rowHasChanged={this.rowHasChanged}
// If firstDay=1 week starts from Monday. Note that dayNames and dayNamesShort should still start from Sunday. // If firstDay=1 week starts from Monday. Note that dayNames and dayNamesShort should still start from Sunday.
firstDay={1} firstDay={1}
// ref to this agenda in order to handle back button event // ref to this agenda in order to handle back button event
@ -240,15 +263,15 @@ class PlanningScreen extends React.Component<Props, State> {
/> />
<MascotPopup <MascotPopup
prefKey={AsyncStorageManager.PREFERENCES.eventsShowBanner.key} prefKey={AsyncStorageManager.PREFERENCES.eventsShowBanner.key}
title={i18n.t("screens.planning.mascotDialog.title")} title={i18n.t('screens.planning.mascotDialog.title')}
message={i18n.t("screens.planning.mascotDialog.message")} message={i18n.t('screens.planning.mascotDialog.message')}
icon={"party-popper"} icon="party-popper"
buttons={{ buttons={{
action: null, action: null,
cancel: { cancel: {
message: i18n.t("screens.planning.mascotDialog.button"), message: i18n.t('screens.planning.mascotDialog.button'),
icon: "check", icon: 'check',
} },
}} }}
emotion={MASCOT_STYLE.HAPPY} emotion={MASCOT_STYLE.HAPPY}
/> />

View file

@ -2,43 +2,48 @@
import * as React from 'react'; import * as React from 'react';
import {Image, View} from 'react-native'; import {Image, View} from 'react-native';
import i18n from "i18n-js"; import i18n from 'i18n-js';
import {Card, List, Paragraph, Text, Title} from 'react-native-paper'; import {Card, List, Paragraph, Text, Title} from 'react-native-paper';
import CustomTabBar from "../../components/Tabbar/CustomTabBar"; import CustomTabBar from '../../components/Tabbar/CustomTabBar';
import CollapsibleScrollView from "../../components/Collapsible/CollapsibleScrollView"; import CollapsibleScrollView from '../../components/Collapsible/CollapsibleScrollView';
type Props = {}; const LOGO = 'https://etud.insa-toulouse.fr/~amicale_app/images/Proxiwash.png';
const LOGO = "https://etud.insa-toulouse.fr/~amicale_app/images/Proxiwash.png";
/** /**
* Class defining the proxiwash about screen. * Class defining the proxiwash about screen.
*/ */
export default class ProxiwashAboutScreen extends React.Component<Props> { // eslint-disable-next-line react/prefer-stateless-function
export default class ProxiwashAboutScreen extends React.Component<null> {
render() { render(): React.Node {
return ( return (
<CollapsibleScrollView <CollapsibleScrollView style={{padding: 5}} hasTab>
style={{padding: 5}} <View
hasTab={true} style={{
>
<View style={{
width: '100%', width: '100%',
height: 100, height: 100,
marginTop: 20, marginTop: 20,
marginBottom: 20, marginBottom: 20,
justifyContent: 'center', justifyContent: 'center',
alignItems: 'center' alignItems: 'center',
}}> }}>
<Image <Image
source={{uri: LOGO}} source={{uri: LOGO}}
style={{height: '100%', width: '100%', resizeMode: "contain"}}/> style={{height: '100%', width: '100%', resizeMode: 'contain'}}
/>
</View> </View>
<Text>{i18n.t('screens.proxiwash.description')}</Text> <Text>{i18n.t('screens.proxiwash.description')}</Text>
<Card style={{margin: 5}}> <Card style={{margin: 5}}>
<Card.Title <Card.Title
title={i18n.t('screens.proxiwash.dryer')} title={i18n.t('screens.proxiwash.dryer')}
left={props => <List.Icon {...props} icon={'tumble-dryer'}/>} left={({
size,
color,
}: {
size: number,
color: string,
}): React.Node => (
<List.Icon size={size} color={color} icon="tumble-dryer" />
)}
/> />
<Card.Content> <Card.Content>
<Title>{i18n.t('screens.proxiwash.procedure')}</Title> <Title>{i18n.t('screens.proxiwash.procedure')}</Title>
@ -51,7 +56,15 @@ export default class ProxiwashAboutScreen extends React.Component<Props> {
<Card style={{margin: 5}}> <Card style={{margin: 5}}>
<Card.Title <Card.Title
title={i18n.t('screens.proxiwash.washer')} title={i18n.t('screens.proxiwash.washer')}
left={props => <List.Icon {...props} icon={'washing-machine'}/>} left={({
size,
color,
}: {
size: number,
color: string,
}): React.Node => (
<List.Icon size={size} color={color} icon="washing-machine" />
)}
/> />
<Card.Content> <Card.Content>
<Title>{i18n.t('screens.proxiwash.procedure')}</Title> <Title>{i18n.t('screens.proxiwash.procedure')}</Title>
@ -64,20 +77,39 @@ export default class ProxiwashAboutScreen extends React.Component<Props> {
<Card style={{margin: 5}}> <Card style={{margin: 5}}>
<Card.Title <Card.Title
title={i18n.t('screens.proxiwash.tariffs')} title={i18n.t('screens.proxiwash.tariffs')}
left={props => <List.Icon {...props} icon={'circle-multiple'}/>} left={({
size,
color,
}: {
size: number,
color: string,
}): React.Node => (
<List.Icon size={size} color={color} icon="circle-multiple" />
)}
/> />
<Card.Content> <Card.Content>
<Paragraph>{i18n.t('screens.proxiwash.washersTariff')}</Paragraph> <Paragraph>{i18n.t('screens.proxiwash.washersTariff')}</Paragraph>
<Paragraph>{i18n.t('screens.proxiwash.dryersTariff')}</Paragraph> <Paragraph>{i18n.t('screens.proxiwash.dryersTariff')}</Paragraph>
</Card.Content> </Card.Content>
</Card> </Card>
<Card style={{margin: 5, marginBottom: CustomTabBar.TAB_BAR_HEIGHT + 20}}> <Card
style={{margin: 5, marginBottom: CustomTabBar.TAB_BAR_HEIGHT + 20}}>
<Card.Title <Card.Title
title={i18n.t('screens.proxiwash.paymentMethods')} title={i18n.t('screens.proxiwash.paymentMethods')}
left={props => <List.Icon {...props} icon={'cash'}/>} left={({
size,
color,
}: {
size: number,
color: string,
}): React.Node => (
<List.Icon size={size} color={color} icon="cash" />
)}
/> />
<Card.Content> <Card.Content>
<Paragraph>{i18n.t('screens.proxiwash.paymentMethodsDescription')}</Paragraph> <Paragraph>
{i18n.t('screens.proxiwash.paymentMethodsDescription')}
</Paragraph>
</Card.Content> </Card.Content>
</Card> </Card>
</CollapsibleScrollView> </CollapsibleScrollView>

View file

@ -2,32 +2,40 @@
import * as React from 'react'; import * as React from 'react';
import {Alert, View} from 'react-native'; import {Alert, View} from 'react-native';
import i18n from "i18n-js"; import i18n from 'i18n-js';
import WebSectionList from "../../components/Screens/WebSectionList";
import * as Notifications from "../../utils/Notifications";
import AsyncStorageManager from "../../managers/AsyncStorageManager";
import {Avatar, Button, Card, Text, withTheme} from 'react-native-paper'; import {Avatar, Button, Card, Text, withTheme} from 'react-native-paper';
import ProxiwashListItem from "../../components/Lists/Proxiwash/ProxiwashListItem"; import {StackNavigationProp} from '@react-navigation/stack';
import ProxiwashConstants from "../../constants/ProxiwashConstants"; import {Modalize} from 'react-native-modalize';
import CustomModal from "../../components/Overrides/CustomModal"; import WebSectionList from '../../components/Screens/WebSectionList';
import AprilFoolsManager from "../../managers/AprilFoolsManager"; import * as Notifications from '../../utils/Notifications';
import MaterialHeaderButtons, {Item} from "../../components/Overrides/CustomHeaderButton"; import AsyncStorageManager from '../../managers/AsyncStorageManager';
import ProxiwashSectionHeader from "../../components/Lists/Proxiwash/ProxiwashSectionHeader"; import ProxiwashListItem from '../../components/Lists/Proxiwash/ProxiwashListItem';
import type {CustomTheme} from "../../managers/ThemeManager"; import ProxiwashConstants from '../../constants/ProxiwashConstants';
import {StackNavigationProp} from "@react-navigation/stack"; import CustomModal from '../../components/Overrides/CustomModal';
import {getCleanedMachineWatched, getMachineEndDate, isMachineWatched} from "../../utils/Proxiwash"; import AprilFoolsManager from '../../managers/AprilFoolsManager';
import {Modalize} from "react-native-modalize"; import MaterialHeaderButtons, {
import {MASCOT_STYLE} from "../../components/Mascot/Mascot"; Item,
import MascotPopup from "../../components/Mascot/MascotPopup"; } from '../../components/Overrides/CustomHeaderButton';
import ProxiwashSectionHeader from '../../components/Lists/Proxiwash/ProxiwashSectionHeader';
import type {CustomThemeType} from '../../managers/ThemeManager';
import {
getCleanedMachineWatched,
getMachineEndDate,
isMachineWatched,
} from '../../utils/Proxiwash';
import {MASCOT_STYLE} from '../../components/Mascot/Mascot';
import MascotPopup from '../../components/Mascot/MascotPopup';
import type {SectionListDataType} from '../../components/Screens/WebSectionList';
const DATA_URL = "https://etud.insa-toulouse.fr/~amicale_app/v2/washinsa/washinsa_data.json"; const DATA_URL =
'https://etud.insa-toulouse.fr/~amicale_app/v2/washinsa/washinsa_data.json';
let modalStateStrings = {}; const modalStateStrings = {};
const REFRESH_TIME = 1000 * 10; // Refresh every 10 seconds const REFRESH_TIME = 1000 * 10; // Refresh every 10 seconds
const LIST_ITEM_HEIGHT = 64; const LIST_ITEM_HEIGHT = 64;
export type Machine = { export type ProxiwashMachineType = {
number: string, number: string,
state: string, state: string,
startTime: string, startTime: string,
@ -35,62 +43,89 @@ export type Machine = {
donePercent: string, donePercent: string,
remainingTime: string, remainingTime: string,
program: string, program: string,
}
type Props = {
navigation: StackNavigationProp,
theme: CustomTheme,
}
type State = {
refreshing: boolean,
modalCurrentDisplayItem: React.Node,
machinesWatched: Array<Machine>,
}; };
type PropsType = {
navigation: StackNavigationProp,
theme: CustomThemeType,
};
type StateType = {
modalCurrentDisplayItem: React.Node,
machinesWatched: Array<ProxiwashMachineType>,
};
/** /**
* Class defining the app's proxiwash screen. This screen shows information about washing machines and * Class defining the app's proxiwash screen. This screen shows information about washing machines and
* dryers, taken from a scrapper reading proxiwash website * dryers, taken from a scrapper reading proxiwash website
*/ */
class ProxiwashScreen extends React.Component<Props, State> { class ProxiwashScreen extends React.Component<PropsType, StateType> {
/**
* Shows a warning telling the user notifications are disabled for the app
*/
static showNotificationsDisabledWarning() {
Alert.alert(
i18n.t('screens.proxiwash.modal.notificationErrorTitle'),
i18n.t('screens.proxiwash.modal.notificationErrorDescription'),
);
}
modalRef: null | Modalize; modalRef: null | Modalize;
fetchedData: { fetchedData: {
dryers: Array<Machine>, dryers: Array<ProxiwashMachineType>,
washers: Array<Machine>, washers: Array<ProxiwashMachineType>,
};
state = {
refreshing: false,
modalCurrentDisplayItem: null,
machinesWatched: AsyncStorageManager.getObject(AsyncStorageManager.PREFERENCES.proxiwashWatchedMachines.key),
}; };
/** /**
* Creates machine state parameters using current theme and translations * Creates machine state parameters using current theme and translations
*/ */
constructor(props) { constructor() {
super(props); super();
modalStateStrings[ProxiwashConstants.machineStates.AVAILABLE] = i18n.t('screens.proxiwash.modal.ready'); this.state = {
modalStateStrings[ProxiwashConstants.machineStates.RUNNING] = i18n.t('screens.proxiwash.modal.running'); modalCurrentDisplayItem: null,
modalStateStrings[ProxiwashConstants.machineStates.RUNNING_NOT_STARTED] = i18n.t('screens.proxiwash.modal.runningNotStarted'); machinesWatched: AsyncStorageManager.getObject(
modalStateStrings[ProxiwashConstants.machineStates.FINISHED] = i18n.t('screens.proxiwash.modal.finished'); AsyncStorageManager.PREFERENCES.proxiwashWatchedMachines.key,
modalStateStrings[ProxiwashConstants.machineStates.UNAVAILABLE] = i18n.t('screens.proxiwash.modal.broken'); ),
modalStateStrings[ProxiwashConstants.machineStates.ERROR] = i18n.t('screens.proxiwash.modal.error'); };
modalStateStrings[ProxiwashConstants.machineStates.UNKNOWN] = i18n.t('screens.proxiwash.modal.unknown'); modalStateStrings[ProxiwashConstants.machineStates.AVAILABLE] = i18n.t(
'screens.proxiwash.modal.ready',
);
modalStateStrings[ProxiwashConstants.machineStates.RUNNING] = i18n.t(
'screens.proxiwash.modal.running',
);
modalStateStrings[
ProxiwashConstants.machineStates.RUNNING_NOT_STARTED
] = i18n.t('screens.proxiwash.modal.runningNotStarted');
modalStateStrings[ProxiwashConstants.machineStates.FINISHED] = i18n.t(
'screens.proxiwash.modal.finished',
);
modalStateStrings[ProxiwashConstants.machineStates.UNAVAILABLE] = i18n.t(
'screens.proxiwash.modal.broken',
);
modalStateStrings[ProxiwashConstants.machineStates.ERROR] = i18n.t(
'screens.proxiwash.modal.error',
);
modalStateStrings[ProxiwashConstants.machineStates.UNKNOWN] = i18n.t(
'screens.proxiwash.modal.unknown',
);
} }
/** /**
* Setup notification channel for android and add listeners to detect notifications fired * Setup notification channel for android and add listeners to detect notifications fired
*/ */
componentDidMount() { componentDidMount() {
this.props.navigation.setOptions({ const {navigation} = this.props;
headerRight: () => navigation.setOptions({
headerRight: (): React.Node => (
<MaterialHeaderButtons> <MaterialHeaderButtons>
<Item title="information" iconName="information" onPress={this.onAboutPress}/> <Item
</MaterialHeaderButtons>, title="information"
iconName="information"
onPress={this.onAboutPress}
/>
</MaterialHeaderButtons>
),
}); });
} }
@ -98,7 +133,158 @@ class ProxiwashScreen extends React.Component<Props, State> {
* Callback used when pressing the about button. * Callback used when pressing the about button.
* This will open the ProxiwashAboutScreen. * This will open the ProxiwashAboutScreen.
*/ */
onAboutPress = () => this.props.navigation.navigate('proxiwash-about'); onAboutPress = () => {
const {navigation} = this.props;
navigation.navigate('proxiwash-about');
};
/**
* Callback used when the user clicks on enable notifications for a machine
*
* @param machine The machine to set notifications for
*/
onSetupNotificationsPress(machine: ProxiwashMachineType) {
if (this.modalRef) {
this.modalRef.close();
}
this.setupNotifications(machine);
}
/**
* Callback used when receiving modal ref
*
* @param ref
*/
onModalRef = (ref: Modalize) => {
this.modalRef = ref;
};
/**
* Generates the modal content.
* This shows information for the given machine.
*
* @param title The title to use
* @param item The item to display information for in the modal
* @param isDryer True if the given item is a dryer
* @return {*}
*/
getModalContent(
title: string,
item: ProxiwashMachineType,
isDryer: boolean,
): React.Node {
const {props, state} = this;
let button = {
text: i18n.t('screens.proxiwash.modal.ok'),
icon: '',
onPress: undefined,
};
let message = modalStateStrings[item.state];
const onPress = this.onSetupNotificationsPress.bind(this, item);
if (item.state === ProxiwashConstants.machineStates.RUNNING) {
let remainingTime = parseInt(item.remainingTime, 10);
if (remainingTime < 0) remainingTime = 0;
button = {
text: isMachineWatched(item, state.machinesWatched)
? i18n.t('screens.proxiwash.modal.disableNotifications')
: i18n.t('screens.proxiwash.modal.enableNotifications'),
icon: '',
onPress,
};
message = i18n.t('screens.proxiwash.modal.running', {
start: item.startTime,
end: item.endTime,
remaining: remainingTime,
program: item.program,
});
} else if (item.state === ProxiwashConstants.machineStates.AVAILABLE) {
if (isDryer) message += `\n${i18n.t('screens.proxiwash.dryersTariff')}`;
else message += `\n${i18n.t('screens.proxiwash.washersTariff')}`;
}
return (
<View
style={{
flex: 1,
padding: 20,
}}>
<Card.Title
title={title}
left={(): React.Node => (
<Avatar.Icon
icon={isDryer ? 'tumble-dryer' : 'washing-machine'}
color={props.theme.colors.text}
style={{backgroundColor: 'transparent'}}
/>
)}
/>
<Card.Content>
<Text>{message}</Text>
</Card.Content>
{button.onPress !== undefined ? (
<Card.Actions>
<Button
icon={button.icon}
mode="contained"
onPress={button.onPress}
style={{marginLeft: 'auto', marginRight: 'auto'}}>
{button.text}
</Button>
</Card.Actions>
) : null}
</View>
);
}
/**
* Gets the section render item
*
* @param section The section to render
* @return {*}
*/
getRenderSectionHeader = ({
section,
}: {
section: {title: string},
}): React.Node => {
const isDryer = section.title === i18n.t('screens.proxiwash.dryers');
const nbAvailable = this.getMachineAvailableNumber(isDryer);
return (
<ProxiwashSectionHeader
title={section.title}
nbAvailable={nbAvailable}
isDryer={isDryer}
/>
);
};
/**
* Gets the list item to be rendered
*
* @param item The object containing the item's FetchedData
* @param section The object describing the current SectionList section
* @returns {React.Node}
*/
getRenderItem = ({
item,
section,
}: {
item: ProxiwashMachineType,
section: {title: string},
}): React.Node => {
const {machinesWatched} = this.state;
const isDryer = section.title === i18n.t('screens.proxiwash.dryers');
return (
<ProxiwashListItem
item={item}
onPress={this.showModal}
isWatched={isMachineWatched(item, machinesWatched)}
isDryer={isDryer}
height={LIST_ITEM_HEIGHT}
/>
);
};
/** /**
* Extracts the key for the given item * Extracts the key for the given item
@ -106,7 +292,7 @@ class ProxiwashScreen extends React.Component<Props, State> {
* @param item The item to extract the key from * @param item The item to extract the key from
* @return {*} The extracted key * @return {*} The extracted key
*/ */
getKeyExtractor = (item: Machine) => item.number; getKeyExtractor = (item: ProxiwashMachineType): string => item.number;
/** /**
* Setups notifications for the machine with the given ID. * Setups notifications for the machine with the given ID.
@ -115,72 +301,58 @@ class ProxiwashScreen extends React.Component<Props, State> {
* *
* @param machine The machine to watch * @param machine The machine to watch
*/ */
setupNotifications(machine: Machine) { setupNotifications(machine: ProxiwashMachineType) {
if (!isMachineWatched(machine, this.state.machinesWatched)) { const {machinesWatched} = this.state;
Notifications.setupMachineNotification(machine.number, true, getMachineEndDate(machine)) if (!isMachineWatched(machine, machinesWatched)) {
Notifications.setupMachineNotification(
machine.number,
true,
getMachineEndDate(machine),
)
.then(() => { .then(() => {
this.saveNotificationToState(machine); this.saveNotificationToState(machine);
}) })
.catch(() => { .catch(() => {
this.showNotificationsDisabledWarning(); ProxiwashScreen.showNotificationsDisabledWarning();
}); });
} else { } else {
Notifications.setupMachineNotification(machine.number, false, null) Notifications.setupMachineNotification(machine.number, false, null).then(
.then(() => { () => {
this.removeNotificationFromState(machine); this.removeNotificationFromState(machine);
}); },
}
}
/**
* Shows a warning telling the user notifications are disabled for the app
*/
showNotificationsDisabledWarning() {
Alert.alert(
i18n.t("screens.proxiwash.modal.notificationErrorTitle"),
i18n.t("screens.proxiwash.modal.notificationErrorDescription"),
); );
} }
}
/** /**
* Adds the given notifications associated to a machine ID to the watchlist, and saves the array to the preferences * Gets the number of machines available
* *
* @param machine * @param isDryer True if we are only checking for dryer, false for washers
* @return {number} The number of machines available
*/ */
saveNotificationToState(machine: Machine) { getMachineAvailableNumber(isDryer: boolean): number {
let data = this.state.machinesWatched; let data;
data.push(machine); if (isDryer) data = this.fetchedData.dryers;
this.saveNewWatchedList(data); else data = this.fetchedData.washers;
let count = 0;
data.forEach((machine: ProxiwashMachineType) => {
if (machine.state === ProxiwashConstants.machineStates.AVAILABLE)
count += 1;
});
return count;
} }
/** /**
* Removes the given index from the watchlist array and saves it to preferences * Creates the dataset to be used by the FlatList
*
* @param machine
*/
removeNotificationFromState(machine: Machine) {
let data = this.state.machinesWatched;
for (let i = 0; i < data.length; i++) {
if (data[i].number === machine.number && data[i].endTime === machine.endTime) {
data.splice(i, 1);
break;
}
}
this.saveNewWatchedList(data);
}
saveNewWatchedList(list: Array<Machine>) {
this.setState({machinesWatched: list});
AsyncStorageManager.set(AsyncStorageManager.PREFERENCES.proxiwashWatchedMachines.key, list);
}
/**
* Creates the dataset to be used by the flatlist
* *
* @param fetchedData * @param fetchedData
* @return {*} * @return {*}
*/ */
createDataset = (fetchedData: Object) => { createDataset = (fetchedData: {
dryers: Array<ProxiwashMachineType>,
washers: Array<ProxiwashMachineType>,
}): SectionListDataType<ProxiwashMachineType> => {
const {state} = this;
let data = fetchedData; let data = fetchedData;
if (AprilFoolsManager.getInstance().isAprilFoolsEnabled()) { if (AprilFoolsManager.getInstance().isAprilFoolsEnabled()) {
data = JSON.parse(JSON.stringify(fetchedData)); // Deep copy data = JSON.parse(JSON.stringify(fetchedData)); // Deep copy
@ -188,20 +360,22 @@ class ProxiwashScreen extends React.Component<Props, State> {
AprilFoolsManager.getNewProxiwashWasherOrderedList(data.washers); AprilFoolsManager.getNewProxiwashWasherOrderedList(data.washers);
} }
this.fetchedData = data; this.fetchedData = data;
this.state.machinesWatched = this.state.machinesWatched = getCleanedMachineWatched(
getCleanedMachineWatched(this.state.machinesWatched, [...data.dryers, ...data.washers]); state.machinesWatched,
[...data.dryers, ...data.washers],
);
return [ return [
{ {
title: i18n.t('screens.proxiwash.dryers'), title: i18n.t('screens.proxiwash.dryers'),
icon: 'tumble-dryer', icon: 'tumble-dryer',
data: data.dryers === undefined ? [] : data.dryers, data: data.dryers === undefined ? [] : data.dryers,
keyExtractor: this.getKeyExtractor keyExtractor: this.getKeyExtractor,
}, },
{ {
title: i18n.t('screens.proxiwash.washers'), title: i18n.t('screens.proxiwash.washers'),
icon: 'washing-machine', icon: 'washing-machine',
data: data.washers === undefined ? [] : data.washers, data: data.washers === undefined ? [] : data.washers,
keyExtractor: this.getKeyExtractor keyExtractor: this.getKeyExtractor,
}, },
]; ];
}; };
@ -213,9 +387,9 @@ class ProxiwashScreen extends React.Component<Props, State> {
* @param item The item to display information for in the modal * @param item The item to display information for in the modal
* @param isDryer True if the given item is a dryer * @param isDryer True if the given item is a dryer
*/ */
showModal = (title: string, item: Object, isDryer: boolean) => { showModal = (title: string, item: ProxiwashMachineType, isDryer: boolean) => {
this.setState({ this.setState({
modalCurrentDisplayItem: this.getModalContent(title, item, isDryer) modalCurrentDisplayItem: this.getModalContent(title, item, isDryer),
}); });
if (this.modalRef) { if (this.modalRef) {
this.modalRef.open(); this.modalRef.open();
@ -223,196 +397,81 @@ class ProxiwashScreen extends React.Component<Props, State> {
}; };
/** /**
* Callback used when the user clicks on enable notifications for a machine * Adds the given notifications associated to a machine ID to the watchlist, and saves the array to the preferences
* *
* @param machine The machine to set notifications for * @param machine
*/ */
onSetupNotificationsPress(machine: Machine) { saveNotificationToState(machine: ProxiwashMachineType) {
if (this.modalRef) { const {machinesWatched} = this.state;
this.modalRef.close(); const data = machinesWatched;
} data.push(machine);
this.setupNotifications(machine); this.saveNewWatchedList(data);
} }
/** /**
* Generates the modal content. * Removes the given index from the watchlist array and saves it to preferences
* This shows information for the given machine.
* *
* @param title The title to use * @param selectedMachine
* @param item The item to display information for in the modal
* @param isDryer True if the given item is a dryer
* @return {*}
*/ */
getModalContent(title: string, item: Machine, isDryer: boolean) { removeNotificationFromState(selectedMachine: ProxiwashMachineType) {
let button = { const {machinesWatched} = this.state;
text: i18n.t("screens.proxiwash.modal.ok"), const newList = [...machinesWatched];
icon: '', machinesWatched.forEach((machine: ProxiwashMachineType, index: number) => {
onPress: undefined if (
}; machine.number === selectedMachine.number &&
let message = modalStateStrings[item.state]; machine.endTime === selectedMachine.endTime
const onPress = this.onSetupNotificationsPress.bind(this, item); )
if (item.state === ProxiwashConstants.machineStates.RUNNING) { newList.splice(index, 1);
let remainingTime = parseInt(item.remainingTime)
if (remainingTime < 0)
remainingTime = 0;
button =
{
text: isMachineWatched(item, this.state.machinesWatched) ?
i18n.t("screens.proxiwash.modal.disableNotifications") :
i18n.t("screens.proxiwash.modal.enableNotifications"),
icon: '',
onPress: onPress
}
;
message = i18n.t('screens.proxiwash.modal.running',
{
start: item.startTime,
end: item.endTime,
remaining: remainingTime,
program: item.program
}); });
} else if (item.state === ProxiwashConstants.machineStates.AVAILABLE) { this.saveNewWatchedList(newList);
if (isDryer)
message += '\n' + i18n.t('screens.proxiwash.dryersTariff');
else
message += '\n' + i18n.t('screens.proxiwash.washersTariff');
} }
return (
<View style={{
flex: 1,
padding: 20
}}>
<Card.Title
title={title}
left={() => <Avatar.Icon
icon={isDryer ? 'tumble-dryer' : 'washing-machine'}
color={this.props.theme.colors.text}
style={{backgroundColor: 'transparent'}}/>}
/> saveNewWatchedList(list: Array<ProxiwashMachineType>) {
<Card.Content> this.setState({machinesWatched: list});
<Text>{message}</Text> AsyncStorageManager.set(
</Card.Content> AsyncStorageManager.PREFERENCES.proxiwashWatchedMachines.key,
list,
{button.onPress !== undefined ?
<Card.Actions>
<Button
icon={button.icon}
mode="contained"
onPress={button.onPress}
style={{marginLeft: 'auto', marginRight: 'auto'}}
>
{button.text}
</Button>
</Card.Actions> : null}
</View>
); );
} }
/** render(): React.Node {
* Callback used when receiving modal ref const {state} = this;
* const {navigation} = this.props;
* @param ref
*/
onModalRef = (ref: Object) => {
this.modalRef = ref;
};
/**
* Gets the number of machines available
*
* @param isDryer True if we are only checking for dryer, false for washers
* @return {number} The number of machines available
*/
getMachineAvailableNumber(isDryer: boolean) {
let data;
if (isDryer)
data = this.fetchedData.dryers;
else
data = this.fetchedData.washers;
let count = 0;
for (let i = 0; i < data.length; i++) {
if (data[i].state === ProxiwashConstants.machineStates.AVAILABLE)
count += 1;
}
return count;
}
/**
* Gets the section render item
*
* @param section The section to render
* @return {*}
*/
getRenderSectionHeader = ({section}: Object) => {
const isDryer = section.title === i18n.t('screens.proxiwash.dryers');
const nbAvailable = this.getMachineAvailableNumber(isDryer);
return (
<ProxiwashSectionHeader
title={section.title}
nbAvailable={nbAvailable}
isDryer={isDryer}/>
);
};
/**
* Gets the list item to be rendered
*
* @param item The object containing the item's FetchedData
* @param section The object describing the current SectionList section
* @returns {React.Node}
*/
getRenderItem = ({item, section}: Object) => {
const isDryer = section.title === i18n.t('screens.proxiwash.dryers');
return (
<ProxiwashListItem
item={item}
onPress={this.showModal}
isWatched={isMachineWatched(item, this.state.machinesWatched)}
isDryer={isDryer}
height={LIST_ITEM_HEIGHT}
/>
);
};
render() {
const nav = this.props.navigation;
return ( return (
<View style={{flex: 1}}>
<View <View
style={{flex: 1}} style={{
> position: 'absolute',
<View style={{ width: '100%',
position: "absolute", height: '100%',
width: "100%",
height: "100%",
}}> }}>
<WebSectionList <WebSectionList
createDataset={this.createDataset} createDataset={this.createDataset}
navigation={nav} navigation={navigation}
fetchUrl={DATA_URL} fetchUrl={DATA_URL}
renderItem={this.getRenderItem} renderItem={this.getRenderItem}
renderSectionHeader={this.getRenderSectionHeader} renderSectionHeader={this.getRenderSectionHeader}
autoRefreshTime={REFRESH_TIME} autoRefreshTime={REFRESH_TIME}
refreshOnFocus={true} refreshOnFocus
updateData={this.state.machinesWatched.length}/> updateData={state.machinesWatched.length}
/>
</View> </View>
<MascotPopup <MascotPopup
prefKey={AsyncStorageManager.PREFERENCES.proxiwashShowBanner.key} prefKey={AsyncStorageManager.PREFERENCES.proxiwashShowBanner.key}
title={i18n.t("screens.proxiwash.mascotDialog.title")} title={i18n.t('screens.proxiwash.mascotDialog.title')}
message={i18n.t("screens.proxiwash.mascotDialog.message")} message={i18n.t('screens.proxiwash.mascotDialog.message')}
icon={"information"} icon="information"
buttons={{ buttons={{
action: null, action: null,
cancel: { cancel: {
message: i18n.t("screens.proxiwash.mascotDialog.ok"), message: i18n.t('screens.proxiwash.mascotDialog.ok'),
icon: "check", icon: 'check',
} },
}} }}
emotion={MASCOT_STYLE.NORMAL} emotion={MASCOT_STYLE.NORMAL}
/> />
<CustomModal onRef={this.onModalRef}> <CustomModal onRef={this.onModalRef}>
{this.state.modalCurrentDisplayItem} {state.modalCurrentDisplayItem}
</CustomModal> </CustomModal>
</View> </View>
); );

View file

@ -19,7 +19,7 @@ import ProximoListItem from '../../../components/Lists/Proximo/ProximoListItem';
import MaterialHeaderButtons, { import MaterialHeaderButtons, {
Item, Item,
} from '../../../components/Overrides/CustomHeaderButton'; } from '../../../components/Overrides/CustomHeaderButton';
import type {CustomTheme} from '../../../managers/ThemeManager'; import type {CustomThemeType} from '../../../managers/ThemeManager';
import CollapsibleFlatList from '../../../components/Collapsible/CollapsibleFlatList'; import CollapsibleFlatList from '../../../components/Collapsible/CollapsibleFlatList';
import type {ProximoArticleType} from './ProximoMainScreen'; import type {ProximoArticleType} from './ProximoMainScreen';
@ -56,7 +56,7 @@ type PropsType = {
shouldFocusSearchBar: boolean, shouldFocusSearchBar: boolean,
}, },
}, },
theme: CustomTheme, theme: CustomThemeType,
}; };
type StateType = { type StateType = {

View file

@ -8,7 +8,7 @@ import WebSectionList from '../../../components/Screens/WebSectionList';
import MaterialHeaderButtons, { import MaterialHeaderButtons, {
Item, Item,
} from '../../../components/Overrides/CustomHeaderButton'; } from '../../../components/Overrides/CustomHeaderButton';
import type {CustomTheme} from '../../../managers/ThemeManager'; import type {CustomThemeType} from '../../../managers/ThemeManager';
import type {SectionListDataType} from '../../../components/Screens/WebSectionList'; import type {SectionListDataType} from '../../../components/Screens/WebSectionList';
const DATA_URL = 'https://etud.insa-toulouse.fr/~proximo/data/stock-v2.json'; const DATA_URL = 'https://etud.insa-toulouse.fr/~proximo/data/stock-v2.json';
@ -43,7 +43,7 @@ export type ProximoDataType = {
type PropsType = { type PropsType = {
navigation: StackNavigationProp, navigation: StackNavigationProp,
theme: CustomTheme, theme: CustomThemeType,
}; };
/** /**

View file

@ -2,34 +2,51 @@
import * as React from 'react'; import * as React from 'react';
import {View} from 'react-native'; import {View} from 'react-native';
import DateManager from "../../managers/DateManager";
import WebSectionList from "../../components/Screens/WebSectionList";
import {Card, Text, withTheme} from 'react-native-paper'; import {Card, Text, withTheme} from 'react-native-paper';
import AprilFoolsManager from "../../managers/AprilFoolsManager"; import {StackNavigationProp} from '@react-navigation/stack';
import {StackNavigationProp} from "@react-navigation/stack";
import type {CustomTheme} from "../../managers/ThemeManager";
import i18n from 'i18n-js'; import i18n from 'i18n-js';
import DateManager from '../../managers/DateManager';
import WebSectionList from '../../components/Screens/WebSectionList';
import type {CustomThemeType} from '../../managers/ThemeManager';
import type {SectionListDataType} from '../../components/Screens/WebSectionList';
const DATA_URL = "https://etud.insa-toulouse.fr/~amicale_app/menu/menu_data.json"; const DATA_URL =
'https://etud.insa-toulouse.fr/~amicale_app/menu/menu_data.json';
type Props = { type PropsType = {
navigation: StackNavigationProp, navigation: StackNavigationProp,
theme: CustomTheme, theme: CustomThemeType,
} };
export type RuFoodCategoryType = {
name: string,
dishes: Array<{name: string}>,
};
type RuMealType = {
name: string,
foodcategory: Array<RuFoodCategoryType>,
};
type RawRuMenuType = {
restaurant_id: number,
id: number,
date: string,
meal: Array<RuMealType>,
};
/** /**
* Class defining the app's menu screen. * Class defining the app's menu screen.
*/ */
class SelfMenuScreen extends React.Component<Props> { class SelfMenuScreen extends React.Component<PropsType> {
/** /**
* Extract a key for the given item * Formats the given string to make sure it starts with a capital letter
* *
* @param item The item to extract the key from * @param name The string to format
* @return {*} The extracted key * @return {string} The formatted string
*/ */
getKeyExtractor(item: Object) { static formatName(name: string): string {
return item !== undefined ? item['name'] : undefined; return name.charAt(0) + name.substr(1).toLowerCase();
} }
/** /**
@ -38,31 +55,28 @@ class SelfMenuScreen extends React.Component<Props> {
* @param fetchedData * @param fetchedData
* @return {[]} * @return {[]}
*/ */
createDataset = (fetchedData: Object) => { createDataset = (
fetchedData: Array<RawRuMenuType>,
): SectionListDataType<RuFoodCategoryType> => {
let result = []; let result = [];
if (fetchedData == null || Object.keys(fetchedData).length === 0) { if (fetchedData == null || fetchedData.length === 0) {
result = [ result = [
{ {
title: i18n.t("general.notAvailable"), title: i18n.t('general.notAvailable'),
data: [], data: [],
keyExtractor: this.getKeyExtractor keyExtractor: this.getKeyExtractor,
} },
]; ];
} else { } else {
if (AprilFoolsManager.getInstance().isAprilFoolsEnabled() && fetchedData.length > 0) fetchedData.forEach((item: RawRuMenuType) => {
fetchedData[0].meal[0].foodcategory = AprilFoolsManager.getFakeMenuItem(fetchedData[0].meal[0].foodcategory); result.push({
// fetched data is an array here title: DateManager.getInstance().getTranslatedDate(item.date),
for (let i = 0; i < fetchedData.length; i++) { data: item.meal[0].foodcategory,
result.push(
{
title: DateManager.getInstance().getTranslatedDate(fetchedData[i].date),
data: fetchedData[i].meal[0].foodcategory,
keyExtractor: this.getKeyExtractor, keyExtractor: this.getKeyExtractor,
});
});
} }
); return result;
}
}
return result
}; };
/** /**
@ -71,9 +85,14 @@ class SelfMenuScreen extends React.Component<Props> {
* @param section The section to render the header from * @param section The section to render the header from
* @return {*} * @return {*}
*/ */
getRenderSectionHeader = ({section}: Object) => { getRenderSectionHeader = ({
section,
}: {
section: {title: string},
}): React.Node => {
return ( return (
<Card style={{ <Card
style={{
width: '95%', width: '95%',
marginLeft: 'auto', marginLeft: 'auto',
marginRight: 'auto', marginRight: 'auto',
@ -84,10 +103,10 @@ class SelfMenuScreen extends React.Component<Props> {
<Card.Title <Card.Title
title={section.title} title={section.title}
titleStyle={{ titleStyle={{
textAlign: 'center' textAlign: 'center',
}} }}
subtitleStyle={{ subtitleStyle={{
textAlign: 'center' textAlign: 'center',
}} }}
style={{ style={{
paddingLeft: 0, paddingLeft: 0,
@ -103,64 +122,66 @@ class SelfMenuScreen extends React.Component<Props> {
* @param item The item to render * @param item The item to render
* @return {*} * @return {*}
*/ */
getRenderItem = ({item}: Object) => { getRenderItem = ({item}: {item: RuFoodCategoryType}): React.Node => {
const {theme} = this.props;
return ( return (
<Card style={{ <Card
style={{
flex: 0, flex: 0,
marginHorizontal: 10, marginHorizontal: 10,
marginVertical: 5, marginVertical: 5,
}}> }}>
<Card.Title <Card.Title style={{marginTop: 5}} title={item.name} />
style={{marginTop: 5}} <View
title={item.name} style={{
/>
<View style={{
width: '80%', width: '80%',
marginLeft: 'auto', marginLeft: 'auto',
marginRight: 'auto', marginRight: 'auto',
borderBottomWidth: 1, borderBottomWidth: 1,
borderBottomColor: this.props.theme.colors.primary, borderBottomColor: theme.colors.primary,
marginTop: 5, marginTop: 5,
marginBottom: 5, marginBottom: 5,
}}/> }}
/>
<Card.Content> <Card.Content>
{item.dishes.map((object) => {item.dishes.map((object: {name: string}): React.Node =>
<View> object.name !== '' ? (
{object.name !== "" ? <Text
<Text style={{ style={{
marginTop: 5, marginTop: 5,
marginBottom: 5, marginBottom: 5,
textAlign: 'center' textAlign: 'center',
}}>{this.formatName(object.name)}</Text> }}>
: <View/>} {SelfMenuScreen.formatName(object.name)}
</View>)} </Text>
) : null,
)}
</Card.Content> </Card.Content>
</Card> </Card>
); );
}; };
/** /**
* Formats the given string to make sure it starts with a capital letter * Extract a key for the given item
* *
* @param name The string to format * @param item The item to extract the key from
* @return {string} The formatted string * @return {*} The extracted key
*/ */
formatName(name: String) { getKeyExtractor = (item: RuFoodCategoryType): string => item.name;
return name.charAt(0) + name.substr(1).toLowerCase();
}
render() { render(): React.Node {
const nav = this.props.navigation; const {navigation} = this.props;
return ( return (
<WebSectionList <WebSectionList
createDataset={this.createDataset} createDataset={this.createDataset}
navigation={nav} navigation={navigation}
autoRefreshTime={0} autoRefreshTime={0}
refreshOnFocus={false} refreshOnFocus={false}
fetchUrl={DATA_URL} fetchUrl={DATA_URL}
renderItem={this.getRenderItem} renderItem={this.getRenderItem}
renderSectionHeader={this.getRenderSectionHeader} renderSectionHeader={this.getRenderSectionHeader}
stickyHeader={true}/> stickyHeader
/>
); );
} }
} }

View file

@ -13,7 +13,7 @@ import {
import i18n from 'i18n-js'; import i18n from 'i18n-js';
import {StackNavigationProp} from '@react-navigation/stack'; import {StackNavigationProp} from '@react-navigation/stack';
import CardList from '../../components/Lists/CardList/CardList'; import CardList from '../../components/Lists/CardList/CardList';
import type {CustomTheme} from '../../managers/ThemeManager'; import type {CustomThemeType} from '../../managers/ThemeManager';
import MaterialHeaderButtons, { import MaterialHeaderButtons, {
Item, Item,
} from '../../components/Overrides/CustomHeaderButton'; } from '../../components/Overrides/CustomHeaderButton';
@ -28,7 +28,7 @@ import type {ServiceCategoryType} from '../../managers/ServicesManager';
type PropsType = { type PropsType = {
navigation: StackNavigationProp, navigation: StackNavigationProp,
theme: CustomTheme, theme: CustomThemeType,
}; };
class ServicesScreen extends React.Component<PropsType> { class ServicesScreen extends React.Component<PropsType> {

View file

@ -6,7 +6,7 @@ import {CommonActions} from '@react-navigation/native';
import {StackNavigationProp} from '@react-navigation/stack'; import {StackNavigationProp} from '@react-navigation/stack';
import CardList from '../../components/Lists/CardList/CardList'; import CardList from '../../components/Lists/CardList/CardList';
import CustomTabBar from '../../components/Tabbar/CustomTabBar'; import CustomTabBar from '../../components/Tabbar/CustomTabBar';
import {withCollapsible} from '../../utils/withCollapsible'; import withCollapsible from '../../utils/withCollapsible';
import type {ServiceCategoryType} from '../../managers/ServicesManager'; import type {ServiceCategoryType} from '../../managers/ServicesManager';
type PropsType = { type PropsType = {

View file

@ -1,60 +1,71 @@
// @flow // @flow
import * as React from 'react'; import * as React from 'react';
import {StackNavigationProp} from "@react-navigation/stack"; import {StackNavigationProp} from '@react-navigation/stack';
import WebViewScreen from "../../components/Screens/WebViewScreen"; import WebViewScreen from '../../components/Screens/WebViewScreen';
import AvailableWebsites from "../../constants/AvailableWebsites"; import AvailableWebsites from '../../constants/AvailableWebsites';
import BasicLoadingScreen from "../../components/Screens/BasicLoadingScreen"; import BasicLoadingScreen from '../../components/Screens/BasicLoadingScreen';
type Props = { type PropsType = {
navigation: StackNavigationProp, navigation: StackNavigationProp,
route: { params: { host: string, path: string | null, title: string } }, route: {params: {host: string, path: string | null, title: string}},
} };
class WebsiteScreen extends React.Component<Props> { const ENABLE_MOBILE_STRING = `<meta name="viewport" content="width=device-width, initial-scale=1.0">`;
const AVAILABLE_ROOMS_STYLE = `<style>body,body>.container2{padding-top:0;width:100%}b,body>.container2>h1,body>.container2>h3,br,header{display:none}.table-bordered td,.table-bordered th{border:none;border-right:1px solid #dee2e6;border-bottom:1px solid #dee2e6}.table{padding:0;margin:0;width:200%;max-width:200%;display:block}tbody{display:block;width:100%}thead{display:block;width:100%}.table tbody tr,tbody tr[bgcolor],thead tr{width:100%;display:inline-flex}.table tbody td,.table thead td[colspan]{padding:0;flex:1;height:50px;margin:0}.table tbody td[bgcolor=white],.table thead td,.table>tbody>tr>td:nth-child(1){flex:0 0 150px;height:50px}</style>`;
const BIB_STYLE = `<style>.hero-unit,.navbar,footer{display:none}.hero-unit-form,.hero-unit2,.hero-unit3{background-color:#fff;box-shadow:none;padding:0;margin:0}.hero-unit-form h4{font-size:2rem;line-height:2rem}.btn{font-size:1.5rem;line-height:1.5rem;padding:20px}.btn-danger{background-image:none;background-color:#be1522}.table{font-size:.8rem}.table td{padding:0;height:18.2333px;border:none;border-bottom:1px solid #c1c1c1}.table td[style="max-width:55px;"]{max-width:110px!important}.table-bordered{min-width:50px}th{height:50px}.table-bordered{border-collapse:collapse}</style>`;
const BIB_BACK_BUTTON =
`<div style='width: 100%; display: flex'>` +
`<a style='margin: auto' href='${AvailableWebsites.websites.BIB}'>` +
`<button id='customBackButton' class='btn btn-primary'>Retour</button>` +
`</a>` +
`</div>`;
class WebsiteScreen extends React.Component<PropsType> {
fullUrl: string; fullUrl: string;
injectedJS: { [key: string]: string };
customPaddingFunctions: {[key: string]: (padding: string) => string} injectedJS: {[key: string]: string};
customPaddingFunctions: {[key: string]: (padding: string) => string};
host: string; host: string;
constructor(props: Props) { constructor(props: PropsType) {
super(props); super(props);
this.props.navigation.addListener('focus', this.onScreenFocus); props.navigation.addListener('focus', this.onScreenFocus);
this.injectedJS = {}; this.injectedJS = {};
this.customPaddingFunctions = {}; this.customPaddingFunctions = {};
this.injectedJS[AvailableWebsites.websites.AVAILABLE_ROOMS] = this.injectedJS[AvailableWebsites.websites.AVAILABLE_ROOMS] =
'document.querySelector(\'head\').innerHTML += \'<meta name="viewport" content="width=device-width, initial-scale=1.0">\';' + `document.querySelector('head').innerHTML += '${ENABLE_MOBILE_STRING}';` +
'document.querySelector(\'head\').innerHTML += \'<style>body,body>.container2{padding-top:0;width:100%}b,body>.container2>h1,body>.container2>h3,br,header{display:none}.table-bordered td,.table-bordered th{border:none;border-right:1px solid #dee2e6;border-bottom:1px solid #dee2e6}.table{padding:0;margin:0;width:200%;max-width:200%;display:block}tbody{display:block;width:100%}thead{display:block;width:100%}.table tbody tr,tbody tr[bgcolor],thead tr{width:100%;display:inline-flex}.table tbody td,.table thead td[colspan]{padding:0;flex:1;height:50px;margin:0}.table tbody td[bgcolor=white],.table thead td,.table>tbody>tr>td:nth-child(1){flex:0 0 150px;height:50px}</style>\'; true;'; `document.querySelector('head').innerHTML += '${AVAILABLE_ROOMS_STYLE}'; true;`;
this.injectedJS[AvailableWebsites.websites.BIB] = this.injectedJS[AvailableWebsites.websites.BIB] =
'document.querySelector(\'head\').innerHTML += \'<meta name="viewport" content="width=device-width, initial-scale=1.0">\';' + `document.querySelector('head').innerHTML += '${ENABLE_MOBILE_STRING}';` +
'document.querySelector(\'head\').innerHTML += \'<style>.hero-unit,.navbar,footer{display:none}.hero-unit-form,.hero-unit2,.hero-unit3{background-color:#fff;box-shadow:none;padding:0;margin:0}.hero-unit-form h4{font-size:2rem;line-height:2rem}.btn{font-size:1.5rem;line-height:1.5rem;padding:20px}.btn-danger{background-image:none;background-color:#be1522}.table{font-size:.8rem}.table td{padding:0;height:18.2333px;border:none;border-bottom:1px solid #c1c1c1}.table td[style="max-width:55px;"]{max-width:110px!important}.table-bordered{min-width:50px}th{height:50px}.table-bordered{border-collapse:collapse}</style>\';' + `document.querySelector('head').innerHTML += '${BIB_STYLE}';` +
'if ($(".hero-unit-form").length > 0 && $("#customBackButton").length === 0)' + `if ($(".hero-unit-form").length > 0 && $("#customBackButton").length === 0)` +
'$(".hero-unit-form").append("' + `$(".hero-unit-form").append("${BIB_BACK_BUTTON}");true;`;
'<div style=\'width: 100%; display: flex\'>' +
'<a style=\'margin: auto\' href=\'' + AvailableWebsites.websites.BIB + '\'>' +
'<button id=\'customBackButton\' class=\'btn btn-primary\'>Retour</button>' +
'</a>' +
'</div>");true;';
this.customPaddingFunctions[AvailableWebsites.websites.BLUEMIND] = (padding: string) => { this.customPaddingFunctions[AvailableWebsites.websites.BLUEMIND] = (
padding: string,
): string => {
return ( return (
"$('head').append('<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">');" + `$('head').append('${ENABLE_MOBILE_STRING}');` +
"$('.minwidth').css('top', " + padding + ");" + `$('.minwidth').css('top', ${padding}` +
"$('#mailview-bottom').css('min-height', 500);" `$('#mailview-bottom').css('min-height', 500);`
); );
}; };
this.customPaddingFunctions[AvailableWebsites.websites.WIKETUD] = (padding: string) => { this.customPaddingFunctions[AvailableWebsites.websites.WIKETUD] = (
padding: string,
): string => {
return ( return (
"$('#p-logo-text').css('top', 10 + " + padding + ");" + `$('#p-logo-text').css('top', 10 + ${padding});` +
"$('#site-navigation h2').css('top', 10 + " + padding + ");" + `$('#site-navigation h2').css('top', 10 + ${padding});` +
"$('#site-tools h2').css('top', 10 + " + padding + ");" + `$('#site-tools h2').css('top', 10 + ${padding});` +
"$('#user-tools h2').css('top', 10 + " + padding + ");" `$('#user-tools h2').css('top', 10 + ${padding});`
); );
} };
} }
onScreenFocus = () => { onScreenFocus = () => {
@ -65,23 +76,23 @@ class WebsiteScreen extends React.Component<Props> {
* *
*/ */
handleNavigationParams() { handleNavigationParams() {
if (this.props.route.params != null) { const {route, navigation} = this.props;
this.host = this.props.route.params.host; if (route.params != null) {
let path = this.props.route.params.path; this.host = route.params.host;
const title = this.props.route.params.title; let {path} = route.params;
const {title} = route.params;
if (this.host != null && path != null) { if (this.host != null && path != null) {
path = path.replace(this.host, ""); path = path.replace(this.host, '');
this.fullUrl = this.host + path; this.fullUrl = this.host + path;
}else } else this.fullUrl = this.host;
this.fullUrl = this.host;
if (title != null) if (title != null) navigation.setOptions({title});
this.props.navigation.setOptions({title: title});
} }
} }
render() { render(): React.Node {
let injectedJavascript = ""; const {navigation} = this.props;
let injectedJavascript = '';
let customPadding = null; let customPadding = null;
if (this.host != null && this.injectedJS[this.host] != null) if (this.host != null && this.injectedJS[this.host] != null)
injectedJavascript = this.injectedJS[this.host]; injectedJavascript = this.injectedJS[this.host];
@ -91,18 +102,14 @@ class WebsiteScreen extends React.Component<Props> {
if (this.fullUrl != null) { if (this.fullUrl != null) {
return ( return (
<WebViewScreen <WebViewScreen
{...this.props} navigation={navigation}
url={this.fullUrl} url={this.fullUrl}
customJS={injectedJavascript} customJS={injectedJavascript}
customPaddingFunction={customPadding} customPaddingFunction={customPadding}
/> />
); );
} else {
return (
<BasicLoadingScreen/>
);
} }
return <BasicLoadingScreen />;
} }
} }

View file

@ -1,18 +1,28 @@
// @flow // @flow
import * as React from 'react';
const speedOffset = 5; const speedOffset = 5;
type ListenerFunctionType = (shouldHide: boolean) => void;
export type OnScrollType = {
nativeEvent: {
contentInset: {bottom: number, left: number, right: number, top: number},
contentOffset: {x: number, y: number},
contentSize: {height: number, width: number},
layoutMeasurement: {height: number, width: number},
zoomScale: number,
},
};
/** /**
* Class used to detect when to show or hide a component based on scrolling * Class used to detect when to show or hide a component based on scrolling
*/ */
export default class AutoHideHandler { export default class AutoHideHandler {
lastOffset: number; lastOffset: number;
isHidden: boolean; isHidden: boolean;
listeners: Array<Function>; listeners: Array<ListenerFunctionType>;
constructor(startHidden: boolean) { constructor(startHidden: boolean) {
this.listeners = []; this.listeners = [];
@ -24,7 +34,7 @@ export default class AutoHideHandler {
* *
* @param listener * @param listener
*/ */
addListener(listener: Function) { addListener(listener: (shouldHide: boolean) => void) {
this.listeners.push(listener); this.listeners.push(listener);
} }
@ -34,9 +44,9 @@ export default class AutoHideHandler {
* @param shouldHide * @param shouldHide
*/ */
notifyListeners(shouldHide: boolean) { notifyListeners(shouldHide: boolean) {
for (let i = 0; i < this.listeners.length; i++) { this.listeners.forEach((func: ListenerFunctionType) => {
this.listeners[i](shouldHide); func(shouldHide);
} });
} }
/** /**
@ -53,18 +63,23 @@ export default class AutoHideHandler {
* this can trigger the hide event as it scrolls down the list to show the refresh indicator. * this can trigger the hide event as it scrolls down the list to show the refresh indicator.
* Android shows the refresh indicator on top of the list so this is not an issue. * Android shows the refresh indicator on top of the list so this is not an issue.
* *
* @param nativeEvent The scroll event generated by the animated component onScroll prop * @param event The scroll event generated by the animated component onScroll prop
*/ */
onScroll({nativeEvent}: Object) { onScroll(event: OnScrollType) {
const speed = nativeEvent.contentOffset.y < 0 ? 0 : this.lastOffset - nativeEvent.contentOffset.y; const {nativeEvent} = event;
if (speed < -speedOffset && !this.isHidden) { // Go down const speed =
nativeEvent.contentOffset.y < 0
? 0
: this.lastOffset - nativeEvent.contentOffset.y;
if (speed < -speedOffset && !this.isHidden) {
// Go down
this.notifyListeners(true); this.notifyListeners(true);
this.isHidden = true; this.isHidden = true;
} else if (speed > speedOffset && this.isHidden) { // Go up } else if (speed > speedOffset && this.isHidden) {
// Go up
this.notifyListeners(false); this.notifyListeners(false);
this.isHidden = false; this.isHidden = false;
} }
this.lastOffset = nativeEvent.contentOffset.y; this.lastOffset = nativeEvent.contentOffset.y;
} }
} }

View file

@ -1,9 +1,9 @@
// @flow // @flow
import * as React from 'react'; import * as React from 'react';
import {useTheme} from "react-native-paper"; import {useTheme} from 'react-native-paper';
import {createCollapsibleStack} from "react-navigation-collapsible"; import {createCollapsibleStack} from 'react-navigation-collapsible';
import StackNavigator, {StackNavigationOptions} from "@react-navigation/stack"; import StackNavigator, {StackNavigationOptions} from '@react-navigation/stack';
/** /**
* Creates a navigation stack with the collapsible library, allowing the header to collapse on scroll. * Creates a navigation stack with the collapsible library, allowing the header to collapse on scroll.
@ -24,11 +24,13 @@ import StackNavigator, {StackNavigationOptions} from "@react-navigation/stack";
export function createScreenCollapsibleStack( export function createScreenCollapsibleStack(
name: string, name: string,
Stack: StackNavigator, Stack: StackNavigator,
// eslint-disable-next-line flowtype/no-weak-types
component: React.ComponentType<any>, component: React.ComponentType<any>,
title: string, title: string,
useNativeDriver?: boolean, useNativeDriver?: boolean,
options?: StackNavigationOptions, options?: StackNavigationOptions,
headerColor?: string) { headerColor?: string,
): React.Node {
const {colors} = useTheme(); const {colors} = useTheme();
const screenOptions = options != null ? options : {}; const screenOptions = options != null ? options : {};
return createCollapsibleStack( return createCollapsibleStack(
@ -36,18 +38,18 @@ export function createScreenCollapsibleStack(
name={name} name={name}
component={component} component={component}
options={{ options={{
title: title, title,
headerStyle: { headerStyle: {
backgroundColor: headerColor!=null ? headerColor :colors.surface, backgroundColor: headerColor != null ? headerColor : colors.surface,
}, },
...screenOptions, ...screenOptions,
}} }}
/>, />,
{ {
collapsedColor: headerColor!=null ? headerColor :colors.surface, collapsedColor: headerColor != null ? headerColor : colors.surface,
useNativeDriver: useNativeDriver != null ? useNativeDriver : true, // native driver does not work with webview useNativeDriver: useNativeDriver != null ? useNativeDriver : true, // native driver does not work with webview
} },
) );
} }
/** /**
@ -62,6 +64,12 @@ export function createScreenCollapsibleStack(
* @param title * @param title
* @returns {JSX.Element} * @returns {JSX.Element}
*/ */
export function getWebsiteStack(name: string, Stack: any, component: any, title: string) { export function getWebsiteStack(
name: string,
Stack: StackNavigator,
// eslint-disable-next-line flowtype/no-weak-types
component: React.ComponentType<any>,
title: string,
): React.Node {
return createScreenCollapsibleStack(name, Stack, component, title, false); return createScreenCollapsibleStack(name, Stack, component, title, false);
} }

View file

@ -3,7 +3,7 @@
import i18n from 'i18n-js'; import i18n from 'i18n-js';
import type {DeviceType} from '../screens/Amicale/Equipment/EquipmentListScreen'; import type {DeviceType} from '../screens/Amicale/Equipment/EquipmentListScreen';
import DateManager from '../managers/DateManager'; import DateManager from '../managers/DateManager';
import type {CustomTheme} from '../managers/ThemeManager'; import type {CustomThemeType} from '../managers/ThemeManager';
import type {MarkedDatesObjectType} from '../screens/Amicale/Equipment/EquipmentRentScreen'; import type {MarkedDatesObjectType} from '../screens/Amicale/Equipment/EquipmentRentScreen';
/** /**
@ -161,7 +161,7 @@ export function getValidRange(
*/ */
export function generateMarkedDates( export function generateMarkedDates(
isSelection: boolean, isSelection: boolean,
theme: CustomTheme, theme: CustomThemeType,
range: Array<string>, range: Array<string>,
): MarkedDatesObjectType { ): MarkedDatesObjectType {
const markedDates = {}; const markedDates = {};

Some files were not shown because too many files have changed in this diff Show more