From 42731d26a1f47d0c8a8443fd35ea6ab2b8ad7a43 Mon Sep 17 00:00:00 2001 From: Arnaud Vergnet Date: Sat, 14 Mar 2020 15:58:57 +0100 Subject: [PATCH 001/398] Refactored some lines --- screens/HomeScreen.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/screens/HomeScreen.js b/screens/HomeScreen.js index 464f196..538584d 100644 --- a/screens/HomeScreen.js +++ b/screens/HomeScreen.js @@ -40,7 +40,7 @@ class HomeScreen extends React.Component { getRenderItem: Function; createDataset: Function; - colors : Object; + colors: Object; constructor(props) { super(props); From 3aaf56a660bdbfc73d0943e9437c10ee9b6446a3 Mon Sep 17 00:00:00 2001 From: Arnaud Vergnet Date: Sun, 15 Mar 2020 18:44:32 +0100 Subject: [PATCH 002/398] Added basic tetris functionality --- components/Sidebar.js | 11 ++- navigation/DrawerNavigator.js | 29 ++++++ screens/Tetris/GameLogic.js | 158 ++++++++++++++++++++++++++++++ screens/Tetris/TetrisScreen.js | 116 ++++++++++++++++++++++ screens/Tetris/Tetromino.js | 82 ++++++++++++++++ screens/Tetris/components/Cell.js | 21 ++++ screens/Tetris/components/Grid.js | 63 ++++++++++++ 7 files changed, 479 insertions(+), 1 deletion(-) create mode 100644 screens/Tetris/GameLogic.js create mode 100644 screens/Tetris/TetrisScreen.js create mode 100644 screens/Tetris/Tetromino.js create mode 100644 screens/Tetris/components/Cell.js create mode 100644 screens/Tetris/components/Grid.js diff --git a/components/Sidebar.js b/components/Sidebar.js index 4f8fb9f..3fca4cd 100644 --- a/components/Sidebar.js +++ b/components/Sidebar.js @@ -6,6 +6,7 @@ import i18n from "i18n-js"; import * as WebBrowser from 'expo-web-browser'; import SidebarDivider from "./SidebarDivider"; import SidebarItem from "./SidebarItem"; +import {TouchableRipple} from "react-native-paper"; const deviceWidth = Dimensions.get("window").width; @@ -154,9 +155,17 @@ export default class SideBar extends React.PureComponent { } render() { + const onPress = this.onListItemPress.bind(this, {route: 'TetrisScreen'}); return ( - + + + + { + const openDrawer = getDrawerButton.bind(this, navigation); + return { + title: 'Tetris', + headerLeft: openDrawer + }; + }} + /> + + ); +} + const Drawer = createDrawerNavigator(); function getDrawerContent(props) { @@ -202,6 +227,10 @@ export default function DrawerNavigator() { name="BibScreen" component={BibStackComponent} /> + ); } diff --git a/screens/Tetris/GameLogic.js b/screens/Tetris/GameLogic.js new file mode 100644 index 0000000..a9b8263 --- /dev/null +++ b/screens/Tetris/GameLogic.js @@ -0,0 +1,158 @@ +// @flow + +import Tetromino from "./Tetromino"; + +export default class GameLogic { + + currentGrid: Array>; + + height: number; + width: number; + + gameRunning: boolean; + gameTime: number; + score: number; + + currentObject: Tetromino; + + gameTick: number; + gameTickInterval: IntervalID; + + onTick: Function; + + constructor(height: number, width: number) { + this.height = height; + this.width = width; + this.gameRunning = false; + this.gameTick = 250; + } + + getHeight(): number { + return this.height; + } + + getWidth(): number { + return this.width; + } + + isGameRunning(): boolean { + return this.gameRunning; + } + + getEmptyGrid() { + let grid = []; + for (let row = 0; row < this.getHeight(); row++) { + grid.push([]); + for (let col = 0; col < this.getWidth(); col++) { + grid[row].push({ + color: '#fff', + isEmpty: true, + }); + } + } + return grid; + } + + getGridCopy() { + return JSON.parse(JSON.stringify(this.currentGrid)); + } + + getFinalGrid() { + let coord = this.currentObject.getCellsCoordinates(); + let finalGrid = this.getGridCopy(); + for (let i = 0; i < coord.length; i++) { + finalGrid[coord[i].y][coord[i].x] = { + color: this.currentObject.getColor(), + isEmpty: false, + }; + } + return finalGrid; + } + + freezeTetromino() { + let coord = this.currentObject.getCellsCoordinates(); + for (let i = 0; i < coord.length; i++) { + this.currentGrid[coord[i].y][coord[i].x] = { + color: this.currentObject.getColor(), + isEmpty: false, + }; + } + } + + isTetrominoPositionValid() { + let isValid = true; + let coord = this.currentObject.getCellsCoordinates(); + for (let i = 0; i < coord.length; i++) { + if (coord[i].x >= this.getWidth() + || coord[i].x < 0 + || coord[i].y >= this.getHeight() + || coord[i].y < 0 + || !this.currentGrid[coord[i].y][coord[i].x].isEmpty) { + isValid = false; + break; + } + } + return isValid; + } + + tryMoveTetromino(x: number, y: number) { + if (x > 1) x = 1; // Prevent moving from more than one tile + if (x < -1) x = -1; + if (y > 1) y = 1; + if (y < -1) y = -1; + if (x !== 0 && y !== 0) y = 0; // Prevent diagonal movement + + this.currentObject.move(x, y); + let isValid = this.isTetrominoPositionValid(); + + if (!isValid && x !== 0) + this.currentObject.move(-x, 0); + else if (!isValid && y !== 0) { + this.currentObject.move(0, -y); + this.freezeTetromino(); + this.createTetromino(); + } + } + + onTick(callback: Function) { + this.gameTime++; + this.score++; + this.tryMoveTetromino(0, 1); + callback(this.gameTime, this.score, this.getFinalGrid()); + } + + rightPressed(callback: Function) { + this.tryMoveTetromino(1, 0); + callback(this.getFinalGrid()); + } + + leftPressed(callback: Function) { + this.tryMoveTetromino(-1, 0); + callback(this.getFinalGrid()); + } + + createTetromino() { + let shape = Math.floor(Math.random() * 7); + this.currentObject = new Tetromino(shape); + if (!this.isTetrominoPositionValid()) + this.endGame(); + } + + endGame() { + console.log('Game Over!'); + clearInterval(this.gameTickInterval); + } + + startGame(callback: Function) { + if (this.gameRunning) + return; + this.gameRunning = true; + this.gameTime = 0; + this.score = 0; + this.currentGrid = this.getEmptyGrid(); + this.createTetromino(); + this.onTick = this.onTick.bind(this, callback); + this.gameTickInterval = setInterval(this.onTick, this.gameTick); + } + +} diff --git a/screens/Tetris/TetrisScreen.js b/screens/Tetris/TetrisScreen.js new file mode 100644 index 0000000..a405e05 --- /dev/null +++ b/screens/Tetris/TetrisScreen.js @@ -0,0 +1,116 @@ +// @flow + +import * as React from 'react'; +import {View} from 'react-native'; +import {IconButton, Text, withTheme} from 'react-native-paper'; +import GameLogic from "./GameLogic"; +import Grid from "./components/Grid"; + +type Props = { + navigation: Object, +} + +type State = { + grid: Array>, + gameTime: number, + gameScore: number +} + +class TetrisScreen extends React.Component { + + colors: Object; + + logic: GameLogic; + onTick: Function; + updateGrid: Function; + + constructor(props) { + super(props); + this.colors = props.theme.colors; + this.logic = new GameLogic(20, 10); + this.state = { + grid: this.logic.getEmptyGrid(), + gameTime: 0, + gameScore: 0, + }; + this.onTick = this.onTick.bind(this); + this.updateGrid = this.updateGrid.bind(this); + const onScreenBlur = this.onScreenBlur.bind(this); + this.props.navigation.addListener('blur', onScreenBlur); + } + + + /** + * Remove any interval on un-focus + */ + onScreenBlur() { + this.logic.endGame(); + } + + onTick(time: number, score: number, newGrid: Array>) { + this.setState({ + gameTime: time, + gameScore: score, + grid: newGrid, + }); + } + + updateGrid(newGrid: Array>) { + this.setState({ + grid: newGrid, + }); + } + + startGame() { + if (!this.logic.isGameRunning()) { + this.logic.startGame(this.onTick); + } + } + + render() { + return ( + + + Score: {this.state.gameScore} + + + time: {this.state.gameTime} + + + + this.logic.rightPressed(this.updateGrid)} + /> + this.logic.leftPressed(this.updateGrid)} + /> + this.startGame()} + /> + + + ); + } + +} + +export default withTheme(TetrisScreen); diff --git a/screens/Tetris/Tetromino.js b/screens/Tetris/Tetromino.js new file mode 100644 index 0000000..1b15293 --- /dev/null +++ b/screens/Tetris/Tetromino.js @@ -0,0 +1,82 @@ +export default class Tetromino { + + static types = { + 'I': 0, + 'O': 1, + 'T': 2, + 'S': 3, + 'Z': 4, + 'J': 5, + 'L': 6, + }; + + static shapes = { + 0: [ + [1, 1, 1, 1] + ], + 1: [ + [1, 1], + [1, 1] + ], + 2: [ + [0, 1, 0], + [1, 1, 1], + ], + 3: [ + [0, 1, 1], + [1, 1, 0], + ], + 4: [ + [1, 1, 0], + [0, 1, 1], + ], + 5: [ + [1, 0, 0], + [1, 1, 1], + ], + 6: [ + [0, 0, 1], + [1, 1, 1], + ], + }; + + static colors = { + 0: '#00f8ff', + 1: '#ffe200', + 2: '#b817ff', + 3: '#0cff34', + 4: '#ff000b', + 5: '#1000ff', + 6: '#ff9400', + } + + + currentType: Tetromino.types; + position: Object; + + constructor(type: Tetromino.types) { + this.currentType = type; + this.position = {x: 0, y: 0}; + } + + getColor() { + return Tetromino.colors[this.currentType]; + } + + getCellsCoordinates() { + let coordinates = []; + for (let row = 0; row < Tetromino.shapes[this.currentType].length; row++) { + for (let col = 0; col < Tetromino.shapes[this.currentType][row].length; col++) { + if (Tetromino.shapes[this.currentType][row][col] === 1) + coordinates.push({x: this.position.x + col, y: this.position.y + row}); + } + } + return coordinates; + } + + move(x: number, y: number) { + this.position.x += x; + this.position.y += y; + } + +} diff --git a/screens/Tetris/components/Cell.js b/screens/Tetris/components/Cell.js new file mode 100644 index 0000000..6ebb28e --- /dev/null +++ b/screens/Tetris/components/Cell.js @@ -0,0 +1,21 @@ +// @flow + +import * as React from 'react'; +import {View} from 'react-native'; +import {withTheme} from 'react-native-paper'; + +function Cell(props) { + const colors = props.theme.colors; + return ( + + ); +} + +export default withTheme(Cell); diff --git a/screens/Tetris/components/Grid.js b/screens/Tetris/components/Grid.js new file mode 100644 index 0000000..5acaa26 --- /dev/null +++ b/screens/Tetris/components/Grid.js @@ -0,0 +1,63 @@ +// @flow + +import * as React from 'react'; +import {View} from 'react-native'; +import {withTheme} from 'react-native-paper'; +import Cell from "./Cell"; + +type Props = { + navigation: Object, + grid: Array>, + height: number, + width: number, +} + +class Grid extends React.Component{ + + colors: Object; + + constructor(props) { + super(props); + this.colors = props.theme.colors; + } + + getRow(rowNumber: number) { + let cells = []; + for (let i = 0; i < this.props.width; i++) { + let cell = this.props.grid[rowNumber][i]; + cells.push(); + } + return( + + {cells} + + ); + } + + getGrid() { + let rows = []; + for (let i = 0; i < this.props.height; i++) { + rows.push(this.getRow(i)); + } + return rows; + } + + render() { + return ( + + {this.getGrid()} + + ); + } +} + +export default withTheme(Grid); From bb54186d9e74cd9044a6d57334ba3e9fc4d4919d Mon Sep 17 00:00:00 2001 From: Arnaud Vergnet Date: Sun, 15 Mar 2020 19:28:41 +0100 Subject: [PATCH 003/398] Added rotation feature --- screens/Tetris/GameLogic.js | 20 +++++++++++++++-- screens/Tetris/TetrisScreen.js | 18 +++++++++++++-- screens/Tetris/Tetromino.js | 41 +++++++++++++++++++++++++++++----- 3 files changed, 70 insertions(+), 9 deletions(-) diff --git a/screens/Tetris/GameLogic.js b/screens/Tetris/GameLogic.js index a9b8263..cacda8f 100644 --- a/screens/Tetris/GameLogic.js +++ b/screens/Tetris/GameLogic.js @@ -19,6 +19,7 @@ export default class GameLogic { gameTickInterval: IntervalID; onTick: Function; + endCallback: Function; constructor(height: number, width: number) { this.height = height; @@ -114,6 +115,12 @@ export default class GameLogic { } } + tryRotateTetromino() { + this.currentObject.rotate(true); + if (!this.isTetrominoPositionValid()) + this.currentObject.rotate(false); + } + onTick(callback: Function) { this.gameTime++; this.score++; @@ -131,6 +138,11 @@ export default class GameLogic { callback(this.getFinalGrid()); } + rotatePressed(callback: Function) { + this.tryRotateTetromino(); + callback(this.getFinalGrid()); + } + createTetromino() { let shape = Math.floor(Math.random() * 7); this.currentObject = new Tetromino(shape); @@ -140,10 +152,12 @@ export default class GameLogic { endGame() { console.log('Game Over!'); + this.gameRunning = false; clearInterval(this.gameTickInterval); + this.endCallback(this.gameTime, this.score); } - startGame(callback: Function) { + startGame(tickCallback: Function, endCallback: Function) { if (this.gameRunning) return; this.gameRunning = true; @@ -151,8 +165,10 @@ export default class GameLogic { this.score = 0; this.currentGrid = this.getEmptyGrid(); this.createTetromino(); - this.onTick = this.onTick.bind(this, callback); + tickCallback(this.gameTime, this.score, this.getFinalGrid()); + this.onTick = this.onTick.bind(this, tickCallback); this.gameTickInterval = setInterval(this.onTick, this.gameTick); + this.endCallback = endCallback; } } diff --git a/screens/Tetris/TetrisScreen.js b/screens/Tetris/TetrisScreen.js index a405e05..a21c2a3 100644 --- a/screens/Tetris/TetrisScreen.js +++ b/screens/Tetris/TetrisScreen.js @@ -22,6 +22,7 @@ class TetrisScreen extends React.Component { logic: GameLogic; onTick: Function; + onGameEnd: Function; updateGrid: Function; constructor(props) { @@ -34,6 +35,7 @@ class TetrisScreen extends React.Component { gameScore: 0, }; this.onTick = this.onTick.bind(this); + this.onGameEnd = this.onGameEnd.bind(this); this.updateGrid = this.updateGrid.bind(this); const onScreenBlur = this.onScreenBlur.bind(this); this.props.navigation.addListener('blur', onScreenBlur); @@ -63,10 +65,17 @@ class TetrisScreen extends React.Component { startGame() { if (!this.logic.isGameRunning()) { - this.logic.startGame(this.onTick); + this.logic.startGame(this.onTick, this.onGameEnd); } } + onGameEnd(time: number, score: number) { + this.setState({ + gameTime: time, + gameScore: score, + }) + } + render() { return ( { this.startGame()} + onPress={() => this.logic.rotatePressed(this.updateGrid)} /> + this.startGame()} + /> ); diff --git a/screens/Tetris/Tetromino.js b/screens/Tetris/Tetromino.js index 1b15293..5aa75fe 100644 --- a/screens/Tetris/Tetromino.js +++ b/screens/Tetris/Tetromino.js @@ -22,6 +22,11 @@ export default class Tetromino { [0, 1, 0], [1, 1, 1], ], + 20: [ + [1, 0], + [1, 1], + [1, 0], + ], 3: [ [0, 1, 1], [1, 1, 0], @@ -48,14 +53,18 @@ export default class Tetromino { 4: '#ff000b', 5: '#1000ff', 6: '#ff9400', - } + }; - currentType: Tetromino.types; + currentType: Object; + currentShape: Object; + currentRotation: number; position: Object; constructor(type: Tetromino.types) { this.currentType = type; + this.currentShape = Tetromino.shapes[type]; + this.currentRotation = 0; this.position = {x: 0, y: 0}; } @@ -65,15 +74,37 @@ export default class Tetromino { getCellsCoordinates() { let coordinates = []; - for (let row = 0; row < Tetromino.shapes[this.currentType].length; row++) { - for (let col = 0; col < Tetromino.shapes[this.currentType][row].length; col++) { - if (Tetromino.shapes[this.currentType][row][col] === 1) + for (let row = 0; row < this.currentShape.length; row++) { + for (let col = 0; col < this.currentShape[row].length; col++) { + if (this.currentShape[row][col] === 1) coordinates.push({x: this.position.x + col, y: this.position.y + row}); } } return coordinates; } + rotate(isForward) { + this.currentRotation++; + if (this.currentRotation > 3) + this.currentRotation = 0; + + if (this.currentRotation === 0) { + this.currentShape = Tetromino.shapes[this.currentType]; + } else { + let result = []; + for(let i = 0; i < this.currentShape[0].length; i++) { + let row = this.currentShape.map(e => e[i]); + + if (isForward) + result.push(row.reverse()); + else + result.push(row); + } + this.currentShape = result; + } + + } + move(x: number, y: number) { this.position.x += x; this.position.y += y; From 7b45841c30c38ebf4f7c942bc40197e09c78533c Mon Sep 17 00:00:00 2001 From: Arnaud Vergnet Date: Sun, 15 Mar 2020 20:18:48 +0100 Subject: [PATCH 004/398] Use pure component for cells --- screens/Tetris/GameLogic.js | 2 +- screens/Tetris/components/Cell.js | 43 ++++++++++++++++++++++--------- screens/Tetris/components/Grid.js | 3 ++- 3 files changed, 34 insertions(+), 14 deletions(-) diff --git a/screens/Tetris/GameLogic.js b/screens/Tetris/GameLogic.js index cacda8f..c93c4d0 100644 --- a/screens/Tetris/GameLogic.js +++ b/screens/Tetris/GameLogic.js @@ -25,7 +25,7 @@ export default class GameLogic { this.height = height; this.width = width; this.gameRunning = false; - this.gameTick = 250; + this.gameTick = 1000; } getHeight(): number { diff --git a/screens/Tetris/components/Cell.js b/screens/Tetris/components/Cell.js index 6ebb28e..a3fd525 100644 --- a/screens/Tetris/components/Cell.js +++ b/screens/Tetris/components/Cell.js @@ -4,18 +4,37 @@ import * as React from 'react'; import {View} from 'react-native'; import {withTheme} from 'react-native-paper'; -function Cell(props) { - const colors = props.theme.colors; - return ( - - ); +type Props = { + color: string, + isEmpty: boolean, + id: string, +} + +class Cell extends React.PureComponent { + + colors: Object; + + constructor(props) { + super(props); + this.colors = props.theme.colors; + } + + render() { + return ( + + ); + } + + } export default withTheme(Cell); diff --git a/screens/Tetris/components/Grid.js b/screens/Tetris/components/Grid.js index 5acaa26..19be7f9 100644 --- a/screens/Tetris/components/Grid.js +++ b/screens/Tetris/components/Grid.js @@ -25,7 +25,8 @@ class Grid extends React.Component{ let cells = []; for (let i = 0; i < this.props.width; i++) { let cell = this.props.grid[rowNumber][i]; - cells.push(); + let key = rowNumber + ':' + i; + cells.push(); } return( Date: Sun, 15 Mar 2020 20:34:20 +0100 Subject: [PATCH 005/398] Improved colors --- screens/Tetris/GameLogic.js | 9 ++++++--- screens/Tetris/TetrisScreen.js | 2 +- screens/Tetris/Tetromino.js | 24 +++++++++++++----------- screens/Tetris/components/Cell.js | 2 +- screens/Tetris/components/Grid.js | 2 +- utils/ThemeManager.js | 22 ++++++++++++++++++++++ 6 files changed, 44 insertions(+), 17 deletions(-) diff --git a/screens/Tetris/GameLogic.js b/screens/Tetris/GameLogic.js index c93c4d0..44e19a6 100644 --- a/screens/Tetris/GameLogic.js +++ b/screens/Tetris/GameLogic.js @@ -21,11 +21,14 @@ export default class GameLogic { onTick: Function; endCallback: Function; - constructor(height: number, width: number) { + colors: Object; + + constructor(height: number, width: number, colors: Object) { this.height = height; this.width = width; this.gameRunning = false; this.gameTick = 1000; + this.colors = colors; } getHeight(): number { @@ -46,7 +49,7 @@ export default class GameLogic { grid.push([]); for (let col = 0; col < this.getWidth(); col++) { grid[row].push({ - color: '#fff', + color: this.colors.tetrisBackground, isEmpty: true, }); } @@ -145,7 +148,7 @@ export default class GameLogic { createTetromino() { let shape = Math.floor(Math.random() * 7); - this.currentObject = new Tetromino(shape); + this.currentObject = new Tetromino(shape, this.colors); if (!this.isTetrominoPositionValid()) this.endGame(); } diff --git a/screens/Tetris/TetrisScreen.js b/screens/Tetris/TetrisScreen.js index a21c2a3..c0bb6dc 100644 --- a/screens/Tetris/TetrisScreen.js +++ b/screens/Tetris/TetrisScreen.js @@ -28,7 +28,7 @@ class TetrisScreen extends React.Component { constructor(props) { super(props); this.colors = props.theme.colors; - this.logic = new GameLogic(20, 10); + this.logic = new GameLogic(20, 10, this.colors); this.state = { grid: this.logic.getEmptyGrid(), gameTime: 0, diff --git a/screens/Tetris/Tetromino.js b/screens/Tetris/Tetromino.js index 5aa75fe..470b97a 100644 --- a/screens/Tetris/Tetromino.js +++ b/screens/Tetris/Tetromino.js @@ -45,27 +45,29 @@ export default class Tetromino { ], }; - static colors = { - 0: '#00f8ff', - 1: '#ffe200', - 2: '#b817ff', - 3: '#0cff34', - 4: '#ff000b', - 5: '#1000ff', - 6: '#ff9400', - }; - + static colors: Object; currentType: Object; currentShape: Object; currentRotation: number; position: Object; + colors: Object; - constructor(type: Tetromino.types) { + constructor(type: Tetromino.types, colors: Object) { this.currentType = type; this.currentShape = Tetromino.shapes[type]; this.currentRotation = 0; this.position = {x: 0, y: 0}; + this.colors = colors; + Tetromino.colors = { + 0: colors.tetrisI, + 1: colors.tetrisO, + 2: colors.tetrisT, + 3: colors.tetrisS, + 4: colors.tetrisZ, + 5: colors.tetrisJ, + 6: colors.tetrisL, + }; } getColor() { diff --git a/screens/Tetris/components/Cell.js b/screens/Tetris/components/Cell.js index a3fd525..f0e764c 100644 --- a/screens/Tetris/components/Cell.js +++ b/screens/Tetris/components/Cell.js @@ -25,7 +25,7 @@ class Cell extends React.PureComponent { style={{ flex: 1, backgroundColor: this.props.color, - borderColor: this.props.isEmpty ? this.props.color : "#393939", + borderColor: this.props.isEmpty ? this.props.color : this.colors.tetrisBorder, borderStyle: 'solid', borderWidth: 1, aspectRatio: 1, diff --git a/screens/Tetris/components/Grid.js b/screens/Tetris/components/Grid.js index 19be7f9..53e7904 100644 --- a/screens/Tetris/components/Grid.js +++ b/screens/Tetris/components/Grid.js @@ -31,7 +31,7 @@ class Grid extends React.Component{ return( {cells} diff --git a/utils/ThemeManager.js b/utils/ThemeManager.js index 86ae540..eb3f914 100644 --- a/utils/ThemeManager.js +++ b/utils/ThemeManager.js @@ -54,6 +54,17 @@ export default class ThemeManager { proxiwashColor: '#1fa5ee', menuColor: '#e91314', tutorinsaColor: '#f93943', + + // Tetris + tetrisBackground:'#d1d1d1', + tetrisBorder:'#afafaf', + tetrisI : '#42f1ff', + tetrisO : '#ffdd00', + tetrisT : '#ba19ff', + tetrisS : '#0bff34', + tetrisZ : '#ff0009', + tetrisJ : '#134cff', + tetrisL : '#ff8834', }, }; } @@ -94,6 +105,17 @@ export default class ThemeManager { proxiwashColor: '#1fa5ee', menuColor: '#b81213', tutorinsaColor: '#f93943', + + // Tetris + tetrisBackground:'#2c2c2c', + tetrisBorder:'#1b1b1b', + tetrisI : '#30b3be', + tetrisO : '#c1a700', + tetrisT : '#9114c7', + tetrisS : '#08a121', + tetrisZ : '#b50008', + tetrisJ : '#0f37b9', + tetrisL : '#b96226', }, }; } From 3fe1d85eec6b475313f1bbb92e6351fe2b44a39a Mon Sep 17 00:00:00 2001 From: Arnaud Vergnet Date: Mon, 16 Mar 2020 08:22:18 +0100 Subject: [PATCH 006/398] Fixed start position --- screens/Tetris/GameLogic.js | 2 +- screens/Tetris/Tetromino.js | 9 ++++----- 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/screens/Tetris/GameLogic.js b/screens/Tetris/GameLogic.js index 44e19a6..80deca8 100644 --- a/screens/Tetris/GameLogic.js +++ b/screens/Tetris/GameLogic.js @@ -27,7 +27,7 @@ export default class GameLogic { this.height = height; this.width = width; this.gameRunning = false; - this.gameTick = 1000; + this.gameTick = 250; this.colors = colors; } diff --git a/screens/Tetris/Tetromino.js b/screens/Tetris/Tetromino.js index 470b97a..5a48fc1 100644 --- a/screens/Tetris/Tetromino.js +++ b/screens/Tetris/Tetromino.js @@ -22,11 +22,6 @@ export default class Tetromino { [0, 1, 0], [1, 1, 1], ], - 20: [ - [1, 0], - [1, 1], - [1, 0], - ], 3: [ [0, 1, 1], [1, 1, 0], @@ -58,6 +53,10 @@ export default class Tetromino { this.currentShape = Tetromino.shapes[type]; this.currentRotation = 0; this.position = {x: 0, y: 0}; + if (this.currentType === Tetromino.types.O) + this.position.x = 4; + else + this.position.x = 3; this.colors = colors; Tetromino.colors = { 0: colors.tetrisI, From 8fc5cfb25e5dc313549e89f725fd383d23b4a17e Mon Sep 17 00:00:00 2001 From: Arnaud Vergnet Date: Mon, 16 Mar 2020 14:58:13 +0100 Subject: [PATCH 007/398] Remove full lines --- screens/Tetris/GameLogic.js | 44 +++++++++++++++++++++++++++++++------ 1 file changed, 37 insertions(+), 7 deletions(-) diff --git a/screens/Tetris/GameLogic.js b/screens/Tetris/GameLogic.js index 80deca8..05a14eb 100644 --- a/screens/Tetris/GameLogic.js +++ b/screens/Tetris/GameLogic.js @@ -43,16 +43,21 @@ export default class GameLogic { return this.gameRunning; } + getEmptyLine() { + let line = []; + for (let col = 0; col < this.getWidth(); col++) { + line.push({ + color: this.colors.tetrisBackground, + isEmpty: true, + }); + } + return line; + } + getEmptyGrid() { let grid = []; for (let row = 0; row < this.getHeight(); row++) { - grid.push([]); - for (let col = 0; col < this.getWidth(); col++) { - grid[row].push({ - color: this.colors.tetrisBackground, - isEmpty: true, - }); - } + grid.push(this.getEmptyLine()); } return grid; } @@ -81,6 +86,31 @@ export default class GameLogic { isEmpty: false, }; } + this.clearLines(this.getLinesToClear(coord)); + } + + clearLines(lines: Array) { + lines.sort(); + for (let i = 0; i < lines.length; i++) { + this.currentGrid.splice(lines[i], 1); + this.currentGrid.unshift(this.getEmptyLine()); + } + } + + getLinesToClear(coord: Object) { + let rows = []; + for (let i = 0; i < coord.length; i++) { + let isLineFull = true; + for (let col = 0; col < this.getWidth(); col++) { + if (this.currentGrid[coord[i].y][col].isEmpty) { + isLineFull = false; + break; + } + } + if (isLineFull && rows.indexOf(coord[i].y) === -1) + rows.push(coord[i].y); + } + return rows; } isTetrominoPositionValid() { From 7f33c8376d45e368a41a05f154f57082e65ebc58 Mon Sep 17 00:00:00 2001 From: Arnaud Vergnet Date: Mon, 16 Mar 2020 19:10:32 +0100 Subject: [PATCH 008/398] Improved game UI and state management --- screens/Tetris/GameLogic.js | 41 +++++++-- screens/Tetris/TetrisScreen.js | 151 +++++++++++++++++++++++++++------ utils/ThemeManager.js | 2 + 3 files changed, 162 insertions(+), 32 deletions(-) diff --git a/screens/Tetris/GameLogic.js b/screens/Tetris/GameLogic.js index 05a14eb..4863e01 100644 --- a/screens/Tetris/GameLogic.js +++ b/screens/Tetris/GameLogic.js @@ -10,6 +10,7 @@ export default class GameLogic { width: number; gameRunning: boolean; + gamePaused: boolean; gameTime: number; score: number; @@ -27,6 +28,7 @@ export default class GameLogic { this.height = height; this.width = width; this.gameRunning = false; + this.gamePaused = false; this.gameTick = 250; this.colors = colors; } @@ -43,6 +45,10 @@ export default class GameLogic { return this.gameRunning; } + isGamePaused(): boolean { + return this.gamePaused; + } + getEmptyLine() { let line = []; for (let col = 0; col < this.getWidth(); col++) { @@ -161,17 +167,30 @@ export default class GameLogic { callback(this.gameTime, this.score, this.getFinalGrid()); } + canUseInput() { + return this.gameRunning && !this.gamePaused + } + rightPressed(callback: Function) { + if (!this.canUseInput()) + return; + this.tryMoveTetromino(1, 0); callback(this.getFinalGrid()); } leftPressed(callback: Function) { + if (!this.canUseInput()) + return; + this.tryMoveTetromino(-1, 0); callback(this.getFinalGrid()); } rotatePressed(callback: Function) { + if (!this.canUseInput()) + return; + this.tryRotateTetromino(); callback(this.getFinalGrid()); } @@ -180,20 +199,32 @@ export default class GameLogic { let shape = Math.floor(Math.random() * 7); this.currentObject = new Tetromino(shape, this.colors); if (!this.isTetrominoPositionValid()) - this.endGame(); + this.endGame(false); } - endGame() { - console.log('Game Over!'); + togglePause() { + if (!this.gameRunning) + return; + this.gamePaused = !this.gamePaused; + if (this.gamePaused) { + clearInterval(this.gameTickInterval); + } else { + this.gameTickInterval = setInterval(this.onTick, this.gameTick); + } + } + + endGame(isRestart: boolean) { this.gameRunning = false; + this.gamePaused = false; clearInterval(this.gameTickInterval); - this.endCallback(this.gameTime, this.score); + this.endCallback(this.gameTime, this.score, isRestart); } startGame(tickCallback: Function, endCallback: Function) { if (this.gameRunning) - return; + this.endGame(true); this.gameRunning = true; + this.gamePaused = false; this.gameTime = 0; this.score = 0; this.currentGrid = this.getEmptyGrid(); diff --git a/screens/Tetris/TetrisScreen.js b/screens/Tetris/TetrisScreen.js index c0bb6dc..f9675de 100644 --- a/screens/Tetris/TetrisScreen.js +++ b/screens/Tetris/TetrisScreen.js @@ -1,10 +1,12 @@ // @flow import * as React from 'react'; -import {View} from 'react-native'; +import {Alert, View} from 'react-native'; import {IconButton, Text, withTheme} from 'react-native-paper'; +import {MaterialCommunityIcons} from "@expo/vector-icons"; import GameLogic from "./GameLogic"; import Grid from "./components/Grid"; +import HeaderButton from "../../components/HeaderButton"; type Props = { navigation: Object, @@ -12,6 +14,7 @@ type Props = { type State = { grid: Array>, + gameRunning: boolean, gameTime: number, gameScore: number } @@ -31,22 +34,49 @@ class TetrisScreen extends React.Component { this.logic = new GameLogic(20, 10, this.colors); this.state = { grid: this.logic.getEmptyGrid(), + gameRunning: false, gameTime: 0, gameScore: 0, }; this.onTick = this.onTick.bind(this); this.onGameEnd = this.onGameEnd.bind(this); this.updateGrid = this.updateGrid.bind(this); - const onScreenBlur = this.onScreenBlur.bind(this); - this.props.navigation.addListener('blur', onScreenBlur); + this.props.navigation.addListener('blur', this.onScreenBlur.bind(this)); + this.props.navigation.addListener('focus', this.onScreenFocus.bind(this)); } + componentDidMount() { + const rightButton = this.getRightButton.bind(this); + this.props.navigation.setOptions({ + headerRight: rightButton, + }); + this.startGame(); + } + + getRightButton() { + return ( + + this.togglePause()}/> + + ); + } /** * Remove any interval on un-focus */ onScreenBlur() { - this.logic.endGame(); + if (!this.logic.isGamePaused()) + this.logic.togglePause(); + } + + onScreenFocus() { + if (!this.logic.isGameRunning()) + this.startGame(); + else if (this.logic.isGamePaused()) + this.showPausePopup(); } onTick(time: number, score: number, newGrid: Array>) { @@ -63,17 +93,63 @@ class TetrisScreen extends React.Component { }); } - startGame() { - if (!this.logic.isGameRunning()) { - this.logic.startGame(this.onTick, this.onGameEnd); - } + togglePause() { + this.logic.togglePause(); + if (this.logic.isGamePaused()) + this.showPausePopup(); } - onGameEnd(time: number, score: number) { + showPausePopup() { + Alert.alert( + 'PAUSE', + 'GAME PAUSED', + [ + {text: 'RESTART', onPress: () => this.showRestartConfirm()}, + {text: 'RESUME', onPress: () => this.togglePause()}, + ], + {cancelable: false}, + ); + } + + showRestartConfirm() { + Alert.alert( + 'RESTART?', + 'WHOA THERE', + [ + {text: 'NO', onPress: () => this.showPausePopup()}, + {text: 'YES', onPress: () => this.startGame()}, + ], + {cancelable: false}, + ); + } + + showGameOverConfirm() { + Alert.alert( + 'GAME OVER', + 'NOOB', + [ + {text: 'LEAVE', onPress: () => this.props.navigation.goBack()}, + {text: 'RESTART', onPress: () => this.startGame()}, + ], + {cancelable: false}, + ); + } + + startGame() { + this.logic.startGame(this.onTick, this.onGameEnd); + this.setState({ + gameRunning: true, + }); + } + + onGameEnd(time: number, score: number, isRestart: boolean) { this.setState({ gameTime: time, gameScore: score, - }) + gameRunning: false, + }); + if (!isRestart) + this.showGameOverConfirm(); } render() { @@ -82,28 +158,49 @@ class TetrisScreen extends React.Component { width: '100%', height: '100%', }}> - - Score: {this.state.gameScore} - - + {this.state.gameTime} + + - time: {this.state.gameTime} - + + {this.state.gameScore} + this.logic.rightPressed(this.updateGrid)} + onPress={() => this.logic.rotatePressed(this.updateGrid)} /> { onPress={() => this.logic.leftPressed(this.updateGrid)} /> this.logic.rotatePressed(this.updateGrid)} + onPress={() => this.logic.rightPressed(this.updateGrid)} /> this.startGame()} - /> + icon="arrow-down" + size={40} + onPress={() => this.logic.rightPressed(this.updateGrid)} + /> ); diff --git a/utils/ThemeManager.js b/utils/ThemeManager.js index eb3f914..977df0d 100644 --- a/utils/ThemeManager.js +++ b/utils/ThemeManager.js @@ -58,6 +58,7 @@ export default class ThemeManager { // Tetris tetrisBackground:'#d1d1d1', tetrisBorder:'#afafaf', + tetrisScore:'#fff307', tetrisI : '#42f1ff', tetrisO : '#ffdd00', tetrisT : '#ba19ff', @@ -109,6 +110,7 @@ export default class ThemeManager { // Tetris tetrisBackground:'#2c2c2c', tetrisBorder:'#1b1b1b', + tetrisScore:'#e2d707', tetrisI : '#30b3be', tetrisO : '#c1a700', tetrisT : '#9114c7', From c9237cc8243566e3650d7744dad26dd9d58baef1 Mon Sep 17 00:00:00 2001 From: Arnaud Vergnet Date: Mon, 16 Mar 2020 19:26:42 +0100 Subject: [PATCH 009/398] Improved score updates --- screens/Tetris/GameLogic.js | 28 ++++++++++++++++++++-------- screens/Tetris/TetrisScreen.js | 11 ++++++++++- 2 files changed, 30 insertions(+), 9 deletions(-) diff --git a/screens/Tetris/GameLogic.js b/screens/Tetris/GameLogic.js index 4863e01..5d526e3 100644 --- a/screens/Tetris/GameLogic.js +++ b/screens/Tetris/GameLogic.js @@ -100,6 +100,7 @@ export default class GameLogic { for (let i = 0; i < lines.length; i++) { this.currentGrid.splice(lines[i], 1); this.currentGrid.unshift(this.getEmptyLine()); + this.score += 100; } } @@ -151,7 +152,9 @@ export default class GameLogic { this.currentObject.move(0, -y); this.freezeTetromino(); this.createTetromino(); - } + } else + return true; + return false; } tryRotateTetromino() { @@ -162,7 +165,6 @@ export default class GameLogic { onTick(callback: Function) { this.gameTime++; - this.score++; this.tryMoveTetromino(0, 1); callback(this.gameTime, this.score, this.getFinalGrid()); } @@ -175,24 +177,34 @@ export default class GameLogic { if (!this.canUseInput()) return; - this.tryMoveTetromino(1, 0); - callback(this.getFinalGrid()); + if (this.tryMoveTetromino(1, 0)) + callback(this.getFinalGrid()); } leftPressed(callback: Function) { if (!this.canUseInput()) return; - this.tryMoveTetromino(-1, 0); - callback(this.getFinalGrid()); + if (this.tryMoveTetromino(-1, 0)) + callback(this.getFinalGrid()); + } + + downPressed(callback: Function) { + if (!this.canUseInput()) + return; + + if (this.tryMoveTetromino(0, 1)){ + this.score++; + callback(this.getFinalGrid(), this.score); + } } rotatePressed(callback: Function) { if (!this.canUseInput()) return; - this.tryRotateTetromino(); - callback(this.getFinalGrid()); + if (this.tryRotateTetromino()) + callback(this.getFinalGrid()); } createTetromino() { diff --git a/screens/Tetris/TetrisScreen.js b/screens/Tetris/TetrisScreen.js index f9675de..c4ac291 100644 --- a/screens/Tetris/TetrisScreen.js +++ b/screens/Tetris/TetrisScreen.js @@ -27,6 +27,7 @@ class TetrisScreen extends React.Component { onTick: Function; onGameEnd: Function; updateGrid: Function; + updateGridScore: Function; constructor(props) { super(props); @@ -41,6 +42,7 @@ class TetrisScreen extends React.Component { this.onTick = this.onTick.bind(this); this.onGameEnd = this.onGameEnd.bind(this); this.updateGrid = this.updateGrid.bind(this); + this.updateGridScore = this.updateGridScore.bind(this); this.props.navigation.addListener('blur', this.onScreenBlur.bind(this)); this.props.navigation.addListener('focus', this.onScreenFocus.bind(this)); } @@ -93,6 +95,13 @@ class TetrisScreen extends React.Component { }); } + updateGridScore(newGrid: Array>, score: number) { + this.setState({ + grid: newGrid, + gameScore: score, + }); + } + togglePause() { this.logic.togglePause(); if (this.logic.isGamePaused()) @@ -215,7 +224,7 @@ class TetrisScreen extends React.Component { this.logic.rightPressed(this.updateGrid)} + onPress={() => this.logic.downPressed(this.updateGridScore)} /> From 3affbfcb4033a613dc00f9303d7da5e1d712b229 Mon Sep 17 00:00:00 2001 From: Arnaud Vergnet Date: Mon, 16 Mar 2020 19:29:57 +0100 Subject: [PATCH 010/398] Improved buttons position --- screens/Tetris/TetrisScreen.js | 29 +++++++++++++++++------------ 1 file changed, 17 insertions(+), 12 deletions(-) diff --git a/screens/Tetris/TetrisScreen.js b/screens/Tetris/TetrisScreen.js index c4ac291..ec9af16 100644 --- a/screens/Tetris/TetrisScreen.js +++ b/screens/Tetris/TetrisScreen.js @@ -203,28 +203,33 @@ class TetrisScreen extends React.Component { /> this.logic.rotatePressed(this.updateGrid)} + style={{marginRight: 'auto'}} /> - this.logic.leftPressed(this.updateGrid)} - /> - this.logic.rightPressed(this.updateGrid)} - /> + + this.logic.leftPressed(this.updateGrid)} + /> + this.logic.rightPressed(this.updateGrid)} + /> + this.logic.downPressed(this.updateGridScore)} + style={{marginLeft: 'auto'}} /> From 7980b8b422997b4324a017cb6573fbe06f460694 Mon Sep 17 00:00:00 2001 From: Arnaud Vergnet Date: Mon, 16 Mar 2020 19:40:52 +0100 Subject: [PATCH 011/398] Made clock use seconds not game ticks --- screens/Tetris/GameLogic.js | 20 ++++++++++++++++---- screens/Tetris/TetrisScreen.js | 13 ++++++++++--- 2 files changed, 26 insertions(+), 7 deletions(-) diff --git a/screens/Tetris/GameLogic.js b/screens/Tetris/GameLogic.js index 5d526e3..d8a6709 100644 --- a/screens/Tetris/GameLogic.js +++ b/screens/Tetris/GameLogic.js @@ -18,8 +18,10 @@ export default class GameLogic { gameTick: number; gameTickInterval: IntervalID; + gameTimeInterval: IntervalID; onTick: Function; + onClock: Function; endCallback: Function; colors: Object; @@ -164,9 +166,13 @@ export default class GameLogic { } onTick(callback: Function) { - this.gameTime++; this.tryMoveTetromino(0, 1); - callback(this.gameTime, this.score, this.getFinalGrid()); + callback(this.score, this.getFinalGrid()); + } + + onClock(callback: Function) { + this.gameTime++; + callback(this.gameTime); } canUseInput() { @@ -220,8 +226,10 @@ export default class GameLogic { this.gamePaused = !this.gamePaused; if (this.gamePaused) { clearInterval(this.gameTickInterval); + clearInterval(this.gameTimeInterval); } else { this.gameTickInterval = setInterval(this.onTick, this.gameTick); + this.gameTimeInterval = setInterval(this.onClock, 1000); } } @@ -229,10 +237,11 @@ export default class GameLogic { this.gameRunning = false; this.gamePaused = false; clearInterval(this.gameTickInterval); + clearInterval(this.gameTimeInterval); this.endCallback(this.gameTime, this.score, isRestart); } - startGame(tickCallback: Function, endCallback: Function) { + startGame(tickCallback: Function, clockCallback: Function, endCallback: Function) { if (this.gameRunning) this.endGame(true); this.gameRunning = true; @@ -241,9 +250,12 @@ export default class GameLogic { this.score = 0; this.currentGrid = this.getEmptyGrid(); this.createTetromino(); - tickCallback(this.gameTime, this.score, this.getFinalGrid()); + tickCallback(this.score, this.getFinalGrid()); + clockCallback(this.gameTime); this.onTick = this.onTick.bind(this, tickCallback); + this.onClock = this.onClock.bind(this, clockCallback); this.gameTickInterval = setInterval(this.onTick, this.gameTick); + this.gameTimeInterval = setInterval(this.onClock, 1000); this.endCallback = endCallback; } diff --git a/screens/Tetris/TetrisScreen.js b/screens/Tetris/TetrisScreen.js index ec9af16..14535bc 100644 --- a/screens/Tetris/TetrisScreen.js +++ b/screens/Tetris/TetrisScreen.js @@ -25,6 +25,7 @@ class TetrisScreen extends React.Component { logic: GameLogic; onTick: Function; + onClock: Function; onGameEnd: Function; updateGrid: Function; updateGridScore: Function; @@ -40,6 +41,7 @@ class TetrisScreen extends React.Component { gameScore: 0, }; this.onTick = this.onTick.bind(this); + this.onClock = this.onClock.bind(this); this.onGameEnd = this.onGameEnd.bind(this); this.updateGrid = this.updateGrid.bind(this); this.updateGridScore = this.updateGridScore.bind(this); @@ -81,14 +83,19 @@ class TetrisScreen extends React.Component { this.showPausePopup(); } - onTick(time: number, score: number, newGrid: Array>) { + onTick(score: number, newGrid: Array>) { this.setState({ - gameTime: time, gameScore: score, grid: newGrid, }); } + onClock(time: number) { + this.setState({ + gameTime: time, + }); + } + updateGrid(newGrid: Array>) { this.setState({ grid: newGrid, @@ -145,7 +152,7 @@ class TetrisScreen extends React.Component { } startGame() { - this.logic.startGame(this.onTick, this.onGameEnd); + this.logic.startGame(this.onTick, this.onClock, this.onGameEnd); this.setState({ gameRunning: true, }); From e5bde81964329cf0c5b2e3a8b5190742f84a256b Mon Sep 17 00:00:00 2001 From: Arnaud Vergnet Date: Mon, 16 Mar 2020 19:48:03 +0100 Subject: [PATCH 012/398] Improved light mode colors and game over message --- screens/Tetris/TetrisScreen.js | 4 +++- utils/ThemeManager.js | 16 ++++++++-------- 2 files changed, 11 insertions(+), 9 deletions(-) diff --git a/screens/Tetris/TetrisScreen.js b/screens/Tetris/TetrisScreen.js index 14535bc..bf3555f 100644 --- a/screens/Tetris/TetrisScreen.js +++ b/screens/Tetris/TetrisScreen.js @@ -140,9 +140,11 @@ class TetrisScreen extends React.Component { } showGameOverConfirm() { + let message = 'SCORE: ' + this.state.gameScore + '\n'; + message += 'TIME: ' + this.state.gameTime + '\n'; Alert.alert( 'GAME OVER', - 'NOOB', + message, [ {text: 'LEAVE', onPress: () => this.props.navigation.goBack()}, {text: 'RESTART', onPress: () => this.startGame()}, diff --git a/utils/ThemeManager.js b/utils/ThemeManager.js index 977df0d..767ff1d 100644 --- a/utils/ThemeManager.js +++ b/utils/ThemeManager.js @@ -56,16 +56,16 @@ export default class ThemeManager { tutorinsaColor: '#f93943', // Tetris - tetrisBackground:'#d1d1d1', - tetrisBorder:'#afafaf', - tetrisScore:'#fff307', - tetrisI : '#42f1ff', + tetrisBackground:'#e6e6e6', + tetrisBorder:'#2f2f2f', + tetrisScore:'#e2bd33', + tetrisI : '#3cd9e6', tetrisO : '#ffdd00', - tetrisT : '#ba19ff', - tetrisS : '#0bff34', + tetrisT : '#a716e5', + tetrisS : '#09c528', tetrisZ : '#ff0009', - tetrisJ : '#134cff', - tetrisL : '#ff8834', + tetrisJ : '#2a67e3', + tetrisL : '#da742d', }, }; } From 07d8fb8d1506ddd9533d9193dd6d9cf6eb6f79df Mon Sep 17 00:00:00 2001 From: Arnaud Vergnet Date: Mon, 16 Mar 2020 20:10:54 +0100 Subject: [PATCH 013/398] Added levels --- screens/Tetris/GameLogic.js | 46 +++++++++++++++++++++++++++++++--- screens/Tetris/TetrisScreen.js | 22 ++++++++++++++-- 2 files changed, 63 insertions(+), 5 deletions(-) diff --git a/screens/Tetris/GameLogic.js b/screens/Tetris/GameLogic.js index d8a6709..6887e12 100644 --- a/screens/Tetris/GameLogic.js +++ b/screens/Tetris/GameLogic.js @@ -4,6 +4,32 @@ import Tetromino from "./Tetromino"; export default class GameLogic { + static levelTicks = { + '1': 1000, + '2': 900, + '3': 800, + '4': 700, + '5': 600, + '6': 500, + '7': 400, + '8': 300, + '9': 200, + '10': 150, + }; + + static levelThresholds = { + '1': 100, + '2': 300, + '3': 500, + '4': 700, + '5': 1000, + '7': 1500, + '8': 2000, + '9': 3000, + '10': 4000, + '11': 5000, + }; + currentGrid: Array>; height: number; @@ -13,6 +39,7 @@ export default class GameLogic { gamePaused: boolean; gameTime: number; score: number; + level: number; currentObject: Tetromino; @@ -31,7 +58,6 @@ export default class GameLogic { this.width = width; this.gameRunning = false; this.gamePaused = false; - this.gameTick = 250; this.colors = colors; } @@ -165,9 +191,21 @@ export default class GameLogic { this.currentObject.rotate(false); } + setNewGameTick(level: number) { + if (level > 10) + return; + this.gameTick = GameLogic.levelTicks[level]; + clearInterval(this.gameTickInterval); + this.gameTickInterval = setInterval(this.onTick, this.gameTick); + } + onTick(callback: Function) { this.tryMoveTetromino(0, 1); - callback(this.score, this.getFinalGrid()); + callback(this.score, this.level, this.getFinalGrid()); + if (this.level <= 10 && this.score > GameLogic.levelThresholds[this.level]) { + this.level++; + this.setNewGameTick(this.level); + } } onClock(callback: Function) { @@ -248,9 +286,11 @@ export default class GameLogic { this.gamePaused = false; this.gameTime = 0; this.score = 0; + this.level = 1; + this.gameTick = GameLogic.levelTicks[this.level]; this.currentGrid = this.getEmptyGrid(); this.createTetromino(); - tickCallback(this.score, this.getFinalGrid()); + tickCallback(this.score, this.level, this.getFinalGrid()); clockCallback(this.gameTime); this.onTick = this.onTick.bind(this, tickCallback); this.onClock = this.onClock.bind(this, clockCallback); diff --git a/screens/Tetris/TetrisScreen.js b/screens/Tetris/TetrisScreen.js index bf3555f..e348a60 100644 --- a/screens/Tetris/TetrisScreen.js +++ b/screens/Tetris/TetrisScreen.js @@ -16,7 +16,8 @@ type State = { grid: Array>, gameRunning: boolean, gameTime: number, - gameScore: number + gameScore: number, + gameLevel: number, } class TetrisScreen extends React.Component { @@ -39,6 +40,7 @@ class TetrisScreen extends React.Component { gameRunning: false, gameTime: 0, gameScore: 0, + gameLevel: 0, }; this.onTick = this.onTick.bind(this); this.onClock = this.onClock.bind(this); @@ -83,9 +85,10 @@ class TetrisScreen extends React.Component { this.showPausePopup(); } - onTick(score: number, newGrid: Array>) { + onTick(score: number, level: number, newGrid: Array>) { this.setState({ gameScore: score, + gameLevel: level, grid: newGrid, }); } @@ -141,6 +144,7 @@ class TetrisScreen extends React.Component { showGameOverConfirm() { let message = 'SCORE: ' + this.state.gameScore + '\n'; + message += 'LEVEL: ' + this.state.gameLevel + '\n'; message += 'TIME: ' + this.state.gameTime + '\n'; Alert.alert( 'GAME OVER', @@ -191,6 +195,20 @@ class TetrisScreen extends React.Component { color: this.colors.subtitle }}>{this.state.gameTime} + + + {this.state.gameLevel} + Date: Mon, 16 Mar 2020 20:23:29 +0100 Subject: [PATCH 014/398] Use pretty date formatting --- screens/Tetris/TetrisScreen.js | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/screens/Tetris/TetrisScreen.js b/screens/Tetris/TetrisScreen.js index e348a60..532869b 100644 --- a/screens/Tetris/TetrisScreen.js +++ b/screens/Tetris/TetrisScreen.js @@ -85,6 +85,22 @@ class TetrisScreen extends React.Component { this.showPausePopup(); } + getFormattedTime(seconds: number) { + let date = new Date(); + date.setHours(0); + date.setMinutes(0); + date.setSeconds(seconds); + let format; + console.log(date); + 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: Array>) { this.setState({ gameScore: score, @@ -145,7 +161,7 @@ class TetrisScreen extends React.Component { showGameOverConfirm() { let message = 'SCORE: ' + this.state.gameScore + '\n'; message += 'LEVEL: ' + this.state.gameLevel + '\n'; - message += 'TIME: ' + this.state.gameTime + '\n'; + message += 'TIME: ' + this.getFormattedTime(this.state.gameTime) + '\n'; Alert.alert( 'GAME OVER', message, @@ -193,7 +209,7 @@ class TetrisScreen extends React.Component { {this.state.gameTime} + }}>{this.getFormattedTime(this.state.gameTime)} Date: Mon, 16 Mar 2020 23:36:01 +0100 Subject: [PATCH 015/398] Improved piece rotation --- screens/Tetris/GameLogic.js | 5 +- screens/Tetris/TetrisScreen.js | 1 - screens/Tetris/Tetromino.js | 197 ++++++++++++++++++++++++++------- 3 files changed, 158 insertions(+), 45 deletions(-) diff --git a/screens/Tetris/GameLogic.js b/screens/Tetris/GameLogic.js index 6887e12..8aed8fb 100644 --- a/screens/Tetris/GameLogic.js +++ b/screens/Tetris/GameLogic.js @@ -187,8 +187,11 @@ export default class GameLogic { tryRotateTetromino() { this.currentObject.rotate(true); - if (!this.isTetrominoPositionValid()) + if (!this.isTetrominoPositionValid()){ this.currentObject.rotate(false); + return false; + } + return true; } setNewGameTick(level: number) { diff --git a/screens/Tetris/TetrisScreen.js b/screens/Tetris/TetrisScreen.js index 532869b..a4937c9 100644 --- a/screens/Tetris/TetrisScreen.js +++ b/screens/Tetris/TetrisScreen.js @@ -91,7 +91,6 @@ class TetrisScreen extends React.Component { date.setMinutes(0); date.setSeconds(seconds); let format; - console.log(date); if (date.getHours()) format = date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds(); else if (date.getMinutes()) diff --git a/screens/Tetris/Tetromino.js b/screens/Tetris/Tetromino.js index 5a48fc1..094d764 100644 --- a/screens/Tetris/Tetromino.js +++ b/screens/Tetris/Tetromino.js @@ -10,35 +10,156 @@ export default class Tetromino { 'L': 6, }; - static shapes = { - 0: [ - [1, 1, 1, 1] + static shapes = [ + [ + [ + [0, 0, 0, 0], + [1, 1, 1, 1], + [0, 0, 0, 0], + [0, 0, 0, 0], + ], + [ + [1, 1], + [1, 1], + ], + [ + [0, 1, 0], + [1, 1, 1], + [0, 0, 0], + ], + [ + [0, 1, 1], + [1, 1, 0], + [0, 0, 0], + ], + [ + [1, 1, 0], + [0, 1, 1], + [0, 0, 0], + ], + [ + [1, 0, 0], + [1, 1, 1], + [0, 0, 0], + ], + [ + [0, 0, 1], + [1, 1, 1], + [0, 0, 0], + ], ], - 1: [ - [1, 1], - [1, 1] + [ + [ + [0, 0, 1, 0], + [0, 0, 1, 0], + [0, 0, 1, 0], + [0, 0, 1, 0], + ], + [ + [1, 1], + [1, 1], + ], + [ + [0, 1, 0], + [0, 1, 1], + [0, 1, 0], + ], + [ + [0, 1, 0], + [0, 1, 1], + [0, 0, 1], + ], + [ + [0, 0, 1], + [0, 1, 1], + [0, 1, 0], + ], + [ + [0, 1, 1], + [0, 1, 0], + [0, 1, 0], + ], + [ + [0, 1, 0], + [0, 1, 0], + [0, 1, 1], + ], ], - 2: [ - [0, 1, 0], - [1, 1, 1], + [ + [ + [0, 0, 0, 0], + [0, 0, 0, 0], + [1, 1, 1, 1], + [0, 0, 0, 0], + ], + [ + [1, 1], + [1, 1], + ], + [ + [0, 0, 0], + [1, 1, 1], + [0, 1, 0], + ], + [ + [0, 0, 0], + [0, 1, 1], + [1, 1, 0], + ], + [ + [0, 0, 0], + [1, 1, 0], + [0, 1, 1], + ], + [ + [0, 0, 0], + [1, 1, 1], + [0, 0, 1], + ], + [ + [0, 0, 0], + [1, 1, 1], + [1, 0, 0], + ], ], - 3: [ - [0, 1, 1], - [1, 1, 0], + [ + [ + [0, 1, 0, 0], + [0, 1, 0, 0], + [0, 1, 0, 0], + [0, 1, 0, 0], + ], + [ + [1, 1], + [1, 1], + ], + [ + [0, 1, 0], + [1, 1, 0], + [0, 1, 0], + ], + [ + [1, 0, 0], + [1, 1, 0], + [0, 1, 0], + ], + [ + [0, 1, 0], + [1, 1, 0], + [1, 0, 0], + ], + [ + [0, 1, 0], + [0, 1, 0], + [1, 1, 0], + ], + [ + [1, 1, 0], + [0, 1, 0], + [0, 1, 0], + ], ], - 4: [ - [1, 1, 0], - [0, 1, 1], - ], - 5: [ - [1, 0, 0], - [1, 1, 1], - ], - 6: [ - [0, 0, 1], - [1, 1, 1], - ], - }; + ]; static colors: Object; @@ -50,8 +171,8 @@ export default class Tetromino { constructor(type: Tetromino.types, colors: Object) { this.currentType = type; - this.currentShape = Tetromino.shapes[type]; this.currentRotation = 0; + this.currentShape = Tetromino.shapes[this.currentRotation][type]; this.position = {x: 0, y: 0}; if (this.currentType === Tetromino.types.O) this.position.x = 4; @@ -85,25 +206,15 @@ export default class Tetromino { } rotate(isForward) { - this.currentRotation++; + if (isForward) + this.currentRotation++; + else + this.currentRotation--; if (this.currentRotation > 3) this.currentRotation = 0; - - if (this.currentRotation === 0) { - this.currentShape = Tetromino.shapes[this.currentType]; - } else { - let result = []; - for(let i = 0; i < this.currentShape[0].length; i++) { - let row = this.currentShape.map(e => e[i]); - - if (isForward) - result.push(row.reverse()); - else - result.push(row); - } - this.currentShape = result; - } - + else if (this.currentRotation < 0) + this.currentRotation = 3; + this.currentShape = Tetromino.shapes[this.currentRotation][this.currentType]; } move(x: number, y: number) { From 7d718141e7d329b42149579a34404b9a34413f57 Mon Sep 17 00:00:00 2001 From: Arnaud Vergnet Date: Tue, 17 Mar 2020 00:24:57 +0100 Subject: [PATCH 016/398] Added touch and hold controls --- screens/Tetris/GameLogic.js | 51 ++++++++++++++++++++++------------ screens/Tetris/TetrisScreen.js | 10 +++++-- 2 files changed, 41 insertions(+), 20 deletions(-) diff --git a/screens/Tetris/GameLogic.js b/screens/Tetris/GameLogic.js index 8aed8fb..e0b00a8 100644 --- a/screens/Tetris/GameLogic.js +++ b/screens/Tetris/GameLogic.js @@ -47,6 +47,12 @@ export default class GameLogic { gameTickInterval: IntervalID; gameTimeInterval: IntervalID; + pressInInterval: TimeoutID; + isPressedIn: boolean; + autoRepeatActivationDelay: number; + autoRepeatDelay: number; + + onTick: Function; onClock: Function; endCallback: Function; @@ -59,6 +65,8 @@ export default class GameLogic { this.gameRunning = false; this.gamePaused = false; this.colors = colors; + this.autoRepeatActivationDelay = 300; + this.autoRepeatDelay = 100; } getHeight(): number { @@ -187,7 +195,7 @@ export default class GameLogic { tryRotateTetromino() { this.currentObject.rotate(true); - if (!this.isTetrominoPositionValid()){ + if (!this.isTetrominoPositionValid()) { this.currentObject.rotate(false); return false; } @@ -221,29 +229,37 @@ export default class GameLogic { } rightPressed(callback: Function) { - if (!this.canUseInput()) - return; - - if (this.tryMoveTetromino(1, 0)) - callback(this.getFinalGrid()); + this.isPressedIn = true; + this.movePressedRepeat(true, callback, 1, 0); } - leftPressed(callback: Function) { - if (!this.canUseInput()) - return; - - if (this.tryMoveTetromino(-1, 0)) - callback(this.getFinalGrid()); + leftPressedIn(callback: Function) { + this.isPressedIn = true; + this.movePressedRepeat(true, callback, -1, 0); } - downPressed(callback: Function) { - if (!this.canUseInput()) + downPressedIn(callback: Function) { + this.isPressedIn = true; + this.movePressedRepeat(true, callback, 0, 1); + } + + movePressedRepeat(isInitial: boolean, callback: Function, x: number, y: number) { + if (!this.canUseInput() || !this.isPressedIn) return; - if (this.tryMoveTetromino(0, 1)){ - this.score++; - callback(this.getFinalGrid(), this.score); + if (this.tryMoveTetromino(x, y)) { + if (y === 1) { + this.score++; + callback(this.getFinalGrid(), this.score); + } else + callback(this.getFinalGrid()); } + this.pressInInterval = setTimeout(() => this.movePressedRepeat(false, callback, x, y), isInitial ? this.autoRepeatActivationDelay : this.autoRepeatDelay); + } + + pressedOut() { + this.isPressedIn = false; + clearTimeout(this.pressInInterval); } rotatePressed(callback: Function) { @@ -255,6 +271,7 @@ export default class GameLogic { } createTetromino() { + this.pressedOut(); let shape = Math.floor(Math.random() * 7); this.currentObject = new Tetromino(shape, this.colors); if (!this.isTetrominoPositionValid()) diff --git a/screens/Tetris/TetrisScreen.js b/screens/Tetris/TetrisScreen.js index a4937c9..ceb3ac6 100644 --- a/screens/Tetris/TetrisScreen.js +++ b/screens/Tetris/TetrisScreen.js @@ -259,18 +259,22 @@ class TetrisScreen extends React.Component { this.logic.leftPressed(this.updateGrid)} + onPress={() => this.logic.pressedOut()} + onPressIn={() => this.logic.leftPressedIn(this.updateGrid)} + /> this.logic.rightPressed(this.updateGrid)} + onPress={() => this.logic.pressedOut()} + onPressIn={() => this.logic.rightPressed(this.updateGrid)} /> this.logic.downPressed(this.updateGridScore)} + onPressIn={() => this.logic.downPressedIn(this.updateGridScore)} + onPress={() => this.logic.pressedOut()} style={{marginLeft: 'auto'}} /> From dbe03a2a2d48aba0a2eff793aa0380dd4b525dd0 Mon Sep 17 00:00:00 2001 From: Arnaud Vergnet Date: Tue, 17 Mar 2020 00:25:44 +0100 Subject: [PATCH 017/398] Fixed level 6 missing --- screens/Tetris/GameLogic.js | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/screens/Tetris/GameLogic.js b/screens/Tetris/GameLogic.js index e0b00a8..a9f6776 100644 --- a/screens/Tetris/GameLogic.js +++ b/screens/Tetris/GameLogic.js @@ -23,11 +23,11 @@ export default class GameLogic { '3': 500, '4': 700, '5': 1000, - '7': 1500, - '8': 2000, - '9': 3000, - '10': 4000, - '11': 5000, + '6': 1500, + '7': 2000, + '8': 3000, + '9': 4000, + '10': 5000, }; currentGrid: Array>; From 879ae46abe042b5d5af0400868039b410be4591e Mon Sep 17 00:00:00 2001 From: Arnaud Vergnet Date: Tue, 17 Mar 2020 11:00:45 +0100 Subject: [PATCH 018/398] Improved score management --- screens/Tetris/GameLogic.js | 70 ++++++++++++++++++++++--------------- 1 file changed, 42 insertions(+), 28 deletions(-) diff --git a/screens/Tetris/GameLogic.js b/screens/Tetris/GameLogic.js index a9f6776..d951d7f 100644 --- a/screens/Tetris/GameLogic.js +++ b/screens/Tetris/GameLogic.js @@ -4,31 +4,18 @@ import Tetromino from "./Tetromino"; export default class GameLogic { - static levelTicks = { - '1': 1000, - '2': 900, - '3': 800, - '4': 700, - '5': 600, - '6': 500, - '7': 400, - '8': 300, - '9': 200, - '10': 150, - }; + static levelTicks = [ + 1000, + 800, + 600, + 400, + 300, + 200, + 150, + 100, + ]; - static levelThresholds = { - '1': 100, - '2': 300, - '3': 500, - '4': 700, - '5': 1000, - '6': 1500, - '7': 2000, - '8': 3000, - '9': 4000, - '10': 5000, - }; + static scoreLinesModifier = [40, 100, 300, 1200]; currentGrid: Array>; @@ -59,6 +46,8 @@ export default class GameLogic { colors: Object; + levelProgression: number; + constructor(height: number, width: number, colors: Object) { this.height = height; this.width = width; @@ -120,6 +109,16 @@ export default class GameLogic { return finalGrid; } + getLinesRemovedPoints(numberRemoved: number) { + if (numberRemoved < 1 || numberRemoved > 4) + return 0; + return GameLogic.scoreLinesModifier[numberRemoved-1] * (this.level + 1); + } + + canLevelUp() { + return this.levelProgression > this.level * 5; + } + freezeTetromino() { let coord = this.currentObject.getCellsCoordinates(); for (let i = 0; i < coord.length; i++) { @@ -136,8 +135,22 @@ export default class GameLogic { for (let i = 0; i < lines.length; i++) { this.currentGrid.splice(lines[i], 1); this.currentGrid.unshift(this.getEmptyLine()); - this.score += 100; } + switch (lines.length) { + case 1: + this.levelProgression += 1; + break; + case 2: + this.levelProgression += 3; + break; + case 3: + this.levelProgression += 5; + break; + case 4: // Did a tetris ! + this.levelProgression += 8; + break; + } + this.score += this.getLinesRemovedPoints(lines.length); } getLinesToClear(coord: Object) { @@ -203,7 +216,7 @@ export default class GameLogic { } setNewGameTick(level: number) { - if (level > 10) + if (level >= GameLogic.levelTicks.length) return; this.gameTick = GameLogic.levelTicks[level]; clearInterval(this.gameTickInterval); @@ -213,7 +226,7 @@ export default class GameLogic { onTick(callback: Function) { this.tryMoveTetromino(0, 1); callback(this.score, this.level, this.getFinalGrid()); - if (this.level <= 10 && this.score > GameLogic.levelThresholds[this.level]) { + if (this.canLevelUp()) { this.level++; this.setNewGameTick(this.level); } @@ -306,7 +319,8 @@ export default class GameLogic { this.gamePaused = false; this.gameTime = 0; this.score = 0; - this.level = 1; + this.level = 0; + this.levelProgression = 0; this.gameTick = GameLogic.levelTicks[this.level]; this.currentGrid = this.getEmptyGrid(); this.createTetromino(); From 7a00452cc0346e17b72fa390b8349530b79bf94a Mon Sep 17 00:00:00 2001 From: Arnaud Vergnet Date: Tue, 17 Mar 2020 11:12:55 +0100 Subject: [PATCH 019/398] Improved level cap --- screens/Tetris/GameLogic.js | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/screens/Tetris/GameLogic.js b/screens/Tetris/GameLogic.js index d951d7f..b94b4e7 100644 --- a/screens/Tetris/GameLogic.js +++ b/screens/Tetris/GameLogic.js @@ -55,7 +55,7 @@ export default class GameLogic { this.gamePaused = false; this.colors = colors; this.autoRepeatActivationDelay = 300; - this.autoRepeatDelay = 100; + this.autoRepeatDelay = 50; } getHeight(): number { @@ -116,7 +116,10 @@ export default class GameLogic { } canLevelUp() { - return this.levelProgression > this.level * 5; + let canLevel = this.levelProgression > this.level * 5; + if (canLevel) + this.levelProgression -= this.level * 5; + return canLevel; } freezeTetromino() { From 7da30e0af6a78677671667e2c4d4055066c7ede8 Mon Sep 17 00:00:00 2001 From: Arnaud Vergnet Date: Tue, 17 Mar 2020 14:22:49 +0100 Subject: [PATCH 020/398] Added previews --- screens/Tetris/GameLogic.js | 63 +++++++++++++++++++++------- screens/Tetris/TetrisScreen.js | 16 ++++++- screens/Tetris/Tetromino.js | 7 +++- screens/Tetris/components/Cell.js | 4 +- screens/Tetris/components/Grid.js | 6 ++- screens/Tetris/components/Preview.js | 51 ++++++++++++++++++++++ 6 files changed, 123 insertions(+), 24 deletions(-) create mode 100644 screens/Tetris/components/Preview.js diff --git a/screens/Tetris/GameLogic.js b/screens/Tetris/GameLogic.js index b94b4e7..7682e29 100644 --- a/screens/Tetris/GameLogic.js +++ b/screens/Tetris/GameLogic.js @@ -39,6 +39,8 @@ export default class GameLogic { autoRepeatActivationDelay: number; autoRepeatDelay: number; + nextPieces: Array; + nextPiecesCount: number; onTick: Function; onClock: Function; @@ -56,6 +58,19 @@ export default class GameLogic { this.colors = colors; this.autoRepeatActivationDelay = 300; this.autoRepeatDelay = 50; + this.nextPieces = []; + this.nextPiecesCount = 3; + } + + getNextPieces() { + let finalArray = []; + for (let i = 0; i < this.nextPieces.length; i++) { + finalArray.push(this.getEmptyGrid(4, 4)); + let coord = this.nextPieces[i].getCellsCoordinates(false); + this.tetrominoToGrid(this.nextPieces[i], coord, finalArray[i]); + } + + return finalArray; } getHeight(): number { @@ -74,9 +89,9 @@ export default class GameLogic { return this.gamePaused; } - getEmptyLine() { + getEmptyLine(width: number) { let line = []; - for (let col = 0; col < this.getWidth(); col++) { + for (let col = 0; col < width; col++) { line.push({ color: this.colors.tetrisBackground, isEmpty: true, @@ -85,10 +100,10 @@ export default class GameLogic { return line; } - getEmptyGrid() { + getEmptyGrid(height: number, width: number) { let grid = []; - for (let row = 0; row < this.getHeight(); row++) { - grid.push(this.getEmptyLine()); + for (let row = 0; row < height; row++) { + grid.push(this.getEmptyLine(width)); } return grid; } @@ -98,7 +113,7 @@ export default class GameLogic { } getFinalGrid() { - let coord = this.currentObject.getCellsCoordinates(); + let coord = this.currentObject.getCellsCoordinates(true); let finalGrid = this.getGridCopy(); for (let i = 0; i < coord.length; i++) { finalGrid[coord[i].y][coord[i].x] = { @@ -122,14 +137,18 @@ export default class GameLogic { return canLevel; } - freezeTetromino() { - let coord = this.currentObject.getCellsCoordinates(); + tetrominoToGrid(object: Object, coord : Array, grid: Array>) { for (let i = 0; i < coord.length; i++) { - this.currentGrid[coord[i].y][coord[i].x] = { - color: this.currentObject.getColor(), + grid[coord[i].y][coord[i].x] = { + color: object.getColor(), isEmpty: false, }; } + } + + freezeTetromino() { + let coord = this.currentObject.getCellsCoordinates(true); + this.tetrominoToGrid(this.currentObject, coord, this.currentGrid); this.clearLines(this.getLinesToClear(coord)); } @@ -137,7 +156,7 @@ export default class GameLogic { lines.sort(); for (let i = 0; i < lines.length; i++) { this.currentGrid.splice(lines[i], 1); - this.currentGrid.unshift(this.getEmptyLine()); + this.currentGrid.unshift(this.getEmptyLine(this.getWidth())); } switch (lines.length) { case 1: @@ -174,7 +193,7 @@ export default class GameLogic { isTetrominoPositionValid() { let isValid = true; - let coord = this.currentObject.getCellsCoordinates(); + let coord = this.currentObject.getCellsCoordinates(true); for (let i = 0; i < coord.length; i++) { if (coord[i].x >= this.getWidth() || coord[i].x < 0 @@ -286,10 +305,21 @@ export default class GameLogic { callback(this.getFinalGrid()); } + recoverNextPiece() { + this.currentObject = this.nextPieces.shift(); + this.generateNextPieces(); + } + + generateNextPieces() { + while (this.nextPieces.length < this.nextPiecesCount) { + let shape = Math.floor(Math.random() * 7); + this.nextPieces.push(new Tetromino(shape, this.colors)); + } + } + createTetromino() { this.pressedOut(); - let shape = Math.floor(Math.random() * 7); - this.currentObject = new Tetromino(shape, this.colors); + this.recoverNextPiece(); if (!this.isTetrominoPositionValid()) this.endGame(false); } @@ -325,7 +355,9 @@ export default class GameLogic { this.level = 0; this.levelProgression = 0; this.gameTick = GameLogic.levelTicks[this.level]; - this.currentGrid = this.getEmptyGrid(); + this.currentGrid = this.getEmptyGrid(this.getHeight(), this.getWidth()); + this.nextPieces = []; + this.generateNextPieces(); this.createTetromino(); tickCallback(this.score, this.level, this.getFinalGrid()); clockCallback(this.gameTime); @@ -335,5 +367,4 @@ export default class GameLogic { this.gameTimeInterval = setInterval(this.onClock, 1000); this.endCallback = endCallback; } - } diff --git a/screens/Tetris/TetrisScreen.js b/screens/Tetris/TetrisScreen.js index ceb3ac6..769fa60 100644 --- a/screens/Tetris/TetrisScreen.js +++ b/screens/Tetris/TetrisScreen.js @@ -7,6 +7,7 @@ import {MaterialCommunityIcons} from "@expo/vector-icons"; import GameLogic from "./GameLogic"; import Grid from "./components/Grid"; import HeaderButton from "../../components/HeaderButton"; +import Preview from "./components/Preview"; type Props = { navigation: Object, @@ -36,7 +37,7 @@ class TetrisScreen extends React.Component { this.colors = props.theme.colors; this.logic = new GameLogic(20, 10, this.colors); this.state = { - grid: this.logic.getEmptyGrid(), + grid: this.logic.getEmptyGrid(this.logic.getHeight(), this.logic.getWidth()), gameRunning: false, gameTime: 0, gameScore: 0, @@ -92,7 +93,7 @@ class TetrisScreen extends React.Component { date.setSeconds(seconds); let format; if (date.getHours()) - format = date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds(); + format = date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds(); else if (date.getMinutes()) format = date.getMinutes() + ':' + date.getSeconds(); else @@ -241,8 +242,19 @@ class TetrisScreen extends React.Component { + + + { >, + backgroundColor: string, height: number, width: number, + containerHeight: number|string, } class Grid extends React.Component{ @@ -31,7 +33,6 @@ class Grid extends React.Component{ return( {cells} @@ -50,10 +51,11 @@ class Grid extends React.Component{ return ( {this.getGrid()} diff --git a/screens/Tetris/components/Preview.js b/screens/Tetris/components/Preview.js new file mode 100644 index 0000000..66ff1bc --- /dev/null +++ b/screens/Tetris/components/Preview.js @@ -0,0 +1,51 @@ +// @flow + +import * as React from 'react'; +import {View} from 'react-native'; +import {withTheme} from 'react-native-paper'; +import Grid from "./Grid"; + +type Props = { + next: Object, +} + +class Preview extends React.PureComponent { + + colors: Object; + + constructor(props) { + super(props); + this.colors = props.theme.colors; + } + + getGrids() { + let grids = []; + for (let i = 0; i < this.props.next.length; i++) { + grids.push( + + ); + } + return grids; + } + + render() { + if (this.props.next.length > 0) { + return ( + + {this.getGrids()} + + ); + } else + return null; + } + + +} + +export default withTheme(Preview); From 3bc45704f620e027243ca4e5486e24911245167b Mon Sep 17 00:00:00 2001 From: Arnaud Vergnet Date: Fri, 20 Mar 2020 21:15:37 +0100 Subject: [PATCH 021/398] Improved ui on larger screens --- screens/Tetris/TetrisScreen.js | 8 ++++++-- screens/Tetris/components/Cell.js | 1 + screens/Tetris/components/Grid.js | 8 +++++--- screens/Tetris/components/Preview.js | 3 ++- 4 files changed, 14 insertions(+), 6 deletions(-) diff --git a/screens/Tetris/TetrisScreen.js b/screens/Tetris/TetrisScreen.js index 769fa60..d3a4ef1 100644 --- a/screens/Tetris/TetrisScreen.js +++ b/screens/Tetris/TetrisScreen.js @@ -199,7 +199,7 @@ class TetrisScreen extends React.Component { { @@ -256,6 +257,8 @@ class TetrisScreen extends React.Component { /> @@ -288,6 +291,7 @@ class TetrisScreen extends React.Component { onPressIn={() => this.logic.downPressedIn(this.updateGridScore)} onPress={() => this.logic.pressedOut()} style={{marginLeft: 'auto'}} + color={this.colors.tetrisScore} /> diff --git a/screens/Tetris/components/Cell.js b/screens/Tetris/components/Cell.js index b088e02..39e1051 100644 --- a/screens/Tetris/components/Cell.js +++ b/screens/Tetris/components/Cell.js @@ -27,6 +27,7 @@ class Cell extends React.PureComponent { backgroundColor: this.props.isEmpty ? 'transparent' : this.props.color, borderColor: this.props.isEmpty ? 'transparent' : this.colors.tetrisBorder, borderStyle: 'solid', + borderRadius: 2, borderWidth: 1, aspectRatio: 1, }} diff --git a/screens/Tetris/components/Grid.js b/screens/Tetris/components/Grid.js index 24ff513..39dd5cb 100644 --- a/screens/Tetris/components/Grid.js +++ b/screens/Tetris/components/Grid.js @@ -11,7 +11,8 @@ type Props = { backgroundColor: string, height: number, width: number, - containerHeight: number|string, + containerMaxHeight: number|string, + containerMaxWidth: number|string, } class Grid extends React.Component{ @@ -33,6 +34,7 @@ class Grid extends React.Component{ return( {cells} @@ -51,11 +53,11 @@ class Grid extends React.Component{ return ( {this.getGrid()} diff --git a/screens/Tetris/components/Preview.js b/screens/Tetris/components/Preview.js index 66ff1bc..a1e7893 100644 --- a/screens/Tetris/components/Preview.js +++ b/screens/Tetris/components/Preview.js @@ -26,7 +26,8 @@ class Preview extends React.PureComponent { width={this.props.next[i][0].length} height={this.props.next[i].length} grid={this.props.next[i]} - containerHeight={50} + containerMaxHeight={50} + containerMaxWidth={50} backgroundColor={'transparent'} /> ); From b0094716bef303c5e02452fbde2ce9846b99b8f3 Mon Sep 17 00:00:00 2001 From: Arnaud Vergnet Date: Fri, 20 Mar 2020 22:31:27 +0100 Subject: [PATCH 022/398] Added basic jest tests --- package.json | 12 ++++++++++-- utils/__test__/PlanningEventManager.test.js | 10 ++++++++++ 2 files changed, 20 insertions(+), 2 deletions(-) create mode 100644 utils/__test__/PlanningEventManager.test.js diff --git a/package.json b/package.json index 7c6672f..e5cfed5 100644 --- a/package.json +++ b/package.json @@ -5,7 +5,13 @@ "android": "expo start --android", "ios": "expo start --ios", "web": "expo start --web", - "eject": "expo eject" + "eject": "expo eject", + "test": "jest", + "testw": "jest --watch", + "testc": "jest --coverage" + }, + "jest": { + "preset": "react-native" }, "dependencies": { "@expo/vector-icons": "~10.0.0", @@ -38,7 +44,9 @@ "expo-linear-gradient": "~8.0.0" }, "devDependencies": { - "babel-preset-expo": "^8.0.0" + "babel-preset-expo": "^8.0.0", + "jest": "^25.1.0", + "react-test-renderer": "^16.13.1" }, "private": true } diff --git a/utils/__test__/PlanningEventManager.test.js b/utils/__test__/PlanningEventManager.test.js new file mode 100644 index 0000000..c4f2706 --- /dev/null +++ b/utils/__test__/PlanningEventManager.test.js @@ -0,0 +1,10 @@ +import React from 'react'; +import PlanningEventManager from "../PlanningEventManager"; + +test('time test', () => { + expect(PlanningEventManager.formatTime("1:2")).toBe("1:2"); +}); + +test('time test 2', () => { + expect(PlanningEventManager.formatTime("1:2")).toBe("2:2"); +}); From 5221b73bf26b2ba3f5c32020f3cdeac5f14bad0d Mon Sep 17 00:00:00 2001 From: Arnaud Vergnet Date: Fri, 20 Mar 2020 22:32:48 +0100 Subject: [PATCH 023/398] Added default run and test configs --- .idea/runConfigurations/All_Tests.xml | 11 +++++++++++ .idea/runConfigurations/Expo.xml | 16 ++++++++++++++++ 2 files changed, 27 insertions(+) create mode 100644 .idea/runConfigurations/All_Tests.xml create mode 100644 .idea/runConfigurations/Expo.xml diff --git a/.idea/runConfigurations/All_Tests.xml b/.idea/runConfigurations/All_Tests.xml new file mode 100644 index 0000000..3cbf681 --- /dev/null +++ b/.idea/runConfigurations/All_Tests.xml @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/runConfigurations/Expo.xml b/.idea/runConfigurations/Expo.xml new file mode 100644 index 0000000..284d1e4 --- /dev/null +++ b/.idea/runConfigurations/Expo.xml @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + \ No newline at end of file From 96c9b57d9248ceec6b06012ee069ad0951bde01a Mon Sep 17 00:00:00 2001 From: Arnaud Vergnet Date: Fri, 20 Mar 2020 22:34:55 +0100 Subject: [PATCH 024/398] Improved .gitignore --- .gitignore | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.gitignore b/.gitignore index d40d999..70940e0 100644 --- a/.gitignore +++ b/.gitignore @@ -8,3 +8,8 @@ npm-debug.* *.orig.* web-build/ web-report/ +/.expo-shared/ +/coverage/ +/.idea/ +/package-lock.json +/passwords.json From a4c38168ad6e229d9438fe90bae0c03f8df8cea1 Mon Sep 17 00:00:00 2001 From: Arnaud Vergnet Date: Fri, 20 Mar 2020 22:50:28 +0100 Subject: [PATCH 025/398] Added first real test --- package.json | 4 +++- utils/PlanningEventManager.js | 12 +++++++----- utils/__test__/PlanningEventManager.test.js | 15 ++++++++++----- 3 files changed, 20 insertions(+), 11 deletions(-) diff --git a/package.json b/package.json index e5cfed5..d3e83da 100644 --- a/package.json +++ b/package.json @@ -11,7 +11,8 @@ "testc": "jest --coverage" }, "jest": { - "preset": "react-native" + "preset": "react-native", + "setupFilesAfterEnv": ["jest-extended"] }, "dependencies": { "@expo/vector-icons": "~10.0.0", @@ -46,6 +47,7 @@ "devDependencies": { "babel-preset-expo": "^8.0.0", "jest": "^25.1.0", + "jest-extended": "^0.11.5", "react-test-renderer": "^16.13.1" }, "private": true diff --git a/utils/PlanningEventManager.js b/utils/PlanningEventManager.js index b9cb140..db67157 100644 --- a/utils/PlanningEventManager.js +++ b/utils/PlanningEventManager.js @@ -74,10 +74,12 @@ export default class PlanningEventManager { } static isDescriptionEmpty (description: string) { - return description - .replace('

', '') - .replace('

', '') - .replace('
', '').trim() === ''; + if (description !== undefined && description !== null) { + return description + .replace('

', '') + .replace('

', '') + .replace('
', '').trim() === ''; + } else + return true; } - } diff --git a/utils/__test__/PlanningEventManager.test.js b/utils/__test__/PlanningEventManager.test.js index c4f2706..8451850 100644 --- a/utils/__test__/PlanningEventManager.test.js +++ b/utils/__test__/PlanningEventManager.test.js @@ -1,10 +1,15 @@ import React from 'react'; import PlanningEventManager from "../PlanningEventManager"; -test('time test', () => { - expect(PlanningEventManager.formatTime("1:2")).toBe("1:2"); +test('isDescriptionEmpty', () => { + expect(PlanningEventManager.isDescriptionEmpty("")).toBeTrue(); + expect(PlanningEventManager.isDescriptionEmpty("

")).toBeTrue(); + expect(PlanningEventManager.isDescriptionEmpty("


")).toBeTrue(); + expect(PlanningEventManager.isDescriptionEmpty("


")).toBeTrue(); + expect(PlanningEventManager.isDescriptionEmpty(null)).toBeTrue(); + expect(PlanningEventManager.isDescriptionEmpty(undefined)).toBeTrue(); + expect(PlanningEventManager.isDescriptionEmpty("coucou")).toBeFalse(); + expect(PlanningEventManager.isDescriptionEmpty("

coucou

")).toBeFalse(); }); -test('time test 2', () => { - expect(PlanningEventManager.formatTime("1:2")).toBe("2:2"); -}); + From df79d78165ccaa207f140c5e8415744c04d35e4f Mon Sep 17 00:00:00 2001 From: Arnaud Vergnet Date: Sat, 21 Mar 2020 11:24:30 +0100 Subject: [PATCH 026/398] Improved test and replace method --- utils/PlanningEventManager.js | 8 ++++---- utils/__test__/PlanningEventManager.test.js | 4 ++++ 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/utils/PlanningEventManager.js b/utils/PlanningEventManager.js index db67157..52d53e2 100644 --- a/utils/PlanningEventManager.js +++ b/utils/PlanningEventManager.js @@ -73,12 +73,12 @@ export default class PlanningEventManager { return formattedStr } - static isDescriptionEmpty (description: string) { + static isDescriptionEmpty (description: ?string) { if (description !== undefined && description !== null) { return description - .replace('

', '') - .replace('

', '') - .replace('
', '').trim() === ''; + .split('

').join('') // Equivalent to a replace all + .split('

').join('') + .split('
').join('').trim() === ''; } else return true; } diff --git a/utils/__test__/PlanningEventManager.test.js b/utils/__test__/PlanningEventManager.test.js index 8451850..6c30d50 100644 --- a/utils/__test__/PlanningEventManager.test.js +++ b/utils/__test__/PlanningEventManager.test.js @@ -3,8 +3,12 @@ import PlanningEventManager from "../PlanningEventManager"; test('isDescriptionEmpty', () => { expect(PlanningEventManager.isDescriptionEmpty("")).toBeTrue(); + expect(PlanningEventManager.isDescriptionEmpty(" ")).toBeTrue(); expect(PlanningEventManager.isDescriptionEmpty("

")).toBeTrue(); + expect(PlanningEventManager.isDescriptionEmpty("

")).toBeTrue(); expect(PlanningEventManager.isDescriptionEmpty("


")).toBeTrue(); + expect(PlanningEventManager.isDescriptionEmpty("



")).toBeTrue(); + expect(PlanningEventManager.isDescriptionEmpty("




")).toBeTrue(); expect(PlanningEventManager.isDescriptionEmpty("


")).toBeTrue(); expect(PlanningEventManager.isDescriptionEmpty(null)).toBeTrue(); expect(PlanningEventManager.isDescriptionEmpty(undefined)).toBeTrue(); From 0b84da8b930d4c77d8909d718c92da4689fc0033 Mon Sep 17 00:00:00 2001 From: Arnaud Vergnet Date: Sat, 21 Mar 2020 17:23:59 +0100 Subject: [PATCH 027/398] Added more tests --- components/PreviewEventDashboardItem.js | 4 +- screens/HomeScreen.js | 28 ++--- utils/PlanningEventManager.js | 112 ++++++++++++++++---- utils/__test__/PlanningEventManager.test.js | 64 +++++++++++ 4 files changed, 162 insertions(+), 46 deletions(-) diff --git a/components/PreviewEventDashboardItem.js b/components/PreviewEventDashboardItem.js index 37b0845..237d72d 100644 --- a/components/PreviewEventDashboardItem.js +++ b/components/PreviewEventDashboardItem.js @@ -26,12 +26,12 @@ function PreviewEventDashboardItem(props) { {hasImage ? : } {!isEmpty ? { return this.getDashboardMiddleItem(content); } - /** - * Convert the date string given by in the event list json to a date object - * @param dateString - * @return {Date} - */ - stringToDate(dateString: ?string): ?Date { - let date = new Date(); - if (dateString === undefined || dateString === null) - date = undefined; - else if (dateString.split(' ').length > 1) { - let timeStr = dateString.split(' ')[1]; - date.setHours(parseInt(timeStr.split(':')[0]), parseInt(timeStr.split(':')[1]), 0); - } else - date = undefined; - return date; - } - /** * Get the time limit depending on the current day: * 17:30 for every day of the week except for thursday 11:30 @@ -191,8 +175,8 @@ class HomeScreen extends React.Component { * @return {number} The number of milliseconds */ getEventDuration(event: Object): number { - let start = this.stringToDate(event['date_begin']); - let end = this.stringToDate(event['date_end']); + let start = PlanningEventManager.stringToDate(event['date_begin']); + let end = PlanningEventManager.stringToDate(event['date_end']); let duration = 0; if (start !== undefined && start !== null && end !== undefined && end !== null) duration = end - start; @@ -209,7 +193,7 @@ class HomeScreen extends React.Component { getEventsAfterLimit(events: Object, limit: Date): Array { let validEvents = []; for (let event of events) { - let startDate = this.stringToDate(event['date_begin']); + let startDate = PlanningEventManager.stringToDate(event['date_begin']); if (startDate !== undefined && startDate !== null && startDate >= limit) { validEvents.push(event); } @@ -244,8 +228,8 @@ class HomeScreen extends React.Component { let validEvents = []; let now = new Date(); for (let event of events) { - let startDate = this.stringToDate(event['date_begin']); - let endDate = this.stringToDate(event['date_end']); + let startDate = PlanningEventManager.stringToDate(event['date_begin']); + let endDate = PlanningEventManager.stringToDate(event['date_end']); if (startDate !== undefined && startDate !== null) { if (startDate > now) validEvents.push(event); diff --git a/utils/PlanningEventManager.js b/utils/PlanningEventManager.js index 52d53e2..ffcdcb7 100644 --- a/utils/PlanningEventManager.js +++ b/utils/PlanningEventManager.js @@ -1,5 +1,8 @@ - export default class PlanningEventManager { + + // Regex used to check date string validity + static dateRegExp = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/; + static isEventBefore(event1: Object, event2: Object) { let date1 = new Date(); let date2 = new Date(); @@ -41,39 +44,104 @@ export default class PlanningEventManager { } /** - * Convert the date string given by in the event list json to a date object - * @param dateString - * @return {Date} + * Checks if the given date string is in the format + * YYYY-MM-DD HH:MM:SS + * + * @param dateString The string to check + * @return {boolean} */ - static stringToDate(dateString: ?string): ?Date { + static isDateStringFormatValid(dateString: ?string) { + return dateString !== undefined + && dateString !== null + && PlanningEventManager.dateRegExp.test(dateString); + } + + /** + * Converts the given date string to a date object.
+ * Accepted format: YYYY-MM-DD HH:MM:SS + * + * @param dateString The string to convert + * @return {Date} The date object or undefined if the given string is invalid + */ + static stringToDate(dateString: ?string): Date | undefined { let date = new Date(); - if (dateString === undefined || dateString === null) - date = undefined; - else if (dateString.split(' ').length > 1) { - let timeStr = dateString.split(' ')[1]; - date.setHours(parseInt(timeStr.split(':')[0]), parseInt(timeStr.split(':')[1]), 0); + if (PlanningEventManager.isDateStringFormatValid(dateString)) { + let stringArray = dateString.split(' '); + let dateArray = stringArray[0].split('-'); + let timeArray = stringArray[1].split(':'); + date.setFullYear( + parseInt(dateArray[0]), + parseInt(dateArray[1]) - 1, // Month range from 0 to 11 + parseInt(dateArray[2]) + ); + date.setHours( + parseInt(timeArray[0]), + parseInt(timeArray[1]), + parseInt(timeArray[2]), + 0, + ); } else date = undefined; + return date; } - static padStr(i: number) { - return (i < 10) ? "0" + i : "" + i; + /** + * Returns a padded string for the given number if it is lower than 10 + * + * @param i The string to be converted + * @return {string} + */ + static toPaddedString(i: number): string { + return (i < 10 && i >= 0) ? "0" + i.toString(10) : i.toString(10); } - static getFormattedEventTime(event: Object): string { - let formattedStr = ''; - let startDate = PlanningEventManager.stringToDate(event['date_begin']); - let endDate = PlanningEventManager.stringToDate(event['date_end']); - if (startDate !== undefined && startDate !== null && endDate !== undefined && endDate !== null) - formattedStr = PlanningEventManager.padStr(startDate.getHours()) + ':' + PlanningEventManager.padStr(startDate.getMinutes()) + - ' - ' + PlanningEventManager.padStr(endDate.getHours()) + ':' + PlanningEventManager.padStr(endDate.getMinutes()); - else if (startDate !== undefined && startDate !== null) - formattedStr = PlanningEventManager.padStr(startDate.getHours()) + ':' + PlanningEventManager.padStr(startDate.getMinutes()); + /** + * Returns a string corresponding to the event start and end times in the following format: + * + * HH:MM - HH:MM + * + * If the end date is not specified or is equal to start time, only start time will be shown. + * + * If the end date is not on the same day, 00:00 will be shown as end time + * + * @param start Start time in YYYY-MM-DD HH:MM:SS format + * @param end End time in YYYY-MM-DD HH:MM:SS format + * @return {string} Formatted string or "/ - /" on error + */ + static getFormattedEventTime(start: ?string, end: ?string): string { + let formattedStr = '/ - /'; + let startDate = PlanningEventManager.stringToDate(start); + let endDate = PlanningEventManager.stringToDate(end); + + if (startDate !== undefined && endDate !== undefined && startDate.getTime() !== endDate.getTime()) { + formattedStr = PlanningEventManager.toPaddedString(startDate.getHours()) + ':' + + PlanningEventManager.toPaddedString(startDate.getMinutes()) + ' - '; + if (endDate.getFullYear() > startDate.getFullYear() + || endDate.getMonth() > startDate.getMonth() + || endDate.getDate() > startDate.getDate()) + formattedStr += '00:00'; + else + formattedStr += PlanningEventManager.toPaddedString(endDate.getHours()) + ':' + + PlanningEventManager.toPaddedString(endDate.getMinutes()); + } else if (startDate !== undefined) + formattedStr = + PlanningEventManager.toPaddedString(startDate.getHours()) + ':' + + PlanningEventManager.toPaddedString(startDate.getMinutes()); + return formattedStr } - static isDescriptionEmpty (description: ?string) { + /** + * Checks if the given description can be considered empty. + *
+ * An empty description is composed only of whitespace, br or p tags + * + * + * @param description The text to check + * @return {boolean} + */ + static isDescriptionEmpty(description: ?string): boolean { if (description !== undefined && description !== null) { return description .split('

').join('') // Equivalent to a replace all diff --git a/utils/__test__/PlanningEventManager.test.js b/utils/__test__/PlanningEventManager.test.js index 6c30d50..62cb6f2 100644 --- a/utils/__test__/PlanningEventManager.test.js +++ b/utils/__test__/PlanningEventManager.test.js @@ -16,4 +16,68 @@ test('isDescriptionEmpty', () => { expect(PlanningEventManager.isDescriptionEmpty("

coucou

")).toBeFalse(); }); +test('toPaddedString', () => { + expect(PlanningEventManager.toPaddedString(-1)).toBe("-1"); + expect(PlanningEventManager.toPaddedString(0)).toBe("00"); + expect(PlanningEventManager.toPaddedString(1)).toBe("01"); + expect(PlanningEventManager.toPaddedString(2)).toBe("02"); + expect(PlanningEventManager.toPaddedString(10)).toBe("10"); + expect(PlanningEventManager.toPaddedString(53)).toBe("53"); + expect(PlanningEventManager.toPaddedString(100)).toBe("100"); +}); + +test('isDateStringFormatValid', () => { + expect(PlanningEventManager.isDateStringFormatValid("2020-03-21 09:00:00")).toBeTrue(); + expect(PlanningEventManager.isDateStringFormatValid("3214-64-12 01:16:65")).toBeTrue(); + + expect(PlanningEventManager.isDateStringFormatValid("3214-64-12 1:16:65")).toBeFalse(); + expect(PlanningEventManager.isDateStringFormatValid("3214-f4-12 01:16:65")).toBeFalse(); + expect(PlanningEventManager.isDateStringFormatValid("sqdd 09:00:00")).toBeFalse(); + expect(PlanningEventManager.isDateStringFormatValid("2020-03-21")).toBeFalse(); + expect(PlanningEventManager.isDateStringFormatValid("2020-03-21 truc")).toBeFalse(); + expect(PlanningEventManager.isDateStringFormatValid("3214-64-12 1:16:65")).toBeFalse(); + expect(PlanningEventManager.isDateStringFormatValid("garbage")).toBeFalse(); + expect(PlanningEventManager.isDateStringFormatValid("")).toBeFalse(); + expect(PlanningEventManager.isDateStringFormatValid(undefined)).toBeFalse(); + expect(PlanningEventManager.isDateStringFormatValid(null)).toBeFalse(); +}); + +test('stringToDate', () => { + let testDate = new Date(); + expect(PlanningEventManager.stringToDate(undefined)).toBeUndefined(); + expect(PlanningEventManager.stringToDate("")).toBeUndefined(); + expect(PlanningEventManager.stringToDate("garbage")).toBeUndefined(); + expect(PlanningEventManager.stringToDate("2020-03-21")).toBeUndefined(); + expect(PlanningEventManager.stringToDate("09:00:00")).toBeUndefined(); + expect(PlanningEventManager.stringToDate("2020-03-21 09:g0:00")).toBeUndefined(); + expect(PlanningEventManager.stringToDate("2020-03-21 09:g0:")).toBeUndefined(); + testDate.setFullYear(2020, 2, 21); + testDate.setHours(9, 0, 0, 0); + expect(PlanningEventManager.stringToDate("2020-03-21 09:00:00")).toEqual(testDate); + testDate.setFullYear(2020, 0, 31); + testDate.setHours(18, 30, 50, 0); + expect(PlanningEventManager.stringToDate("2020-01-31 18:30:50")).toEqual(testDate); + testDate.setFullYear(2020, 50, 50); + testDate.setHours(65, 65, 65, 0); + expect(PlanningEventManager.stringToDate("2020-51-50 65:65:65")).toEqual(testDate); +}); + +test('getFormattedEventTime', () => { + expect(PlanningEventManager.getFormattedEventTime(null, null)) + .toBe('/ - /'); + expect(PlanningEventManager.getFormattedEventTime(undefined, undefined)) + .toBe('/ - /'); + expect(PlanningEventManager.getFormattedEventTime("20:30:00", "23:00:00")) + .toBe('/ - /'); + expect(PlanningEventManager.getFormattedEventTime("2020-03-30", "2020-03-31")) + .toBe('/ - /'); + + + expect(PlanningEventManager.getFormattedEventTime("2020-03-21 09:00:00", "2020-03-21 09:00:00")) + .toBe('09:00'); + expect(PlanningEventManager.getFormattedEventTime("2020-03-21 09:00:00", "2020-03-22 17:00:00")) + .toBe('09:00 - 00:00'); + expect(PlanningEventManager.getFormattedEventTime("2020-03-30 20:30:00", "2020-03-30 23:00:00")) + .toBe('20:30 - 23:00'); +}); From 3a301bcbef96dc86fb5815b8d3842f8c0d2ef3be Mon Sep 17 00:00:00 2001 From: Arnaud Vergnet Date: Sat, 21 Mar 2020 18:46:12 +0100 Subject: [PATCH 028/398] Added more tests and removed useless functions --- screens/Planning/PlanningDisplayScreen.js | 7 ++- screens/Planning/PlanningScreen.js | 18 +++---- screens/SelfMenuScreen.js | 35 +----------- utils/DateManager.js | 50 +++++++++++++++++ utils/PlanningEventManager.js | 60 +++++++++------------ utils/__test__/PlanningEventManager.test.js | 43 +++++++++++++++ 6 files changed, 134 insertions(+), 79 deletions(-) create mode 100644 utils/DateManager.js diff --git a/screens/Planning/PlanningDisplayScreen.js b/screens/Planning/PlanningDisplayScreen.js index bbb4a2b..220aa19 100644 --- a/screens/Planning/PlanningDisplayScreen.js +++ b/screens/Planning/PlanningDisplayScreen.js @@ -2,11 +2,11 @@ import * as React from 'react'; import {Image, ScrollView, View} from 'react-native'; -import ThemeManager from "../../utils/ThemeManager"; import HTML from "react-native-render-html"; import {Linking} from "expo"; import PlanningEventManager from '../../utils/PlanningEventManager'; import {Card, withTheme} from 'react-native-paper'; +import DateManager from "../../utils/DateManager"; type Props = { navigation: Object, @@ -37,7 +37,10 @@ class PlanningDisplayScreen extends React.Component { {this.displayData.logo !== null ? diff --git a/screens/Planning/PlanningScreen.js b/screens/Planning/PlanningScreen.js index 829862b..633b8f1 100644 --- a/screens/Planning/PlanningScreen.js +++ b/screens/Planning/PlanningScreen.js @@ -37,7 +37,7 @@ const AGENDA_MONTH_SPAN = 3; */ export default class PlanningScreen extends React.Component { - agendaRef: Agenda; + agendaRef: Object; webDataManager: WebDataManager; lastRefresh: Date; @@ -122,7 +122,7 @@ export default class PlanningScreen extends React.Component { generateEmptyCalendar() { let end = new Date(new Date().setMonth(new Date().getMonth() + AGENDA_MONTH_SPAN + 1)); let daysOfYear = {}; - for (let d = new Date(2019, 8, 1); d <= end; d.setDate(d.getDate() + 1)) { + for (let d = new Date(); d <= end; d.setDate(d.getDate() + 1)) { daysOfYear[this.getFormattedDate(new Date(d))] = [] } return daysOfYear; @@ -136,8 +136,8 @@ export default class PlanningScreen extends React.Component { } @@ -151,7 +151,7 @@ export default class PlanningScreen extends React.Component { @@ -205,8 +205,8 @@ export default class PlanningScreen extends React.Component { generateEventAgenda(eventList: Array) { let agendaItems = this.generateEmptyCalendar(); for (let i = 0; i < eventList.length; i++) { - if (agendaItems[PlanningEventManager.getEventStartDate(eventList[i])] !== undefined) { - this.pushEventInOrder(agendaItems, eventList[i], PlanningEventManager.getEventStartDate(eventList[i])); + if (PlanningEventManager.getDateOnlyString(eventList[i]["date_begin"]) !== undefined) { + this.pushEventInOrder(agendaItems, eventList[i], PlanningEventManager.getDateOnlyString(eventList[i]["date_begin"])); } } this.setState({agendaItems: agendaItems}) @@ -217,7 +217,7 @@ export default class PlanningScreen extends React.Component { agendaItems[startDate].push(event); else { for (let i = 0; i < agendaItems[startDate].length; i++) { - if (PlanningEventManager.isEventBefore(event, agendaItems[startDate][i])) { + if (PlanningEventManager.isEventBefore(event["date_begin"], agendaItems[startDate][i]["date_begin"])) { agendaItems[startDate].splice(i, 0, event); break; } else if (i === agendaItems[startDate].length - 1) { @@ -228,7 +228,7 @@ export default class PlanningScreen extends React.Component { } } - onAgendaRef(ref: Agenda) { + onAgendaRef(ref: Object) { this.agendaRef = ref; } diff --git a/screens/SelfMenuScreen.js b/screens/SelfMenuScreen.js index 45369cf..8bad076 100644 --- a/screens/SelfMenuScreen.js +++ b/screens/SelfMenuScreen.js @@ -2,7 +2,7 @@ import * as React from 'react'; import {View} from 'react-native'; -import i18n from "i18n-js"; +import DateManager from "../utils/DateManager"; import WebSectionList from "../components/WebSectionList"; import {Card, Text, withTheme} from 'react-native-paper'; import AprilFoolsManager from "../utils/AprilFoolsManager"; @@ -19,10 +19,6 @@ type Props = { */ class SelfMenuScreen extends React.Component { - // Hard code strings as toLocaleDateString does not work on current android JS engine - daysOfWeek = []; - monthsOfYear = []; - getRenderItem: Function; getRenderSectionHeader: Function; createDataset: Function; @@ -30,26 +26,6 @@ class SelfMenuScreen extends React.Component { constructor(props) { super(props); - this.daysOfWeek.push(i18n.t("date.daysOfWeek.monday")); - this.daysOfWeek.push(i18n.t("date.daysOfWeek.tuesday")); - this.daysOfWeek.push(i18n.t("date.daysOfWeek.wednesday")); - this.daysOfWeek.push(i18n.t("date.daysOfWeek.thursday")); - this.daysOfWeek.push(i18n.t("date.daysOfWeek.friday")); - this.daysOfWeek.push(i18n.t("date.daysOfWeek.saturday")); - this.daysOfWeek.push(i18n.t("date.daysOfWeek.sunday")); - - this.monthsOfYear.push(i18n.t("date.monthsOfYear.january")); - this.monthsOfYear.push(i18n.t("date.monthsOfYear.february")); - this.monthsOfYear.push(i18n.t("date.monthsOfYear.march")); - this.monthsOfYear.push(i18n.t("date.monthsOfYear.april")); - this.monthsOfYear.push(i18n.t("date.monthsOfYear.may")); - this.monthsOfYear.push(i18n.t("date.monthsOfYear.june")); - this.monthsOfYear.push(i18n.t("date.monthsOfYear.july")); - this.monthsOfYear.push(i18n.t("date.monthsOfYear.august")); - this.monthsOfYear.push(i18n.t("date.monthsOfYear.september")); - this.monthsOfYear.push(i18n.t("date.monthsOfYear.october")); - this.monthsOfYear.push(i18n.t("date.monthsOfYear.november")); - this.monthsOfYear.push(i18n.t("date.monthsOfYear.december")); this.getRenderItem = this.getRenderItem.bind(this); this.getRenderSectionHeader = this.getRenderSectionHeader.bind(this); @@ -80,7 +56,7 @@ class SelfMenuScreen extends React.Component { for (let i = 0; i < fetchedData.length; i++) { result.push( { - title: this.getFormattedDate(fetchedData[i].date), + title: DateManager.getInstance().getTranslatedDate(fetchedData[i].date), data: fetchedData[i].meal[0].foodcategory, extraData: super.state, keyExtractor: this.getKeyExtractor, @@ -90,13 +66,6 @@ class SelfMenuScreen extends React.Component { return result } - getFormattedDate(dateString: string) { - let dateArray = dateString.split('-'); - let date = new Date(); - date.setFullYear(parseInt(dateArray[0]), parseInt(dateArray[1]) - 1, parseInt(dateArray[2])); - return this.daysOfWeek[date.getDay() - 1] + " " + date.getDate() + " " + this.monthsOfYear[date.getMonth()] + " " + date.getFullYear(); - } - getRenderSectionHeader({section}: Object) { return ( 0 && event.date_begin !== null) - return PlanningEventManager.formatTime(event.date_begin.split(" ")[1]); + /** + * Checks if the given date is before the other. + * + * @param event1Date Event 1 date in format YYYY-MM-DD HH:MM:SS + * @param event2Date Event 2 date in format YYYY-MM-DD HH:MM:SS + * @return {boolean} + */ + static isEventBefore(event1Date: ?string, event2Date: ?string) { + let date1 = PlanningEventManager.stringToDate(event1Date); + let date2 = PlanningEventManager.stringToDate(event2Date); + if (date1 !== undefined && date2 !== undefined) + return date1 < date2; else - return ""; + return false; } - static getEventEndTime(event: Object) { - if (event !== undefined && Object.keys(event).length > 0 && event.date_end !== null) - return PlanningEventManager.formatTime(event.date_end.split(" ")[1]); + /** + * Gets only the date part of the given event date string in the format + * YYYY-MM-DD HH:MM:SS + * + * @param dateString The string to get the date from + * @return {string|undefined} Date in format YYYY:MM:DD or undefined if given string is invalid + */ + static getDateOnlyString(dateString: ?string) { + if (PlanningEventManager.isDateStringFormatValid(dateString)) + return dateString.split(" ")[0]; else - return ""; - } - - static getFormattedTime(event: Object) { - if (PlanningEventManager.getEventEndTime(event) !== "") - return PlanningEventManager.getEventStartTime(event) + " - " + PlanningEventManager.getEventEndTime(event); - else - return PlanningEventManager.getEventStartTime(event); - } - - static formatTime(time: string) { - let array = time.split(':'); - return array[0] + ':' + array[1]; + return undefined; } /** @@ -61,7 +51,7 @@ export default class PlanningEventManager { * Accepted format: YYYY-MM-DD HH:MM:SS * * @param dateString The string to convert - * @return {Date} The date object or undefined if the given string is invalid + * @return {Date|undefined} The date object or undefined if the given string is invalid */ static stringToDate(dateString: ?string): Date | undefined { let date = new Date(); diff --git a/utils/__test__/PlanningEventManager.test.js b/utils/__test__/PlanningEventManager.test.js index 62cb6f2..4297e39 100644 --- a/utils/__test__/PlanningEventManager.test.js +++ b/utils/__test__/PlanningEventManager.test.js @@ -4,6 +4,7 @@ import PlanningEventManager from "../PlanningEventManager"; test('isDescriptionEmpty', () => { expect(PlanningEventManager.isDescriptionEmpty("")).toBeTrue(); expect(PlanningEventManager.isDescriptionEmpty(" ")).toBeTrue(); + // noinspection CheckTagEmptyBody expect(PlanningEventManager.isDescriptionEmpty("

")).toBeTrue(); expect(PlanningEventManager.isDescriptionEmpty("

")).toBeTrue(); expect(PlanningEventManager.isDescriptionEmpty("


")).toBeTrue(); @@ -81,3 +82,45 @@ test('getFormattedEventTime', () => { .toBe('20:30 - 23:00'); }); +test('getDateOnlyString', () => { + expect(PlanningEventManager.getDateOnlyString("2020-03-21 09:00:00")).toBe("2020-03-21"); + expect(PlanningEventManager.getDateOnlyString("2021-12-15 09:00:00")).toBe("2021-12-15"); + expect(PlanningEventManager.getDateOnlyString("2021-12-o5 09:00:00")).toBeUndefined(); + expect(PlanningEventManager.getDateOnlyString("2021-12-15 09:")).toBeUndefined(); + expect(PlanningEventManager.getDateOnlyString("2021-12-15")).toBeUndefined(); + expect(PlanningEventManager.getDateOnlyString("garbage")).toBeUndefined(); +}); + +test('isEventBefore', () => { + expect(PlanningEventManager.isEventBefore( + "2020-03-21 09:00:00", "2020-03-21 10:00:00")).toBeTrue(); + expect(PlanningEventManager.isEventBefore( + "2020-03-21 10:00:00", "2020-03-21 10:15:00")).toBeTrue(); + expect(PlanningEventManager.isEventBefore( + "2020-03-21 10:15:05", "2020-03-21 10:15:54")).toBeTrue(); + expect(PlanningEventManager.isEventBefore( + "2020-03-21 10:15:05", "2021-03-21 10:15:05")).toBeTrue(); + expect(PlanningEventManager.isEventBefore( + "2020-03-21 10:15:05", "2020-05-21 10:15:05")).toBeTrue(); + expect(PlanningEventManager.isEventBefore( + "2020-03-21 10:15:05", "2020-03-30 10:15:05")).toBeTrue(); + + expect(PlanningEventManager.isEventBefore( + "2020-03-21 10:00:00", "2020-03-21 09:00:00")).toBeFalse(); + expect(PlanningEventManager.isEventBefore( + "2020-03-21 10:15:00", "2020-03-21 10:00:00")).toBeFalse(); + expect(PlanningEventManager.isEventBefore( + "2020-03-21 10:15:54", "2020-03-21 10:15:05")).toBeFalse(); + expect(PlanningEventManager.isEventBefore( + "2021-03-21 10:15:05", "2020-03-21 10:15:05")).toBeFalse(); + expect(PlanningEventManager.isEventBefore( + "2020-05-21 10:15:05", "2020-03-21 10:15:05")).toBeFalse(); + expect(PlanningEventManager.isEventBefore( + "2020-03-30 10:15:05", "2020-03-21 10:15:05")).toBeFalse(); + + expect(PlanningEventManager.isEventBefore( + "garbage", "2020-03-21 10:15:05")).toBeFalse(); + expect(PlanningEventManager.isEventBefore( + undefined, undefined)).toBeFalse(); +}); + From 7a3d5f16b1a19299a08ee4fb59b92eda920d4da8 Mon Sep 17 00:00:00 2001 From: Arnaud Vergnet Date: Sat, 21 Mar 2020 18:59:42 +0100 Subject: [PATCH 029/398] Moved functions to manager and wrote tests --- screens/Planning/PlanningScreen.js | 14 ++------ utils/PlanningEventManager.js | 31 ++++++++++++++++-- utils/__test__/PlanningEventManager.test.js | 36 +++++++++++++-------- 3 files changed, 53 insertions(+), 28 deletions(-) diff --git a/screens/Planning/PlanningScreen.js b/screens/Planning/PlanningScreen.js index 633b8f1..f2917cd 100644 --- a/screens/Planning/PlanningScreen.js +++ b/screens/Planning/PlanningScreen.js @@ -59,7 +59,7 @@ export default class PlanningScreen extends React.Component { onAgendaRef: Function; onCalendarToggled: Function; onBackButtonPressAndroid: Function; - currentDate = this.getCurrentDate(); + currentDate = PlanningEventManager.getCurrentDateString(); constructor(props: any) { super(props); @@ -107,23 +107,13 @@ export default class PlanningScreen extends React.Component { } }; - getCurrentDate() { - let today = new Date(); - return this.getFormattedDate(today); - } - getFormattedDate(date: Date) { - let dd = String(date.getDate()).padStart(2, '0'); - let mm = String(date.getMonth() + 1).padStart(2, '0'); //January is 0! - let yyyy = date.getFullYear(); - return yyyy + '-' + mm + '-' + dd; - } generateEmptyCalendar() { let end = new Date(new Date().setMonth(new Date().getMonth() + AGENDA_MONTH_SPAN + 1)); let daysOfYear = {}; for (let d = new Date(); d <= end; d.setDate(d.getDate() + 1)) { - daysOfYear[this.getFormattedDate(new Date(d))] = [] + daysOfYear[PlanningEventManager.dateToString(new Date(d))] = [] } return daysOfYear; } diff --git a/utils/PlanningEventManager.js b/utils/PlanningEventManager.js index b10501f..ce5381f 100644 --- a/utils/PlanningEventManager.js +++ b/utils/PlanningEventManager.js @@ -3,6 +3,17 @@ export default class PlanningEventManager { // Regex used to check date string validity static dateRegExp = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/; + /** + * Gets the current day string representation in the format + * YYYY-MM-DD + * + * @return {string} The string representation + */ + static getCurrentDateString() { + return PlanningEventManager.dateToString(new Date()); + } + + /** * Checks if the given date is before the other. * @@ -27,7 +38,7 @@ export default class PlanningEventManager { * @return {string|undefined} Date in format YYYY:MM:DD or undefined if given string is invalid */ static getDateOnlyString(dateString: ?string) { - if (PlanningEventManager.isDateStringFormatValid(dateString)) + if (PlanningEventManager.isEventDateStringFormatValid(dateString)) return dateString.split(" ")[0]; else return undefined; @@ -40,7 +51,7 @@ export default class PlanningEventManager { * @param dateString The string to check * @return {boolean} */ - static isDateStringFormatValid(dateString: ?string) { + static isEventDateStringFormatValid(dateString: ?string) { return dateString !== undefined && dateString !== null && PlanningEventManager.dateRegExp.test(dateString); @@ -55,7 +66,7 @@ export default class PlanningEventManager { */ static stringToDate(dateString: ?string): Date | undefined { let date = new Date(); - if (PlanningEventManager.isDateStringFormatValid(dateString)) { + if (PlanningEventManager.isEventDateStringFormatValid(dateString)) { let stringArray = dateString.split(' '); let dateArray = stringArray[0].split('-'); let timeArray = stringArray[1].split(':'); @@ -76,6 +87,20 @@ export default class PlanningEventManager { return date; } + /** + * Converts a date object to a string in the format + * YYYY-MM-DD + * + * @param date The date object to convert + * @return {string} The converted string + */ + static dateToString(date: Date) { + let dd = String(date.getDate()).padStart(2, '0'); + let mm = String(date.getMonth() + 1).padStart(2, '0'); //January is 0! + let yyyy = date.getFullYear(); + return yyyy + '-' + mm + '-' + dd; + } + /** * Returns a padded string for the given number if it is lower than 10 * diff --git a/utils/__test__/PlanningEventManager.test.js b/utils/__test__/PlanningEventManager.test.js index 4297e39..868bf3d 100644 --- a/utils/__test__/PlanningEventManager.test.js +++ b/utils/__test__/PlanningEventManager.test.js @@ -27,20 +27,20 @@ test('toPaddedString', () => { expect(PlanningEventManager.toPaddedString(100)).toBe("100"); }); -test('isDateStringFormatValid', () => { - expect(PlanningEventManager.isDateStringFormatValid("2020-03-21 09:00:00")).toBeTrue(); - expect(PlanningEventManager.isDateStringFormatValid("3214-64-12 01:16:65")).toBeTrue(); +test('isEventDateStringFormatValid', () => { + expect(PlanningEventManager.isEventDateStringFormatValid("2020-03-21 09:00:00")).toBeTrue(); + expect(PlanningEventManager.isEventDateStringFormatValid("3214-64-12 01:16:65")).toBeTrue(); - expect(PlanningEventManager.isDateStringFormatValid("3214-64-12 1:16:65")).toBeFalse(); - expect(PlanningEventManager.isDateStringFormatValid("3214-f4-12 01:16:65")).toBeFalse(); - expect(PlanningEventManager.isDateStringFormatValid("sqdd 09:00:00")).toBeFalse(); - expect(PlanningEventManager.isDateStringFormatValid("2020-03-21")).toBeFalse(); - expect(PlanningEventManager.isDateStringFormatValid("2020-03-21 truc")).toBeFalse(); - expect(PlanningEventManager.isDateStringFormatValid("3214-64-12 1:16:65")).toBeFalse(); - expect(PlanningEventManager.isDateStringFormatValid("garbage")).toBeFalse(); - expect(PlanningEventManager.isDateStringFormatValid("")).toBeFalse(); - expect(PlanningEventManager.isDateStringFormatValid(undefined)).toBeFalse(); - expect(PlanningEventManager.isDateStringFormatValid(null)).toBeFalse(); + expect(PlanningEventManager.isEventDateStringFormatValid("3214-64-12 1:16:65")).toBeFalse(); + expect(PlanningEventManager.isEventDateStringFormatValid("3214-f4-12 01:16:65")).toBeFalse(); + expect(PlanningEventManager.isEventDateStringFormatValid("sqdd 09:00:00")).toBeFalse(); + expect(PlanningEventManager.isEventDateStringFormatValid("2020-03-21")).toBeFalse(); + expect(PlanningEventManager.isEventDateStringFormatValid("2020-03-21 truc")).toBeFalse(); + expect(PlanningEventManager.isEventDateStringFormatValid("3214-64-12 1:16:65")).toBeFalse(); + expect(PlanningEventManager.isEventDateStringFormatValid("garbage")).toBeFalse(); + expect(PlanningEventManager.isEventDateStringFormatValid("")).toBeFalse(); + expect(PlanningEventManager.isEventDateStringFormatValid(undefined)).toBeFalse(); + expect(PlanningEventManager.isEventDateStringFormatValid(null)).toBeFalse(); }); test('stringToDate', () => { @@ -124,3 +124,13 @@ test('isEventBefore', () => { undefined, undefined)).toBeFalse(); }); +test('dateToString', () => { + let testDate = new Date(); + testDate.setFullYear(2020, 2, 21); + expect(PlanningEventManager.dateToString(testDate)).toBe("2020-03-21"); + testDate.setFullYear(2021, 0, 12); + expect(PlanningEventManager.dateToString(testDate)).toBe("2021-01-12"); + testDate.setFullYear(2022, 11, 31); + expect(PlanningEventManager.dateToString(testDate)).toBe("2022-12-31"); +}); + From 40d7985bbd14ea36ac2a6273c2776bdfe51f27f4 Mon Sep 17 00:00:00 2001 From: Arnaud Vergnet Date: Sat, 21 Mar 2020 20:32:28 +0100 Subject: [PATCH 030/398] Allow events to span on multiple days --- screens/Planning/PlanningScreen.js | 47 +++++++++++++-- utils/DateManager.js | 4 +- utils/PlanningEventManager.js | 64 +++++++++++++-------- utils/__test__/PlanningEventManager.test.js | 29 +++++----- 4 files changed, 100 insertions(+), 44 deletions(-) diff --git a/screens/Planning/PlanningScreen.js b/screens/Planning/PlanningScreen.js index f2917cd..de40716 100644 --- a/screens/Planning/PlanningScreen.js +++ b/screens/Planning/PlanningScreen.js @@ -59,7 +59,7 @@ export default class PlanningScreen extends React.Component { onAgendaRef: Function; onCalendarToggled: Function; onBackButtonPressAndroid: Function; - currentDate = PlanningEventManager.getCurrentDateString(); + currentDate = PlanningEventManager.getDateOnlyString(PlanningEventManager.getCurrentDateString()); constructor(props: any) { super(props); @@ -108,12 +108,14 @@ export default class PlanningScreen extends React.Component { }; - generateEmptyCalendar() { let end = new Date(new Date().setMonth(new Date().getMonth() + AGENDA_MONTH_SPAN + 1)); let daysOfYear = {}; for (let d = new Date(); d <= end; d.setDate(d.getDate() + 1)) { - daysOfYear[PlanningEventManager.dateToString(new Date(d))] = [] + daysOfYear[ + PlanningEventManager.getDateOnlyString( + PlanningEventManager.dateToString(new Date(d)) + )] = [] } return daysOfYear; } @@ -192,16 +194,53 @@ export default class PlanningScreen extends React.Component { } }; + getClonedEventArray(event: Object, times: number) { + let cloneArray = []; + if (times > 1) { + for (let i = 0; i < times; i++) { + let clone = JSON.parse(JSON.stringify(event)); + let startDate = PlanningEventManager.stringToDate(clone["date_begin"]); + let endDate = new Date(); + if (i !== 0) { + startDate.setHours(0, 0, 0); + startDate.setDate(startDate.getDate() + i); + clone["date_begin"] = PlanningEventManager.dateToString(startDate); + } + if (i !== (times - 1)) { + endDate = PlanningEventManager.stringToDate(clone["date_end"]); + endDate.setHours(23, 59, 0); + endDate.setFullYear(startDate.getFullYear(), + startDate.getMonth(), + startDate.getDate() + i); + clone["date_end"] = PlanningEventManager.dateToString(endDate); + } + cloneArray.push(clone) + } + } else + cloneArray = [event]; + return cloneArray; + } + generateEventAgenda(eventList: Array) { let agendaItems = this.generateEmptyCalendar(); for (let i = 0; i < eventList.length; i++) { if (PlanningEventManager.getDateOnlyString(eventList[i]["date_begin"]) !== undefined) { - this.pushEventInOrder(agendaItems, eventList[i], PlanningEventManager.getDateOnlyString(eventList[i]["date_begin"])); + const clonedEventArray = this.getClonedEventArray( + eventList[i], + PlanningEventManager.getEventDaysNumber(eventList[i]["date_begin"], eventList[i]["date_end"]) + ); + this.pushEvents(agendaItems, clonedEventArray); } } this.setState({agendaItems: agendaItems}) } + pushEvents(agendaItems: Object, eventList: Array) { + for (let i = 0; i < eventList.length; i++) { + this.pushEventInOrder(agendaItems, eventList[i], PlanningEventManager.getDateOnlyString(eventList[i]["date_begin"])); + } + } + pushEventInOrder(agendaItems: Object, event: Object, startDate: string) { if (agendaItems[startDate].length === 0) agendaItems[startDate].push(event); diff --git a/utils/DateManager.js b/utils/DateManager.js index 520fbb9..fa22494 100644 --- a/utils/DateManager.js +++ b/utils/DateManager.js @@ -8,13 +8,13 @@ export default class DateManager { monthsOfYear = []; constructor() { + this.daysOfWeek.push(i18n.t("date.daysOfWeek.sunday")); // 0 represents sunday this.daysOfWeek.push(i18n.t("date.daysOfWeek.monday")); this.daysOfWeek.push(i18n.t("date.daysOfWeek.tuesday")); this.daysOfWeek.push(i18n.t("date.daysOfWeek.wednesday")); this.daysOfWeek.push(i18n.t("date.daysOfWeek.thursday")); this.daysOfWeek.push(i18n.t("date.daysOfWeek.friday")); this.daysOfWeek.push(i18n.t("date.daysOfWeek.saturday")); - this.daysOfWeek.push(i18n.t("date.daysOfWeek.sunday")); this.monthsOfYear.push(i18n.t("date.monthsOfYear.january")); this.monthsOfYear.push(i18n.t("date.monthsOfYear.february")); @@ -44,7 +44,7 @@ export default class DateManager { let dateArray = dateString.split('-'); let date = new Date(); date.setFullYear(parseInt(dateArray[0]), parseInt(dateArray[1]) - 1, parseInt(dateArray[2])); - return this.daysOfWeek[date.getDay() - 1] + " " + date.getDate() + " " + this.monthsOfYear[date.getMonth()] + " " + date.getFullYear(); + return this.daysOfWeek[date.getDay()] + " " + date.getDate() + " " + this.monthsOfYear[date.getMonth()] + " " + date.getFullYear(); } } diff --git a/utils/PlanningEventManager.js b/utils/PlanningEventManager.js index ce5381f..fad13d9 100644 --- a/utils/PlanningEventManager.js +++ b/utils/PlanningEventManager.js @@ -9,10 +9,33 @@ export default class PlanningEventManager { * * @return {string} The string representation */ - static getCurrentDateString() { + static getCurrentDateString(): string { return PlanningEventManager.dateToString(new Date()); } + /** + * Gets how many days the event lasts. If no end date is specified, defaults to 1. + * + * + * @param start The start date string in format YYYY-MM-DD HH:MM:SS + * @param end The end date string in format YYYY-MM-DD HH:MM:SS + * @return {number} The number of days, 0 on error + */ + static getEventDaysNumber(start: string, end: string): number { + let startDate = PlanningEventManager.stringToDate(start); + let endDate = PlanningEventManager.stringToDate(end); + if (startDate !== undefined && endDate !== undefined) { + if (startDate.getTime() !== endDate.getTime()) { + const diffTime = endDate - startDate; + return Math.ceil(diffTime / (1000 * 60 * 60 * 24)); + } else + return 1; + } else if (startDate !== undefined) + return 1; + else + return 0; + } + /** * Checks if the given date is before the other. @@ -89,26 +112,19 @@ export default class PlanningEventManager { /** * Converts a date object to a string in the format - * YYYY-MM-DD + * YYYY-MM-DD HH-MM-SS * * @param date The date object to convert * @return {string} The converted string */ static dateToString(date: Date) { - let dd = String(date.getDate()).padStart(2, '0'); - let mm = String(date.getMonth() + 1).padStart(2, '0'); //January is 0! - let yyyy = date.getFullYear(); - return yyyy + '-' + mm + '-' + dd; - } - - /** - * Returns a padded string for the given number if it is lower than 10 - * - * @param i The string to be converted - * @return {string} - */ - static toPaddedString(i: number): string { - return (i < 10 && i >= 0) ? "0" + i.toString(10) : i.toString(10); + const day = String(date.getDate()).padStart(2, '0'); + const month = String(date.getMonth() + 1).padStart(2, '0'); //January is 0! + const year = date.getFullYear(); + const hours = String(date.getHours()).padStart(2, '0'); + const minutes = String(date.getMinutes()).padStart(2, '0'); + const seconds = String(date.getSeconds()).padStart(2, '0'); + return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds; } /** @@ -118,7 +134,7 @@ export default class PlanningEventManager { * * If the end date is not specified or is equal to start time, only start time will be shown. * - * If the end date is not on the same day, 00:00 will be shown as end time + * If the end date is not on the same day, 23:59 will be shown as end time * * @param start Start time in YYYY-MM-DD HH:MM:SS format * @param end End time in YYYY-MM-DD HH:MM:SS format @@ -130,19 +146,19 @@ export default class PlanningEventManager { let endDate = PlanningEventManager.stringToDate(end); if (startDate !== undefined && endDate !== undefined && startDate.getTime() !== endDate.getTime()) { - formattedStr = PlanningEventManager.toPaddedString(startDate.getHours()) + ':' - + PlanningEventManager.toPaddedString(startDate.getMinutes()) + ' - '; + formattedStr = String(startDate.getHours()).padStart(2, '0') + ':' + + String(startDate.getMinutes()).padStart(2, '0') + ' - '; if (endDate.getFullYear() > startDate.getFullYear() || endDate.getMonth() > startDate.getMonth() || endDate.getDate() > startDate.getDate()) - formattedStr += '00:00'; + formattedStr += '23:59'; else - formattedStr += PlanningEventManager.toPaddedString(endDate.getHours()) + ':' - + PlanningEventManager.toPaddedString(endDate.getMinutes()); + formattedStr += String(endDate.getHours()).padStart(2, '0') + ':' + + String(endDate.getMinutes()).padStart(2, '0'); } else if (startDate !== undefined) formattedStr = - PlanningEventManager.toPaddedString(startDate.getHours()) + ':' - + PlanningEventManager.toPaddedString(startDate.getMinutes()); + String(startDate.getHours()).padStart(2, '0') + ':' + + String(startDate.getMinutes()).padStart(2, '0'); return formattedStr } diff --git a/utils/__test__/PlanningEventManager.test.js b/utils/__test__/PlanningEventManager.test.js index 868bf3d..249e2b9 100644 --- a/utils/__test__/PlanningEventManager.test.js +++ b/utils/__test__/PlanningEventManager.test.js @@ -17,16 +17,6 @@ test('isDescriptionEmpty', () => { expect(PlanningEventManager.isDescriptionEmpty("

coucou

")).toBeFalse(); }); -test('toPaddedString', () => { - expect(PlanningEventManager.toPaddedString(-1)).toBe("-1"); - expect(PlanningEventManager.toPaddedString(0)).toBe("00"); - expect(PlanningEventManager.toPaddedString(1)).toBe("01"); - expect(PlanningEventManager.toPaddedString(2)).toBe("02"); - expect(PlanningEventManager.toPaddedString(10)).toBe("10"); - expect(PlanningEventManager.toPaddedString(53)).toBe("53"); - expect(PlanningEventManager.toPaddedString(100)).toBe("100"); -}); - test('isEventDateStringFormatValid', () => { expect(PlanningEventManager.isEventDateStringFormatValid("2020-03-21 09:00:00")).toBeTrue(); expect(PlanningEventManager.isEventDateStringFormatValid("3214-64-12 01:16:65")).toBeTrue(); @@ -77,7 +67,7 @@ test('getFormattedEventTime', () => { expect(PlanningEventManager.getFormattedEventTime("2020-03-21 09:00:00", "2020-03-21 09:00:00")) .toBe('09:00'); expect(PlanningEventManager.getFormattedEventTime("2020-03-21 09:00:00", "2020-03-22 17:00:00")) - .toBe('09:00 - 00:00'); + .toBe('09:00 - 23:59'); expect(PlanningEventManager.getFormattedEventTime("2020-03-30 20:30:00", "2020-03-30 23:00:00")) .toBe('20:30 - 23:00'); }); @@ -127,10 +117,21 @@ test('isEventBefore', () => { test('dateToString', () => { let testDate = new Date(); testDate.setFullYear(2020, 2, 21); - expect(PlanningEventManager.dateToString(testDate)).toBe("2020-03-21"); + testDate.setHours(9, 0, 0, 0); + expect(PlanningEventManager.dateToString(testDate)).toBe("2020-03-21 09:00:00"); testDate.setFullYear(2021, 0, 12); - expect(PlanningEventManager.dateToString(testDate)).toBe("2021-01-12"); + testDate.setHours(9, 10, 0, 0); + expect(PlanningEventManager.dateToString(testDate)).toBe("2021-01-12 09:10:00"); testDate.setFullYear(2022, 11, 31); - expect(PlanningEventManager.dateToString(testDate)).toBe("2022-12-31"); + testDate.setHours(9, 10, 15, 0); + expect(PlanningEventManager.dateToString(testDate)).toBe("2022-12-31 09:10:15"); }); +test('getEventDaysNumber', () => { + expect(PlanningEventManager.getEventDaysNumber('2020-03-21 09:00:00', '2020-03-22 17:00:00')).toBe(2); + expect(PlanningEventManager.getEventDaysNumber('2020-03-21 09:00:00', '2020-03-21 17:00:00')).toBe(1); + expect(PlanningEventManager.getEventDaysNumber('2020-03-21 09:00:00', '2020-03-21 09:00:00')).toBe(1); + expect(PlanningEventManager.getEventDaysNumber('2020-03-21 09:gg:00', '2020-03-21 17:00:00')).toBe(0); + expect(PlanningEventManager.getEventDaysNumber('2020-03-21 09:00:00', undefined)).toBe(1); + expect(PlanningEventManager.getEventDaysNumber('2020-03-21 09:00:00', '2020-04-05 20:00:00')).toBe(16); +}); From 38246833857121f0e05ec3d90d2ce7074ebd32e9 Mon Sep 17 00:00:00 2001 From: Arnaud Vergnet Date: Sat, 21 Mar 2020 21:07:39 +0100 Subject: [PATCH 031/398] Removed unused function --- utils/PlanningEventManager.js | 26 +-------------------- utils/__test__/PlanningEventManager.test.js | 8 ------- 2 files changed, 1 insertion(+), 33 deletions(-) diff --git a/utils/PlanningEventManager.js b/utils/PlanningEventManager.js index fad13d9..b703180 100644 --- a/utils/PlanningEventManager.js +++ b/utils/PlanningEventManager.js @@ -13,31 +13,7 @@ export default class PlanningEventManager { return PlanningEventManager.dateToString(new Date()); } - /** - * Gets how many days the event lasts. If no end date is specified, defaults to 1. - * - * - * @param start The start date string in format YYYY-MM-DD HH:MM:SS - * @param end The end date string in format YYYY-MM-DD HH:MM:SS - * @return {number} The number of days, 0 on error - */ - static getEventDaysNumber(start: string, end: string): number { - let startDate = PlanningEventManager.stringToDate(start); - let endDate = PlanningEventManager.stringToDate(end); - if (startDate !== undefined && endDate !== undefined) { - if (startDate.getTime() !== endDate.getTime()) { - const diffTime = endDate - startDate; - return Math.ceil(diffTime / (1000 * 60 * 60 * 24)); - } else - return 1; - } else if (startDate !== undefined) - return 1; - else - return 0; - } - - - /** + /** * Checks if the given date is before the other. * * @param event1Date Event 1 date in format YYYY-MM-DD HH:MM:SS diff --git a/utils/__test__/PlanningEventManager.test.js b/utils/__test__/PlanningEventManager.test.js index 249e2b9..67e0424 100644 --- a/utils/__test__/PlanningEventManager.test.js +++ b/utils/__test__/PlanningEventManager.test.js @@ -127,11 +127,3 @@ test('dateToString', () => { expect(PlanningEventManager.dateToString(testDate)).toBe("2022-12-31 09:10:15"); }); -test('getEventDaysNumber', () => { - expect(PlanningEventManager.getEventDaysNumber('2020-03-21 09:00:00', '2020-03-22 17:00:00')).toBe(2); - expect(PlanningEventManager.getEventDaysNumber('2020-03-21 09:00:00', '2020-03-21 17:00:00')).toBe(1); - expect(PlanningEventManager.getEventDaysNumber('2020-03-21 09:00:00', '2020-03-21 09:00:00')).toBe(1); - expect(PlanningEventManager.getEventDaysNumber('2020-03-21 09:gg:00', '2020-03-21 17:00:00')).toBe(0); - expect(PlanningEventManager.getEventDaysNumber('2020-03-21 09:00:00', undefined)).toBe(1); - expect(PlanningEventManager.getEventDaysNumber('2020-03-21 09:00:00', '2020-04-05 20:00:00')).toBe(16); -}); From 53ef08219cea3501e1d0b356a81e128146d0dc2d Mon Sep 17 00:00:00 2001 From: Arnaud Vergnet Date: Sat, 21 Mar 2020 21:10:57 +0100 Subject: [PATCH 032/398] Removed multiple day management (will be handled by server) --- screens/Planning/PlanningScreen.js | 39 +----------------------------- 1 file changed, 1 insertion(+), 38 deletions(-) diff --git a/screens/Planning/PlanningScreen.js b/screens/Planning/PlanningScreen.js index de40716..67e30e9 100644 --- a/screens/Planning/PlanningScreen.js +++ b/screens/Planning/PlanningScreen.js @@ -194,53 +194,16 @@ export default class PlanningScreen extends React.Component { } }; - getClonedEventArray(event: Object, times: number) { - let cloneArray = []; - if (times > 1) { - for (let i = 0; i < times; i++) { - let clone = JSON.parse(JSON.stringify(event)); - let startDate = PlanningEventManager.stringToDate(clone["date_begin"]); - let endDate = new Date(); - if (i !== 0) { - startDate.setHours(0, 0, 0); - startDate.setDate(startDate.getDate() + i); - clone["date_begin"] = PlanningEventManager.dateToString(startDate); - } - if (i !== (times - 1)) { - endDate = PlanningEventManager.stringToDate(clone["date_end"]); - endDate.setHours(23, 59, 0); - endDate.setFullYear(startDate.getFullYear(), - startDate.getMonth(), - startDate.getDate() + i); - clone["date_end"] = PlanningEventManager.dateToString(endDate); - } - cloneArray.push(clone) - } - } else - cloneArray = [event]; - return cloneArray; - } - generateEventAgenda(eventList: Array) { let agendaItems = this.generateEmptyCalendar(); for (let i = 0; i < eventList.length; i++) { if (PlanningEventManager.getDateOnlyString(eventList[i]["date_begin"]) !== undefined) { - const clonedEventArray = this.getClonedEventArray( - eventList[i], - PlanningEventManager.getEventDaysNumber(eventList[i]["date_begin"], eventList[i]["date_end"]) - ); - this.pushEvents(agendaItems, clonedEventArray); + this.pushEventInOrder(agendaItems, eventList[i], PlanningEventManager.getDateOnlyString(eventList[i]["date_begin"])); } } this.setState({agendaItems: agendaItems}) } - pushEvents(agendaItems: Object, eventList: Array) { - for (let i = 0; i < eventList.length; i++) { - this.pushEventInOrder(agendaItems, eventList[i], PlanningEventManager.getDateOnlyString(eventList[i]["date_begin"])); - } - } - pushEventInOrder(agendaItems: Object, event: Object, startDate: string) { if (agendaItems[startDate].length === 0) agendaItems[startDate].push(event); From c37f6d07a42f2e27517b6c3edeb1f12d78afa599 Mon Sep 17 00:00:00 2001 From: Arnaud Vergnet Date: Sun, 22 Mar 2020 10:00:35 +0100 Subject: [PATCH 033/398] Updated api link --- screens/Planning/PlanningScreen.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/screens/Planning/PlanningScreen.js b/screens/Planning/PlanningScreen.js index 67e30e9..c2e6e6d 100644 --- a/screens/Planning/PlanningScreen.js +++ b/screens/Planning/PlanningScreen.js @@ -28,7 +28,7 @@ type State = { calendarShowing: boolean, }; -const FETCH_URL = "https://amicale-insat.fr/event/json/list"; +const FETCH_URL = "https://www.amicale-insat.fr/api/event/list"; const AGENDA_MONTH_SPAN = 3; From 81eddd9bddd8fecc6e11c1d450dea7e5b1d6af1d Mon Sep 17 00:00:00 2001 From: Arnaud Vergnet Date: Sun, 22 Mar 2020 10:22:57 +0100 Subject: [PATCH 034/398] Removed unused functions --- screens/About/DebugScreen.js | 29 +--------------- utils/NotificationsManager.js | 63 ----------------------------------- 2 files changed, 1 insertion(+), 91 deletions(-) diff --git a/screens/About/DebugScreen.js b/screens/About/DebugScreen.js index 09df31e..7c4700b 100644 --- a/screens/About/DebugScreen.js +++ b/screens/About/DebugScreen.js @@ -1,9 +1,8 @@ // @flow import * as React from 'react'; -import {Alert, Clipboard, ScrollView, View} from "react-native"; +import {ScrollView, View} from "react-native"; import AsyncStorageManager from "../../utils/AsyncStorageManager"; -import NotificationsManager from "../../utils/NotificationsManager"; import CustomModal from "../../components/CustomModal"; import {Button, Card, List, Subheading, TextInput, Title, withTheme} from 'react-native-paper'; @@ -59,23 +58,6 @@ class DebugScreen extends React.Component { } } - alertCurrentExpoToken() { - let token = AsyncStorageManager.getInstance().preferences.expoToken.current; - Alert.alert( - 'Expo Token', - token, - [ - {text: 'Copy', onPress: () => Clipboard.setString(token)}, - {text: 'OK'} - ] - ); - } - - async forceExpoTokenUpdate() { - await NotificationsManager.forceExpoTokenUpdate(); - this.alertCurrentExpoToken(); - } - showEditModal(item: Object) { this.setState({ modalCurrentDisplayItem: item @@ -142,15 +124,6 @@ class DebugScreen extends React.Component { {this.getModalContent()} - - - - {DebugScreen.getGeneralItem(() => this.alertCurrentExpoToken(), 'bell', 'Get current Expo Token', '')} - {DebugScreen.getGeneralItem(() => this.forceExpoTokenUpdate(), 'bell-ring', 'Force Expo token update', '')} - - } Notification Id - */ - static async sendNotificationImmediately(title: string, body: string) { - await NotificationsManager.askPermissions(); - return await Notifications.presentLocalNotificationAsync({ - title: title, - body: body, - }); - }; - - /** - * Async function sending notification at the specified time - * - * @param title Notification title - * @param body Notification body text - * @param time Time at which we should send the notification - * @param data Data to send with the notification, used for listeners - * @param androidChannelID - * @returns {Promise} Notification Id - */ - static async scheduleNotification(title: string, body: string, time: number, data: Object, androidChannelID: string): Promise { - await NotificationsManager.askPermissions(); - let date = new Date(); - date.setTime(time); - return Notifications.scheduleLocalNotificationAsync( - { - title: title, - body: body, - data: data, - ios: { // configuration for iOS. - sound: true - }, - android: { // configuration for Android. - channelId: androidChannelID, - } - }, - { - time: time, - }, - ); - }; - - /** - * Async function used to cancel the notification of a specific ID - * @param notificationID {Number} The notification ID - * @returns {Promise} - */ - static async cancelScheduledNotification(notificationID: number) { - await Notifications.cancelScheduledNotificationAsync(notificationID); - } - /** * Save expo token to allow sending notifications to this device. * This token is unique for each device and won't change. @@ -105,13 +49,6 @@ export default class NotificationsManager { } } - static async forceExpoTokenUpdate() { - await NotificationsManager.askPermissions(); - let expoToken = await Notifications.getExpoPushTokenAsync(); - // Save token for instant use later on - AsyncStorageManager.getInstance().savePref(AsyncStorageManager.getInstance().preferences.expoToken.key, expoToken); - } - static getMachineNotificationWatchlist(callback: Function) { let token = AsyncStorageManager.getInstance().preferences.expoToken.current; if (token !== '') { From 160dbb00c8bd0d0968ce37f67048e6b7938e9acb Mon Sep 17 00:00:00 2001 From: Arnaud Vergnet Date: Sun, 22 Mar 2020 10:37:59 +0100 Subject: [PATCH 035/398] Reorganized code --- screens/Planning/PlanningScreen.js | 121 ++++++++++------------------- utils/PlanningEventManager.js | 41 ++++++++++ 2 files changed, 81 insertions(+), 81 deletions(-) diff --git a/screens/Planning/PlanningScreen.js b/screens/Planning/PlanningScreen.js index c2e6e6d..10194cc 100644 --- a/screens/Planning/PlanningScreen.js +++ b/screens/Planning/PlanningScreen.js @@ -29,7 +29,6 @@ type State = { }; const FETCH_URL = "https://www.amicale-insat.fr/api/event/list"; - const AGENDA_MONTH_SPAN = 3; /** @@ -107,17 +106,48 @@ export default class PlanningScreen extends React.Component { } }; + rowHasChanged(r1: Object, r2: Object) { + return false; + // if (r1 !== undefined && r2 !== undefined) + // return r1.title !== r2.title; + // else return !(r1 === undefined && r2 === undefined); + } - generateEmptyCalendar() { - let end = new Date(new Date().setMonth(new Date().getMonth() + AGENDA_MONTH_SPAN + 1)); - let daysOfYear = {}; - for (let d = new Date(); d <= end; d.setDate(d.getDate() + 1)) { - daysOfYear[ - PlanningEventManager.getDateOnlyString( - PlanningEventManager.dateToString(new Date(d)) - )] = [] + /** + * Refresh data and show a toast if any error occurred + * @private + */ + onRefresh = () => { + let canRefresh; + if (this.lastRefresh !== undefined) + canRefresh = (new Date().getTime() - this.lastRefresh.getTime()) / 1000 > this.minTimeBetweenRefresh; + else + canRefresh = true; + + if (canRefresh) { + this.setState({refreshing: true}); + this.webDataManager.readData() + .then((fetchedData) => { + this.setState({ + refreshing: false, + agendaItems: PlanningEventManager.generateEventAgenda(fetchedData, AGENDA_MONTH_SPAN) + }); + this.lastRefresh = new Date(); + }) + .catch(() => { + this.setState({ + refreshing: false, + }); + }); } - return daysOfYear; + }; + + onAgendaRef(ref: Object) { + this.agendaRef = ref; + } + + onCalendarToggled(isCalendarOpened: boolean) { + this.setState({calendarShowing: isCalendarOpened}); } getRenderItem(item: Object) { @@ -157,77 +187,6 @@ export default class PlanningScreen extends React.Component { ); } - rowHasChanged(r1: Object, r2: Object) { - return false; - // if (r1 !== undefined && r2 !== undefined) - // return r1.title !== r2.title; - // else return !(r1 === undefined && r2 === undefined); - } - - /** - * Refresh data and show a toast if any error occurred - * @private - */ - onRefresh = () => { - let canRefresh; - if (this.lastRefresh !== undefined) - canRefresh = (new Date().getTime() - this.lastRefresh.getTime()) / 1000 > this.minTimeBetweenRefresh; - else - canRefresh = true; - - if (canRefresh) { - this.setState({refreshing: true}); - this.webDataManager.readData() - .then((fetchedData) => { - this.setState({ - refreshing: false, - }); - this.generateEventAgenda(fetchedData); - this.lastRefresh = new Date(); - }) - .catch((err) => { - this.setState({ - refreshing: false, - }); - // console.log(err); - }); - } - }; - - generateEventAgenda(eventList: Array) { - let agendaItems = this.generateEmptyCalendar(); - for (let i = 0; i < eventList.length; i++) { - if (PlanningEventManager.getDateOnlyString(eventList[i]["date_begin"]) !== undefined) { - this.pushEventInOrder(agendaItems, eventList[i], PlanningEventManager.getDateOnlyString(eventList[i]["date_begin"])); - } - } - this.setState({agendaItems: agendaItems}) - } - - pushEventInOrder(agendaItems: Object, event: Object, startDate: string) { - if (agendaItems[startDate].length === 0) - agendaItems[startDate].push(event); - else { - for (let i = 0; i < agendaItems[startDate].length; i++) { - if (PlanningEventManager.isEventBefore(event["date_begin"], agendaItems[startDate][i]["date_begin"])) { - agendaItems[startDate].splice(i, 0, event); - break; - } else if (i === agendaItems[startDate].length - 1) { - agendaItems[startDate].push(event); - break; - } - } - } - } - - onAgendaRef(ref: Object) { - this.agendaRef = ref; - } - - onCalendarToggled(isCalendarOpened: boolean) { - this.setState({calendarShowing: isCalendarOpened}); - } - render() { // console.log("rendering PlanningScreen"); return ( diff --git a/utils/PlanningEventManager.js b/utils/PlanningEventManager.js index b703180..0cc31c2 100644 --- a/utils/PlanningEventManager.js +++ b/utils/PlanningEventManager.js @@ -157,4 +157,45 @@ export default class PlanningEventManager { } else return true; } + + + static generateEmptyCalendar(numberOfMonths: number) { + let end = new Date(new Date().setMonth(new Date().getMonth() + numberOfMonths + 1)); + let daysOfYear = {}; + for (let d = new Date(); d <= end; d.setDate(d.getDate() + 1)) { + daysOfYear[ + PlanningEventManager.getDateOnlyString( + PlanningEventManager.dateToString(new Date(d)) + )] = [] + } + return daysOfYear; + } + + static generateEventAgenda(eventList: Array, numberOfMonths: number) { + let agendaItems = PlanningEventManager.generateEmptyCalendar(numberOfMonths); + for (let i = 0; i < eventList.length; i++) { + console.log(PlanningEventManager.getDateOnlyString(eventList[i]["date_begin"])); + console.log(eventList[i]["date_begin"]); + if (PlanningEventManager.getDateOnlyString(eventList[i]["date_begin"]) !== undefined) { + this.pushEventInOrder(agendaItems, eventList[i], PlanningEventManager.getDateOnlyString(eventList[i]["date_begin"])); + } + } + return agendaItems; + } + + static pushEventInOrder(agendaItems: Object, event: Object, startDate: string) { + if (agendaItems[startDate].length === 0) + agendaItems[startDate].push(event); + else { + for (let i = 0; i < agendaItems[startDate].length; i++) { + if (PlanningEventManager.isEventBefore(event["date_begin"], agendaItems[startDate][i]["date_begin"])) { + agendaItems[startDate].splice(i, 0, event); + break; + } else if (i === agendaItems[startDate].length - 1) { + agendaItems[startDate].push(event); + break; + } + } + } + } } From a6771f442aa23be6fe8a2eb73c022cef6d901151 Mon Sep 17 00:00:00 2001 From: Arnaud Vergnet Date: Sun, 22 Mar 2020 11:21:55 +0100 Subject: [PATCH 036/398] Improved flow type checking --- screens/Planning/PlanningScreen.js | 3 +- screens/Tetris/Tetromino.js | 2 + utils/DateManager.js | 2 + utils/PlanningEventManager.js | 58 +++++++++++++-------- utils/WebDataManager.js | 3 +- utils/__test__/PlanningEventManager.test.js | 22 ++++---- 6 files changed, 54 insertions(+), 36 deletions(-) diff --git a/screens/Planning/PlanningScreen.js b/screens/Planning/PlanningScreen.js index 10194cc..b5cc293 100644 --- a/screens/Planning/PlanningScreen.js +++ b/screens/Planning/PlanningScreen.js @@ -5,6 +5,7 @@ import {BackHandler, View} from 'react-native'; import i18n from "i18n-js"; import {LocaleConfig} from 'react-native-calendars'; import WebDataManager from "../../utils/WebDataManager"; +import type {eventObject} from "../../utils/PlanningEventManager"; import PlanningEventManager from '../../utils/PlanningEventManager'; import {Avatar, Divider, List} from 'react-native-paper'; import CustomAgenda from "../../components/CustomAgenda"; @@ -150,7 +151,7 @@ export default class PlanningScreen extends React.Component { this.setState({calendarShowing: isCalendarOpened}); } - getRenderItem(item: Object) { + getRenderItem(item: eventObject) { const onPress = this.props.navigation.navigate.bind(this, 'PlanningDisplayScreen', {data: item}); if (item.logo !== null) { return ( diff --git a/screens/Tetris/Tetromino.js b/screens/Tetris/Tetromino.js index 6483e98..19359af 100644 --- a/screens/Tetris/Tetromino.js +++ b/screens/Tetris/Tetromino.js @@ -1,3 +1,5 @@ +// @flow + export default class Tetromino { static types = { diff --git a/utils/DateManager.js b/utils/DateManager.js index fa22494..3ca46ee 100644 --- a/utils/DateManager.js +++ b/utils/DateManager.js @@ -1,3 +1,5 @@ +// @flow + import i18n from 'i18n-js'; export default class DateManager { diff --git a/utils/PlanningEventManager.js b/utils/PlanningEventManager.js index 0cc31c2..8198751 100644 --- a/utils/PlanningEventManager.js +++ b/utils/PlanningEventManager.js @@ -1,3 +1,17 @@ +// @flow + +export type eventObject = { + id: number, + title: string, + logo: string, + date_begin: string, + date_end: string, + description: string, + club: string, + category_id: number, + url: string, +}; + export default class PlanningEventManager { // Regex used to check date string validity @@ -20,10 +34,10 @@ export default class PlanningEventManager { * @param event2Date Event 2 date in format YYYY-MM-DD HH:MM:SS * @return {boolean} */ - static isEventBefore(event1Date: ?string, event2Date: ?string) { + static isEventBefore(event1Date: string, event2Date: string) { let date1 = PlanningEventManager.stringToDate(event1Date); let date2 = PlanningEventManager.stringToDate(event2Date); - if (date1 !== undefined && date2 !== undefined) + if (date1 !== null && date2 !== null) return date1 < date2; else return false; @@ -34,13 +48,13 @@ export default class PlanningEventManager { * YYYY-MM-DD HH:MM:SS * * @param dateString The string to get the date from - * @return {string|undefined} Date in format YYYY:MM:DD or undefined if given string is invalid + * @return {string|null} Date in format YYYY:MM:DD or null if given string is invalid */ - static getDateOnlyString(dateString: ?string) { + static getDateOnlyString(dateString: string) { if (PlanningEventManager.isEventDateStringFormatValid(dateString)) return dateString.split(" ")[0]; else - return undefined; + return null; } /** @@ -61,9 +75,9 @@ export default class PlanningEventManager { * Accepted format: YYYY-MM-DD HH:MM:SS * * @param dateString The string to convert - * @return {Date|undefined} The date object or undefined if the given string is invalid + * @return {Date|null} The date object or null if the given string is invalid */ - static stringToDate(dateString: ?string): Date | undefined { + static stringToDate(dateString: string): Date | null { let date = new Date(); if (PlanningEventManager.isEventDateStringFormatValid(dateString)) { let stringArray = dateString.split(' '); @@ -81,7 +95,7 @@ export default class PlanningEventManager { 0, ); } else - date = undefined; + date = null; return date; } @@ -116,12 +130,12 @@ export default class PlanningEventManager { * @param end End time in YYYY-MM-DD HH:MM:SS format * @return {string} Formatted string or "/ - /" on error */ - static getFormattedEventTime(start: ?string, end: ?string): string { + static getFormattedEventTime(start: string, end: string): string { let formattedStr = '/ - /'; let startDate = PlanningEventManager.stringToDate(start); let endDate = PlanningEventManager.stringToDate(end); - if (startDate !== undefined && endDate !== undefined && startDate.getTime() !== endDate.getTime()) { + if (startDate !== null && endDate !== null && startDate.getTime() !== endDate.getTime()) { formattedStr = String(startDate.getHours()).padStart(2, '0') + ':' + String(startDate.getMinutes()).padStart(2, '0') + ' - '; if (endDate.getFullYear() > startDate.getFullYear() @@ -131,7 +145,7 @@ export default class PlanningEventManager { else formattedStr += String(endDate.getHours()).padStart(2, '0') + ':' + String(endDate.getMinutes()).padStart(2, '0'); - } else if (startDate !== undefined) + } else if (startDate !== null) formattedStr = String(startDate.getHours()).padStart(2, '0') + ':' + String(startDate.getMinutes()).padStart(2, '0'); @@ -163,32 +177,30 @@ export default class PlanningEventManager { let end = new Date(new Date().setMonth(new Date().getMonth() + numberOfMonths + 1)); let daysOfYear = {}; for (let d = new Date(); d <= end; d.setDate(d.getDate() + 1)) { - daysOfYear[ - PlanningEventManager.getDateOnlyString( - PlanningEventManager.dateToString(new Date(d)) - )] = [] + const dateString = PlanningEventManager.getDateOnlyString( + PlanningEventManager.dateToString(new Date(d))); + if (dateString !== null) + daysOfYear[dateString] = [] } return daysOfYear; } - static generateEventAgenda(eventList: Array, numberOfMonths: number) { + static generateEventAgenda(eventList: Array, numberOfMonths: number) { let agendaItems = PlanningEventManager.generateEmptyCalendar(numberOfMonths); for (let i = 0; i < eventList.length; i++) { - console.log(PlanningEventManager.getDateOnlyString(eventList[i]["date_begin"])); - console.log(eventList[i]["date_begin"]); - if (PlanningEventManager.getDateOnlyString(eventList[i]["date_begin"]) !== undefined) { - this.pushEventInOrder(agendaItems, eventList[i], PlanningEventManager.getDateOnlyString(eventList[i]["date_begin"])); - } + const dateString = PlanningEventManager.getDateOnlyString(eventList[i].date_begin); + if (dateString !== null) + this.pushEventInOrder(agendaItems, eventList[i], dateString); } return agendaItems; } - static pushEventInOrder(agendaItems: Object, event: Object, startDate: string) { + static pushEventInOrder(agendaItems: Object, event: eventObject, startDate: string) { if (agendaItems[startDate].length === 0) agendaItems[startDate].push(event); else { for (let i = 0; i < agendaItems[startDate].length; i++) { - if (PlanningEventManager.isEventBefore(event["date_begin"], agendaItems[startDate][i]["date_begin"])) { + if (PlanningEventManager.isEventBefore(event.date_begin, agendaItems[startDate][i].date_end)) { agendaItems[startDate].splice(i, 0, event); break; } else if (i === agendaItems[startDate].length - 1) { diff --git a/utils/WebDataManager.js b/utils/WebDataManager.js index 2ee84cc..8db8e2a 100644 --- a/utils/WebDataManager.js +++ b/utils/WebDataManager.js @@ -1,3 +1,4 @@ +// @flow /** * Class used to get json data from the web @@ -8,7 +9,7 @@ export default class WebDataManager { lastDataFetched: Object = {}; - constructor(url) { + constructor(url: string) { this.FETCH_URL = url; } diff --git a/utils/__test__/PlanningEventManager.test.js b/utils/__test__/PlanningEventManager.test.js index 67e0424..11ea11e 100644 --- a/utils/__test__/PlanningEventManager.test.js +++ b/utils/__test__/PlanningEventManager.test.js @@ -35,13 +35,13 @@ test('isEventDateStringFormatValid', () => { test('stringToDate', () => { let testDate = new Date(); - expect(PlanningEventManager.stringToDate(undefined)).toBeUndefined(); - expect(PlanningEventManager.stringToDate("")).toBeUndefined(); - expect(PlanningEventManager.stringToDate("garbage")).toBeUndefined(); - expect(PlanningEventManager.stringToDate("2020-03-21")).toBeUndefined(); - expect(PlanningEventManager.stringToDate("09:00:00")).toBeUndefined(); - expect(PlanningEventManager.stringToDate("2020-03-21 09:g0:00")).toBeUndefined(); - expect(PlanningEventManager.stringToDate("2020-03-21 09:g0:")).toBeUndefined(); + expect(PlanningEventManager.stringToDate(undefined)).toBeNull(); + expect(PlanningEventManager.stringToDate("")).toBeNull(); + expect(PlanningEventManager.stringToDate("garbage")).toBeNull(); + expect(PlanningEventManager.stringToDate("2020-03-21")).toBeNull(); + expect(PlanningEventManager.stringToDate("09:00:00")).toBeNull(); + expect(PlanningEventManager.stringToDate("2020-03-21 09:g0:00")).toBeNull(); + expect(PlanningEventManager.stringToDate("2020-03-21 09:g0:")).toBeNull(); testDate.setFullYear(2020, 2, 21); testDate.setHours(9, 0, 0, 0); expect(PlanningEventManager.stringToDate("2020-03-21 09:00:00")).toEqual(testDate); @@ -75,10 +75,10 @@ test('getFormattedEventTime', () => { test('getDateOnlyString', () => { expect(PlanningEventManager.getDateOnlyString("2020-03-21 09:00:00")).toBe("2020-03-21"); expect(PlanningEventManager.getDateOnlyString("2021-12-15 09:00:00")).toBe("2021-12-15"); - expect(PlanningEventManager.getDateOnlyString("2021-12-o5 09:00:00")).toBeUndefined(); - expect(PlanningEventManager.getDateOnlyString("2021-12-15 09:")).toBeUndefined(); - expect(PlanningEventManager.getDateOnlyString("2021-12-15")).toBeUndefined(); - expect(PlanningEventManager.getDateOnlyString("garbage")).toBeUndefined(); + expect(PlanningEventManager.getDateOnlyString("2021-12-o5 09:00:00")).toBeNull(); + expect(PlanningEventManager.getDateOnlyString("2021-12-15 09:")).toBeNull(); + expect(PlanningEventManager.getDateOnlyString("2021-12-15")).toBeNull(); + expect(PlanningEventManager.getDateOnlyString("garbage")).toBeNull(); }); test('isEventBefore', () => { From c6fb369863b53990571ad61f0316bf3bfdbbf45a Mon Sep 17 00:00:00 2001 From: Arnaud Vergnet Date: Sun, 22 Mar 2020 11:58:24 +0100 Subject: [PATCH 037/398] removed seconds for new api implementation --- utils/PlanningEventManager.js | 44 +++++++------ utils/__test__/PlanningEventManager.test.js | 73 +++++++++++---------- 2 files changed, 60 insertions(+), 57 deletions(-) diff --git a/utils/PlanningEventManager.js b/utils/PlanningEventManager.js index 8198751..05fba06 100644 --- a/utils/PlanningEventManager.js +++ b/utils/PlanningEventManager.js @@ -15,7 +15,7 @@ export type eventObject = { export default class PlanningEventManager { // Regex used to check date string validity - static dateRegExp = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/; + static dateRegExp = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}$/; /** * Gets the current day string representation in the format @@ -30,8 +30,8 @@ export default class PlanningEventManager { /** * Checks if the given date is before the other. * - * @param event1Date Event 1 date in format YYYY-MM-DD HH:MM:SS - * @param event2Date Event 2 date in format YYYY-MM-DD HH:MM:SS + * @param event1Date Event 1 date in format YYYY-MM-DD HH:MM + * @param event2Date Event 2 date in format YYYY-MM-DD HH:MM * @return {boolean} */ static isEventBefore(event1Date: string, event2Date: string) { @@ -45,7 +45,7 @@ export default class PlanningEventManager { /** * Gets only the date part of the given event date string in the format - * YYYY-MM-DD HH:MM:SS + * YYYY-MM-DD HH:MM * * @param dateString The string to get the date from * @return {string|null} Date in format YYYY:MM:DD or null if given string is invalid @@ -59,7 +59,7 @@ export default class PlanningEventManager { /** * Checks if the given date string is in the format - * YYYY-MM-DD HH:MM:SS + * YYYY-MM-DD HH:MM * * @param dateString The string to check * @return {boolean} @@ -72,7 +72,7 @@ export default class PlanningEventManager { /** * Converts the given date string to a date object.
- * Accepted format: YYYY-MM-DD HH:MM:SS + * Accepted format: YYYY-MM-DD HH:MM * * @param dateString The string to convert * @return {Date|null} The date object or null if the given string is invalid @@ -91,7 +91,7 @@ export default class PlanningEventManager { date.setHours( parseInt(timeArray[0]), parseInt(timeArray[1]), - parseInt(timeArray[2]), + 0, 0, ); } else @@ -113,8 +113,7 @@ export default class PlanningEventManager { const year = date.getFullYear(); const hours = String(date.getHours()).padStart(2, '0'); const minutes = String(date.getMinutes()).padStart(2, '0'); - const seconds = String(date.getSeconds()).padStart(2, '0'); - return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds; + return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes; } /** @@ -172,9 +171,8 @@ export default class PlanningEventManager { return true; } - static generateEmptyCalendar(numberOfMonths: number) { - let end = new Date(new Date().setMonth(new Date().getMonth() + numberOfMonths + 1)); + const end = new Date(new Date().setMonth(new Date().getMonth() + numberOfMonths + 1)); let daysOfYear = {}; for (let d = new Date(); d <= end; d.setDate(d.getDate() + 1)) { const dateString = PlanningEventManager.getDateOnlyString( @@ -189,6 +187,7 @@ export default class PlanningEventManager { let agendaItems = PlanningEventManager.generateEmptyCalendar(numberOfMonths); for (let i = 0; i < eventList.length; i++) { const dateString = PlanningEventManager.getDateOnlyString(eventList[i].date_begin); + console.log(dateString); if (dateString !== null) this.pushEventInOrder(agendaItems, eventList[i], dateString); } @@ -196,18 +195,21 @@ export default class PlanningEventManager { } static pushEventInOrder(agendaItems: Object, event: eventObject, startDate: string) { - if (agendaItems[startDate].length === 0) - agendaItems[startDate].push(event); - else { - for (let i = 0; i < agendaItems[startDate].length; i++) { - if (PlanningEventManager.isEventBefore(event.date_begin, agendaItems[startDate][i].date_end)) { - agendaItems[startDate].splice(i, 0, event); - break; - } else if (i === agendaItems[startDate].length - 1) { - agendaItems[startDate].push(event); - break; + if (agendaItems[startDate] !== undefined) { + if (agendaItems[startDate].length === 0) + agendaItems[startDate].push(event); + else { + for (let i = 0; i < agendaItems[startDate].length; i++) { + if (PlanningEventManager.isEventBefore(event.date_begin, agendaItems[startDate][i].date_end)) { + agendaItems[startDate].splice(i, 0, event); + break; + } else if (i === agendaItems[startDate].length - 1) { + agendaItems[startDate].push(event); + break; + } } } } + } } diff --git a/utils/__test__/PlanningEventManager.test.js b/utils/__test__/PlanningEventManager.test.js index 11ea11e..a125a16 100644 --- a/utils/__test__/PlanningEventManager.test.js +++ b/utils/__test__/PlanningEventManager.test.js @@ -18,12 +18,13 @@ test('isDescriptionEmpty', () => { }); test('isEventDateStringFormatValid', () => { - expect(PlanningEventManager.isEventDateStringFormatValid("2020-03-21 09:00:00")).toBeTrue(); - expect(PlanningEventManager.isEventDateStringFormatValid("3214-64-12 01:16:65")).toBeTrue(); + expect(PlanningEventManager.isEventDateStringFormatValid("2020-03-21 09:00")).toBeTrue(); + expect(PlanningEventManager.isEventDateStringFormatValid("3214-64-12 01:16")).toBeTrue(); - expect(PlanningEventManager.isEventDateStringFormatValid("3214-64-12 1:16:65")).toBeFalse(); - expect(PlanningEventManager.isEventDateStringFormatValid("3214-f4-12 01:16:65")).toBeFalse(); - expect(PlanningEventManager.isEventDateStringFormatValid("sqdd 09:00:00")).toBeFalse(); + expect(PlanningEventManager.isEventDateStringFormatValid("3214-64-12 01:16:00")).toBeFalse(); + expect(PlanningEventManager.isEventDateStringFormatValid("3214-64-12 1:16")).toBeFalse(); + expect(PlanningEventManager.isEventDateStringFormatValid("3214-f4-12 01:16")).toBeFalse(); + expect(PlanningEventManager.isEventDateStringFormatValid("sqdd 09:00")).toBeFalse(); expect(PlanningEventManager.isEventDateStringFormatValid("2020-03-21")).toBeFalse(); expect(PlanningEventManager.isEventDateStringFormatValid("2020-03-21 truc")).toBeFalse(); expect(PlanningEventManager.isEventDateStringFormatValid("3214-64-12 1:16:65")).toBeFalse(); @@ -40,17 +41,17 @@ test('stringToDate', () => { expect(PlanningEventManager.stringToDate("garbage")).toBeNull(); expect(PlanningEventManager.stringToDate("2020-03-21")).toBeNull(); expect(PlanningEventManager.stringToDate("09:00:00")).toBeNull(); - expect(PlanningEventManager.stringToDate("2020-03-21 09:g0:00")).toBeNull(); + expect(PlanningEventManager.stringToDate("2020-03-21 09:g0")).toBeNull(); expect(PlanningEventManager.stringToDate("2020-03-21 09:g0:")).toBeNull(); testDate.setFullYear(2020, 2, 21); testDate.setHours(9, 0, 0, 0); - expect(PlanningEventManager.stringToDate("2020-03-21 09:00:00")).toEqual(testDate); + expect(PlanningEventManager.stringToDate("2020-03-21 09:00")).toEqual(testDate); testDate.setFullYear(2020, 0, 31); - testDate.setHours(18, 30, 50, 0); - expect(PlanningEventManager.stringToDate("2020-01-31 18:30:50")).toEqual(testDate); + testDate.setHours(18, 30, 0, 0); + expect(PlanningEventManager.stringToDate("2020-01-31 18:30")).toEqual(testDate); testDate.setFullYear(2020, 50, 50); - testDate.setHours(65, 65, 65, 0); - expect(PlanningEventManager.stringToDate("2020-51-50 65:65:65")).toEqual(testDate); + testDate.setHours(65, 65, 0, 0); + expect(PlanningEventManager.stringToDate("2020-51-50 65:65")).toEqual(testDate); }); test('getFormattedEventTime', () => { @@ -58,24 +59,24 @@ test('getFormattedEventTime', () => { .toBe('/ - /'); expect(PlanningEventManager.getFormattedEventTime(undefined, undefined)) .toBe('/ - /'); - expect(PlanningEventManager.getFormattedEventTime("20:30:00", "23:00:00")) + expect(PlanningEventManager.getFormattedEventTime("20:30", "23:00")) .toBe('/ - /'); expect(PlanningEventManager.getFormattedEventTime("2020-03-30", "2020-03-31")) .toBe('/ - /'); - expect(PlanningEventManager.getFormattedEventTime("2020-03-21 09:00:00", "2020-03-21 09:00:00")) + expect(PlanningEventManager.getFormattedEventTime("2020-03-21 09:00", "2020-03-21 09:00")) .toBe('09:00'); - expect(PlanningEventManager.getFormattedEventTime("2020-03-21 09:00:00", "2020-03-22 17:00:00")) + expect(PlanningEventManager.getFormattedEventTime("2020-03-21 09:00", "2020-03-22 17:00")) .toBe('09:00 - 23:59'); - expect(PlanningEventManager.getFormattedEventTime("2020-03-30 20:30:00", "2020-03-30 23:00:00")) + expect(PlanningEventManager.getFormattedEventTime("2020-03-30 20:30", "2020-03-30 23:00")) .toBe('20:30 - 23:00'); }); test('getDateOnlyString', () => { - expect(PlanningEventManager.getDateOnlyString("2020-03-21 09:00:00")).toBe("2020-03-21"); - expect(PlanningEventManager.getDateOnlyString("2021-12-15 09:00:00")).toBe("2021-12-15"); - expect(PlanningEventManager.getDateOnlyString("2021-12-o5 09:00:00")).toBeNull(); + expect(PlanningEventManager.getDateOnlyString("2020-03-21 09:00")).toBe("2020-03-21"); + expect(PlanningEventManager.getDateOnlyString("2021-12-15 09:00")).toBe("2021-12-15"); + expect(PlanningEventManager.getDateOnlyString("2021-12-o5 09:00")).toBeNull(); expect(PlanningEventManager.getDateOnlyString("2021-12-15 09:")).toBeNull(); expect(PlanningEventManager.getDateOnlyString("2021-12-15")).toBeNull(); expect(PlanningEventManager.getDateOnlyString("garbage")).toBeNull(); @@ -83,33 +84,29 @@ test('getDateOnlyString', () => { test('isEventBefore', () => { expect(PlanningEventManager.isEventBefore( - "2020-03-21 09:00:00", "2020-03-21 10:00:00")).toBeTrue(); + "2020-03-21 09:00", "2020-03-21 10:00")).toBeTrue(); expect(PlanningEventManager.isEventBefore( - "2020-03-21 10:00:00", "2020-03-21 10:15:00")).toBeTrue(); + "2020-03-21 10:00", "2020-03-21 10:15")).toBeTrue(); expect(PlanningEventManager.isEventBefore( - "2020-03-21 10:15:05", "2020-03-21 10:15:54")).toBeTrue(); + "2020-03-21 10:15", "2021-03-21 10:15")).toBeTrue(); expect(PlanningEventManager.isEventBefore( - "2020-03-21 10:15:05", "2021-03-21 10:15:05")).toBeTrue(); + "2020-03-21 10:15", "2020-05-21 10:15")).toBeTrue(); expect(PlanningEventManager.isEventBefore( - "2020-03-21 10:15:05", "2020-05-21 10:15:05")).toBeTrue(); - expect(PlanningEventManager.isEventBefore( - "2020-03-21 10:15:05", "2020-03-30 10:15:05")).toBeTrue(); + "2020-03-21 10:15", "2020-03-30 10:15")).toBeTrue(); expect(PlanningEventManager.isEventBefore( - "2020-03-21 10:00:00", "2020-03-21 09:00:00")).toBeFalse(); + "2020-03-21 10:00", "2020-03-21 09:00")).toBeFalse(); expect(PlanningEventManager.isEventBefore( - "2020-03-21 10:15:00", "2020-03-21 10:00:00")).toBeFalse(); + "2020-03-21 10:15", "2020-03-21 10:00")).toBeFalse(); expect(PlanningEventManager.isEventBefore( - "2020-03-21 10:15:54", "2020-03-21 10:15:05")).toBeFalse(); + "2021-03-21 10:15", "2020-03-21 10:15")).toBeFalse(); expect(PlanningEventManager.isEventBefore( - "2021-03-21 10:15:05", "2020-03-21 10:15:05")).toBeFalse(); + "2020-05-21 10:15", "2020-03-21 10:15")).toBeFalse(); expect(PlanningEventManager.isEventBefore( - "2020-05-21 10:15:05", "2020-03-21 10:15:05")).toBeFalse(); - expect(PlanningEventManager.isEventBefore( - "2020-03-30 10:15:05", "2020-03-21 10:15:05")).toBeFalse(); + "2020-03-30 10:15", "2020-03-21 10:15")).toBeFalse(); expect(PlanningEventManager.isEventBefore( - "garbage", "2020-03-21 10:15:05")).toBeFalse(); + "garbage", "2020-03-21 10:15")).toBeFalse(); expect(PlanningEventManager.isEventBefore( undefined, undefined)).toBeFalse(); }); @@ -118,12 +115,16 @@ test('dateToString', () => { let testDate = new Date(); testDate.setFullYear(2020, 2, 21); testDate.setHours(9, 0, 0, 0); - expect(PlanningEventManager.dateToString(testDate)).toBe("2020-03-21 09:00:00"); + expect(PlanningEventManager.dateToString(testDate)).toBe("2020-03-21 09:00"); testDate.setFullYear(2021, 0, 12); testDate.setHours(9, 10, 0, 0); - expect(PlanningEventManager.dateToString(testDate)).toBe("2021-01-12 09:10:00"); + expect(PlanningEventManager.dateToString(testDate)).toBe("2021-01-12 09:10"); testDate.setFullYear(2022, 11, 31); testDate.setHours(9, 10, 15, 0); - expect(PlanningEventManager.dateToString(testDate)).toBe("2022-12-31 09:10:15"); + expect(PlanningEventManager.dateToString(testDate)).toBe("2022-12-31 09:10"); +}); + +test('generateEmptyCalendar', () => { + }); From bf0c81166c801458cbff2a09a5a0edd23c3319f8 Mon Sep 17 00:00:00 2001 From: Arnaud Vergnet Date: Sun, 22 Mar 2020 12:15:16 +0100 Subject: [PATCH 038/398] Improved JSdoc --- utils/PlanningEventManager.js | 75 ++++++++++++++++++++++++----------- 1 file changed, 51 insertions(+), 24 deletions(-) diff --git a/utils/PlanningEventManager.js b/utils/PlanningEventManager.js index 05fba06..c3b64f7 100644 --- a/utils/PlanningEventManager.js +++ b/utils/PlanningEventManager.js @@ -27,14 +27,14 @@ export default class PlanningEventManager { return PlanningEventManager.dateToString(new Date()); } - /** + /** * Checks if the given date is before the other. * * @param event1Date Event 1 date in format YYYY-MM-DD HH:MM * @param event2Date Event 2 date in format YYYY-MM-DD HH:MM * @return {boolean} */ - static isEventBefore(event1Date: string, event2Date: string) { + static isEventBefore(event1Date: string, event2Date: string): boolean { let date1 = PlanningEventManager.stringToDate(event1Date); let date2 = PlanningEventManager.stringToDate(event2Date); if (date1 !== null && date2 !== null) @@ -50,7 +50,7 @@ export default class PlanningEventManager { * @param dateString The string to get the date from * @return {string|null} Date in format YYYY:MM:DD or null if given string is invalid */ - static getDateOnlyString(dateString: string) { + static getDateOnlyString(dateString: string): string | null { if (PlanningEventManager.isEventDateStringFormatValid(dateString)) return dateString.split(" ")[0]; else @@ -64,7 +64,7 @@ export default class PlanningEventManager { * @param dateString The string to check * @return {boolean} */ - static isEventDateStringFormatValid(dateString: ?string) { + static isEventDateStringFormatValid(dateString: ?string): boolean { return dateString !== undefined && dateString !== null && PlanningEventManager.dateRegExp.test(dateString); @@ -107,7 +107,7 @@ export default class PlanningEventManager { * @param date The date object to convert * @return {string} The converted string */ - static dateToString(date: Date) { + static dateToString(date: Date): string { const day = String(date.getDate()).padStart(2, '0'); const month = String(date.getMonth() + 1).padStart(2, '0'); //January is 0! const year = date.getFullYear(); @@ -171,7 +171,15 @@ export default class PlanningEventManager { return true; } - static generateEmptyCalendar(numberOfMonths: number) { + /** + * Generates an object with an empty array for each key. + * Each key is a date string in the format + * YYYY-MM-DD + * + * @param numberOfMonths The number of months to create, starting from the current date + * @return {Object} + */ + static generateEmptyCalendar(numberOfMonths: number): Object { const end = new Date(new Date().setMonth(new Date().getMonth() + numberOfMonths + 1)); let daysOfYear = {}; for (let d = new Date(); d <= end; d.setDate(d.getDate() + 1)) { @@ -183,33 +191,52 @@ export default class PlanningEventManager { return daysOfYear; } - static generateEventAgenda(eventList: Array, numberOfMonths: number) { + /** + * Generates an object with an array of eventObject at each key. + * Each key is a date string in the format + * YYYY-MM-DD. + * + * If no event is available at the given key, the array will be empty + * + * @param eventList The list of events to map to the agenda + * @param numberOfMonths The number of months to create the agenda for + * @return {Object} + */ + static generateEventAgenda(eventList: Array, numberOfMonths: number): Object { let agendaItems = PlanningEventManager.generateEmptyCalendar(numberOfMonths); for (let i = 0; i < eventList.length; i++) { const dateString = PlanningEventManager.getDateOnlyString(eventList[i].date_begin); - console.log(dateString); - if (dateString !== null) - this.pushEventInOrder(agendaItems, eventList[i], dateString); + if (dateString !== null) { + const eventArray = agendaItems[dateString]; + if (eventArray !== undefined) + this.pushEventInOrder(eventArray, eventList[i]); + } + } return agendaItems; } - static pushEventInOrder(agendaItems: Object, event: eventObject, startDate: string) { - if (agendaItems[startDate] !== undefined) { - if (agendaItems[startDate].length === 0) - agendaItems[startDate].push(event); - else { - for (let i = 0; i < agendaItems[startDate].length; i++) { - if (PlanningEventManager.isEventBefore(event.date_begin, agendaItems[startDate][i].date_end)) { - agendaItems[startDate].splice(i, 0, event); - break; - } else if (i === agendaItems[startDate].length - 1) { - agendaItems[startDate].push(event); - break; - } + /** + * Adds events to the given array depending on their starting date. + * + * Events starting before are added at the front. + * + * @param eventArray The array to hold sorted events + * @param event The event to add to the array + */ + static pushEventInOrder(eventArray: Array, event: eventObject): Object { + if (eventArray.length === 0) + eventArray.push(event); + else { + for (let i = 0; i < eventArray.length; i++) { + if (PlanningEventManager.isEventBefore(event.date_begin, eventArray[i].date_end)) { + eventArray.splice(i, 0, event); + break; + } else if (i === eventArray.length - 1) { + eventArray.push(event); + break; } } } - } } From 667ceb0e718ca3df287bf3e1e0b216cb36d41dd6 Mon Sep 17 00:00:00 2001 From: Arnaud Vergnet Date: Sun, 22 Mar 2020 16:05:28 +0100 Subject: [PATCH 039/398] Added remaining tests --- .gitignore | 5 +- .../All_Tests__coverage_.xml | 12 +++ utils/PlanningEventManager.js | 9 +- utils/__test__/PlanningEventManager.test.js | 82 ++++++++++++++++++- 4 files changed, 102 insertions(+), 6 deletions(-) create mode 100644 .idea/runConfigurations/All_Tests__coverage_.xml diff --git a/.gitignore b/.gitignore index 70940e0..aa13269 100644 --- a/.gitignore +++ b/.gitignore @@ -10,6 +10,9 @@ web-build/ web-report/ /.expo-shared/ /coverage/ -/.idea/ /package-lock.json /passwords.json + +!/.idea/ +/.idea/* +!/.idea/runConfigurations diff --git a/.idea/runConfigurations/All_Tests__coverage_.xml b/.idea/runConfigurations/All_Tests__coverage_.xml new file mode 100644 index 0000000..8b07c24 --- /dev/null +++ b/.idea/runConfigurations/All_Tests__coverage_.xml @@ -0,0 +1,12 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/utils/PlanningEventManager.js b/utils/PlanningEventManager.js index c3b64f7..b32d3af 100644 --- a/utils/PlanningEventManager.js +++ b/utils/PlanningEventManager.js @@ -24,7 +24,7 @@ export default class PlanningEventManager { * @return {string} The string representation */ static getCurrentDateString(): string { - return PlanningEventManager.dateToString(new Date()); + return PlanningEventManager.dateToString(new Date(Date.now())); } /** @@ -180,9 +180,10 @@ export default class PlanningEventManager { * @return {Object} */ static generateEmptyCalendar(numberOfMonths: number): Object { - const end = new Date(new Date().setMonth(new Date().getMonth() + numberOfMonths + 1)); + let end = new Date(Date.now()); + end.setMonth(end.getMonth() + numberOfMonths); let daysOfYear = {}; - for (let d = new Date(); d <= end; d.setDate(d.getDate() + 1)) { + for (let d = new Date(Date.now()); d <= end; d.setDate(d.getDate() + 1)) { const dateString = PlanningEventManager.getDateOnlyString( PlanningEventManager.dateToString(new Date(d))); if (dateString !== null) @@ -229,7 +230,7 @@ export default class PlanningEventManager { eventArray.push(event); else { for (let i = 0; i < eventArray.length; i++) { - if (PlanningEventManager.isEventBefore(event.date_begin, eventArray[i].date_end)) { + if (PlanningEventManager.isEventBefore(event.date_begin, eventArray[i].date_begin)) { eventArray.splice(i, 0, event); break; } else if (i === eventArray.length - 1) { diff --git a/utils/__test__/PlanningEventManager.test.js b/utils/__test__/PlanningEventManager.test.js index a125a16..0ec7ed2 100644 --- a/utils/__test__/PlanningEventManager.test.js +++ b/utils/__test__/PlanningEventManager.test.js @@ -94,6 +94,8 @@ test('isEventBefore', () => { expect(PlanningEventManager.isEventBefore( "2020-03-21 10:15", "2020-03-30 10:15")).toBeTrue(); + expect(PlanningEventManager.isEventBefore( + "2020-03-21 10:00", "2020-03-21 10:00")).toBeFalse(); expect(PlanningEventManager.isEventBefore( "2020-03-21 10:00", "2020-03-21 09:00")).toBeFalse(); expect(PlanningEventManager.isEventBefore( @@ -125,6 +127,84 @@ test('dateToString', () => { }); test('generateEmptyCalendar', () => { - + jest.spyOn(Date, 'now') + .mockImplementation(() => + new Date('2020-01-14T00:00:00.000Z').getTime() + ); + let calendar = PlanningEventManager.generateEmptyCalendar(1); + expect(calendar).toHaveProperty("2020-01-14"); + expect(calendar).toHaveProperty("2020-01-20"); + expect(calendar).toHaveProperty("2020-02-10"); + expect(Object.keys(calendar).length).toBe(32); + calendar = PlanningEventManager.generateEmptyCalendar(3); + expect(calendar).toHaveProperty("2020-01-14"); + expect(calendar).toHaveProperty("2020-01-20"); + expect(calendar).toHaveProperty("2020-02-10"); + expect(calendar).toHaveProperty("2020-02-14"); + expect(calendar).toHaveProperty("2020-03-20"); + expect(calendar).toHaveProperty("2020-04-12"); + expect(Object.keys(calendar).length).toBe(92); }); +test('pushEventInOrder', () => { + let eventArray = []; + let event1 = {date_begin: "2020-01-14 09:15"}; + PlanningEventManager.pushEventInOrder(eventArray, event1); + expect(eventArray.length).toBe(1); + expect(eventArray[0]).toBe(event1); + + let event2 = {date_begin: "2020-01-14 10:15"}; + PlanningEventManager.pushEventInOrder(eventArray, event2); + expect(eventArray.length).toBe(2); + expect(eventArray[0]).toBe(event1); + expect(eventArray[1]).toBe(event2); + + let event3 = {date_begin: "2020-01-14 10:15", title: "garbage"}; + PlanningEventManager.pushEventInOrder(eventArray, event3); + expect(eventArray.length).toBe(3); + expect(eventArray[0]).toBe(event1); + expect(eventArray[1]).toBe(event2); + expect(eventArray[2]).toBe(event3); + + let event4 = {date_begin: "2020-01-13 09:00"}; + PlanningEventManager.pushEventInOrder(eventArray, event4); + expect(eventArray.length).toBe(4); + expect(eventArray[0]).toBe(event4); + expect(eventArray[1]).toBe(event1); + expect(eventArray[2]).toBe(event2); + expect(eventArray[3]).toBe(event3); +}); + +test('generateEventAgenda', () => { + jest.spyOn(Date, 'now') + .mockImplementation(() => + new Date('2020-01-14T00:00:00.000Z').getTime() + ); + let eventList = [ + {date_begin: "2020-01-14 09:15"}, + {date_begin: "2020-02-01 09:15"}, + {date_begin: "2020-01-15 09:15"}, + {date_begin: "2020-02-01 09:30"}, + {date_begin: "2020-02-01 08:30"}, + ]; + const calendar = PlanningEventManager.generateEventAgenda(eventList, 2); + expect(calendar["2020-01-14"].length).toBe(1); + expect(calendar["2020-01-14"][0]).toBe(eventList[0]); + expect(calendar["2020-01-15"].length).toBe(1); + expect(calendar["2020-01-15"][0]).toBe(eventList[2]); + expect(calendar["2020-02-01"].length).toBe(3); + expect(calendar["2020-02-01"][0]).toBe(eventList[4]); + expect(calendar["2020-02-01"][1]).toBe(eventList[1]); + expect(calendar["2020-02-01"][2]).toBe(eventList[3]); +}); + +test('getCurrentDateString', () => { + jest.spyOn(Date, 'now') + .mockImplementation(() => { + let date = new Date(); + date.setFullYear(2020, 0, 14); + date.setHours(15, 30, 54, 65); + return date.getTime(); + }); + expect(PlanningEventManager.getCurrentDateString()).toBe('2020-01-14 15:30'); +}); From 38a52a9e951ec69149b67673baabe4e95a3ddcf9 Mon Sep 17 00:00:00 2001 From: Arnaud Vergnet Date: Sun, 22 Mar 2020 16:09:39 +0100 Subject: [PATCH 040/398] Added coverage report --- .gitignore | 1 - coverage/clover.xml | 74 ++ coverage/coverage-final.json | 2 + .../lcov-report/PlanningEventManager.js.html | 809 ++++++++++++++++++ coverage/lcov-report/base.css | 224 +++++ coverage/lcov-report/block-navigation.js | 79 ++ coverage/lcov-report/favicon.png | Bin 0 -> 540 bytes coverage/lcov-report/index.html | 111 +++ coverage/lcov-report/prettify.css | 1 + coverage/lcov-report/prettify.js | 2 + coverage/lcov-report/sort-arrow-sprite.png | Bin 0 -> 209 bytes coverage/lcov-report/sorter.js | 170 ++++ coverage/lcov.info | 135 +++ 13 files changed, 1607 insertions(+), 1 deletion(-) create mode 100644 coverage/clover.xml create mode 100644 coverage/coverage-final.json create mode 100644 coverage/lcov-report/PlanningEventManager.js.html create mode 100644 coverage/lcov-report/base.css create mode 100644 coverage/lcov-report/block-navigation.js create mode 100644 coverage/lcov-report/favicon.png create mode 100644 coverage/lcov-report/index.html create mode 100644 coverage/lcov-report/prettify.css create mode 100644 coverage/lcov-report/prettify.js create mode 100644 coverage/lcov-report/sort-arrow-sprite.png create mode 100644 coverage/lcov-report/sorter.js create mode 100644 coverage/lcov.info diff --git a/.gitignore b/.gitignore index aa13269..465fb62 100644 --- a/.gitignore +++ b/.gitignore @@ -9,7 +9,6 @@ npm-debug.* web-build/ web-report/ /.expo-shared/ -/coverage/ /package-lock.json /passwords.json diff --git a/coverage/clover.xml b/coverage/clover.xml new file mode 100644 index 0000000..8e579e1 --- /dev/null +++ b/coverage/clover.xml @@ -0,0 +1,74 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/coverage/coverage-final.json b/coverage/coverage-final.json new file mode 100644 index 0000000..f9428cd --- /dev/null +++ b/coverage/coverage-final.json @@ -0,0 +1,2 @@ +{"/home/keplyx/expo-projects/application-amicale/utils/PlanningEventManager.js": {"path":"/home/keplyx/expo-projects/application-amicale/utils/PlanningEventManager.js","statementMap":{"0":{"start":{"line":18,"column":24},"end":{"line":18,"column":57}},"1":{"start":{"line":27,"column":8},"end":{"line":27,"column":71}},"2":{"start":{"line":38,"column":20},"end":{"line":38,"column":65}},"3":{"start":{"line":39,"column":20},"end":{"line":39,"column":65}},"4":{"start":{"line":40,"column":8},"end":{"line":43,"column":25}},"5":{"start":{"line":41,"column":12},"end":{"line":41,"column":33}},"6":{"start":{"line":43,"column":12},"end":{"line":43,"column":25}},"7":{"start":{"line":54,"column":8},"end":{"line":57,"column":24}},"8":{"start":{"line":55,"column":12},"end":{"line":55,"column":44}},"9":{"start":{"line":57,"column":12},"end":{"line":57,"column":24}},"10":{"start":{"line":68,"column":8},"end":{"line":70,"column":64}},"11":{"start":{"line":81,"column":19},"end":{"line":81,"column":29}},"12":{"start":{"line":82,"column":8},"end":{"line":98,"column":24}},"13":{"start":{"line":83,"column":30},"end":{"line":83,"column":51}},"14":{"start":{"line":84,"column":28},"end":{"line":84,"column":53}},"15":{"start":{"line":85,"column":28},"end":{"line":85,"column":53}},"16":{"start":{"line":86,"column":12},"end":{"line":90,"column":14}},"17":{"start":{"line":91,"column":12},"end":{"line":96,"column":14}},"18":{"start":{"line":98,"column":12},"end":{"line":98,"column":24}},"19":{"start":{"line":100,"column":8},"end":{"line":100,"column":20}},"20":{"start":{"line":111,"column":20},"end":{"line":111,"column":59}},"21":{"start":{"line":112,"column":22},"end":{"line":112,"column":66}},"22":{"start":{"line":113,"column":21},"end":{"line":113,"column":39}},"23":{"start":{"line":114,"column":22},"end":{"line":114,"column":62}},"24":{"start":{"line":115,"column":24},"end":{"line":115,"column":66}},"25":{"start":{"line":116,"column":8},"end":{"line":116,"column":76}},"26":{"start":{"line":133,"column":27},"end":{"line":133,"column":34}},"27":{"start":{"line":134,"column":24},"end":{"line":134,"column":64}},"28":{"start":{"line":135,"column":22},"end":{"line":135,"column":60}},"29":{"start":{"line":137,"column":8},"end":{"line":150,"column":66}},"30":{"start":{"line":138,"column":12},"end":{"line":139,"column":74}},"31":{"start":{"line":140,"column":12},"end":{"line":146,"column":68}},"32":{"start":{"line":143,"column":16},"end":{"line":143,"column":40}},"33":{"start":{"line":145,"column":16},"end":{"line":146,"column":68}},"34":{"start":{"line":147,"column":15},"end":{"line":150,"column":66}},"35":{"start":{"line":148,"column":12},"end":{"line":150,"column":66}},"36":{"start":{"line":152,"column":8},"end":{"line":152,"column":27}},"37":{"start":{"line":165,"column":8},"end":{"line":171,"column":24}},"38":{"start":{"line":166,"column":12},"end":{"line":169,"column":54}},"39":{"start":{"line":171,"column":12},"end":{"line":171,"column":24}},"40":{"start":{"line":183,"column":18},"end":{"line":183,"column":38}},"41":{"start":{"line":184,"column":8},"end":{"line":184,"column":54}},"42":{"start":{"line":185,"column":25},"end":{"line":185,"column":27}},"43":{"start":{"line":186,"column":8},"end":{"line":191,"column":9}},"44":{"start":{"line":186,"column":21},"end":{"line":186,"column":41}},"45":{"start":{"line":187,"column":31},"end":{"line":188,"column":63}},"46":{"start":{"line":189,"column":12},"end":{"line":190,"column":43}},"47":{"start":{"line":190,"column":16},"end":{"line":190,"column":43}},"48":{"start":{"line":192,"column":8},"end":{"line":192,"column":26}},"49":{"start":{"line":207,"column":26},"end":{"line":207,"column":84}},"50":{"start":{"line":208,"column":8},"end":{"line":216,"column":9}},"51":{"start":{"line":208,"column":21},"end":{"line":208,"column":22}},"52":{"start":{"line":209,"column":31},"end":{"line":209,"column":94}},"53":{"start":{"line":210,"column":12},"end":{"line":214,"column":13}},"54":{"start":{"line":211,"column":35},"end":{"line":211,"column":58}},"55":{"start":{"line":212,"column":16},"end":{"line":213,"column":68}},"56":{"start":{"line":213,"column":20},"end":{"line":213,"column":68}},"57":{"start":{"line":217,"column":8},"end":{"line":217,"column":27}},"58":{"start":{"line":229,"column":8},"end":{"line":241,"column":9}},"59":{"start":{"line":230,"column":12},"end":{"line":230,"column":35}},"60":{"start":{"line":232,"column":12},"end":{"line":240,"column":13}},"61":{"start":{"line":232,"column":25},"end":{"line":232,"column":26}},"62":{"start":{"line":233,"column":16},"end":{"line":239,"column":17}},"63":{"start":{"line":234,"column":20},"end":{"line":234,"column":51}},"64":{"start":{"line":235,"column":20},"end":{"line":235,"column":26}},"65":{"start":{"line":236,"column":23},"end":{"line":239,"column":17}},"66":{"start":{"line":237,"column":20},"end":{"line":237,"column":43}},"67":{"start":{"line":238,"column":20},"end":{"line":238,"column":26}}},"fnMap":{"0":{"name":"(anonymous_0)","decl":{"start":{"line":26,"column":4},"end":{"line":26,"column":5}},"loc":{"start":{"line":26,"column":42},"end":{"line":28,"column":5}},"line":26},"1":{"name":"(anonymous_1)","decl":{"start":{"line":37,"column":4},"end":{"line":37,"column":5}},"loc":{"start":{"line":37,"column":74},"end":{"line":44,"column":5}},"line":37},"2":{"name":"(anonymous_2)","decl":{"start":{"line":53,"column":4},"end":{"line":53,"column":5}},"loc":{"start":{"line":53,"column":64},"end":{"line":58,"column":5}},"line":53},"3":{"name":"(anonymous_3)","decl":{"start":{"line":67,"column":4},"end":{"line":67,"column":5}},"loc":{"start":{"line":67,"column":70},"end":{"line":71,"column":5}},"line":67},"4":{"name":"(anonymous_4)","decl":{"start":{"line":80,"column":4},"end":{"line":80,"column":5}},"loc":{"start":{"line":80,"column":57},"end":{"line":101,"column":5}},"line":80},"5":{"name":"(anonymous_5)","decl":{"start":{"line":110,"column":4},"end":{"line":110,"column":5}},"loc":{"start":{"line":110,"column":44},"end":{"line":117,"column":5}},"line":110},"6":{"name":"(anonymous_6)","decl":{"start":{"line":132,"column":4},"end":{"line":132,"column":5}},"loc":{"start":{"line":132,"column":69},"end":{"line":153,"column":5}},"line":132},"7":{"name":"(anonymous_7)","decl":{"start":{"line":164,"column":4},"end":{"line":164,"column":5}},"loc":{"start":{"line":164,"column":61},"end":{"line":172,"column":5}},"line":164},"8":{"name":"(anonymous_8)","decl":{"start":{"line":182,"column":4},"end":{"line":182,"column":5}},"loc":{"start":{"line":182,"column":65},"end":{"line":193,"column":5}},"line":182},"9":{"name":"(anonymous_9)","decl":{"start":{"line":206,"column":4},"end":{"line":206,"column":5}},"loc":{"start":{"line":206,"column":94},"end":{"line":218,"column":5}},"line":206},"10":{"name":"(anonymous_10)","decl":{"start":{"line":228,"column":4},"end":{"line":228,"column":5}},"loc":{"start":{"line":228,"column":88},"end":{"line":242,"column":5}},"line":228}},"branchMap":{"0":{"loc":{"start":{"line":40,"column":8},"end":{"line":43,"column":25}},"type":"if","locations":[{"start":{"line":40,"column":8},"end":{"line":43,"column":25}},{"start":{"line":40,"column":8},"end":{"line":43,"column":25}}],"line":40},"1":{"loc":{"start":{"line":40,"column":12},"end":{"line":40,"column":44}},"type":"binary-expr","locations":[{"start":{"line":40,"column":12},"end":{"line":40,"column":26}},{"start":{"line":40,"column":30},"end":{"line":40,"column":44}}],"line":40},"2":{"loc":{"start":{"line":54,"column":8},"end":{"line":57,"column":24}},"type":"if","locations":[{"start":{"line":54,"column":8},"end":{"line":57,"column":24}},{"start":{"line":54,"column":8},"end":{"line":57,"column":24}}],"line":54},"3":{"loc":{"start":{"line":68,"column":15},"end":{"line":70,"column":63}},"type":"binary-expr","locations":[{"start":{"line":68,"column":15},"end":{"line":68,"column":39}},{"start":{"line":69,"column":15},"end":{"line":69,"column":34}},{"start":{"line":70,"column":15},"end":{"line":70,"column":63}}],"line":68},"4":{"loc":{"start":{"line":82,"column":8},"end":{"line":98,"column":24}},"type":"if","locations":[{"start":{"line":82,"column":8},"end":{"line":98,"column":24}},{"start":{"line":82,"column":8},"end":{"line":98,"column":24}}],"line":82},"5":{"loc":{"start":{"line":137,"column":8},"end":{"line":150,"column":66}},"type":"if","locations":[{"start":{"line":137,"column":8},"end":{"line":150,"column":66}},{"start":{"line":137,"column":8},"end":{"line":150,"column":66}}],"line":137},"6":{"loc":{"start":{"line":137,"column":12},"end":{"line":137,"column":95}},"type":"binary-expr","locations":[{"start":{"line":137,"column":12},"end":{"line":137,"column":30}},{"start":{"line":137,"column":34},"end":{"line":137,"column":50}},{"start":{"line":137,"column":54},"end":{"line":137,"column":95}}],"line":137},"7":{"loc":{"start":{"line":140,"column":12},"end":{"line":146,"column":68}},"type":"if","locations":[{"start":{"line":140,"column":12},"end":{"line":146,"column":68}},{"start":{"line":140,"column":12},"end":{"line":146,"column":68}}],"line":140},"8":{"loc":{"start":{"line":140,"column":16},"end":{"line":142,"column":58}},"type":"binary-expr","locations":[{"start":{"line":140,"column":16},"end":{"line":140,"column":63}},{"start":{"line":141,"column":19},"end":{"line":141,"column":60}},{"start":{"line":142,"column":19},"end":{"line":142,"column":58}}],"line":140},"9":{"loc":{"start":{"line":147,"column":15},"end":{"line":150,"column":66}},"type":"if","locations":[{"start":{"line":147,"column":15},"end":{"line":150,"column":66}},{"start":{"line":147,"column":15},"end":{"line":150,"column":66}}],"line":147},"10":{"loc":{"start":{"line":165,"column":8},"end":{"line":171,"column":24}},"type":"if","locations":[{"start":{"line":165,"column":8},"end":{"line":171,"column":24}},{"start":{"line":165,"column":8},"end":{"line":171,"column":24}}],"line":165},"11":{"loc":{"start":{"line":165,"column":12},"end":{"line":165,"column":61}},"type":"binary-expr","locations":[{"start":{"line":165,"column":12},"end":{"line":165,"column":37}},{"start":{"line":165,"column":41},"end":{"line":165,"column":61}}],"line":165},"12":{"loc":{"start":{"line":189,"column":12},"end":{"line":190,"column":43}},"type":"if","locations":[{"start":{"line":189,"column":12},"end":{"line":190,"column":43}},{"start":{"line":189,"column":12},"end":{"line":190,"column":43}}],"line":189},"13":{"loc":{"start":{"line":210,"column":12},"end":{"line":214,"column":13}},"type":"if","locations":[{"start":{"line":210,"column":12},"end":{"line":214,"column":13}},{"start":{"line":210,"column":12},"end":{"line":214,"column":13}}],"line":210},"14":{"loc":{"start":{"line":212,"column":16},"end":{"line":213,"column":68}},"type":"if","locations":[{"start":{"line":212,"column":16},"end":{"line":213,"column":68}},{"start":{"line":212,"column":16},"end":{"line":213,"column":68}}],"line":212},"15":{"loc":{"start":{"line":229,"column":8},"end":{"line":241,"column":9}},"type":"if","locations":[{"start":{"line":229,"column":8},"end":{"line":241,"column":9}},{"start":{"line":229,"column":8},"end":{"line":241,"column":9}}],"line":229},"16":{"loc":{"start":{"line":233,"column":16},"end":{"line":239,"column":17}},"type":"if","locations":[{"start":{"line":233,"column":16},"end":{"line":239,"column":17}},{"start":{"line":233,"column":16},"end":{"line":239,"column":17}}],"line":233},"17":{"loc":{"start":{"line":236,"column":23},"end":{"line":239,"column":17}},"type":"if","locations":[{"start":{"line":236,"column":23},"end":{"line":239,"column":17}},{"start":{"line":236,"column":23},"end":{"line":239,"column":17}}],"line":236}},"s":{"0":1,"1":1,"2":19,"3":19,"4":19,"5":17,"6":2,"7":196,"8":192,"9":4,"10":271,"11":62,"12":62,"13":44,"14":44,"15":44,"16":44,"17":44,"18":18,"19":62,"20":189,"21":189,"22":189,"23":189,"24":189,"25":189,"26":7,"27":7,"28":7,"29":7,"30":2,"31":2,"32":1,"33":1,"34":5,"35":1,"36":7,"37":12,"38":10,"39":2,"40":3,"41":3,"42":3,"43":3,"44":3,"45":185,"46":185,"47":185,"48":3,"49":1,"50":1,"51":1,"52":5,"53":5,"54":5,"55":5,"56":5,"57":1,"58":9,"59":4,"60":5,"61":5,"62":6,"63":2,"64":2,"65":4,"66":3,"67":3},"f":{"0":1,"1":19,"2":196,"3":271,"4":62,"5":189,"6":7,"7":12,"8":3,"9":1,"10":9},"b":{"0":[17,2],"1":[19,17],"2":[192,4],"3":[271,265,262],"4":[44,18],"5":[2,5],"6":[7,3,3],"7":[1,1],"8":[2,2,2],"9":[1,4],"10":[10,2],"11":[12,11],"12":[185,0],"13":[5,0],"14":[5,0],"15":[4,5],"16":[2,4],"17":[3,1]},"_coverageSchema":"1a1c01bbd47fc00a2c39e90264f33305004495a9","hash":"108f166f2d84e61aaf8504ff7f7e13e0c6d35992"} +} diff --git a/coverage/lcov-report/PlanningEventManager.js.html b/coverage/lcov-report/PlanningEventManager.js.html new file mode 100644 index 0000000..bef4141 --- /dev/null +++ b/coverage/lcov-report/PlanningEventManager.js.html @@ -0,0 +1,809 @@ + + + + + + Code coverage report for PlanningEventManager.js + + + + + + + + + +
+
+

All files PlanningEventManager.js

+
+ +
+ 100% + Statements + 68/68 +
+ + +
+ 92.31% + Branches + 36/39 +
+ + +
+ 100% + Functions + 11/11 +
+ + +
+ 100% + Lines + 65/65 +
+ + +
+

+ Press n or j to go to the next uncovered block, b, p or k for the previous block. +

+
+
+

+
1 +2 +3 +4 +5 +6 +7 +8 +9 +10 +11 +12 +13 +14 +15 +16 +17 +18 +19 +20 +21 +22 +23 +24 +25 +26 +27 +28 +29 +30 +31 +32 +33 +34 +35 +36 +37 +38 +39 +40 +41 +42 +43 +44 +45 +46 +47 +48 +49 +50 +51 +52 +53 +54 +55 +56 +57 +58 +59 +60 +61 +62 +63 +64 +65 +66 +67 +68 +69 +70 +71 +72 +73 +74 +75 +76 +77 +78 +79 +80 +81 +82 +83 +84 +85 +86 +87 +88 +89 +90 +91 +92 +93 +94 +95 +96 +97 +98 +99 +100 +101 +102 +103 +104 +105 +106 +107 +108 +109 +110 +111 +112 +113 +114 +115 +116 +117 +118 +119 +120 +121 +122 +123 +124 +125 +126 +127 +128 +129 +130 +131 +132 +133 +134 +135 +136 +137 +138 +139 +140 +141 +142 +143 +144 +145 +146 +147 +148 +149 +150 +151 +152 +153 +154 +155 +156 +157 +158 +159 +160 +161 +162 +163 +164 +165 +166 +167 +168 +169 +170 +171 +172 +173 +174 +175 +176 +177 +178 +179 +180 +181 +182 +183 +184 +185 +186 +187 +188 +189 +190 +191 +192 +193 +194 +195 +196 +197 +198 +199 +200 +201 +202 +203 +204 +205 +206 +207 +208 +209 +210 +211 +212 +213 +214 +215 +216 +217 +218 +219 +220 +221 +222 +223 +224 +225 +226 +227 +228 +229 +230 +231 +232 +233 +234 +235 +236 +237 +238 +239 +240 +241 +242 +243 +244  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +1x +  +  +  +  +  +  +  +  +1x +  +  +  +  +  +  +  +  +  +  +19x +19x +19x +17x +  +2x +  +  +  +  +  +  +  +  +  +  +196x +192x +  +4x +  +  +  +  +  +  +  +  +  +  +271x +  +  +  +  +  +  +  +  +  +  +  +  +62x +62x +44x +44x +44x +44x +  +  +  +  +44x +  +  +  +  +  +  +18x +  +62x +  +  +  +  +  +  +  +  +  +  +189x +189x +189x +189x +189x +189x +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +7x +7x +7x +  +7x +2x +  +2x +  +  +1x +  +1x +  +5x +1x +  +  +  +7x +  +  +  +  +  +  +  +  +  +  +  +  +12x +10x +  +  +  +  +2x +  +  +  +  +  +  +  +  +  +  +  +3x +3x +3x +3x +185x +  +185x +185x +  +3x +  +  +  +  +  +  +  +  +  +  +  +  +  +  +1x +1x +5x +5x +5x +5x +5x +  +  +  +1x +  +  +  +  +  +  +  +  +  +  +  +9x +4x +  +5x +6x +2x +2x +4x +3x +3x +  +  +  +  +  + 
// @flow
+ 
+export type eventObject = {
+    id: number,
+    title: string,
+    logo: string,
+    date_begin: string,
+    date_end: string,
+    description: string,
+    club: string,
+    category_id: number,
+    url: string,
+};
+ 
+export default class PlanningEventManager {
+ 
+    // Regex used to check date string validity
+    static dateRegExp = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}$/;
+ 
+    /**
+     * Gets the current day string representation in the format
+     * YYYY-MM-DD
+     *
+     * @return {string} The string representation
+     */
+    static getCurrentDateString(): string {
+        return PlanningEventManager.dateToString(new Date(Date.now()));
+    }
+ 
+    /**
+     * Checks if the given date is before the other.
+     *
+     * @param event1Date Event 1 date in format YYYY-MM-DD HH:MM
+     * @param event2Date Event 2 date in format YYYY-MM-DD HH:MM
+     * @return {boolean}
+     */
+    static isEventBefore(event1Date: string, event2Date: string): boolean {
+        let date1 = PlanningEventManager.stringToDate(event1Date);
+        let date2 = PlanningEventManager.stringToDate(event2Date);
+        if (date1 !== null && date2 !== null)
+            return date1 < date2;
+        else
+            return false;
+    }
+ 
+    /**
+     * Gets only the date part of the given event date string in the format
+     * YYYY-MM-DD HH:MM
+     *
+     * @param dateString The string to get the date from
+     * @return {string|null} Date in format YYYY:MM:DD or null if given string is invalid
+     */
+    static getDateOnlyString(dateString: string): string | null {
+        if (PlanningEventManager.isEventDateStringFormatValid(dateString))
+            return dateString.split(" ")[0];
+        else
+            return null;
+    }
+ 
+    /**
+     * Checks if the given date string is in the format
+     * YYYY-MM-DD HH:MM
+     *
+     * @param dateString The string to check
+     * @return {boolean}
+     */
+    static isEventDateStringFormatValid(dateString: ?string): boolean {
+        return dateString !== undefined
+            && dateString !== null
+            && PlanningEventManager.dateRegExp.test(dateString);
+    }
+ 
+    /**
+     * Converts the given date string to a date object.<br>
+     * Accepted format: YYYY-MM-DD HH:MM
+     *
+     * @param dateString The string to convert
+     * @return {Date|null} The date object or null if the given string is invalid
+     */
+    static stringToDate(dateString: string): Date | null {
+        let date = new Date();
+        if (PlanningEventManager.isEventDateStringFormatValid(dateString)) {
+            let stringArray = dateString.split(' ');
+            let dateArray = stringArray[0].split('-');
+            let timeArray = stringArray[1].split(':');
+            date.setFullYear(
+                parseInt(dateArray[0]),
+                parseInt(dateArray[1]) - 1, // Month range from 0 to 11
+                parseInt(dateArray[2])
+            );
+            date.setHours(
+                parseInt(timeArray[0]),
+                parseInt(timeArray[1]),
+                0,
+                0,
+            );
+        } else
+            date = null;
+ 
+        return date;
+    }
+ 
+    /**
+     * Converts a date object to a string in the format
+     * YYYY-MM-DD HH-MM-SS
+     *
+     * @param date The date object to convert
+     * @return {string} The converted string
+     */
+    static dateToString(date: Date): string {
+        const day = String(date.getDate()).padStart(2, '0');
+        const month = String(date.getMonth() + 1).padStart(2, '0'); //January is 0!
+        const year = date.getFullYear();
+        const hours = String(date.getHours()).padStart(2, '0');
+        const minutes = String(date.getMinutes()).padStart(2, '0');
+        return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes;
+    }
+ 
+    /**
+     * Returns a string corresponding to the event start and end times in the following format:
+     *
+     * HH:MM - HH:MM
+     *
+     * If the end date is not specified or is equal to start time, only start time will be shown.
+     *
+     * If the end date is not on the same day, 23:59 will be shown as end time
+     *
+     * @param start Start time in YYYY-MM-DD HH:MM:SS format
+     * @param end End time in YYYY-MM-DD HH:MM:SS format
+     * @return {string} Formatted string or "/ - /" on error
+     */
+    static getFormattedEventTime(start: string, end: string): string {
+        let formattedStr = '/ - /';
+        let startDate = PlanningEventManager.stringToDate(start);
+        let endDate = PlanningEventManager.stringToDate(end);
+ 
+        if (startDate !== null && endDate !== null && startDate.getTime() !== endDate.getTime()) {
+            formattedStr = String(startDate.getHours()).padStart(2, '0') + ':'
+                + String(startDate.getMinutes()).padStart(2, '0') + ' - ';
+            if (endDate.getFullYear() > startDate.getFullYear()
+                || endDate.getMonth() > startDate.getMonth()
+                || endDate.getDate() > startDate.getDate())
+                formattedStr += '23:59';
+            else
+                formattedStr += String(endDate.getHours()).padStart(2, '0') + ':'
+                    + String(endDate.getMinutes()).padStart(2, '0');
+        } else if (startDate !== null)
+            formattedStr =
+                String(startDate.getHours()).padStart(2, '0') + ':'
+                + String(startDate.getMinutes()).padStart(2, '0');
+ 
+        return formattedStr
+    }
+ 
+    /**
+     * Checks if the given description can be considered empty.
+     * <br>
+     * An empty description is composed only of whitespace, <b>br</b> or <b>p</b> tags
+     *
+     *
+     * @param description The text to check
+     * @return {boolean}
+     */
+    static isDescriptionEmpty(description: ?string): boolean {
+        if (description !== undefined && description !== null) {
+            return description
+                .split('<p>').join('') // Equivalent to a replace all
+                .split('</p>').join('')
+                .split('<br>').join('').trim() === '';
+        } else
+            return true;
+    }
+ 
+    /**
+     * Generates an object with an empty array for each key.
+     * Each key is a date string in the format
+     * YYYY-MM-DD
+     *
+     * @param numberOfMonths The number of months to create, starting from the current date
+     * @return {Object}
+     */
+    static generateEmptyCalendar(numberOfMonths: number): Object {
+        let end = new Date(Date.now());
+        end.setMonth(end.getMonth() + numberOfMonths);
+        let daysOfYear = {};
+        for (let d = new Date(Date.now()); d <= end; d.setDate(d.getDate() + 1)) {
+            const dateString = PlanningEventManager.getDateOnlyString(
+                PlanningEventManager.dateToString(new Date(d)));
+            Eif (dateString !== null)
+                daysOfYear[dateString] = []
+        }
+        return daysOfYear;
+    }
+ 
+    /**
+     * Generates an object with an array of eventObject at each key.
+     * Each key is a date string in the format
+     * YYYY-MM-DD.
+     *
+     * If no event is available at the given key, the array will be empty
+     *
+     * @param eventList The list of events to map to the agenda
+     * @param numberOfMonths The number of months to create the agenda for
+     * @return {Object}
+     */
+    static generateEventAgenda(eventList: Array<eventObject>, numberOfMonths: number): Object {
+        let agendaItems = PlanningEventManager.generateEmptyCalendar(numberOfMonths);
+        for (let i = 0; i < eventList.length; i++) {
+            const dateString = PlanningEventManager.getDateOnlyString(eventList[i].date_begin);
+            Eif (dateString !== null) {
+                const eventArray = agendaItems[dateString];
+                Eif (eventArray !== undefined)
+                    this.pushEventInOrder(eventArray, eventList[i]);
+            }
+ 
+        }
+        return agendaItems;
+    }
+ 
+    /**
+     * Adds events to the given array depending on their starting date.
+     *
+     * Events starting before are added at the front.
+     *
+     * @param eventArray The array to hold sorted events
+     * @param event The event to add to the array
+     */
+    static pushEventInOrder(eventArray: Array<eventObject>, event: eventObject): Object {
+        if (eventArray.length === 0)
+            eventArray.push(event);
+        else {
+            for (let i = 0; i < eventArray.length; i++) {
+                if (PlanningEventManager.isEventBefore(event.date_begin, eventArray[i].date_begin)) {
+                    eventArray.splice(i, 0, event);
+                    break;
+                } else if (i === eventArray.length - 1) {
+                    eventArray.push(event);
+                    break;
+                }
+            }
+        }
+    }
+}
+ 
+ +
+
+ + + + + + + + + \ No newline at end of file diff --git a/coverage/lcov-report/base.css b/coverage/lcov-report/base.css new file mode 100644 index 0000000..f418035 --- /dev/null +++ b/coverage/lcov-report/base.css @@ -0,0 +1,224 @@ +body, html { + margin:0; padding: 0; + height: 100%; +} +body { + font-family: Helvetica Neue, Helvetica, Arial; + font-size: 14px; + color:#333; +} +.small { font-size: 12px; } +*, *:after, *:before { + -webkit-box-sizing:border-box; + -moz-box-sizing:border-box; + box-sizing:border-box; + } +h1 { font-size: 20px; margin: 0;} +h2 { font-size: 14px; } +pre { + font: 12px/1.4 Consolas, "Liberation Mono", Menlo, Courier, monospace; + margin: 0; + padding: 0; + -moz-tab-size: 2; + -o-tab-size: 2; + tab-size: 2; +} +a { color:#0074D9; text-decoration:none; } +a:hover { text-decoration:underline; } +.strong { font-weight: bold; } +.space-top1 { padding: 10px 0 0 0; } +.pad2y { padding: 20px 0; } +.pad1y { padding: 10px 0; } +.pad2x { padding: 0 20px; } +.pad2 { padding: 20px; } +.pad1 { padding: 10px; } +.space-left2 { padding-left:55px; } +.space-right2 { padding-right:20px; } +.center { text-align:center; } +.clearfix { display:block; } +.clearfix:after { + content:''; + display:block; + height:0; + clear:both; + visibility:hidden; + } +.fl { float: left; } +@media only screen and (max-width:640px) { + .col3 { width:100%; max-width:100%; } + .hide-mobile { display:none!important; } +} + +.quiet { + color: #7f7f7f; + color: rgba(0,0,0,0.5); +} +.quiet a { opacity: 0.7; } + +.fraction { + font-family: Consolas, 'Liberation Mono', Menlo, Courier, monospace; + font-size: 10px; + color: #555; + background: #E8E8E8; + padding: 4px 5px; + border-radius: 3px; + vertical-align: middle; +} + +div.path a:link, div.path a:visited { color: #333; } +table.coverage { + border-collapse: collapse; + margin: 10px 0 0 0; + padding: 0; +} + +table.coverage td { + margin: 0; + padding: 0; + vertical-align: top; +} +table.coverage td.line-count { + text-align: right; + padding: 0 5px 0 20px; +} +table.coverage td.line-coverage { + text-align: right; + padding-right: 10px; + min-width:20px; +} + +table.coverage td span.cline-any { + display: inline-block; + padding: 0 5px; + width: 100%; +} +.missing-if-branch { + display: inline-block; + margin-right: 5px; + border-radius: 3px; + position: relative; + padding: 0 4px; + background: #333; + color: yellow; +} + +.skip-if-branch { + display: none; + margin-right: 10px; + position: relative; + padding: 0 4px; + background: #ccc; + color: white; +} +.missing-if-branch .typ, .skip-if-branch .typ { + color: inherit !important; +} +.coverage-summary { + border-collapse: collapse; + width: 100%; +} +.coverage-summary tr { border-bottom: 1px solid #bbb; } +.keyline-all { border: 1px solid #ddd; } +.coverage-summary td, .coverage-summary th { padding: 10px; } +.coverage-summary tbody { border: 1px solid #bbb; } +.coverage-summary td { border-right: 1px solid #bbb; } +.coverage-summary td:last-child { border-right: none; } +.coverage-summary th { + text-align: left; + font-weight: normal; + white-space: nowrap; +} +.coverage-summary th.file { border-right: none !important; } +.coverage-summary th.pct { } +.coverage-summary th.pic, +.coverage-summary th.abs, +.coverage-summary td.pct, +.coverage-summary td.abs { text-align: right; } +.coverage-summary td.file { white-space: nowrap; } +.coverage-summary td.pic { min-width: 120px !important; } +.coverage-summary tfoot td { } + +.coverage-summary .sorter { + height: 10px; + width: 7px; + display: inline-block; + margin-left: 0.5em; + background: url(sort-arrow-sprite.png) no-repeat scroll 0 0 transparent; +} +.coverage-summary .sorted .sorter { + background-position: 0 -20px; +} +.coverage-summary .sorted-desc .sorter { + background-position: 0 -10px; +} +.status-line { height: 10px; } +/* yellow */ +.cbranch-no { background: yellow !important; color: #111; } +/* dark red */ +.red.solid, .status-line.low, .low .cover-fill { background:#C21F39 } +.low .chart { border:1px solid #C21F39 } +.highlighted, +.highlighted .cstat-no, .highlighted .fstat-no, .highlighted .cbranch-no{ + background: #C21F39 !important; +} +/* medium red */ +.cstat-no, .fstat-no, .cbranch-no, .cbranch-no { background:#F6C6CE } +/* light red */ +.low, .cline-no { background:#FCE1E5 } +/* light green */ +.high, .cline-yes { background:rgb(230,245,208) } +/* medium green */ +.cstat-yes { background:rgb(161,215,106) } +/* dark green */ +.status-line.high, .high .cover-fill { background:rgb(77,146,33) } +.high .chart { border:1px solid rgb(77,146,33) } +/* dark yellow (gold) */ +.status-line.medium, .medium .cover-fill { background: #f9cd0b; } +.medium .chart { border:1px solid #f9cd0b; } +/* light yellow */ +.medium { background: #fff4c2; } + +.cstat-skip { background: #ddd; color: #111; } +.fstat-skip { background: #ddd; color: #111 !important; } +.cbranch-skip { background: #ddd !important; color: #111; } + +span.cline-neutral { background: #eaeaea; } + +.coverage-summary td.empty { + opacity: .5; + padding-top: 4px; + padding-bottom: 4px; + line-height: 1; + color: #888; +} + +.cover-fill, .cover-empty { + display:inline-block; + height: 12px; +} +.chart { + line-height: 0; +} +.cover-empty { + background: white; +} +.cover-full { + border-right: none !important; +} +pre.prettyprint { + border: none !important; + padding: 0 !important; + margin: 0 !important; +} +.com { color: #999 !important; } +.ignore-none { color: #999; font-weight: normal; } + +.wrapper { + min-height: 100%; + height: auto !important; + height: 100%; + margin: 0 auto -48px; +} +.footer, .push { + height: 48px; +} diff --git a/coverage/lcov-report/block-navigation.js b/coverage/lcov-report/block-navigation.js new file mode 100644 index 0000000..c7ff5a5 --- /dev/null +++ b/coverage/lcov-report/block-navigation.js @@ -0,0 +1,79 @@ +/* eslint-disable */ +var jumpToCode = (function init() { + // Classes of code we would like to highlight in the file view + var missingCoverageClasses = ['.cbranch-no', '.cstat-no', '.fstat-no']; + + // Elements to highlight in the file listing view + var fileListingElements = ['td.pct.low']; + + // We don't want to select elements that are direct descendants of another match + var notSelector = ':not(' + missingCoverageClasses.join('):not(') + ') > '; // becomes `:not(a):not(b) > ` + + // Selecter that finds elements on the page to which we can jump + var selector = + fileListingElements.join(', ') + + ', ' + + notSelector + + missingCoverageClasses.join(', ' + notSelector); // becomes `:not(a):not(b) > a, :not(a):not(b) > b` + + // The NodeList of matching elements + var missingCoverageElements = document.querySelectorAll(selector); + + var currentIndex; + + function toggleClass(index) { + missingCoverageElements + .item(currentIndex) + .classList.remove('highlighted'); + missingCoverageElements.item(index).classList.add('highlighted'); + } + + function makeCurrent(index) { + toggleClass(index); + currentIndex = index; + missingCoverageElements.item(index).scrollIntoView({ + behavior: 'smooth', + block: 'center', + inline: 'center' + }); + } + + function goToPrevious() { + var nextIndex = 0; + if (typeof currentIndex !== 'number' || currentIndex === 0) { + nextIndex = missingCoverageElements.length - 1; + } else if (missingCoverageElements.length > 1) { + nextIndex = currentIndex - 1; + } + + makeCurrent(nextIndex); + } + + function goToNext() { + var nextIndex = 0; + + if ( + typeof currentIndex === 'number' && + currentIndex < missingCoverageElements.length - 1 + ) { + nextIndex = currentIndex + 1; + } + + makeCurrent(nextIndex); + } + + return function jump(event) { + switch (event.which) { + case 78: // n + case 74: // j + goToNext(); + break; + case 66: // b + case 75: // k + case 80: // p + goToPrevious(); + break; + } + }; +})(); +window.addEventListener('keydown', jumpToCode); diff --git a/coverage/lcov-report/favicon.png b/coverage/lcov-report/favicon.png new file mode 100644 index 0000000000000000000000000000000000000000..6691817834a957c938e7f09640a37a645fb31457 GIT binary patch literal 540 zcmV+%0^|LOP)wSzy{h>9elhJ=8GnBQmf?)AI(^#wDA_`!QTxaXXE&bjxo zTGCc%V|W`}Lwz0rDO*qBbGY-M@aNENIZ1rK?nOAibaC*vb%CF;I_~lkJawax%_+1J zLn(#pv_v{f0`v`Cfp6()7MB(>IoTAiQdKxgxX?VyV&KVZ7b$vn<8|Z<9$35C+G_8SH0x6Y(xB&~bmn%r}ceRwbc0000 + + + + Code coverage report for All files + + + + + + + + + +
+
+

All files

+
+ +
+ 100% + Statements + 68/68 +
+ + +
+ 92.31% + Branches + 36/39 +
+ + +
+ 100% + Functions + 11/11 +
+ + +
+ 100% + Lines + 65/65 +
+ + +
+

+ Press n or j to go to the next uncovered block, b, p or k for the previous block. +

+
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FileStatementsBranchesFunctionsLines
PlanningEventManager.js +
+
100%68/6892.31%36/39100%11/11100%65/65
+
+
+
+ + + + + + + + + \ No newline at end of file diff --git a/coverage/lcov-report/prettify.css b/coverage/lcov-report/prettify.css new file mode 100644 index 0000000..b317a7c --- /dev/null +++ b/coverage/lcov-report/prettify.css @@ -0,0 +1 @@ +.pln{color:#000}@media screen{.str{color:#080}.kwd{color:#008}.com{color:#800}.typ{color:#606}.lit{color:#066}.pun,.opn,.clo{color:#660}.tag{color:#008}.atn{color:#606}.atv{color:#080}.dec,.var{color:#606}.fun{color:red}}@media print,projection{.str{color:#060}.kwd{color:#006;font-weight:bold}.com{color:#600;font-style:italic}.typ{color:#404;font-weight:bold}.lit{color:#044}.pun,.opn,.clo{color:#440}.tag{color:#006;font-weight:bold}.atn{color:#404}.atv{color:#060}}pre.prettyprint{padding:2px;border:1px solid #888}ol.linenums{margin-top:0;margin-bottom:0}li.L0,li.L1,li.L2,li.L3,li.L5,li.L6,li.L7,li.L8{list-style-type:none}li.L1,li.L3,li.L5,li.L7,li.L9{background:#eee} diff --git a/coverage/lcov-report/prettify.js b/coverage/lcov-report/prettify.js new file mode 100644 index 0000000..b322523 --- /dev/null +++ b/coverage/lcov-report/prettify.js @@ -0,0 +1,2 @@ +/* eslint-disable */ +window.PR_SHOULD_USE_CONTINUATION=true;(function(){var h=["break,continue,do,else,for,if,return,while"];var u=[h,"auto,case,char,const,default,double,enum,extern,float,goto,int,long,register,short,signed,sizeof,static,struct,switch,typedef,union,unsigned,void,volatile"];var p=[u,"catch,class,delete,false,import,new,operator,private,protected,public,this,throw,true,try,typeof"];var l=[p,"alignof,align_union,asm,axiom,bool,concept,concept_map,const_cast,constexpr,decltype,dynamic_cast,explicit,export,friend,inline,late_check,mutable,namespace,nullptr,reinterpret_cast,static_assert,static_cast,template,typeid,typename,using,virtual,where"];var x=[p,"abstract,boolean,byte,extends,final,finally,implements,import,instanceof,null,native,package,strictfp,super,synchronized,throws,transient"];var R=[x,"as,base,by,checked,decimal,delegate,descending,dynamic,event,fixed,foreach,from,group,implicit,in,interface,internal,into,is,lock,object,out,override,orderby,params,partial,readonly,ref,sbyte,sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort,var"];var r="all,and,by,catch,class,else,extends,false,finally,for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then,true,try,unless,until,when,while,yes";var w=[p,"debugger,eval,export,function,get,null,set,undefined,var,with,Infinity,NaN"];var s="caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END";var I=[h,"and,as,assert,class,def,del,elif,except,exec,finally,from,global,import,in,is,lambda,nonlocal,not,or,pass,print,raise,try,with,yield,False,True,None"];var f=[h,"alias,and,begin,case,class,def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo,rescue,retry,self,super,then,true,undef,unless,until,when,yield,BEGIN,END"];var H=[h,"case,done,elif,esac,eval,fi,function,in,local,set,then,until"];var A=[l,R,w,s+I,f,H];var e=/^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)/;var C="str";var z="kwd";var j="com";var O="typ";var G="lit";var L="pun";var F="pln";var m="tag";var E="dec";var J="src";var P="atn";var n="atv";var N="nocode";var M="(?:^^\\.?|[+-]|\\!|\\!=|\\!==|\\#|\\%|\\%=|&|&&|&&=|&=|\\(|\\*|\\*=|\\+=|\\,|\\-=|\\->|\\/|\\/=|:|::|\\;|<|<<|<<=|<=|=|==|===|>|>=|>>|>>=|>>>|>>>=|\\?|\\@|\\[|\\^|\\^=|\\^\\^|\\^\\^=|\\{|\\||\\|=|\\|\\||\\|\\|=|\\~|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\\s*";function k(Z){var ad=0;var S=false;var ac=false;for(var V=0,U=Z.length;V122)){if(!(al<65||ag>90)){af.push([Math.max(65,ag)|32,Math.min(al,90)|32])}if(!(al<97||ag>122)){af.push([Math.max(97,ag)&~32,Math.min(al,122)&~32])}}}}af.sort(function(av,au){return(av[0]-au[0])||(au[1]-av[1])});var ai=[];var ap=[NaN,NaN];for(var ar=0;arat[0]){if(at[1]+1>at[0]){an.push("-")}an.push(T(at[1]))}}an.push("]");return an.join("")}function W(al){var aj=al.source.match(new RegExp("(?:\\[(?:[^\\x5C\\x5D]|\\\\[\\s\\S])*\\]|\\\\u[A-Fa-f0-9]{4}|\\\\x[A-Fa-f0-9]{2}|\\\\[0-9]+|\\\\[^ux0-9]|\\(\\?[:!=]|[\\(\\)\\^]|[^\\x5B\\x5C\\(\\)\\^]+)","g"));var ah=aj.length;var an=[];for(var ak=0,am=0;ak=2&&ai==="["){aj[ak]=X(ag)}else{if(ai!=="\\"){aj[ak]=ag.replace(/[a-zA-Z]/g,function(ao){var ap=ao.charCodeAt(0);return"["+String.fromCharCode(ap&~32,ap|32)+"]"})}}}}return aj.join("")}var aa=[];for(var V=0,U=Z.length;V=0;){S[ac.charAt(ae)]=Y}}var af=Y[1];var aa=""+af;if(!ag.hasOwnProperty(aa)){ah.push(af);ag[aa]=null}}ah.push(/[\0-\uffff]/);V=k(ah)})();var X=T.length;var W=function(ah){var Z=ah.sourceCode,Y=ah.basePos;var ad=[Y,F];var af=0;var an=Z.match(V)||[];var aj={};for(var ae=0,aq=an.length;ae=5&&"lang-"===ap.substring(0,5);if(am&&!(ai&&typeof ai[1]==="string")){am=false;ap=J}if(!am){aj[ag]=ap}}var ab=af;af+=ag.length;if(!am){ad.push(Y+ab,ap)}else{var al=ai[1];var ak=ag.indexOf(al);var ac=ak+al.length;if(ai[2]){ac=ag.length-ai[2].length;ak=ac-al.length}var ar=ap.substring(5);B(Y+ab,ag.substring(0,ak),W,ad);B(Y+ab+ak,al,q(ar,al),ad);B(Y+ab+ac,ag.substring(ac),W,ad)}}ah.decorations=ad};return W}function i(T){var W=[],S=[];if(T.tripleQuotedStrings){W.push([C,/^(?:\'\'\'(?:[^\'\\]|\\[\s\S]|\'{1,2}(?=[^\']))*(?:\'\'\'|$)|\"\"\"(?:[^\"\\]|\\[\s\S]|\"{1,2}(?=[^\"]))*(?:\"\"\"|$)|\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$))/,null,"'\""])}else{if(T.multiLineStrings){W.push([C,/^(?:\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$)|\`(?:[^\\\`]|\\[\s\S])*(?:\`|$))/,null,"'\"`"])}else{W.push([C,/^(?:\'(?:[^\\\'\r\n]|\\.)*(?:\'|$)|\"(?:[^\\\"\r\n]|\\.)*(?:\"|$))/,null,"\"'"])}}if(T.verbatimStrings){S.push([C,/^@\"(?:[^\"]|\"\")*(?:\"|$)/,null])}var Y=T.hashComments;if(Y){if(T.cStyleComments){if(Y>1){W.push([j,/^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/,null,"#"])}else{W.push([j,/^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\r\n]*)/,null,"#"])}S.push([C,/^<(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)>/,null])}else{W.push([j,/^#[^\r\n]*/,null,"#"])}}if(T.cStyleComments){S.push([j,/^\/\/[^\r\n]*/,null]);S.push([j,/^\/\*[\s\S]*?(?:\*\/|$)/,null])}if(T.regexLiterals){var X=("/(?=[^/*])(?:[^/\\x5B\\x5C]|\\x5C[\\s\\S]|\\x5B(?:[^\\x5C\\x5D]|\\x5C[\\s\\S])*(?:\\x5D|$))+/");S.push(["lang-regex",new RegExp("^"+M+"("+X+")")])}var V=T.types;if(V){S.push([O,V])}var U=(""+T.keywords).replace(/^ | $/g,"");if(U.length){S.push([z,new RegExp("^(?:"+U.replace(/[\s,]+/g,"|")+")\\b"),null])}W.push([F,/^\s+/,null," \r\n\t\xA0"]);S.push([G,/^@[a-z_$][a-z_$@0-9]*/i,null],[O,/^(?:[@_]?[A-Z]+[a-z][A-Za-z_$@0-9]*|\w+_t\b)/,null],[F,/^[a-z_$][a-z_$@0-9]*/i,null],[G,new RegExp("^(?:0x[a-f0-9]+|(?:\\d(?:_\\d+)*\\d*(?:\\.\\d*)?|\\.\\d\\+)(?:e[+\\-]?\\d+)?)[a-z]*","i"),null,"0123456789"],[F,/^\\[\s\S]?/,null],[L,/^.[^\s\w\.$@\'\"\`\/\#\\]*/,null]);return g(W,S)}var K=i({keywords:A,hashComments:true,cStyleComments:true,multiLineStrings:true,regexLiterals:true});function Q(V,ag){var U=/(?:^|\s)nocode(?:\s|$)/;var ab=/\r\n?|\n/;var ac=V.ownerDocument;var S;if(V.currentStyle){S=V.currentStyle.whiteSpace}else{if(window.getComputedStyle){S=ac.defaultView.getComputedStyle(V,null).getPropertyValue("white-space")}}var Z=S&&"pre"===S.substring(0,3);var af=ac.createElement("LI");while(V.firstChild){af.appendChild(V.firstChild)}var W=[af];function ae(al){switch(al.nodeType){case 1:if(U.test(al.className)){break}if("BR"===al.nodeName){ad(al);if(al.parentNode){al.parentNode.removeChild(al)}}else{for(var an=al.firstChild;an;an=an.nextSibling){ae(an)}}break;case 3:case 4:if(Z){var am=al.nodeValue;var aj=am.match(ab);if(aj){var ai=am.substring(0,aj.index);al.nodeValue=ai;var ah=am.substring(aj.index+aj[0].length);if(ah){var ak=al.parentNode;ak.insertBefore(ac.createTextNode(ah),al.nextSibling)}ad(al);if(!ai){al.parentNode.removeChild(al)}}}break}}function ad(ak){while(!ak.nextSibling){ak=ak.parentNode;if(!ak){return}}function ai(al,ar){var aq=ar?al.cloneNode(false):al;var ao=al.parentNode;if(ao){var ap=ai(ao,1);var an=al.nextSibling;ap.appendChild(aq);for(var am=an;am;am=an){an=am.nextSibling;ap.appendChild(am)}}return aq}var ah=ai(ak.nextSibling,0);for(var aj;(aj=ah.parentNode)&&aj.nodeType===1;){ah=aj}W.push(ah)}for(var Y=0;Y=S){ah+=2}if(V>=ap){Z+=2}}}var t={};function c(U,V){for(var S=V.length;--S>=0;){var T=V[S];if(!t.hasOwnProperty(T)){t[T]=U}else{if(window.console){console.warn("cannot override language handler %s",T)}}}}function q(T,S){if(!(T&&t.hasOwnProperty(T))){T=/^\s*]*(?:>|$)/],[j,/^<\!--[\s\S]*?(?:-\->|$)/],["lang-",/^<\?([\s\S]+?)(?:\?>|$)/],["lang-",/^<%([\s\S]+?)(?:%>|$)/],[L,/^(?:<[%?]|[%?]>)/],["lang-",/^]*>([\s\S]+?)<\/xmp\b[^>]*>/i],["lang-js",/^]*>([\s\S]*?)(<\/script\b[^>]*>)/i],["lang-css",/^]*>([\s\S]*?)(<\/style\b[^>]*>)/i],["lang-in.tag",/^(<\/?[a-z][^<>]*>)/i]]),["default-markup","htm","html","mxml","xhtml","xml","xsl"]);c(g([[F,/^[\s]+/,null," \t\r\n"],[n,/^(?:\"[^\"]*\"?|\'[^\']*\'?)/,null,"\"'"]],[[m,/^^<\/?[a-z](?:[\w.:-]*\w)?|\/?>$/i],[P,/^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],["lang-uq.val",/^=\s*([^>\'\"\s]*(?:[^>\'\"\s\/]|\/(?=\s)))/],[L,/^[=<>\/]+/],["lang-js",/^on\w+\s*=\s*\"([^\"]+)\"/i],["lang-js",/^on\w+\s*=\s*\'([^\']+)\'/i],["lang-js",/^on\w+\s*=\s*([^\"\'>\s]+)/i],["lang-css",/^style\s*=\s*\"([^\"]+)\"/i],["lang-css",/^style\s*=\s*\'([^\']+)\'/i],["lang-css",/^style\s*=\s*([^\"\'>\s]+)/i]]),["in.tag"]);c(g([],[[n,/^[\s\S]+/]]),["uq.val"]);c(i({keywords:l,hashComments:true,cStyleComments:true,types:e}),["c","cc","cpp","cxx","cyc","m"]);c(i({keywords:"null,true,false"}),["json"]);c(i({keywords:R,hashComments:true,cStyleComments:true,verbatimStrings:true,types:e}),["cs"]);c(i({keywords:x,cStyleComments:true}),["java"]);c(i({keywords:H,hashComments:true,multiLineStrings:true}),["bsh","csh","sh"]);c(i({keywords:I,hashComments:true,multiLineStrings:true,tripleQuotedStrings:true}),["cv","py"]);c(i({keywords:s,hashComments:true,multiLineStrings:true,regexLiterals:true}),["perl","pl","pm"]);c(i({keywords:f,hashComments:true,multiLineStrings:true,regexLiterals:true}),["rb"]);c(i({keywords:w,cStyleComments:true,regexLiterals:true}),["js"]);c(i({keywords:r,hashComments:3,cStyleComments:true,multilineStrings:true,tripleQuotedStrings:true,regexLiterals:true}),["coffee"]);c(g([],[[C,/^[\s\S]+/]]),["regex"]);function d(V){var U=V.langExtension;try{var S=a(V.sourceNode);var T=S.sourceCode;V.sourceCode=T;V.spans=S.spans;V.basePos=0;q(U,T)(V);D(V)}catch(W){if("console" in window){console.log(W&&W.stack?W.stack:W)}}}function y(W,V,U){var S=document.createElement("PRE");S.innerHTML=W;if(U){Q(S,U)}var T={langExtension:V,numberLines:U,sourceNode:S};d(T);return S.innerHTML}function b(ad){function Y(af){return document.getElementsByTagName(af)}var ac=[Y("pre"),Y("code"),Y("xmp")];var T=[];for(var aa=0;aa=0){var ah=ai.match(ab);var am;if(!ah&&(am=o(aj))&&"CODE"===am.tagName){ah=am.className.match(ab)}if(ah){ah=ah[1]}var al=false;for(var ak=aj.parentNode;ak;ak=ak.parentNode){if((ak.tagName==="pre"||ak.tagName==="code"||ak.tagName==="xmp")&&ak.className&&ak.className.indexOf("prettyprint")>=0){al=true;break}}if(!al){var af=aj.className.match(/\blinenums\b(?::(\d+))?/);af=af?af[1]&&af[1].length?+af[1]:true:false;if(af){Q(aj,af)}S={langExtension:ah,sourceNode:aj,numberLines:af};d(S)}}}if(X]*(?:>|$)/],[PR.PR_COMMENT,/^<\!--[\s\S]*?(?:-\->|$)/],[PR.PR_PUNCTUATION,/^(?:<[%?]|[%?]>)/],["lang-",/^<\?([\s\S]+?)(?:\?>|$)/],["lang-",/^<%([\s\S]+?)(?:%>|$)/],["lang-",/^]*>([\s\S]+?)<\/xmp\b[^>]*>/i],["lang-handlebars",/^]*type\s*=\s*['"]?text\/x-handlebars-template['"]?\b[^>]*>([\s\S]*?)(<\/script\b[^>]*>)/i],["lang-js",/^]*>([\s\S]*?)(<\/script\b[^>]*>)/i],["lang-css",/^]*>([\s\S]*?)(<\/style\b[^>]*>)/i],["lang-in.tag",/^(<\/?[a-z][^<>]*>)/i],[PR.PR_DECLARATION,/^{{[#^>/]?\s*[\w.][^}]*}}/],[PR.PR_DECLARATION,/^{{&?\s*[\w.][^}]*}}/],[PR.PR_DECLARATION,/^{{{>?\s*[\w.][^}]*}}}/],[PR.PR_COMMENT,/^{{![^}]*}}/]]),["handlebars","hbs"]);PR.registerLangHandler(PR.createSimpleLexer([[PR.PR_PLAIN,/^[ \t\r\n\f]+/,null," \t\r\n\f"]],[[PR.PR_STRING,/^\"(?:[^\n\r\f\\\"]|\\(?:\r\n?|\n|\f)|\\[\s\S])*\"/,null],[PR.PR_STRING,/^\'(?:[^\n\r\f\\\']|\\(?:\r\n?|\n|\f)|\\[\s\S])*\'/,null],["lang-css-str",/^url\(([^\)\"\']*)\)/i],[PR.PR_KEYWORD,/^(?:url|rgb|\!important|@import|@page|@media|@charset|inherit)(?=[^\-\w]|$)/i,null],["lang-css-kw",/^(-?(?:[_a-z]|(?:\\[0-9a-f]+ ?))(?:[_a-z0-9\-]|\\(?:\\[0-9a-f]+ ?))*)\s*:/i],[PR.PR_COMMENT,/^\/\*[^*]*\*+(?:[^\/*][^*]*\*+)*\//],[PR.PR_COMMENT,/^(?:)/],[PR.PR_LITERAL,/^(?:\d+|\d*\.\d+)(?:%|[a-z]+)?/i],[PR.PR_LITERAL,/^#(?:[0-9a-f]{3}){1,2}/i],[PR.PR_PLAIN,/^-?(?:[_a-z]|(?:\\[\da-f]+ ?))(?:[_a-z\d\-]|\\(?:\\[\da-f]+ ?))*/i],[PR.PR_PUNCTUATION,/^[^\s\w\'\"]+/]]),["css"]);PR.registerLangHandler(PR.createSimpleLexer([],[[PR.PR_KEYWORD,/^-?(?:[_a-z]|(?:\\[\da-f]+ ?))(?:[_a-z\d\-]|\\(?:\\[\da-f]+ ?))*/i]]),["css-kw"]);PR.registerLangHandler(PR.createSimpleLexer([],[[PR.PR_STRING,/^[^\)\"\']+/]]),["css-str"]); diff --git a/coverage/lcov-report/sort-arrow-sprite.png b/coverage/lcov-report/sort-arrow-sprite.png new file mode 100644 index 0000000000000000000000000000000000000000..03f704a609c6fd0dbfdac63466a7d7c958b5cbf3 GIT binary patch literal 209 zcmeAS@N?(olHy`uVBq!ia0vp^>_9Bd!3HEZxJ@+%Qj#UE5hcO-X(i=}MX3yqDfvmM z3ZA)%>8U}fi7AzZCsS>Jii$m5978H@?Fn+^JD|Y9yzj{W`447Gxa{7*dM7nnnD-Lb z6^}Hx2)'; + } + } + return cols; + } + // attaches a data attribute to every tr element with an object + // of data values keyed by column name + function loadRowData(tableRow) { + var tableCols = tableRow.querySelectorAll('td'), + colNode, + col, + data = {}, + i, + val; + for (i = 0; i < tableCols.length; i += 1) { + colNode = tableCols[i]; + col = cols[i]; + val = colNode.getAttribute('data-value'); + if (col.type === 'number') { + val = Number(val); + } + data[col.key] = val; + } + return data; + } + // loads all row data + function loadData() { + var rows = getTableBody().querySelectorAll('tr'), + i; + + for (i = 0; i < rows.length; i += 1) { + rows[i].data = loadRowData(rows[i]); + } + } + // sorts the table using the data for the ith column + function sortByIndex(index, desc) { + var key = cols[index].key, + sorter = function(a, b) { + a = a.data[key]; + b = b.data[key]; + return a < b ? -1 : a > b ? 1 : 0; + }, + finalSorter = sorter, + tableBody = document.querySelector('.coverage-summary tbody'), + rowNodes = tableBody.querySelectorAll('tr'), + rows = [], + i; + + if (desc) { + finalSorter = function(a, b) { + return -1 * sorter(a, b); + }; + } + + for (i = 0; i < rowNodes.length; i += 1) { + rows.push(rowNodes[i]); + tableBody.removeChild(rowNodes[i]); + } + + rows.sort(finalSorter); + + for (i = 0; i < rows.length; i += 1) { + tableBody.appendChild(rows[i]); + } + } + // removes sort indicators for current column being sorted + function removeSortIndicators() { + var col = getNthColumn(currentSort.index), + cls = col.className; + + cls = cls.replace(/ sorted$/, '').replace(/ sorted-desc$/, ''); + col.className = cls; + } + // adds sort indicators for current column being sorted + function addSortIndicators() { + getNthColumn(currentSort.index).className += currentSort.desc + ? ' sorted-desc' + : ' sorted'; + } + // adds event listeners for all sorter widgets + function enableUI() { + var i, + el, + ithSorter = function ithSorter(i) { + var col = cols[i]; + + return function() { + var desc = col.defaultDescSort; + + if (currentSort.index === i) { + desc = !currentSort.desc; + } + sortByIndex(i, desc); + removeSortIndicators(); + currentSort.index = i; + currentSort.desc = desc; + addSortIndicators(); + }; + }; + for (i = 0; i < cols.length; i += 1) { + if (cols[i].sortable) { + // add the click event handler on the th so users + // dont have to click on those tiny arrows + el = getNthColumn(i).querySelector('.sorter').parentElement; + if (el.addEventListener) { + el.addEventListener('click', ithSorter(i)); + } else { + el.attachEvent('onclick', ithSorter(i)); + } + } + } + } + // adds sorting functionality to the UI + return function() { + if (!getTable()) { + return; + } + cols = loadColumns(); + loadData(); + addSortIndicators(); + enableUI(); + }; +})(); + +window.addEventListener('load', addSorting); diff --git a/coverage/lcov.info b/coverage/lcov.info new file mode 100644 index 0000000..d6659e6 --- /dev/null +++ b/coverage/lcov.info @@ -0,0 +1,135 @@ +TN: +SF:utils/PlanningEventManager.js +FN:26,(anonymous_0) +FN:37,(anonymous_1) +FN:53,(anonymous_2) +FN:67,(anonymous_3) +FN:80,(anonymous_4) +FN:110,(anonymous_5) +FN:132,(anonymous_6) +FN:164,(anonymous_7) +FN:182,(anonymous_8) +FN:206,(anonymous_9) +FN:228,(anonymous_10) +FNF:11 +FNH:11 +FNDA:1,(anonymous_0) +FNDA:19,(anonymous_1) +FNDA:196,(anonymous_2) +FNDA:271,(anonymous_3) +FNDA:62,(anonymous_4) +FNDA:189,(anonymous_5) +FNDA:7,(anonymous_6) +FNDA:12,(anonymous_7) +FNDA:3,(anonymous_8) +FNDA:1,(anonymous_9) +FNDA:9,(anonymous_10) +DA:18,1 +DA:27,1 +DA:38,19 +DA:39,19 +DA:40,19 +DA:41,17 +DA:43,2 +DA:54,196 +DA:55,192 +DA:57,4 +DA:68,271 +DA:81,62 +DA:82,62 +DA:83,44 +DA:84,44 +DA:85,44 +DA:86,44 +DA:91,44 +DA:98,18 +DA:100,62 +DA:111,189 +DA:112,189 +DA:113,189 +DA:114,189 +DA:115,189 +DA:116,189 +DA:133,7 +DA:134,7 +DA:135,7 +DA:137,7 +DA:138,2 +DA:140,2 +DA:143,1 +DA:145,1 +DA:147,5 +DA:148,1 +DA:152,7 +DA:165,12 +DA:166,10 +DA:171,2 +DA:183,3 +DA:184,3 +DA:185,3 +DA:186,3 +DA:187,185 +DA:189,185 +DA:190,185 +DA:192,3 +DA:207,1 +DA:208,1 +DA:209,5 +DA:210,5 +DA:211,5 +DA:212,5 +DA:213,5 +DA:217,1 +DA:229,9 +DA:230,4 +DA:232,5 +DA:233,6 +DA:234,2 +DA:235,2 +DA:236,4 +DA:237,3 +DA:238,3 +LF:65 +LH:65 +BRDA:40,0,0,17 +BRDA:40,0,1,2 +BRDA:40,1,0,19 +BRDA:40,1,1,17 +BRDA:54,2,0,192 +BRDA:54,2,1,4 +BRDA:68,3,0,271 +BRDA:68,3,1,265 +BRDA:68,3,2,262 +BRDA:82,4,0,44 +BRDA:82,4,1,18 +BRDA:137,5,0,2 +BRDA:137,5,1,5 +BRDA:137,6,0,7 +BRDA:137,6,1,3 +BRDA:137,6,2,3 +BRDA:140,7,0,1 +BRDA:140,7,1,1 +BRDA:140,8,0,2 +BRDA:140,8,1,2 +BRDA:140,8,2,2 +BRDA:147,9,0,1 +BRDA:147,9,1,4 +BRDA:165,10,0,10 +BRDA:165,10,1,2 +BRDA:165,11,0,12 +BRDA:165,11,1,11 +BRDA:189,12,0,185 +BRDA:189,12,1,0 +BRDA:210,13,0,5 +BRDA:210,13,1,0 +BRDA:212,14,0,5 +BRDA:212,14,1,0 +BRDA:229,15,0,4 +BRDA:229,15,1,5 +BRDA:233,16,0,2 +BRDA:233,16,1,4 +BRDA:236,17,0,3 +BRDA:236,17,1,1 +BRF:39 +BRH:36 +end_of_record From 965ddd3cb2616edde586ad6472e9a66c3a5a06b7 Mon Sep 17 00:00:00 2001 From: Arnaud Vergnet Date: Sun, 22 Mar 2020 17:02:00 +0100 Subject: [PATCH 041/398] Removed remaining flow errors --- components/WebSectionList.js | 4 +++- screens/About/AboutDependenciesScreen.js | 8 +++++++- screens/About/DebugScreen.js | 7 ++++++- screens/Planning/PlanningDisplayScreen.js | 10 ++++++---- screens/Tetris/Tetromino.js | 24 +++++++++++------------ utils/AsyncStorageManager.js | 1 + 6 files changed, 35 insertions(+), 19 deletions(-) diff --git a/components/WebSectionList.js b/components/WebSectionList.js index 3e2c58d..c3c96ff 100644 --- a/components/WebSectionList.js +++ b/components/WebSectionList.js @@ -37,7 +37,7 @@ export default class WebSectionList extends React.PureComponent { static defaultProps = { renderSectionHeader: null, stickyHeader: false, - updateData: null, + updateData: 0, }; webDataManager: WebDataManager; @@ -213,7 +213,9 @@ export default class WebSectionList extends React.PureComponent { onRefresh={this.onRefresh} /> } + //$FlowFixMe renderSectionHeader={shouldRenderHeader ? this.props.renderSectionHeader : this.getEmptySectionHeader} + //$FlowFixMe renderItem={isEmpty ? this.getEmptyRenderItem : this.props.renderItem} style={{minHeight: 300, width: '100%'}} stickySectionHeadersEnabled={this.props.stickyHeader} diff --git a/screens/About/AboutDependenciesScreen.js b/screens/About/AboutDependenciesScreen.js index e351280..06cdc33 100644 --- a/screens/About/AboutDependenciesScreen.js +++ b/screens/About/AboutDependenciesScreen.js @@ -5,13 +5,19 @@ import {FlatList} from "react-native"; import packageJson from '../../package'; import {List} from 'react-native-paper'; -function generateListFromObject(object) { +type listItem = { + name: string, + version: string +}; + +function generateListFromObject(object: { [string]: string }): Array { let list = []; let keys = Object.keys(object); let values = Object.values(object); for (let i = 0; i < keys.length; i++) { list.push({name: keys[i], version: values[i]}); } + //$FlowFixMe return list; } diff --git a/screens/About/DebugScreen.js b/screens/About/DebugScreen.js index 7c4700b..404353a 100644 --- a/screens/About/DebugScreen.js +++ b/screens/About/DebugScreen.js @@ -131,7 +131,12 @@ class DebugScreen extends React.Component { {Object.values(this.state.currentPreferences).map((object) => - {DebugScreen.getGeneralItem(() => this.showEditModal(object), undefined, object.key, 'Click to edit')} + {DebugScreen.getGeneralItem( + () => this.showEditModal(object), + undefined, + //$FlowFixMe + object.key, + 'Click to edit')} )} diff --git a/screens/Planning/PlanningDisplayScreen.js b/screens/Planning/PlanningDisplayScreen.js index 220aa19..a2bf9d5 100644 --- a/screens/Planning/PlanningDisplayScreen.js +++ b/screens/Planning/PlanningDisplayScreen.js @@ -33,14 +33,16 @@ class PlanningDisplayScreen extends React.Component { render() { // console.log("rendering planningDisplayScreen"); + let subtitle = PlanningEventManager.getFormattedEventTime( + this.displayData["date_begin"], this.displayData["date_end"]); + let dateString = PlanningEventManager.getDateOnlyString(this.displayData["date_begin"]); + if (dateString !== null) + subtitle += ' | ' + DateManager.getInstance().getTranslatedDate(dateString); return ( {this.displayData.logo !== null ? diff --git a/screens/Tetris/Tetromino.js b/screens/Tetris/Tetromino.js index 19359af..ba2c091 100644 --- a/screens/Tetris/Tetromino.js +++ b/screens/Tetris/Tetromino.js @@ -165,13 +165,13 @@ export default class Tetromino { static colors: Object; - currentType: Object; + currentType: number; currentShape: Object; currentRotation: number; position: Object; colors: Object; - constructor(type: Tetromino.types, colors: Object) { + constructor(type: number, colors: Object) { this.currentType = type; this.currentRotation = 0; this.currentShape = Tetromino.shapes[this.currentRotation][type]; @@ -181,15 +181,15 @@ export default class Tetromino { else this.position.x = 3; this.colors = colors; - Tetromino.colors = { - 0: colors.tetrisI, - 1: colors.tetrisO, - 2: colors.tetrisT, - 3: colors.tetrisS, - 4: colors.tetrisZ, - 5: colors.tetrisJ, - 6: colors.tetrisL, - }; + Tetromino.colors = [ + colors.tetrisI, + colors.tetrisO, + colors.tetrisT, + colors.tetrisS, + colors.tetrisZ, + colors.tetrisJ, + colors.tetrisL, + ]; } getColor() { @@ -210,7 +210,7 @@ export default class Tetromino { return coordinates; } - rotate(isForward) { + rotate(isForward: boolean) { if (isForward) this.currentRotation++; else diff --git a/utils/AsyncStorageManager.js b/utils/AsyncStorageManager.js index 46461ed..6dcac31 100644 --- a/utils/AsyncStorageManager.js +++ b/utils/AsyncStorageManager.js @@ -96,6 +96,7 @@ export default class AsyncStorageManager { let prefKeys = []; // Get all available keys for (let [key, value] of Object.entries(this.preferences)) { + //$FlowFixMe prefKeys.push(value.key); } // Get corresponding values From c75a7dc8fc9385bd4b5232b357902959b3ca7728 Mon Sep 17 00:00:00 2001 From: Arnaud Vergnet Date: Mon, 23 Mar 2020 11:32:50 +0100 Subject: [PATCH 042/398] Improved game organization --- screens/Tetris/GameLogic.js | 101 +++------ screens/Tetris/Piece.js | 85 ++++++++ screens/Tetris/Shapes/BaseShape.js | 65 ++++++ screens/Tetris/Shapes/ShapeI.js | 47 +++++ screens/Tetris/Shapes/ShapeJ.js | 43 ++++ screens/Tetris/Shapes/ShapeL.js | 43 ++++ screens/Tetris/Shapes/ShapeO.js | 39 ++++ screens/Tetris/Shapes/ShapeS.js | 43 ++++ screens/Tetris/Shapes/ShapeT.js | 43 ++++ screens/Tetris/Shapes/ShapeZ.js | 43 ++++ screens/Tetris/TetrisScreen.js | 2 +- screens/Tetris/Tetromino.js | 230 --------------------- screens/Tetris/__tests__/Tetromino.test.js | 104 ++++++++++ 13 files changed, 579 insertions(+), 309 deletions(-) create mode 100644 screens/Tetris/Piece.js create mode 100644 screens/Tetris/Shapes/BaseShape.js create mode 100644 screens/Tetris/Shapes/ShapeI.js create mode 100644 screens/Tetris/Shapes/ShapeJ.js create mode 100644 screens/Tetris/Shapes/ShapeL.js create mode 100644 screens/Tetris/Shapes/ShapeO.js create mode 100644 screens/Tetris/Shapes/ShapeS.js create mode 100644 screens/Tetris/Shapes/ShapeT.js create mode 100644 screens/Tetris/Shapes/ShapeZ.js delete mode 100644 screens/Tetris/Tetromino.js create mode 100644 screens/Tetris/__tests__/Tetromino.test.js diff --git a/screens/Tetris/GameLogic.js b/screens/Tetris/GameLogic.js index 7682e29..684ac65 100644 --- a/screens/Tetris/GameLogic.js +++ b/screens/Tetris/GameLogic.js @@ -1,6 +1,6 @@ // @flow -import Tetromino from "./Tetromino"; +import Piece from "./Piece"; export default class GameLogic { @@ -28,7 +28,7 @@ export default class GameLogic { score: number; level: number; - currentObject: Tetromino; + currentObject: Piece; gameTick: number; gameTickInterval: IntervalID; @@ -39,7 +39,7 @@ export default class GameLogic { autoRepeatActivationDelay: number; autoRepeatDelay: number; - nextPieces: Array; + nextPieces: Array; nextPiecesCount: number; onTick: Function; @@ -62,12 +62,11 @@ export default class GameLogic { this.nextPiecesCount = 3; } - getNextPieces() { + getNextPiecesPreviews() { let finalArray = []; for (let i = 0; i < this.nextPieces.length; i++) { finalArray.push(this.getEmptyGrid(4, 4)); - let coord = this.nextPieces[i].getCellsCoordinates(false); - this.tetrominoToGrid(this.nextPieces[i], coord, finalArray[i]); + this.nextPieces[i].toGrid(finalArray[i], true); } return finalArray; @@ -113,14 +112,8 @@ export default class GameLogic { } getFinalGrid() { - let coord = this.currentObject.getCellsCoordinates(true); let finalGrid = this.getGridCopy(); - for (let i = 0; i < coord.length; i++) { - finalGrid[coord[i].y][coord[i].x] = { - color: this.currentObject.getColor(), - isEmpty: false, - }; - } + this.currentObject.toGrid(finalGrid, false); return finalGrid; } @@ -137,19 +130,9 @@ export default class GameLogic { return canLevel; } - tetrominoToGrid(object: Object, coord : Array, grid: Array>) { - for (let i = 0; i < coord.length; i++) { - grid[coord[i].y][coord[i].x] = { - color: object.getColor(), - isEmpty: false, - }; - } - } - freezeTetromino() { - let coord = this.currentObject.getCellsCoordinates(true); - this.tetrominoToGrid(this.currentObject, coord, this.currentGrid); - this.clearLines(this.getLinesToClear(coord)); + this.currentObject.toGrid(this.currentGrid, false); + this.clearLines(this.getLinesToClear(this.currentObject.getCoordinates())); } clearLines(lines: Array) { @@ -191,52 +174,6 @@ export default class GameLogic { return rows; } - isTetrominoPositionValid() { - let isValid = true; - let coord = this.currentObject.getCellsCoordinates(true); - for (let i = 0; i < coord.length; i++) { - if (coord[i].x >= this.getWidth() - || coord[i].x < 0 - || coord[i].y >= this.getHeight() - || coord[i].y < 0 - || !this.currentGrid[coord[i].y][coord[i].x].isEmpty) { - isValid = false; - break; - } - } - return isValid; - } - - tryMoveTetromino(x: number, y: number) { - if (x > 1) x = 1; // Prevent moving from more than one tile - if (x < -1) x = -1; - if (y > 1) y = 1; - if (y < -1) y = -1; - if (x !== 0 && y !== 0) y = 0; // Prevent diagonal movement - - this.currentObject.move(x, y); - let isValid = this.isTetrominoPositionValid(); - - if (!isValid && x !== 0) - this.currentObject.move(-x, 0); - else if (!isValid && y !== 0) { - this.currentObject.move(0, -y); - this.freezeTetromino(); - this.createTetromino(); - } else - return true; - return false; - } - - tryRotateTetromino() { - this.currentObject.rotate(true); - if (!this.isTetrominoPositionValid()) { - this.currentObject.rotate(false); - return false; - } - return true; - } - setNewGameTick(level: number) { if (level >= GameLogic.levelTicks.length) return; @@ -245,8 +182,15 @@ export default class GameLogic { this.gameTickInterval = setInterval(this.onTick, this.gameTick); } + onFreeze() { + this.freezeTetromino(); + this.createTetromino(); + } + onTick(callback: Function) { - this.tryMoveTetromino(0, 1); + this.currentObject.tryMove(0, 1, + this.currentGrid, this.getWidth(), this.getHeight(), + () => this.onFreeze()); callback(this.score, this.level, this.getFinalGrid()); if (this.canLevelUp()) { this.level++; @@ -281,8 +225,10 @@ export default class GameLogic { movePressedRepeat(isInitial: boolean, callback: Function, x: number, y: number) { if (!this.canUseInput() || !this.isPressedIn) return; - - if (this.tryMoveTetromino(x, y)) { + const moved = this.currentObject.tryMove(x, y, + this.currentGrid, this.getWidth(), this.getHeight(), + () => this.onFreeze()); + if (moved) { if (y === 1) { this.score++; callback(this.getFinalGrid(), this.score); @@ -301,7 +247,7 @@ export default class GameLogic { if (!this.canUseInput()) return; - if (this.tryRotateTetromino()) + if (this.currentObject.tryRotate(this.currentGrid, this.getWidth(), this.getHeight())) callback(this.getFinalGrid()); } @@ -312,15 +258,14 @@ export default class GameLogic { generateNextPieces() { while (this.nextPieces.length < this.nextPiecesCount) { - let shape = Math.floor(Math.random() * 7); - this.nextPieces.push(new Tetromino(shape, this.colors)); + this.nextPieces.push(new Piece(this.colors)); } } createTetromino() { this.pressedOut(); this.recoverNextPiece(); - if (!this.isTetrominoPositionValid()) + if (!this.currentObject.isPositionValid(this.currentGrid, this.getWidth(), this.getHeight())) this.endGame(false); } diff --git a/screens/Tetris/Piece.js b/screens/Tetris/Piece.js new file mode 100644 index 0000000..8818d0c --- /dev/null +++ b/screens/Tetris/Piece.js @@ -0,0 +1,85 @@ +import ShapeL from "./Shapes/ShapeL"; +import ShapeI from "./Shapes/ShapeI"; +import ShapeJ from "./Shapes/ShapeJ"; +import ShapeO from "./Shapes/ShapeO"; +import ShapeS from "./Shapes/ShapeS"; +import ShapeT from "./Shapes/ShapeT"; +import ShapeZ from "./Shapes/ShapeZ"; + +export default class Piece { + + #shapes = [ + ShapeL, + ShapeI, + ShapeJ, + ShapeO, + ShapeS, + ShapeT, + ShapeZ, + ]; + + #currentShape: Object; + + constructor(colors: Object) { + this.#currentShape = new this.#shapes[Math.floor(Math.random() * 7)](colors); + } + + toGrid(grid: Array>, isPreview: boolean) { + const coord = this.#currentShape.getCellsCoordinates(!isPreview); + for (let i = 0; i < coord.length; i++) { + grid[coord[i].y][coord[i].x] = { + color: this.#currentShape.getColor(), + isEmpty: false, + }; + } + } + + isPositionValid(grid, width, height) { + let isValid = true; + const coord = this.#currentShape.getCellsCoordinates(true); + for (let i = 0; i < coord.length; i++) { + if (coord[i].x >= width + || coord[i].x < 0 + || coord[i].y >= height + || coord[i].y < 0 + || !grid[coord[i].y][coord[i].x].isEmpty) { + isValid = false; + break; + } + } + return isValid; + } + + tryMove(x: number, y: number, grid, width, height, freezeCallback: Function) { + if (x > 1) x = 1; // Prevent moving from more than one tile + if (x < -1) x = -1; + if (y > 1) y = 1; + if (y < -1) y = -1; + if (x !== 0 && y !== 0) y = 0; // Prevent diagonal movement + + this.#currentShape.move(x, y); + let isValid = this.isPositionValid(grid, width, height); + + if (!isValid && x !== 0) + this.#currentShape.move(-x, 0); + else if (!isValid && y !== 0) { + this.#currentShape.move(0, -y); + freezeCallback(); + } else + return true; + return false; + } + + tryRotate(grid, width, height) { + this.#currentShape.rotate(true); + if (!this.isPositionValid(grid, width, height)) { + this.#currentShape.rotate(false); + return false; + } + return true; + } + + getCoordinates() { + return this.#currentShape.getCellsCoordinates(true); + } +} diff --git a/screens/Tetris/Shapes/BaseShape.js b/screens/Tetris/Shapes/BaseShape.js new file mode 100644 index 0000000..717ef8a --- /dev/null +++ b/screens/Tetris/Shapes/BaseShape.js @@ -0,0 +1,65 @@ +// @flow + +/** + * Abstract class used to represent a BaseShape. + * Abstract classes do not exist by default in Javascript: we force it by throwing errors in the constructor + * and in methods to implement + */ +export default class BaseShape { + + #currentShape: Array>; + #rotation: number; + position: Object; + + constructor() { + if (this.constructor === BaseShape) + throw new Error("Abstract class can't be instantiated"); + this.#rotation = 0; + this.position = {x: 0, y: 0}; + this.#currentShape = this.getShapes()[this.#rotation]; + } + + getColor(): string { + throw new Error("Method 'getColor()' must be implemented"); + } + + getShapes(): Array>> { + throw new Error("Method 'getShapes()' must be implemented"); + } + + getCurrentShape() { + return this.#currentShape; + } + + getCellsCoordinates(isAbsolute: boolean) { + let coordinates = []; + for (let row = 0; row < this.#currentShape.length; row++) { + for (let col = 0; col < this.#currentShape[row].length; col++) { + if (this.#currentShape[row][col] === 1) + if (isAbsolute) + coordinates.push({x: this.position.x + col, y: this.position.y + row}); + else + coordinates.push({x: col, y: row}); + } + } + return coordinates; + } + + rotate(isForward: boolean) { + if (isForward) + this.#rotation++; + else + this.#rotation--; + if (this.#rotation > 3) + this.#rotation = 0; + else if (this.#rotation < 0) + this.#rotation = 3; + this.#currentShape = this.getShapes()[this.#rotation]; + } + + move(x: number, y: number) { + this.position.x += x; + this.position.y += y; + } + +} diff --git a/screens/Tetris/Shapes/ShapeI.js b/screens/Tetris/Shapes/ShapeI.js new file mode 100644 index 0000000..d3d2205 --- /dev/null +++ b/screens/Tetris/Shapes/ShapeI.js @@ -0,0 +1,47 @@ +// @flow + +import BaseShape from "./BaseShape"; + +export default class ShapeI extends BaseShape { + + #colors: Object; + + constructor(colors: Object) { + super(); + this.position.x = 3; + this.#colors = colors; + } + + getColor(): string { + return this.#colors.tetrisI; + } + + getShapes() { + return [ + [ + [0, 0, 0, 0], + [1, 1, 1, 1], + [0, 0, 0, 0], + [0, 0, 0, 0], + ], + [ + [0, 0, 1, 0], + [0, 0, 1, 0], + [0, 0, 1, 0], + [0, 0, 1, 0], + ], + [ + [0, 0, 0, 0], + [0, 0, 0, 0], + [1, 1, 1, 1], + [0, 0, 0, 0], + ], + [ + [0, 1, 0, 0], + [0, 1, 0, 0], + [0, 1, 0, 0], + [0, 1, 0, 0], + ], + ]; + } +} diff --git a/screens/Tetris/Shapes/ShapeJ.js b/screens/Tetris/Shapes/ShapeJ.js new file mode 100644 index 0000000..391e180 --- /dev/null +++ b/screens/Tetris/Shapes/ShapeJ.js @@ -0,0 +1,43 @@ +// @flow + +import BaseShape from "./BaseShape"; + +export default class ShapeJ extends BaseShape { + + #colors: Object; + + constructor(colors: Object) { + super(); + this.position.x = 3; + this.#colors = colors; + } + + getColor(): string { + return this.#colors.tetrisJ; + } + + getShapes() { + return [ + [ + [1, 0, 0], + [1, 1, 1], + [0, 0, 0], + ], + [ + [0, 1, 1], + [0, 1, 0], + [0, 1, 0], + ], + [ + [0, 0, 0], + [1, 1, 1], + [0, 0, 1], + ], + [ + [0, 1, 0], + [0, 1, 0], + [1, 1, 0], + ], + ]; + } +} diff --git a/screens/Tetris/Shapes/ShapeL.js b/screens/Tetris/Shapes/ShapeL.js new file mode 100644 index 0000000..77562cc --- /dev/null +++ b/screens/Tetris/Shapes/ShapeL.js @@ -0,0 +1,43 @@ +// @flow + +import BaseShape from "./BaseShape"; + +export default class ShapeL extends BaseShape { + + #colors: Object; + + constructor(colors: Object) { + super(); + this.position.x = 3; + this.#colors = colors; + } + + getColor(): string { + return this.#colors.tetrisL; + } + + getShapes() { + return [ + [ + [0, 0, 1], + [1, 1, 1], + [0, 0, 0], + ], + [ + [0, 1, 0], + [0, 1, 0], + [0, 1, 1], + ], + [ + [0, 0, 0], + [1, 1, 1], + [1, 0, 0], + ], + [ + [1, 1, 0], + [0, 1, 0], + [0, 1, 0], + ], + ]; + } +} diff --git a/screens/Tetris/Shapes/ShapeO.js b/screens/Tetris/Shapes/ShapeO.js new file mode 100644 index 0000000..e55b3aa --- /dev/null +++ b/screens/Tetris/Shapes/ShapeO.js @@ -0,0 +1,39 @@ +// @flow + +import BaseShape from "./BaseShape"; + +export default class ShapeO extends BaseShape { + + #colors: Object; + + constructor(colors: Object) { + super(); + this.position.x = 4; + this.#colors = colors; + } + + getColor(): string { + return this.#colors.tetrisO; + } + + getShapes() { + return [ + [ + [1, 1], + [1, 1], + ], + [ + [1, 1], + [1, 1], + ], + [ + [1, 1], + [1, 1], + ], + [ + [1, 1], + [1, 1], + ], + ]; + } +} diff --git a/screens/Tetris/Shapes/ShapeS.js b/screens/Tetris/Shapes/ShapeS.js new file mode 100644 index 0000000..2124a00 --- /dev/null +++ b/screens/Tetris/Shapes/ShapeS.js @@ -0,0 +1,43 @@ +// @flow + +import BaseShape from "./BaseShape"; + +export default class ShapeS extends BaseShape { + + #colors: Object; + + constructor(colors: Object) { + super(); + this.position.x = 3; + this.#colors = colors; + } + + getColor(): string { + return this.#colors.tetrisS; + } + + getShapes() { + return [ + [ + [0, 1, 1], + [1, 1, 0], + [0, 0, 0], + ], + [ + [0, 1, 0], + [0, 1, 1], + [0, 0, 1], + ], + [ + [0, 0, 0], + [0, 1, 1], + [1, 1, 0], + ], + [ + [1, 0, 0], + [1, 1, 0], + [0, 1, 0], + ], + ]; + } +} diff --git a/screens/Tetris/Shapes/ShapeT.js b/screens/Tetris/Shapes/ShapeT.js new file mode 100644 index 0000000..244bfae --- /dev/null +++ b/screens/Tetris/Shapes/ShapeT.js @@ -0,0 +1,43 @@ +// @flow + +import BaseShape from "./BaseShape"; + +export default class ShapeT extends BaseShape { + + #colors: Object; + + constructor(colors: Object) { + super(); + this.position.x = 3; + this.#colors = colors; + } + + getColor(): string { + return this.#colors.tetrisT; + } + + getShapes() { + return [ + [ + [0, 1, 0], + [1, 1, 1], + [0, 0, 0], + ], + [ + [0, 1, 0], + [0, 1, 1], + [0, 1, 0], + ], + [ + [0, 0, 0], + [1, 1, 1], + [0, 1, 0], + ], + [ + [0, 1, 0], + [1, 1, 0], + [0, 1, 0], + ], + ]; + } +} diff --git a/screens/Tetris/Shapes/ShapeZ.js b/screens/Tetris/Shapes/ShapeZ.js new file mode 100644 index 0000000..05a619f --- /dev/null +++ b/screens/Tetris/Shapes/ShapeZ.js @@ -0,0 +1,43 @@ +// @flow + +import BaseShape from "./BaseShape"; + +export default class ShapeZ extends BaseShape { + + #colors: Object; + + constructor(colors: Object) { + super(); + this.position.x = 3; + this.#colors = colors; + } + + getColor(): string { + return this.#colors.tetrisZ; + } + + getShapes() { + return [ + [ + [1, 1, 0], + [0, 1, 1], + [0, 0, 0], + ], + [ + [0, 0, 1], + [0, 1, 1], + [0, 1, 0], + ], + [ + [0, 0, 0], + [1, 1, 0], + [0, 1, 1], + ], + [ + [0, 1, 0], + [1, 1, 0], + [1, 0, 0], + ], + ]; + } +} diff --git a/screens/Tetris/TetrisScreen.js b/screens/Tetris/TetrisScreen.js index d3a4ef1..60d409d 100644 --- a/screens/Tetris/TetrisScreen.js +++ b/screens/Tetris/TetrisScreen.js @@ -253,7 +253,7 @@ class TetrisScreen extends React.Component { right: 5, }}> 3) - this.currentRotation = 0; - else if (this.currentRotation < 0) - this.currentRotation = 3; - this.currentShape = Tetromino.shapes[this.currentRotation][this.currentType]; - } - - move(x: number, y: number) { - this.position.x += x; - this.position.y += y; - } - -} diff --git a/screens/Tetris/__tests__/Tetromino.test.js b/screens/Tetris/__tests__/Tetromino.test.js new file mode 100644 index 0000000..3a4537e --- /dev/null +++ b/screens/Tetris/__tests__/Tetromino.test.js @@ -0,0 +1,104 @@ +import React from 'react'; +import BaseShape from "../Shapes/BaseShape"; +import ShapeI from "../Shapes/ShapeI"; + +const colors = { + tetrisI: '#000001', + tetrisO: '#000002', + tetrisT: '#000003', + tetrisS: '#000004', + tetrisZ: '#000005', + tetrisJ: '#000006', + tetrisL: '#000007', +}; + +test('constructor', () => { + expect(() => new BaseShape()).toThrow(Error); + + let T = new ShapeI(colors); + expect(T.position.y).toBe(0); + expect(T.position.x).toBe(3); + expect(T.getCurrentShape()).toStrictEqual(T.getShapes()[0]); + expect(T.getColor()).toBe(colors.tetrisI); +}); + +test("move", () => { + let T = new ShapeI(colors); + T.move(0, 1); + expect(T.position.x).toBe(3); + expect(T.position.y).toBe(1); + T.move(1, 0); + expect(T.position.x).toBe(4); + expect(T.position.y).toBe(1); + T.move(1, 1); + expect(T.position.x).toBe(5); + expect(T.position.y).toBe(2); + T.move(2, 2); + expect(T.position.x).toBe(7); + expect(T.position.y).toBe(4); + T.move(-1, -1); + expect(T.position.x).toBe(6); + expect(T.position.y).toBe(3); +}); + +test('rotate', () => { + let T = new ShapeI(colors); + T.rotate(true); + expect(T.getCurrentShape()).toStrictEqual(T.getShapes()[1]); + T.rotate(true); + expect(T.getCurrentShape()).toStrictEqual(T.getShapes()[2]); + T.rotate(true); + expect(T.getCurrentShape()).toStrictEqual(T.getShapes()[3]); + T.rotate(true); + expect(T.getCurrentShape()).toStrictEqual(T.getShapes()[0]); + T.rotate(false); + expect(T.getCurrentShape()).toStrictEqual(T.getShapes()[3]); + T.rotate(false); + expect(T.getCurrentShape()).toStrictEqual(T.getShapes()[2]); + T.rotate(false); + expect(T.getCurrentShape()).toStrictEqual(T.getShapes()[1]); + T.rotate(false); + expect(T.getCurrentShape()).toStrictEqual(T.getShapes()[0]); +}); + +test('getCellsCoordinates', () => { + let T = new ShapeI(colors); + expect(T.getCellsCoordinates(false)).toStrictEqual([ + {x: 0, y: 1}, + {x: 1, y: 1}, + {x: 2, y: 1}, + {x: 3, y: 1}, + ]); + expect(T.getCellsCoordinates(true)).toStrictEqual([ + {x: 3, y: 1}, + {x: 4, y: 1}, + {x: 5, y: 1}, + {x: 6, y: 1}, + ]); + T.move(1, 1); + expect(T.getCellsCoordinates(false)).toStrictEqual([ + {x: 0, y: 1}, + {x: 1, y: 1}, + {x: 2, y: 1}, + {x: 3, y: 1}, + ]); + expect(T.getCellsCoordinates(true)).toStrictEqual([ + {x: 4, y: 2}, + {x: 5, y: 2}, + {x: 6, y: 2}, + {x: 7, y: 2}, + ]); + T.rotate(true); + expect(T.getCellsCoordinates(false)).toStrictEqual([ + {x: 2, y: 0}, + {x: 2, y: 1}, + {x: 2, y: 2}, + {x: 2, y: 3}, + ]); + expect(T.getCellsCoordinates(true)).toStrictEqual([ + {x: 6, y: 1}, + {x: 6, y: 2}, + {x: 6, y: 3}, + {x: 6, y: 4}, + ]); +}); From fcec2a3c8a2502f74cdbab795d3800e71bcc9ee0 Mon Sep 17 00:00:00 2001 From: Arnaud Vergnet Date: Mon, 23 Mar 2020 17:30:24 +0100 Subject: [PATCH 043/398] Added tests for Piece class --- .../All_Tests__coverage_.xml | 12 -- screens/Tetris/Piece.js | 6 +- screens/Tetris/__tests__/Piece.test.js | 109 ++++++++++++++++++ .../{Tetromino.test.js => Shape.test.js} | 0 4 files changed, 114 insertions(+), 13 deletions(-) delete mode 100644 .idea/runConfigurations/All_Tests__coverage_.xml create mode 100644 screens/Tetris/__tests__/Piece.test.js rename screens/Tetris/__tests__/{Tetromino.test.js => Shape.test.js} (100%) diff --git a/.idea/runConfigurations/All_Tests__coverage_.xml b/.idea/runConfigurations/All_Tests__coverage_.xml deleted file mode 100644 index 8b07c24..0000000 --- a/.idea/runConfigurations/All_Tests__coverage_.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - - - \ No newline at end of file diff --git a/screens/Tetris/Piece.js b/screens/Tetris/Piece.js index 8818d0c..306b9ef 100644 --- a/screens/Tetris/Piece.js +++ b/screens/Tetris/Piece.js @@ -21,7 +21,11 @@ export default class Piece { #currentShape: Object; constructor(colors: Object) { - this.#currentShape = new this.#shapes[Math.floor(Math.random() * 7)](colors); + this.#currentShape = this.getRandomShape(colors); + } + + getRandomShape(colors: Object) { + return new this.#shapes[Math.floor(Math.random() * 7)](colors); } toGrid(grid: Array>, isPreview: boolean) { diff --git a/screens/Tetris/__tests__/Piece.test.js b/screens/Tetris/__tests__/Piece.test.js new file mode 100644 index 0000000..f750848 --- /dev/null +++ b/screens/Tetris/__tests__/Piece.test.js @@ -0,0 +1,109 @@ +import React from 'react'; +import Piece from "../Piece"; +import ShapeI from "../Shapes/ShapeI"; + +let colors = { + tetrisI: "#000001", + tetrisBackground: "#000002" +}; + +jest.mock("../Shapes/ShapeI"); + +beforeAll(() => { + jest.spyOn(Piece.prototype, 'getRandomShape') + .mockImplementation((colors: Object) => {return new ShapeI(colors);}); +}); + +afterAll(() => { + jest.restoreAllMocks(); +}); + +test('isPositionValid', () => { + let x = 0; + let y = 0; + let spy = jest.spyOn(ShapeI.prototype, 'getCellsCoordinates') + .mockImplementation(() => {return [{x: x, y: y}];}); + let grid = [ + [{isEmpty: true}, {isEmpty: true}], + [{isEmpty: true}, {isEmpty: false}], + ]; + let size = 2; + + let p = new Piece(colors); + expect(p.isPositionValid(grid, size, size)).toBeTrue(); + x = 1; y = 0; + expect(p.isPositionValid(grid, size, size)).toBeTrue(); + x = 0; y = 1; + expect(p.isPositionValid(grid, size, size)).toBeTrue(); + x = 1; y = 1; + expect(p.isPositionValid(grid, size, size)).toBeFalse(); + x = 2; y = 0; + expect(p.isPositionValid(grid, size, size)).toBeFalse(); + x = -1; y = 0; + expect(p.isPositionValid(grid, size, size)).toBeFalse(); + x = 0; y = 2; + expect(p.isPositionValid(grid, size, size)).toBeFalse(); + x = 0; y = -1; + expect(p.isPositionValid(grid, size, size)).toBeFalse(); + + spy.mockRestore(); +}); + +test('tryMove', () => { + let p = new Piece(colors); + const callbackMock = jest.fn(); + let isValid = true; + let spy = jest.spyOn(Piece.prototype, 'isPositionValid') + .mockImplementation(() => {return isValid;}); + + expect(p.tryMove(-1, 0, null, null, null, callbackMock)).toBeTrue(); + isValid = false; + expect(p.tryMove(-1, 0, null, null, null, callbackMock)).toBeFalse(); + isValid = true; + expect(p.tryMove(0, 1, null, null, null, callbackMock)).toBeTrue(); + expect(callbackMock).toBeCalledTimes(0); + + isValid = false; + expect(p.tryMove(0, 1, null, null, null, callbackMock)).toBeFalse(); + expect(callbackMock).toBeCalledTimes(1); + + spy.mockRestore(); +}); + +test('tryRotate', () => { + let p = new Piece(colors); + let isValid = true; + let spy = jest.spyOn(Piece.prototype, 'isPositionValid') + .mockImplementation(() => {return isValid;}); + + expect(p.tryRotate( null, null, null)).toBeTrue(); + isValid = false; + expect(p.tryRotate( null, null, null)).toBeFalse(); + + spy.mockRestore(); +}); + + +test('toGrid', () => { + let x = 0; + let y = 0; + let spy1 = jest.spyOn(ShapeI.prototype, 'getCellsCoordinates') + .mockImplementation(() => {return [{x: x, y: y}];}); + let spy2 = jest.spyOn(ShapeI.prototype, 'getColor') + .mockImplementation(() => {return colors.tetrisI;}); + let grid = [ + [{isEmpty: true}, {isEmpty: true}], + [{isEmpty: true}, {isEmpty: true}], + ]; + let expectedGrid = [ + [{color: colors.tetrisI, isEmpty: false}, {isEmpty: true}], + [{isEmpty: true}, {isEmpty: true}], + ]; + + let p = new Piece(colors); + p.toGrid(grid, true); + expect(grid).toStrictEqual(expectedGrid); + + spy1.mockRestore(); + spy2.mockRestore(); +}); diff --git a/screens/Tetris/__tests__/Tetromino.test.js b/screens/Tetris/__tests__/Shape.test.js similarity index 100% rename from screens/Tetris/__tests__/Tetromino.test.js rename to screens/Tetris/__tests__/Shape.test.js From 8dc620b987b3cf804cfda469c1631707f976f848 Mon Sep 17 00:00:00 2001 From: Arnaud Vergnet Date: Mon, 23 Mar 2020 18:10:45 +0100 Subject: [PATCH 044/398] Moved grid and score logic in separate files --- screens/Tetris/GameLogic.js | 171 +++++++++------------------------ screens/Tetris/GridManager.js | 78 +++++++++++++++ screens/Tetris/ScoreManager.js | 58 +++++++++++ screens/Tetris/TetrisScreen.js | 2 +- 4 files changed, 182 insertions(+), 127 deletions(-) create mode 100644 screens/Tetris/GridManager.js create mode 100644 screens/Tetris/ScoreManager.js diff --git a/screens/Tetris/GameLogic.js b/screens/Tetris/GameLogic.js index 684ac65..7c46513 100644 --- a/screens/Tetris/GameLogic.js +++ b/screens/Tetris/GameLogic.js @@ -1,6 +1,8 @@ // @flow import Piece from "./Piece"; +import ScoreManager from "./ScoreManager"; +import GridManager from "./GridManager"; export default class GameLogic { @@ -15,9 +17,8 @@ export default class GameLogic { 100, ]; - static scoreLinesModifier = [40, 100, 300, 1200]; - - currentGrid: Array>; + scoreManager: ScoreManager; + gridManager: GridManager; height: number; width: number; @@ -25,8 +26,6 @@ export default class GameLogic { gameRunning: boolean; gamePaused: boolean; gameTime: number; - score: number; - level: number; currentObject: Piece; @@ -48,8 +47,6 @@ export default class GameLogic { colors: Object; - levelProgression: number; - constructor(height: number, width: number, colors: Object) { this.height = height; this.width = width; @@ -60,16 +57,8 @@ export default class GameLogic { this.autoRepeatDelay = 50; this.nextPieces = []; this.nextPiecesCount = 3; - } - - getNextPiecesPreviews() { - let finalArray = []; - for (let i = 0; i < this.nextPieces.length; i++) { - finalArray.push(this.getEmptyGrid(4, 4)); - this.nextPieces[i].toGrid(finalArray[i], true); - } - - return finalArray; + this.scoreManager = new ScoreManager(); + this.gridManager = new GridManager(this.getWidth(), this.getHeight(), this.colors); } getHeight(): number { @@ -80,6 +69,10 @@ export default class GameLogic { return this.width; } + getCurrentGrid() { + return this.gridManager.getCurrentGrid(); + } + isGameRunning(): boolean { return this.gameRunning; } @@ -88,90 +81,9 @@ export default class GameLogic { return this.gamePaused; } - getEmptyLine(width: number) { - let line = []; - for (let col = 0; col < width; col++) { - line.push({ - color: this.colors.tetrisBackground, - isEmpty: true, - }); - } - return line; - } - - getEmptyGrid(height: number, width: number) { - let grid = []; - for (let row = 0; row < height; row++) { - grid.push(this.getEmptyLine(width)); - } - return grid; - } - - getGridCopy() { - return JSON.parse(JSON.stringify(this.currentGrid)); - } - - getFinalGrid() { - let finalGrid = this.getGridCopy(); - this.currentObject.toGrid(finalGrid, false); - return finalGrid; - } - - getLinesRemovedPoints(numberRemoved: number) { - if (numberRemoved < 1 || numberRemoved > 4) - return 0; - return GameLogic.scoreLinesModifier[numberRemoved-1] * (this.level + 1); - } - - canLevelUp() { - let canLevel = this.levelProgression > this.level * 5; - if (canLevel) - this.levelProgression -= this.level * 5; - return canLevel; - } - - freezeTetromino() { - this.currentObject.toGrid(this.currentGrid, false); - this.clearLines(this.getLinesToClear(this.currentObject.getCoordinates())); - } - - clearLines(lines: Array) { - lines.sort(); - for (let i = 0; i < lines.length; i++) { - this.currentGrid.splice(lines[i], 1); - this.currentGrid.unshift(this.getEmptyLine(this.getWidth())); - } - switch (lines.length) { - case 1: - this.levelProgression += 1; - break; - case 2: - this.levelProgression += 3; - break; - case 3: - this.levelProgression += 5; - break; - case 4: // Did a tetris ! - this.levelProgression += 8; - break; - } - this.score += this.getLinesRemovedPoints(lines.length); - } - - getLinesToClear(coord: Object) { - let rows = []; - for (let i = 0; i < coord.length; i++) { - let isLineFull = true; - for (let col = 0; col < this.getWidth(); col++) { - if (this.currentGrid[coord[i].y][col].isEmpty) { - isLineFull = false; - break; - } - } - if (isLineFull && rows.indexOf(coord[i].y) === -1) - rows.push(coord[i].y); - } - return rows; + onFreeze() { + this.gridManager.freezeTetromino(this.currentObject, this.scoreManager); + this.createTetromino(); } setNewGameTick(level: number) { @@ -182,20 +94,16 @@ export default class GameLogic { this.gameTickInterval = setInterval(this.onTick, this.gameTick); } - onFreeze() { - this.freezeTetromino(); - this.createTetromino(); - } - onTick(callback: Function) { this.currentObject.tryMove(0, 1, - this.currentGrid, this.getWidth(), this.getHeight(), + this.gridManager.getCurrentGrid(), this.getWidth(), this.getHeight(), () => this.onFreeze()); - callback(this.score, this.level, this.getFinalGrid()); - if (this.canLevelUp()) { - this.level++; - this.setNewGameTick(this.level); - } + callback( + this.scoreManager.getScore(), + this.scoreManager.getLevel(), + this.gridManager.getFinalGrid(this.currentObject)); + if (this.scoreManager.canLevelUp()) + this.setNewGameTick(this.scoreManager.getLevel()); } onClock(callback: Function) { @@ -226,14 +134,14 @@ export default class GameLogic { if (!this.canUseInput() || !this.isPressedIn) return; const moved = this.currentObject.tryMove(x, y, - this.currentGrid, this.getWidth(), this.getHeight(), + this.gridManager.getCurrentGrid(), this.getWidth(), this.getHeight(), () => this.onFreeze()); if (moved) { if (y === 1) { - this.score++; - callback(this.getFinalGrid(), this.score); + this.scoreManager.incrementScore(); + callback(this.gridManager.getFinalGrid(this.currentObject), this.scoreManager.getScore()); } else - callback(this.getFinalGrid()); + callback(this.gridManager.getFinalGrid(this.currentObject)); } this.pressInInterval = setTimeout(() => this.movePressedRepeat(false, callback, x, y), isInitial ? this.autoRepeatActivationDelay : this.autoRepeatDelay); } @@ -247,8 +155,18 @@ export default class GameLogic { if (!this.canUseInput()) return; - if (this.currentObject.tryRotate(this.currentGrid, this.getWidth(), this.getHeight())) - callback(this.getFinalGrid()); + if (this.currentObject.tryRotate(this.gridManager.getCurrentGrid(), this.getWidth(), this.getHeight())) + callback(this.gridManager.getFinalGrid(this.currentObject)); + } + + getNextPiecesPreviews() { + let finalArray = []; + for (let i = 0; i < this.nextPieces.length; i++) { + finalArray.push(this.gridManager.getEmptyGrid(4, 4)); + this.nextPieces[i].toGrid(finalArray[i], true); + } + + return finalArray; } recoverNextPiece() { @@ -265,7 +183,7 @@ export default class GameLogic { createTetromino() { this.pressedOut(); this.recoverNextPiece(); - if (!this.currentObject.isPositionValid(this.currentGrid, this.getWidth(), this.getHeight())) + if (!this.currentObject.isPositionValid(this.gridManager.getCurrentGrid(), this.getWidth(), this.getHeight())) this.endGame(false); } @@ -287,7 +205,7 @@ export default class GameLogic { this.gamePaused = false; clearInterval(this.gameTickInterval); clearInterval(this.gameTimeInterval); - this.endCallback(this.gameTime, this.score, isRestart); + this.endCallback(this.gameTime, this.scoreManager.getScore(), isRestart); } startGame(tickCallback: Function, clockCallback: Function, endCallback: Function) { @@ -296,15 +214,16 @@ export default class GameLogic { this.gameRunning = true; this.gamePaused = false; this.gameTime = 0; - this.score = 0; - this.level = 0; - this.levelProgression = 0; - this.gameTick = GameLogic.levelTicks[this.level]; - this.currentGrid = this.getEmptyGrid(this.getHeight(), this.getWidth()); + this.scoreManager = new ScoreManager(); + this.gameTick = GameLogic.levelTicks[this.scoreManager.getLevel()]; + this.gridManager = new GridManager(this.getWidth(), this.getHeight(), this.colors); this.nextPieces = []; this.generateNextPieces(); this.createTetromino(); - tickCallback(this.score, this.level, this.getFinalGrid()); + tickCallback( + this.scoreManager.getScore(), + this.scoreManager.getLevel(), + this.gridManager.getFinalGrid(this.currentObject)); clockCallback(this.gameTime); this.onTick = this.onTick.bind(this, tickCallback); this.onClock = this.onClock.bind(this, clockCallback); diff --git a/screens/Tetris/GridManager.js b/screens/Tetris/GridManager.js new file mode 100644 index 0000000..21d6ae4 --- /dev/null +++ b/screens/Tetris/GridManager.js @@ -0,0 +1,78 @@ +// @flow + +import Piece from "./Piece"; +import ScoreManager from "./ScoreManager"; + +export default class GridManager { + + #currentGrid: Array>; + #colors: Object; + + constructor(width: number, height: number, colors: Object) { + this.#colors = colors; + this.#currentGrid = this.getEmptyGrid(height, width); + } + + getCurrentGrid() { + return this.#currentGrid; + } + + getEmptyLine(width: number) { + let line = []; + for (let col = 0; col < width; col++) { + line.push({ + color: this.#colors.tetrisBackground, + isEmpty: true, + }); + } + return line; + } + + getEmptyGrid(height: number, width: number) { + let grid = []; + for (let row = 0; row < height; row++) { + grid.push(this.getEmptyLine(width)); + } + return grid; + } + + getGridCopy() { + return JSON.parse(JSON.stringify(this.#currentGrid)); + } + + getFinalGrid(currentObject: Piece) { + let finalGrid = this.getGridCopy(); + currentObject.toGrid(finalGrid, false); + return finalGrid; + } + + clearLines(lines: Array, scoreManager: ScoreManager) { + lines.sort(); + for (let i = 0; i < lines.length; i++) { + this.#currentGrid.splice(lines[i], 1); + this.#currentGrid.unshift(this.getEmptyLine(this.#currentGrid[0].length)); + } + scoreManager.addLinesRemovedPoints(lines.length); + } + + getLinesToClear(coord: Object) { + let rows = []; + for (let i = 0; i < coord.length; i++) { + let isLineFull = true; + for (let col = 0; col < this.#currentGrid[coord[i].y].length; col++) { + if (this.#currentGrid[coord[i].y][col].isEmpty) { + isLineFull = false; + break; + } + } + if (isLineFull && rows.indexOf(coord[i].y) === -1) + rows.push(coord[i].y); + } + return rows; + } + + freezeTetromino(currentObject: Piece, scoreManager: ScoreManager) { + currentObject.toGrid(this.#currentGrid, false); + this.clearLines(this.getLinesToClear(currentObject.getCoordinates()), scoreManager); + } +} diff --git a/screens/Tetris/ScoreManager.js b/screens/Tetris/ScoreManager.js new file mode 100644 index 0000000..353818b --- /dev/null +++ b/screens/Tetris/ScoreManager.js @@ -0,0 +1,58 @@ +// @flow + +export default class ScoreManager { + + #scoreLinesModifier = [40, 100, 300, 1200]; + + #score: number; + #level: number; + #levelProgression: number; + + constructor() { + this.#score = 0; + this.#level = 0; + this.#levelProgression = 0; + } + + getScore(): number { + return this.#score; + } + + getLevel(): number { + return this.#level; + } + + incrementScore() { + this.#score++; + } + + addLinesRemovedPoints(numberRemoved: number) { + if (numberRemoved < 1 || numberRemoved > 4) + return 0; + this.#score += this.#scoreLinesModifier[numberRemoved-1] * (this.#level + 1); + switch (numberRemoved) { + case 1: + this.#levelProgression += 1; + break; + case 2: + this.#levelProgression += 3; + break; + case 3: + this.#levelProgression += 5; + break; + case 4: // Did a tetris ! + this.#levelProgression += 8; + break; + } + } + + canLevelUp() { + let canLevel = this.#levelProgression > this.#level * 5; + if (canLevel){ + this.#levelProgression -= this.#level * 5; + this.#level++; + } + return canLevel; + } + +} diff --git a/screens/Tetris/TetrisScreen.js b/screens/Tetris/TetrisScreen.js index 60d409d..47e92b6 100644 --- a/screens/Tetris/TetrisScreen.js +++ b/screens/Tetris/TetrisScreen.js @@ -37,7 +37,7 @@ class TetrisScreen extends React.Component { this.colors = props.theme.colors; this.logic = new GameLogic(20, 10, this.colors); this.state = { - grid: this.logic.getEmptyGrid(this.logic.getHeight(), this.logic.getWidth()), + grid: this.logic.getCurrentGrid(), gameRunning: false, gameTime: 0, gameScore: 0, From e6fcbdb1652f691bab9b07f4d7897ab712119d5c Mon Sep 17 00:00:00 2001 From: Arnaud Vergnet Date: Mon, 23 Mar 2020 19:31:02 +0100 Subject: [PATCH 045/398] Added score tests --- screens/Tetris/ScoreManager.js | 4 ++ screens/Tetris/__tests__/ScoreManager.test.js | 71 +++++++++++++++++++ 2 files changed, 75 insertions(+) create mode 100644 screens/Tetris/__tests__/ScoreManager.test.js diff --git a/screens/Tetris/ScoreManager.js b/screens/Tetris/ScoreManager.js index 353818b..263d27b 100644 --- a/screens/Tetris/ScoreManager.js +++ b/screens/Tetris/ScoreManager.js @@ -22,6 +22,10 @@ export default class ScoreManager { return this.#level; } + getLevelProgression(): number { + return this.#levelProgression; + } + incrementScore() { this.#score++; } diff --git a/screens/Tetris/__tests__/ScoreManager.test.js b/screens/Tetris/__tests__/ScoreManager.test.js new file mode 100644 index 0000000..e84654d --- /dev/null +++ b/screens/Tetris/__tests__/ScoreManager.test.js @@ -0,0 +1,71 @@ +import React from 'react'; +import ScoreManager from "../ScoreManager"; + + +test('incrementScore', () => { + let scoreManager = new ScoreManager(); + expect(scoreManager.getScore()).toBe(0); + scoreManager.incrementScore(); + expect(scoreManager.getScore()).toBe(1); +}); + +test('addLinesRemovedPoints', () => { + let scoreManager = new ScoreManager(); + scoreManager.addLinesRemovedPoints(0); + scoreManager.addLinesRemovedPoints(5); + expect(scoreManager.getScore()).toBe(0); + expect(scoreManager.getLevelProgression()).toBe(0); + + scoreManager.addLinesRemovedPoints(1); + expect(scoreManager.getScore()).toBe(40); + expect(scoreManager.getLevelProgression()).toBe(1); + + scoreManager.addLinesRemovedPoints(2); + expect(scoreManager.getScore()).toBe(140); + expect(scoreManager.getLevelProgression()).toBe(4); + + scoreManager.addLinesRemovedPoints(3); + expect(scoreManager.getScore()).toBe(440); + expect(scoreManager.getLevelProgression()).toBe(9); + + scoreManager.addLinesRemovedPoints(4); + expect(scoreManager.getScore()).toBe(1640); + expect(scoreManager.getLevelProgression()).toBe(17); +}); + +test('canLevelUp', () => { + let scoreManager = new ScoreManager(); + expect(scoreManager.canLevelUp()).toBeFalse(); + expect(scoreManager.getLevel()).toBe(0); + expect(scoreManager.getLevelProgression()).toBe(0); + + scoreManager.addLinesRemovedPoints(1); + expect(scoreManager.canLevelUp()).toBeTrue(); + expect(scoreManager.getLevel()).toBe(1); + expect(scoreManager.getLevelProgression()).toBe(1); + + scoreManager.addLinesRemovedPoints(1); + expect(scoreManager.canLevelUp()).toBeFalse(); + expect(scoreManager.getLevel()).toBe(1); + expect(scoreManager.getLevelProgression()).toBe(2); + + scoreManager.addLinesRemovedPoints(2); + expect(scoreManager.canLevelUp()).toBeFalse(); + expect(scoreManager.getLevel()).toBe(1); + expect(scoreManager.getLevelProgression()).toBe(5); + + scoreManager.addLinesRemovedPoints(1); + expect(scoreManager.canLevelUp()).toBeTrue(); + expect(scoreManager.getLevel()).toBe(2); + expect(scoreManager.getLevelProgression()).toBe(1); + + scoreManager.addLinesRemovedPoints(4); + expect(scoreManager.canLevelUp()).toBeFalse(); + expect(scoreManager.getLevel()).toBe(2); + expect(scoreManager.getLevelProgression()).toBe(9); + + scoreManager.addLinesRemovedPoints(2); + expect(scoreManager.canLevelUp()).toBeTrue(); + expect(scoreManager.getLevel()).toBe(3); + expect(scoreManager.getLevelProgression()).toBe(2); +}); From 3d45bc62b830c145dc0609e5ab333395f7f04b55 Mon Sep 17 00:00:00 2001 From: Arnaud Vergnet Date: Tue, 24 Mar 2020 10:43:05 +0100 Subject: [PATCH 046/398] Added more tests and improved performance by not making deep copies of the grid --- screens/Tetris/GameLogic.js | 10 ++-- screens/Tetris/GridManager.js | 15 ++---- screens/Tetris/Piece.js | 32 +++++++++--- screens/Tetris/__tests__/GridManager.test.js | 34 ++++++++++++ screens/Tetris/__tests__/Piece.test.js | 54 ++++++++++++++++++-- 5 files changed, 116 insertions(+), 29 deletions(-) create mode 100644 screens/Tetris/__tests__/GridManager.test.js diff --git a/screens/Tetris/GameLogic.js b/screens/Tetris/GameLogic.js index 7c46513..b3de919 100644 --- a/screens/Tetris/GameLogic.js +++ b/screens/Tetris/GameLogic.js @@ -101,7 +101,7 @@ export default class GameLogic { callback( this.scoreManager.getScore(), this.scoreManager.getLevel(), - this.gridManager.getFinalGrid(this.currentObject)); + this.gridManager.getCurrentGrid()); if (this.scoreManager.canLevelUp()) this.setNewGameTick(this.scoreManager.getLevel()); } @@ -139,9 +139,9 @@ export default class GameLogic { if (moved) { if (y === 1) { this.scoreManager.incrementScore(); - callback(this.gridManager.getFinalGrid(this.currentObject), this.scoreManager.getScore()); + callback(this.gridManager.getCurrentGrid(), this.scoreManager.getScore()); } else - callback(this.gridManager.getFinalGrid(this.currentObject)); + callback(this.gridManager.getCurrentGrid()); } this.pressInInterval = setTimeout(() => this.movePressedRepeat(false, callback, x, y), isInitial ? this.autoRepeatActivationDelay : this.autoRepeatDelay); } @@ -156,7 +156,7 @@ export default class GameLogic { return; if (this.currentObject.tryRotate(this.gridManager.getCurrentGrid(), this.getWidth(), this.getHeight())) - callback(this.gridManager.getFinalGrid(this.currentObject)); + callback(this.gridManager.getCurrentGrid()); } getNextPiecesPreviews() { @@ -223,7 +223,7 @@ export default class GameLogic { tickCallback( this.scoreManager.getScore(), this.scoreManager.getLevel(), - this.gridManager.getFinalGrid(this.currentObject)); + this.gridManager.getCurrentGrid()); clockCallback(this.gameTime); this.onTick = this.onTick.bind(this, tickCallback); this.onClock = this.onClock.bind(this, clockCallback); diff --git a/screens/Tetris/GridManager.js b/screens/Tetris/GridManager.js index 21d6ae4..ced9a07 100644 --- a/screens/Tetris/GridManager.js +++ b/screens/Tetris/GridManager.js @@ -3,9 +3,11 @@ import Piece from "./Piece"; import ScoreManager from "./ScoreManager"; +export type grid = Array>; + export default class GridManager { - #currentGrid: Array>; + #currentGrid: grid; #colors: Object; constructor(width: number, height: number, colors: Object) { @@ -36,16 +38,6 @@ export default class GridManager { return grid; } - getGridCopy() { - return JSON.parse(JSON.stringify(this.#currentGrid)); - } - - getFinalGrid(currentObject: Piece) { - let finalGrid = this.getGridCopy(); - currentObject.toGrid(finalGrid, false); - return finalGrid; - } - clearLines(lines: Array, scoreManager: ScoreManager) { lines.sort(); for (let i = 0; i < lines.length; i++) { @@ -72,7 +64,6 @@ export default class GridManager { } freezeTetromino(currentObject: Piece, scoreManager: ScoreManager) { - currentObject.toGrid(this.#currentGrid, false); this.clearLines(this.getLinesToClear(currentObject.getCoordinates()), scoreManager); } } diff --git a/screens/Tetris/Piece.js b/screens/Tetris/Piece.js index 306b9ef..86cbc68 100644 --- a/screens/Tetris/Piece.js +++ b/screens/Tetris/Piece.js @@ -17,17 +17,28 @@ export default class Piece { ShapeT, ShapeZ, ]; - #currentShape: Object; + #colors: Object; constructor(colors: Object) { this.#currentShape = this.getRandomShape(colors); + this.#colors = colors; } getRandomShape(colors: Object) { return new this.#shapes[Math.floor(Math.random() * 7)](colors); } + removeFromGrid(grid) { + const coord = this.#currentShape.getCellsCoordinates(true); + for (let i = 0; i < coord.length; i++) { + grid[coord[i].y][coord[i].x] = { + color: this.#colors.tetrisBackground, + isEmpty: true, + }; + } + } + toGrid(grid: Array>, isPreview: boolean) { const coord = this.#currentShape.getCellsCoordinates(!isPreview); for (let i = 0; i < coord.length; i++) { @@ -61,25 +72,30 @@ export default class Piece { if (y < -1) y = -1; if (x !== 0 && y !== 0) y = 0; // Prevent diagonal movement + this.removeFromGrid(grid); this.#currentShape.move(x, y); let isValid = this.isPositionValid(grid, width, height); + let shouldFreeze = false; - if (!isValid && x !== 0) - this.#currentShape.move(-x, 0); - else if (!isValid && y !== 0) { - this.#currentShape.move(0, -y); + if (!isValid) + this.#currentShape.move(-x, -y); + + shouldFreeze = !isValid && y !== 0; + this.toGrid(grid, false); + if (shouldFreeze) freezeCallback(); - } else - return true; - return false; + return isValid; } tryRotate(grid, width, height) { + this.removeFromGrid(grid); this.#currentShape.rotate(true); if (!this.isPositionValid(grid, width, height)) { this.#currentShape.rotate(false); + this.toGrid(grid, false); return false; } + this.toGrid(grid, false); return true; } diff --git a/screens/Tetris/__tests__/GridManager.test.js b/screens/Tetris/__tests__/GridManager.test.js new file mode 100644 index 0000000..43d1f0e --- /dev/null +++ b/screens/Tetris/__tests__/GridManager.test.js @@ -0,0 +1,34 @@ +import React from 'react'; +import GridManager from "../GridManager"; + +let colors = { + tetrisBackground: "#000002" +}; + +test('getEmptyLine', () => { + let g = new GridManager(2, 2, colors); + expect(g.getEmptyLine(2)).toStrictEqual([ + {color: colors.tetrisBackground, isEmpty: true}, + {color: colors.tetrisBackground, isEmpty: true}, + ]); + + expect(g.getEmptyLine(-1)).toStrictEqual([]); +}); + +test('getEmptyGrid', () => { + let g = new GridManager(2, 2, colors); + expect(g.getEmptyGrid(2, 2)).toStrictEqual([ + [ + {color: colors.tetrisBackground, isEmpty: true}, + {color: colors.tetrisBackground, isEmpty: true}, + ], + [ + {color: colors.tetrisBackground, isEmpty: true}, + {color: colors.tetrisBackground, isEmpty: true}, + ], + ]); + + expect(g.getEmptyGrid(-1, 2)).toStrictEqual([]); + expect(g.getEmptyGrid(2, -1)).toStrictEqual([[], []]); +}); + diff --git a/screens/Tetris/__tests__/Piece.test.js b/screens/Tetris/__tests__/Piece.test.js index f750848..da5d7b2 100644 --- a/screens/Tetris/__tests__/Piece.test.js +++ b/screens/Tetris/__tests__/Piece.test.js @@ -53,8 +53,12 @@ test('tryMove', () => { let p = new Piece(colors); const callbackMock = jest.fn(); let isValid = true; - let spy = jest.spyOn(Piece.prototype, 'isPositionValid') + let spy1 = jest.spyOn(Piece.prototype, 'isPositionValid') .mockImplementation(() => {return isValid;}); + let spy2 = jest.spyOn(Piece.prototype, 'removeFromGrid') + .mockImplementation(() => {}); + let spy3 = jest.spyOn(Piece.prototype, 'toGrid') + .mockImplementation(() => {}); expect(p.tryMove(-1, 0, null, null, null, callbackMock)).toBeTrue(); isValid = false; @@ -67,20 +71,34 @@ test('tryMove', () => { expect(p.tryMove(0, 1, null, null, null, callbackMock)).toBeFalse(); expect(callbackMock).toBeCalledTimes(1); - spy.mockRestore(); + expect(spy2).toBeCalledTimes(4); + expect(spy3).toBeCalledTimes(4); + + spy1.mockRestore(); + spy2.mockRestore(); + spy3.mockRestore(); }); test('tryRotate', () => { let p = new Piece(colors); let isValid = true; - let spy = jest.spyOn(Piece.prototype, 'isPositionValid') + let spy1 = jest.spyOn(Piece.prototype, 'isPositionValid') .mockImplementation(() => {return isValid;}); + let spy2 = jest.spyOn(Piece.prototype, 'removeFromGrid') + .mockImplementation(() => {}); + let spy3 = jest.spyOn(Piece.prototype, 'toGrid') + .mockImplementation(() => {}); expect(p.tryRotate( null, null, null)).toBeTrue(); isValid = false; expect(p.tryRotate( null, null, null)).toBeFalse(); - spy.mockRestore(); + expect(spy2).toBeCalledTimes(2); + expect(spy3).toBeCalledTimes(2); + + spy1.mockRestore(); + spy2.mockRestore(); + spy3.mockRestore(); }); @@ -107,3 +125,31 @@ test('toGrid', () => { spy1.mockRestore(); spy2.mockRestore(); }); + +test('removeFromGrid', () => { + let gridOld = [ + [ + {color: colors.tetrisI, isEmpty: false}, + {color: colors.tetrisI, isEmpty: false}, + {color: colors.tetrisBackground, isEmpty: true}, + ], + ]; + let gridNew = [ + [ + {color: colors.tetrisBackground, isEmpty: true}, + {color: colors.tetrisBackground, isEmpty: true}, + {color: colors.tetrisBackground, isEmpty: true}, + ], + ]; + let oldCoord = [{x: 0, y: 0}, {x: 1, y: 0}]; + 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); + p.removeFromGrid(gridOld); + expect(gridOld).toStrictEqual(gridNew); + + spy1.mockRestore(); + spy2.mockRestore(); +}); From 931d7b0fe6d311cbbf0bf9d363c28331ee6d7f93 Mon Sep 17 00:00:00 2001 From: Arnaud Vergnet Date: Tue, 24 Mar 2020 14:23:19 +0100 Subject: [PATCH 047/398] Added grid tests --- screens/Tetris/__tests__/GridManager.test.js | 69 ++++++++++++++++++++ 1 file changed, 69 insertions(+) diff --git a/screens/Tetris/__tests__/GridManager.test.js b/screens/Tetris/__tests__/GridManager.test.js index 43d1f0e..8808754 100644 --- a/screens/Tetris/__tests__/GridManager.test.js +++ b/screens/Tetris/__tests__/GridManager.test.js @@ -1,10 +1,19 @@ import React from 'react'; import GridManager from "../GridManager"; +import ScoreManager from "../ScoreManager"; +import Piece from "../Piece"; let colors = { tetrisBackground: "#000002" }; +jest.mock("../ScoreManager"); + +afterAll(() => { + jest.restoreAllMocks(); +}); + + test('getEmptyLine', () => { let g = new GridManager(2, 2, colors); expect(g.getEmptyLine(2)).toStrictEqual([ @@ -32,3 +41,63 @@ test('getEmptyGrid', () => { expect(g.getEmptyGrid(2, -1)).toStrictEqual([[], []]); }); +test('getLinesToClear', () => { + let g = new GridManager(2, 2, colors); + g.getCurrentGrid()[0][0].isEmpty = false; + g.getCurrentGrid()[0][1].isEmpty = false; + let coord = [{x: 1, y: 0}]; + expect(g.getLinesToClear(coord)).toStrictEqual([0]); + + g.getCurrentGrid()[0][0].isEmpty = true; + g.getCurrentGrid()[0][1].isEmpty = true; + g.getCurrentGrid()[1][0].isEmpty = false; + g.getCurrentGrid()[1][1].isEmpty = false; + expect(g.getLinesToClear(coord)).toStrictEqual([]); + coord = [{x: 1, y: 1}]; + expect(g.getLinesToClear(coord)).toStrictEqual([1]); +}); + +test('clearLines', () => { + let g = new GridManager(2, 2, colors); + let grid = [ + [ + {color: colors.tetrisBackground, isEmpty: true}, + {color: colors.tetrisBackground, isEmpty: true}, + ], + [ + {color: '0', isEmpty: true}, + {color: '0', isEmpty: true}, + ], + ]; + g.getCurrentGrid()[1][0].color = '0'; + g.getCurrentGrid()[1][1].color = '0'; + expect(g.getCurrentGrid()).toStrictEqual(grid); + let scoreManager = new ScoreManager(); + g.clearLines([1], scoreManager); + grid = [ + [ + {color: colors.tetrisBackground, isEmpty: true}, + {color: colors.tetrisBackground, isEmpty: true}, + ], + [ + {color: colors.tetrisBackground, isEmpty: true}, + {color: colors.tetrisBackground, isEmpty: true}, + ], + ]; + expect(g.getCurrentGrid()).toStrictEqual(grid); +}); + +test('freezeTetromino', () => { + let g = new GridManager(2, 2, colors); + let spy1 = jest.spyOn(GridManager.prototype, 'getLinesToClear') + .mockImplementation(() => {}); + let spy2 = jest.spyOn(GridManager.prototype, 'clearLines') + .mockImplementation(() => {}); + g.freezeTetromino(new Piece({}), null); + + expect(spy1).toHaveBeenCalled(); + expect(spy2).toHaveBeenCalled(); + + spy1.mockRestore(); + spy2.mockRestore(); +}); From cded72137e1f51d25d07af26617308582483c6e9 Mon Sep 17 00:00:00 2001 From: Arnaud Vergnet Date: Sat, 28 Mar 2020 12:08:08 +0100 Subject: [PATCH 048/398] Updated doc and used private class members --- screens/Tetris/GameLogic.js | 201 +++++++++++++++-------------- screens/Tetris/GridManager.js | 62 ++++++++- screens/Tetris/Piece.js | 81 ++++++++++-- screens/Tetris/ScoreManager.js | 41 +++++- screens/Tetris/Shapes/BaseShape.js | 47 ++++++- 5 files changed, 313 insertions(+), 119 deletions(-) diff --git a/screens/Tetris/GameLogic.js b/screens/Tetris/GameLogic.js index b3de919..98c1257 100644 --- a/screens/Tetris/GameLogic.js +++ b/screens/Tetris/GameLogic.js @@ -17,218 +17,221 @@ export default class GameLogic { 100, ]; - scoreManager: ScoreManager; - gridManager: GridManager; + #scoreManager: ScoreManager; + #gridManager: GridManager; - height: number; - width: number; + #height: number; + #width: number; - gameRunning: boolean; - gamePaused: boolean; - gameTime: number; + #gameRunning: boolean; + #gamePaused: boolean; + #gameTime: number; - currentObject: Piece; + #currentObject: Piece; - gameTick: number; - gameTickInterval: IntervalID; - gameTimeInterval: IntervalID; + #gameTick: number; + #gameTickInterval: IntervalID; + #gameTimeInterval: IntervalID; - pressInInterval: TimeoutID; - isPressedIn: boolean; - autoRepeatActivationDelay: number; - autoRepeatDelay: number; + #pressInInterval: TimeoutID; + #isPressedIn: boolean; + #autoRepeatActivationDelay: number; + #autoRepeatDelay: number; - nextPieces: Array; - nextPiecesCount: number; + #nextPieces: Array; + #nextPiecesCount: number; - onTick: Function; - onClock: Function; + #onTick: Function; + #onClock: Function; endCallback: Function; - colors: Object; + #colors: Object; constructor(height: number, width: number, colors: Object) { - this.height = height; - this.width = width; - this.gameRunning = false; - this.gamePaused = false; - this.colors = colors; - this.autoRepeatActivationDelay = 300; - this.autoRepeatDelay = 50; - this.nextPieces = []; - this.nextPiecesCount = 3; - this.scoreManager = new ScoreManager(); - this.gridManager = new GridManager(this.getWidth(), this.getHeight(), this.colors); + this.#height = height; + this.#width = width; + this.#gameRunning = false; + this.#gamePaused = false; + this.#colors = colors; + this.#autoRepeatActivationDelay = 300; + this.#autoRepeatDelay = 50; + this.#nextPieces = []; + this.#nextPiecesCount = 3; + this.#scoreManager = new ScoreManager(); + this.#gridManager = new GridManager(this.getWidth(), this.getHeight(), this.#colors); } getHeight(): number { - return this.height; + return this.#height; } getWidth(): number { - return this.width; + return this.#width; } getCurrentGrid() { - return this.gridManager.getCurrentGrid(); + return this.#gridManager.getCurrentGrid(); } isGameRunning(): boolean { - return this.gameRunning; + return this.#gameRunning; } isGamePaused(): boolean { - return this.gamePaused; + return this.#gamePaused; } onFreeze() { - this.gridManager.freezeTetromino(this.currentObject, this.scoreManager); + this.#gridManager.freezeTetromino(this.#currentObject, this.#scoreManager); this.createTetromino(); } setNewGameTick(level: number) { if (level >= GameLogic.levelTicks.length) return; - this.gameTick = GameLogic.levelTicks[level]; - clearInterval(this.gameTickInterval); - this.gameTickInterval = setInterval(this.onTick, this.gameTick); + this.#gameTick = GameLogic.levelTicks[level]; + clearInterval(this.#gameTickInterval); + this.#gameTickInterval = setInterval(this.#onTick, this.#gameTick); } onTick(callback: Function) { - this.currentObject.tryMove(0, 1, - this.gridManager.getCurrentGrid(), this.getWidth(), this.getHeight(), + this.#currentObject.tryMove(0, 1, + this.#gridManager.getCurrentGrid(), this.getWidth(), this.getHeight(), () => this.onFreeze()); callback( - this.scoreManager.getScore(), - this.scoreManager.getLevel(), - this.gridManager.getCurrentGrid()); - if (this.scoreManager.canLevelUp()) - this.setNewGameTick(this.scoreManager.getLevel()); + this.#scoreManager.getScore(), + this.#scoreManager.getLevel(), + this.#gridManager.getCurrentGrid()); + if (this.#scoreManager.canLevelUp()) + this.setNewGameTick(this.#scoreManager.getLevel()); } onClock(callback: Function) { - this.gameTime++; - callback(this.gameTime); + this.#gameTime++; + callback(this.#gameTime); } canUseInput() { - return this.gameRunning && !this.gamePaused + return this.#gameRunning && !this.#gamePaused } rightPressed(callback: Function) { - this.isPressedIn = true; + this.#isPressedIn = true; this.movePressedRepeat(true, callback, 1, 0); } leftPressedIn(callback: Function) { - this.isPressedIn = true; + this.#isPressedIn = true; this.movePressedRepeat(true, callback, -1, 0); } downPressedIn(callback: Function) { - this.isPressedIn = true; + this.#isPressedIn = true; this.movePressedRepeat(true, callback, 0, 1); } movePressedRepeat(isInitial: boolean, callback: Function, x: number, y: number) { - if (!this.canUseInput() || !this.isPressedIn) + if (!this.canUseInput() || !this.#isPressedIn) return; - const moved = this.currentObject.tryMove(x, y, - this.gridManager.getCurrentGrid(), this.getWidth(), this.getHeight(), + const moved = this.#currentObject.tryMove(x, y, + this.#gridManager.getCurrentGrid(), this.getWidth(), this.getHeight(), () => this.onFreeze()); if (moved) { if (y === 1) { - this.scoreManager.incrementScore(); - callback(this.gridManager.getCurrentGrid(), this.scoreManager.getScore()); + this.#scoreManager.incrementScore(); + callback(this.#gridManager.getCurrentGrid(), this.#scoreManager.getScore()); } else - callback(this.gridManager.getCurrentGrid()); + callback(this.#gridManager.getCurrentGrid()); } - this.pressInInterval = setTimeout(() => this.movePressedRepeat(false, callback, x, y), isInitial ? this.autoRepeatActivationDelay : this.autoRepeatDelay); + this.#pressInInterval = setTimeout(() => + this.movePressedRepeat(false, callback, x, y), + isInitial ? this.#autoRepeatActivationDelay : this.#autoRepeatDelay + ); } pressedOut() { - this.isPressedIn = false; - clearTimeout(this.pressInInterval); + this.#isPressedIn = false; + clearTimeout(this.#pressInInterval); } rotatePressed(callback: Function) { if (!this.canUseInput()) return; - if (this.currentObject.tryRotate(this.gridManager.getCurrentGrid(), this.getWidth(), this.getHeight())) - callback(this.gridManager.getCurrentGrid()); + if (this.#currentObject.tryRotate(this.#gridManager.getCurrentGrid(), this.getWidth(), this.getHeight())) + callback(this.#gridManager.getCurrentGrid()); } getNextPiecesPreviews() { let finalArray = []; - for (let i = 0; i < this.nextPieces.length; i++) { - finalArray.push(this.gridManager.getEmptyGrid(4, 4)); - this.nextPieces[i].toGrid(finalArray[i], true); + for (let i = 0; i < this.#nextPieces.length; i++) { + finalArray.push(this.#gridManager.getEmptyGrid(4, 4)); + this.#nextPieces[i].toGrid(finalArray[i], true); } return finalArray; } recoverNextPiece() { - this.currentObject = this.nextPieces.shift(); + this.#currentObject = this.#nextPieces.shift(); this.generateNextPieces(); } generateNextPieces() { - while (this.nextPieces.length < this.nextPiecesCount) { - this.nextPieces.push(new Piece(this.colors)); + while (this.#nextPieces.length < this.#nextPiecesCount) { + this.#nextPieces.push(new Piece(this.#colors)); } } createTetromino() { this.pressedOut(); 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); } togglePause() { - if (!this.gameRunning) + if (!this.#gameRunning) return; - this.gamePaused = !this.gamePaused; - if (this.gamePaused) { - clearInterval(this.gameTickInterval); - clearInterval(this.gameTimeInterval); + this.#gamePaused = !this.#gamePaused; + if (this.#gamePaused) { + clearInterval(this.#gameTickInterval); + clearInterval(this.#gameTimeInterval); } else { - this.gameTickInterval = setInterval(this.onTick, this.gameTick); - this.gameTimeInterval = setInterval(this.onClock, 1000); + this.#gameTickInterval = setInterval(this.#onTick, this.#gameTick); + this.#gameTimeInterval = setInterval(this.#onClock, 1000); } } endGame(isRestart: boolean) { - this.gameRunning = false; - this.gamePaused = false; - clearInterval(this.gameTickInterval); - clearInterval(this.gameTimeInterval); - this.endCallback(this.gameTime, this.scoreManager.getScore(), isRestart); + this.#gameRunning = false; + this.#gamePaused = false; + clearInterval(this.#gameTickInterval); + clearInterval(this.#gameTimeInterval); + this.endCallback(this.#gameTime, this.#scoreManager.getScore(), isRestart); } startGame(tickCallback: Function, clockCallback: Function, endCallback: Function) { - if (this.gameRunning) + if (this.#gameRunning) this.endGame(true); - this.gameRunning = true; - this.gamePaused = false; - this.gameTime = 0; - this.scoreManager = new ScoreManager(); - this.gameTick = GameLogic.levelTicks[this.scoreManager.getLevel()]; - this.gridManager = new GridManager(this.getWidth(), this.getHeight(), this.colors); - this.nextPieces = []; + this.#gameRunning = true; + this.#gamePaused = false; + this.#gameTime = 0; + this.#scoreManager = new ScoreManager(); + this.#gameTick = GameLogic.levelTicks[this.#scoreManager.getLevel()]; + this.#gridManager = new GridManager(this.getWidth(), this.getHeight(), this.#colors); + this.#nextPieces = []; this.generateNextPieces(); this.createTetromino(); tickCallback( - this.scoreManager.getScore(), - this.scoreManager.getLevel(), - this.gridManager.getCurrentGrid()); - clockCallback(this.gameTime); - this.onTick = this.onTick.bind(this, tickCallback); - this.onClock = this.onClock.bind(this, clockCallback); - this.gameTickInterval = setInterval(this.onTick, this.gameTick); - this.gameTimeInterval = setInterval(this.onClock, 1000); + this.#scoreManager.getScore(), + this.#scoreManager.getLevel(), + this.#gridManager.getCurrentGrid()); + clockCallback(this.#gameTime); + this.#onTick = this.onTick.bind(this, tickCallback); + this.#onClock = this.onClock.bind(this, clockCallback); + this.#gameTickInterval = setInterval(this.#onTick, this.#gameTick); + this.#gameTimeInterval = setInterval(this.#onClock, 1000); this.endCallback = endCallback; } } diff --git a/screens/Tetris/GridManager.js b/screens/Tetris/GridManager.js index ced9a07..4f0b0ca 100644 --- a/screens/Tetris/GridManager.js +++ b/screens/Tetris/GridManager.js @@ -2,24 +2,49 @@ import Piece from "./Piece"; import ScoreManager from "./ScoreManager"; +import type {coordinates} from './Shapes/BaseShape'; -export type grid = Array>; +export type cell = {color: string, isEmpty: boolean}; +export type grid = Array>; + +/** + * Class used to manage the game grid + * + */ export default class GridManager { #currentGrid: grid; #colors: Object; + /** + * Initializes a grid of the given size + * + * @param width The grid width + * @param height The grid height + * @param colors Object containing current theme colors + */ constructor(width: number, height: number, colors: Object) { this.#colors = colors; this.#currentGrid = this.getEmptyGrid(height, width); } - getCurrentGrid() { + /** + * Get the current grid + * + * @return {grid} The current grid + */ + getCurrentGrid(): grid { return this.#currentGrid; } - getEmptyLine(width: number) { + /** + * Get a new empty grid line of the given size + * + * @param width The line size + * @return {Array} + */ + getEmptyLine(width: number): Array { let line = []; for (let col = 0; col < width; col++) { line.push({ @@ -30,7 +55,14 @@ export default class GridManager { return line; } - getEmptyGrid(height: number, width: number) { + /** + * Gets a new empty grid + * + * @param width The grid width + * @param height The grid height + * @return {grid} A new empty grid + */ + getEmptyGrid(height: number, width: number): grid { let grid = []; for (let row = 0; row < height; row++) { grid.push(this.getEmptyLine(width)); @@ -38,6 +70,13 @@ export default class GridManager { return grid; } + /** + * Removes the given lines from the grid, + * shifts down every line on top and adds new empty lines on top. + * + * @param lines An array of line numbers to remove + * @param scoreManager A reference to the score manager + */ clearLines(lines: Array, scoreManager: ScoreManager) { lines.sort(); for (let i = 0; i < lines.length; i++) { @@ -47,7 +86,14 @@ export default class GridManager { scoreManager.addLinesRemovedPoints(lines.length); } - getLinesToClear(coord: Object) { + /** + * Gets the lines to clear around the given piece's coordinates. + * The piece's coordinates are used for optimization and to prevent checking the whole grid. + * + * @param coord The piece's coordinates to check lines at + * @return {Array} An array containing the line numbers to clear + */ + getLinesToClear(coord: Array): Array { let rows = []; for (let i = 0; i < coord.length; i++) { let isLineFull = true; @@ -63,6 +109,12 @@ export default class GridManager { return rows; } + /** + * Freezes the given piece to the grid + * + * @param currentObject The piece to freeze + * @param scoreManager A reference to the score manager + */ freezeTetromino(currentObject: Piece, scoreManager: ScoreManager) { this.clearLines(this.getLinesToClear(currentObject.getCoordinates()), scoreManager); } diff --git a/screens/Tetris/Piece.js b/screens/Tetris/Piece.js index 86cbc68..88d83d9 100644 --- a/screens/Tetris/Piece.js +++ b/screens/Tetris/Piece.js @@ -5,7 +5,14 @@ import ShapeO from "./Shapes/ShapeO"; import ShapeS from "./Shapes/ShapeS"; import ShapeT from "./Shapes/ShapeT"; import ShapeZ from "./Shapes/ShapeZ"; +import type {coordinates} from './Shapes/BaseShape'; +import type {grid} from './GridManager'; +/** + * Class used as an abstraction layer for shapes. + * Use this class to manipulate pieces rather than Shapes directly + * + */ export default class Piece { #shapes = [ @@ -20,17 +27,32 @@ export default class Piece { #currentShape: Object; #colors: Object; + /** + * Initializes this piece's color and shape + * + * @param colors Object containing current theme colors + */ constructor(colors: Object) { this.#currentShape = this.getRandomShape(colors); this.#colors = colors; } + /** + * Gets a random shape object + * + * @param colors Object containing current theme colors + */ getRandomShape(colors: Object) { return new this.#shapes[Math.floor(Math.random() * 7)](colors); } - removeFromGrid(grid) { - const coord = this.#currentShape.getCellsCoordinates(true); + /** + * Removes the piece from the given grid + * + * @param grid The grid to remove the piece from + */ + removeFromGrid(grid: grid) { + const coord: Array = this.#currentShape.getCellsCoordinates(true); for (let i = 0; i < coord.length; i++) { grid[coord[i].y][coord[i].x] = { color: this.#colors.tetrisBackground, @@ -39,8 +61,14 @@ export default class Piece { } } - toGrid(grid: Array>, isPreview: boolean) { - const coord = this.#currentShape.getCellsCoordinates(!isPreview); + /** + * Adds this piece to the given grid + * + * @param grid The grid to add the piece to + * @param isPreview Should we use this piece's current position to determine the cells? + */ + toGrid(grid: grid, isPreview: boolean) { + const coord: Array = this.#currentShape.getCellsCoordinates(!isPreview); for (let i = 0; i < coord.length; i++) { grid[coord[i].y][coord[i].x] = { color: this.#currentShape.getColor(), @@ -49,9 +77,17 @@ export default class Piece { } } - isPositionValid(grid, width, height) { + /** + * Checks if the piece's current position is valid + * + * @param grid The current game grid + * @param width The grid's width + * @param height The grid's height + * @return {boolean} If the position is valid + */ + isPositionValid(grid: grid, width: number, height: number) { let isValid = true; - const coord = this.#currentShape.getCellsCoordinates(true); + const coord: Array = this.#currentShape.getCellsCoordinates(true); for (let i = 0; i < coord.length; i++) { if (coord[i].x >= width || coord[i].x < 0 @@ -65,7 +101,18 @@ export default class Piece { return isValid; } - tryMove(x: number, y: number, grid, width, height, freezeCallback: Function) { + /** + * Tries to move the piece by the given offset on the given grid + * + * @param x Position X offset + * @param y Position Y offset + * @param grid The grid to move the piece on + * @param width The grid's width + * @param height The grid's height + * @param freezeCallback Callback to use if the piece should freeze itself + * @return {boolean} True if the move was valid, false otherwise + */ + tryMove(x: number, y: number, grid: grid, width: number, height: number, freezeCallback: Function) { if (x > 1) x = 1; // Prevent moving from more than one tile if (x < -1) x = -1; if (y > 1) y = 1; @@ -75,19 +122,26 @@ export default class Piece { this.removeFromGrid(grid); this.#currentShape.move(x, y); let isValid = this.isPositionValid(grid, width, height); - let shouldFreeze = false; if (!isValid) this.#currentShape.move(-x, -y); - shouldFreeze = !isValid && y !== 0; + let shouldFreeze = !isValid && y !== 0; this.toGrid(grid, false); if (shouldFreeze) freezeCallback(); return isValid; } - tryRotate(grid, width, height) { + /** + * Tries to rotate the piece + * + * @param grid The grid to rotate the piece on + * @param width The grid's width + * @param height The grid's height + * @return {boolean} True if the rotation was valid, false otherwise + */ + tryRotate(grid: grid, width: number, height: number) { this.removeFromGrid(grid); this.#currentShape.rotate(true); if (!this.isPositionValid(grid, width, height)) { @@ -99,7 +153,12 @@ export default class Piece { return true; } - getCoordinates() { + /** + * Gets this piece used cells coordinates + * + * @return {Array} An array of coordinates + */ + getCoordinates(): Array { return this.#currentShape.getCellsCoordinates(true); } } diff --git a/screens/Tetris/ScoreManager.js b/screens/Tetris/ScoreManager.js index 263d27b..e000202 100644 --- a/screens/Tetris/ScoreManager.js +++ b/screens/Tetris/ScoreManager.js @@ -1,5 +1,8 @@ // @flow +/** + * Class used to manage game score + */ export default class ScoreManager { #scoreLinesModifier = [40, 100, 300, 1200]; @@ -8,31 +11,60 @@ export default class ScoreManager { #level: number; #levelProgression: number; + /** + * Initializes score to 0 + */ constructor() { this.#score = 0; this.#level = 0; this.#levelProgression = 0; } + /** + * Gets the current score + * + * @return {number} The current score + */ getScore(): number { return this.#score; } + /** + * Gets the current level + * + * @return {number} The current level + */ getLevel(): number { return this.#level; } + /** + * Gets the current level progression + * + * @return {number} The current level progression + */ getLevelProgression(): number { return this.#levelProgression; } + /** + * Increments the score by one + */ incrementScore() { this.#score++; } + /** + * Add score corresponding to the number of lines removed at the same time. + * Also updates the level progression. + * + * The more lines cleared at the same time, the more points and level progression the player gets. + * + * @param numberRemoved The number of lines removed at the same time + */ addLinesRemovedPoints(numberRemoved: number) { if (numberRemoved < 1 || numberRemoved > 4) - return 0; + return; this.#score += this.#scoreLinesModifier[numberRemoved-1] * (this.#level + 1); switch (numberRemoved) { case 1: @@ -50,6 +82,13 @@ export default class ScoreManager { } } + /** + * Checks if the player can go to the next level. + * + * If he can, change the level. + * + * @return {boolean} True if the current level has changed + */ canLevelUp() { let canLevel = this.#levelProgression > this.#level * 5; if (canLevel){ diff --git a/screens/Tetris/Shapes/BaseShape.js b/screens/Tetris/Shapes/BaseShape.js index 717ef8a..e1890ac 100644 --- a/screens/Tetris/Shapes/BaseShape.js +++ b/screens/Tetris/Shapes/BaseShape.js @@ -1,5 +1,10 @@ // @flow +export type coordinates = { + x: number, + y: number, +} + /** * Abstract class used to represent a BaseShape. * Abstract classes do not exist by default in Javascript: we force it by throwing errors in the constructor @@ -9,8 +14,11 @@ export default class BaseShape { #currentShape: Array>; #rotation: number; - position: Object; + position: coordinates; + /** + * Prevent instantiation if classname is BaseShape to force class to be abstract + */ constructor() { if (this.constructor === BaseShape) throw new Error("Abstract class can't be instantiated"); @@ -19,19 +27,41 @@ export default class BaseShape { this.#currentShape = this.getShapes()[this.#rotation]; } + /** + * Gets this shape's color. + * Must be implemented by child class + */ getColor(): string { throw new Error("Method 'getColor()' must be implemented"); } + /** + * Gets this object's all possible shapes as an array. + * Must be implemented by child class. + * + * Used by tests to read private fields + */ getShapes(): Array>> { throw new Error("Method 'getShapes()' must be implemented"); } - getCurrentShape() { + /** + * Gets this object's current shape. + * + * Used by tests to read private fields + */ + getCurrentShape(): Array> { return this.#currentShape; } - getCellsCoordinates(isAbsolute: boolean) { + /** + * Gets this object's coordinates. + * This will return an array of coordinates representing the positions of the cells used by this object. + * + * @param isAbsolute Should we take into account the current position of the object? + * @return {Array} This object cells coordinates + */ + getCellsCoordinates(isAbsolute: boolean): Array { let coordinates = []; for (let row = 0; row < this.#currentShape.length; row++) { for (let col = 0; col < this.#currentShape[row].length; col++) { @@ -45,6 +75,11 @@ export default class BaseShape { return coordinates; } + /** + * Rotate this object + * + * @param isForward Should we rotate clockwise? + */ rotate(isForward: boolean) { if (isForward) this.#rotation++; @@ -57,6 +92,12 @@ export default class BaseShape { this.#currentShape = this.getShapes()[this.#rotation]; } + /** + * Move this object + * + * @param x Position X offset to add + * @param y Position Y offset to add + */ move(x: number, y: number) { this.position.x += x; this.position.y += y; From fb1d2cf045b3828e071b8fa9000c2a2f9187143d Mon Sep 17 00:00:00 2001 From: Arnaud Vergnet Date: Sat, 28 Mar 2020 12:21:33 +0100 Subject: [PATCH 049/398] Updated translations --- navigation/DrawerNavigator.js | 2 +- screens/Tetris/TetrisScreen.js | 29 +++++++++++++++-------------- translations/en.json | 20 ++++++++++++++++++++ translations/fr.json | 20 ++++++++++++++++++++ 4 files changed, 56 insertions(+), 15 deletions(-) diff --git a/navigation/DrawerNavigator.js b/navigation/DrawerNavigator.js index 71c7b34..0073467 100644 --- a/navigation/DrawerNavigator.js +++ b/navigation/DrawerNavigator.js @@ -177,7 +177,7 @@ function TetrisStackComponent() { options={({navigation}) => { const openDrawer = getDrawerButton.bind(this, navigation); return { - title: 'Tetris', + title: i18n.t("game.title"), headerLeft: openDrawer }; }} diff --git a/screens/Tetris/TetrisScreen.js b/screens/Tetris/TetrisScreen.js index 47e92b6..c6867c7 100644 --- a/screens/Tetris/TetrisScreen.js +++ b/screens/Tetris/TetrisScreen.js @@ -8,6 +8,7 @@ import GameLogic from "./GameLogic"; import Grid from "./components/Grid"; import HeaderButton from "../../components/HeaderButton"; import Preview from "./components/Preview"; +import i18n from "i18n-js"; type Props = { navigation: Object, @@ -136,11 +137,11 @@ class TetrisScreen extends React.Component { showPausePopup() { Alert.alert( - 'PAUSE', - 'GAME PAUSED', + i18n.t("game.pause"), + i18n.t("game.pauseMessage"), [ - {text: 'RESTART', onPress: () => this.showRestartConfirm()}, - {text: 'RESUME', onPress: () => this.togglePause()}, + {text: i18n.t("game.restart.text"), onPress: () => this.showRestartConfirm()}, + {text: i18n.t("game.resume"), onPress: () => this.togglePause()}, ], {cancelable: false}, ); @@ -148,26 +149,26 @@ class TetrisScreen extends React.Component { showRestartConfirm() { Alert.alert( - 'RESTART?', - 'WHOA THERE', + i18n.t("game.restart.confirm"), + i18n.t("game.restart.confirmMessage"), [ - {text: 'NO', onPress: () => this.showPausePopup()}, - {text: 'YES', onPress: () => this.startGame()}, + {text: i18n.t("game.restart.confirmNo"), onPress: () => this.showPausePopup()}, + {text: i18n.t("game.restart.confirmYes"), onPress: () => this.startGame()}, ], {cancelable: false}, ); } showGameOverConfirm() { - let message = 'SCORE: ' + this.state.gameScore + '\n'; - message += 'LEVEL: ' + this.state.gameLevel + '\n'; - message += 'TIME: ' + this.getFormattedTime(this.state.gameTime) + '\n'; + let message = i18n.t("game.gameOver.score") + this.state.gameScore + '\n'; + message += i18n.t("game.gameOver.level") + this.state.gameLevel + '\n'; + message += i18n.t("game.gameOver.time") + this.getFormattedTime(this.state.gameTime) + '\n'; Alert.alert( - 'GAME OVER', + i18n.t("game.gameOver.text"), message, [ - {text: 'LEAVE', onPress: () => this.props.navigation.goBack()}, - {text: 'RESTART', onPress: () => this.startGame()}, + {text: i18n.t("game.gameOver.exit"), onPress: () => this.props.navigation.goBack()}, + {text: i18n.t("game.restart.text"), onPress: () => this.startGame()}, ], {cancelable: false}, ); diff --git a/translations/en.json b/translations/en.json index 6bf72c7..e1fb992 100644 --- a/translations/en.json +++ b/translations/en.json @@ -235,5 +235,25 @@ "november": "November", "december": "December" } + }, + "game": { + "title": "Game", + "pause": "Game Paused", + "pauseMessage": "The game is paused", + "resume": "Resume", + "restart": { + "text": "Restart", + "confirm": "Are you sure you want to restart?", + "confirmMessage": "You will lose you progress, continue?", + "confirmYes": "Yes", + "confirmNo": "No" + }, + "gameOver": { + "text": "Game Over", + "score": "Score: ", + "level": "Level: ", + "time": "Time: ", + "exit": "leave Game" + } } } diff --git a/translations/fr.json b/translations/fr.json index 1c5d442..3887502 100644 --- a/translations/fr.json +++ b/translations/fr.json @@ -236,5 +236,25 @@ "november": "Novembre", "december": "Décembre" } + }, + "game": { + "title": "Jeu", + "pause": "Pause", + "pauseMessage": "Le jeu est en pause", + "resume": "Continuer", + "restart": { + "text": "Redémarrer", + "confirm": "Êtes vous sûr de vouloir redémarrer ?", + "confirmMessage": "Tout votre progrès sera perdu, continuer ?", + "confirmYes": "Oui", + "confirmNo": "Non" + }, + "gameOver": { + "text": "Game Over", + "score": "Score: ", + "level": "Niveau: ", + "time": "Temps: ", + "exit": "Quitter" + } } } From a533f48a1210f3f690ccb59cdf32fa54503b49aa Mon Sep 17 00:00:00 2001 From: Arnaud Vergnet Date: Sat, 28 Mar 2020 12:26:24 +0100 Subject: [PATCH 050/398] Updated rotate icon to better match action --- screens/Tetris/TetrisScreen.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/screens/Tetris/TetrisScreen.js b/screens/Tetris/TetrisScreen.js index c6867c7..76eeab5 100644 --- a/screens/Tetris/TetrisScreen.js +++ b/screens/Tetris/TetrisScreen.js @@ -264,7 +264,7 @@ class TetrisScreen extends React.Component { width: '100%', }}> this.logic.rotatePressed(this.updateGrid)} style={{marginRight: 'auto'}} From fbabb4d7af52c85dae11af6bdea49070bd17a9d6 Mon Sep 17 00:00:00 2001 From: Arnaud Vergnet Date: Sun, 29 Mar 2020 11:47:27 +0200 Subject: [PATCH 051/398] First draft of connection --- components/Sidebar.js | 5 ++ navigation/DrawerNavigator.js | 29 ++++++ package.json | 7 +- screens/Amicale/LoginScreen.js | 109 +++++++++++++++++++++++ utils/ConnectionManager.js | 65 ++++++++++++++ utils/__test__/ConnectionManager.test.js | 15 ++++ 6 files changed, 228 insertions(+), 2 deletions(-) create mode 100644 screens/Amicale/LoginScreen.js create mode 100644 utils/ConnectionManager.js create mode 100644 utils/__test__/ConnectionManager.test.js diff --git a/components/Sidebar.js b/components/Sidebar.js index 3fca4cd..383ce66 100644 --- a/components/Sidebar.js +++ b/components/Sidebar.js @@ -46,6 +46,11 @@ export default class SideBar extends React.PureComponent { route: "Main", icon: "home", }, + { + name: 'LOGIN', + route: "LoginScreen", + icon: "login", + }, { name: i18n.t('sidenav.divider2'), route: "Divider2" diff --git a/navigation/DrawerNavigator.js b/navigation/DrawerNavigator.js index 0073467..5c3570a 100644 --- a/navigation/DrawerNavigator.js +++ b/navigation/DrawerNavigator.js @@ -15,6 +15,7 @@ import Sidebar from "../components/Sidebar"; import {createStackNavigator, TransitionPresets} from "@react-navigation/stack"; import HeaderButton from "../components/HeaderButton"; import i18n from "i18n-js"; +import LoginScreen from "../screens/Amicale/LoginScreen"; const defaultScreenOptions = { gestureEnabled: true, @@ -186,6 +187,30 @@ function TetrisStackComponent() { ); } +const LoginStack = createStackNavigator(); + +function LoginStackComponent() { + return ( + + { + const openDrawer = getDrawerButton.bind(this, navigation); + return { + title: 'LOGIN', + headerLeft: openDrawer + }; + }} + /> + + ); +} + const Drawer = createDrawerNavigator(); function getDrawerContent(props) { @@ -231,6 +256,10 @@ export default function DrawerNavigator() { name="TetrisScreen" component={TetrisStackComponent} /> + ); } diff --git a/package.json b/package.json index d3e83da..23bc6b6 100644 --- a/package.json +++ b/package.json @@ -12,7 +12,9 @@ }, "jest": { "preset": "react-native", - "setupFilesAfterEnv": ["jest-extended"] + "setupFilesAfterEnv": [ + "jest-extended" + ] }, "dependencies": { "@expo/vector-icons": "~10.0.0", @@ -42,7 +44,8 @@ "react-native-screens": "2.0.0-alpha.12", "react-native-webview": "7.4.3", "react-native-appearance": "~0.3.1", - "expo-linear-gradient": "~8.0.0" + "expo-linear-gradient": "~8.0.0", + "expo-secure-store": "~8.0.0" }, "devDependencies": { "babel-preset-expo": "^8.0.0", diff --git a/screens/Amicale/LoginScreen.js b/screens/Amicale/LoginScreen.js new file mode 100644 index 0000000..00853ba --- /dev/null +++ b/screens/Amicale/LoginScreen.js @@ -0,0 +1,109 @@ +// @flow + +import * as React from 'react'; +import {Keyboard, KeyboardAvoidingView, StyleSheet, TouchableWithoutFeedback, View} from "react-native"; +import {Button, Text, TextInput, Title} from 'react-native-paper'; +import ConnectionManager from "../../utils/ConnectionManager"; + +type Props = { + navigation: Object, +} + +type State = { + email: string, + password: string, +} + + +export default class LoginScreen extends React.Component { + + state = { + email: '', + password: '', + }; + + onEmailChange: Function; + onPasswordChange: Function; + + constructor() { + super(); + this.onEmailChange = this.onInputChange.bind(this, true); + this.onPasswordChange = this.onInputChange.bind(this, false); + } + + onInputChange(isEmail: boolean, value: string) { + if (isEmail) + this.setState({email: value}); + else + this.setState({password: value}); + } + + onSubmit() { + console.log('pressed'); + ConnectionManager.getInstance().connect(this.state.email, this.state.password) + .then((data) => { + console.log(data); + }) + .catch((error) => { + console.log(error); + }); + } + + render() { + return ( + + + + COUCOU + entrez vos identifiants + + + + + + Pas de compte, dommage ! + + + + + + + ); + } +} + +const styles = StyleSheet.create({ + container: { + flex: 1 + }, + inner: { + padding: 24, + flex: 1, + }, + header: { + fontSize: 36, + marginBottom: 48 + }, + textInput: {}, + btnContainer: { + marginTop: 12 + } +}); diff --git a/utils/ConnectionManager.js b/utils/ConnectionManager.js new file mode 100644 index 0000000..64fab55 --- /dev/null +++ b/utils/ConnectionManager.js @@ -0,0 +1,65 @@ +// @flow + +export const ERROR_TYPE = { + BAD_CREDENTIALS: 0, + CONNECTION_ERROR: 1 +}; + +const AUTH_URL = "https://www.amicale-insat.fr/api/password"; + +export default class ConnectionManager { + static instance: ConnectionManager | null = null; + + #email: string; + #token: string; + + constructor() { + + } + + /** + * Get this class instance or create one if none is found + * @returns {ConnectionManager} + */ + static getInstance(): ConnectionManager { + return ConnectionManager.instance === null ? + ConnectionManager.instance = new ConnectionManager() : + ConnectionManager.instance; + } + + async connect(email: string, password: string) { + let data = { + email: email, + password: password, + }; + return new Promise((resolve, reject) => { + fetch(AUTH_URL, { + method: 'POST', + headers: new Headers({ + 'Accept': 'application/json', + 'Content-Type': 'application/json', + }), + body: JSON.stringify(data) + }).then(async (response) => response.json()) + .then((data) => { + console.log(data); + if (this.isResponseValid(data)) + resolve({success: data.success, token: data.token}); + else + reject(ERROR_TYPE.BAD_CREDENTIALS); + }) + .catch((error) => { + console.log(error); + reject(ERROR_TYPE.CONNECTION_ERROR); + }); + }); + } + + isResponseValid(response: Object) { + return response !== undefined + && response.success !== undefined + && response.success + && response.token !== undefined; + } + +} diff --git a/utils/__test__/ConnectionManager.test.js b/utils/__test__/ConnectionManager.test.js new file mode 100644 index 0000000..40bb62c --- /dev/null +++ b/utils/__test__/ConnectionManager.test.js @@ -0,0 +1,15 @@ +import React from 'react'; +import ConnectionManager, {ERROR_TYPE} from "../ConnectionManager"; + +const fetch = require('isomorphic-fetch'); // fetch is not implemented in nodeJS but in react-native +const c = ConnectionManager.getInstance(); + +test("connect bad credentials", () => { + return expect(c.connect('truc', 'chose')) + .rejects.toBe(ERROR_TYPE.BAD_CREDENTIALS); +}); + +test("connect good credentials", () => { + return expect(c.connect('vergnet@etud.insa-toulouse.fr', 'Coucoù512')) + .resolves.toBe('test'); +}); From 4cdfc607e619e074d4d07a9fea4b68832d72f4d1 Mon Sep 17 00:00:00 2001 From: Arnaud Vergnet Date: Sun, 29 Mar 2020 14:46:44 +0200 Subject: [PATCH 052/398] Improved documentation --- components/CustomAgenda.js | 8 ++- components/CustomIntroSlider.js | 66 +++++++++++++------------ components/CustomModal.js | 8 ++- components/EmptyWebSectionListItem.js | 39 ++++++++++----- components/EventDashboardItem.js | 30 ++++++++--- components/FeedItem.js | 15 +++++- components/HeaderButton.js | 8 ++- components/PreviewEventDashboardItem.js | 47 ++++++++++++------ components/ProxiwashListItem.js | 59 ++++++++++++++-------- components/PureFlatList.js | 4 +- components/Sidebar.js | 26 ++++++++-- components/SidebarDivider.js | 10 +++- components/SidebarItem.js | 6 +++ components/SquareDashboardItem.js | 17 +++++-- components/WebSectionList.js | 55 ++++++++++++++++++--- components/WebViewScreen.js | 51 +++++++++---------- constants/Update.js | 20 ++++++++ utils/AsyncStorageManager.js | 6 +-- utils/DateManager.js | 11 ++++- utils/NotificationsManager.js | 16 ++++-- utils/ThemeManager.js | 34 ++++++++++--- 21 files changed, 380 insertions(+), 156 deletions(-) diff --git a/components/CustomAgenda.js b/components/CustomAgenda.js index ee2b61c..8c0f1cd 100644 --- a/components/CustomAgenda.js +++ b/components/CustomAgenda.js @@ -2,8 +2,14 @@ import * as React from 'react'; import {withTheme} from 'react-native-paper'; import {Agenda} from "react-native-calendars"; +/** + * Abstraction layer for Agenda component, using custom configuration + * + * @param props Props to pass to the element. Must specify an onRef prop to get an Agenda ref. + * @return {*} + */ function CustomAgenda(props) { - const { colors } = props.theme; + const {colors} = props.theme; return ( { introSlides: Array; updateSlides: Array; aprilFoolsSlides: Array; + /** + * Generates intro slides + */ constructor() { super(); this.introSlides = [ @@ -126,8 +103,9 @@ export default class CustomIntroSlider extends React.Component { /** * Render item to be used for the intro introSlides - * @param item - * @param dimensions + * + * @param item The item to be displayed + * @param dimensions Dimensions of the item */ static getIntroRenderItem({item, dimensions}: Object) { @@ -178,3 +156,29 @@ export default class CustomIntroSlider extends React.Component { } +const styles = StyleSheet.create({ + mainContent: { + flex: 1, + alignItems: 'center', + justifyContent: 'center', + paddingBottom: 100 + }, + image: { + width: 300, + height: 300, + marginBottom: -50, + }, + text: { + color: 'rgba(255, 255, 255, 0.8)', + backgroundColor: 'transparent', + textAlign: 'center', + paddingHorizontal: 16, + }, + title: { + fontSize: 22, + color: 'white', + backgroundColor: 'transparent', + textAlign: 'center', + marginBottom: 16, + }, +}); diff --git a/components/CustomModal.js b/components/CustomModal.js index 99b38d6..0a9696b 100644 --- a/components/CustomModal.js +++ b/components/CustomModal.js @@ -4,8 +4,14 @@ import * as React from 'react'; import {withTheme} from 'react-native-paper'; import {Modalize} from "react-native-modalize"; +/** + * Abstraction layer for Modalize component, using custom configuration + * + * @param props Props to pass to the element. Must specify an onRef prop to get an Modalize ref. + * @return {*} + */ function CustomModal(props) { - const { colors } = props.theme; + const {colors} = props.theme; return ( - + {props.refreshing ? {props.text} @@ -38,4 +36,19 @@ function EmptyWebSectionListItem(props) { ); } +const styles = StyleSheet.create({ + iconContainer: { + justifyContent: 'center', + alignItems: 'center', + width: '100%', + height: 100, + marginBottom: 20 + }, + subheading: { + textAlign: 'center', + marginRight: 20, + marginLeft: 20, + } +}); + export default withTheme(EmptyWebSectionListItem); diff --git a/components/EventDashboardItem.js b/components/EventDashboardItem.js index cfcd2ee..117f5c4 100644 --- a/components/EventDashboardItem.js +++ b/components/EventDashboardItem.js @@ -2,7 +2,14 @@ import * as React from 'react'; import {Avatar, Card, withTheme} from 'react-native-paper'; +import {StyleSheet} from "react-native"; +/** + * Component used to display a dashboard item containing a preview event + * + * @param props Props to pass to the component + * @return {*} + */ function EventDashBoardItem(props) { const {colors} = props.theme; const iconColor = props.isAvailable ? @@ -13,13 +20,7 @@ function EventDashBoardItem(props) { colors.textDisabled; return ( } + style={styles.avatar}/>} /> {props.children} @@ -41,4 +42,17 @@ function EventDashBoardItem(props) { ); } +const styles = StyleSheet.create({ + card: { + width: 'auto', + marginLeft: 10, + marginRight: 10, + marginTop: 10, + overflow: 'hidden', + }, + avatar: { + backgroundColor: 'transparent' + } +}); + export default withTheme(EventDashBoardItem); diff --git a/components/FeedItem.js b/components/FeedItem.js index 58294a9..e26f4bd 100644 --- a/components/FeedItem.js +++ b/components/FeedItem.js @@ -6,6 +6,11 @@ import i18n from "i18n-js"; const ICON_AMICALE = require('../assets/amicale.png'); +/** + * Gets the amicale INSAT logo + * + * @return {*} + */ function getAvatar() { return ( {i18n.t('homeScreen.dashboard.seeMore')} + icon={'facebook'}> + {i18n.t('homeScreen.dashboard.seeMore')} + ); diff --git a/components/HeaderButton.js b/components/HeaderButton.js index 663dd44..5e09cee 100644 --- a/components/HeaderButton.js +++ b/components/HeaderButton.js @@ -1,8 +1,14 @@ import * as React from 'react'; import {IconButton, withTheme} from 'react-native-paper'; +/** + * Component used to display a header button + * + * @param props Props to pass to the component + * @return {*} + */ function HeaderButton(props) { - const { colors } = props.theme; + const {colors} = props.theme; return ( ; + style={styles.avatar}/>; return ( @@ -34,10 +42,7 @@ function PreviewEventDashboardItem(props) { subtitle={PlanningEventManager.getFormattedEventTime(props.event['date_begin'], props.event['date_end'])} />} {!isEmpty ? - + " + props.event['description'] + ""} tagsStyles={{ p: {color: colors.text,}, @@ -46,11 +51,7 @@ function PreviewEventDashboardItem(props) { : null} - +