From 26a869a189c1b63193d6899bf6e894dfdac314c7 Mon Sep 17 00:00:00 2001 From: Bart Riemens Date: Thu, 5 Sep 2019 22:48:15 +0200 Subject: [PATCH] Implement highscore/leaderboard top 10 best games and add tests with jest --- .gitignore | 1 + Dockerfile | 2 +- README.md | 3 +- default.conf => config/default.conf | 0 nginx.conf => config/nginx.conf | 0 docker.md | 5 + jest.config.js | 188 ++++++++++++++++++++++++++++ package.json | 3 +- src/components/Banner.js | 19 ++- src/components/Button.js | 80 ++++++++++-- src/components/ControlPanel.js | 8 +- src/components/HeaderMenu.js | 4 +- src/components/Highscore.js | 72 +++++++++++ src/components/HighscoreInput.js | 61 +++++++++ src/components/Input.js | 19 +++ src/containers/App.js | 4 +- src/containers/Snake.js | 33 ++++- src/redux/game.js | 25 ++-- src/redux/highscore.js | 70 +++++++++++ src/redux/highscore.spec.js | 111 ++++++++++++++++ src/redux/module.js | 4 + src/redux/snake.js | 88 ++++++------- src/redux/store.js | 17 +-- src/theming/GlobalStyle.js | 4 +- src/theming/themes/dark.js | 7 +- src/theming/themes/darkOcean.js | 5 +- src/theming/themes/default.js | 28 ++++- 27 files changed, 760 insertions(+), 101 deletions(-) rename default.conf => config/default.conf (100%) rename nginx.conf => config/nginx.conf (100%) create mode 100644 docker.md create mode 100644 jest.config.js create mode 100644 src/components/Highscore.js create mode 100644 src/components/HighscoreInput.js create mode 100644 src/components/Input.js create mode 100644 src/redux/highscore.js create mode 100644 src/redux/highscore.spec.js diff --git a/.gitignore b/.gitignore index 5322b1b..76d8fb2 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ node_modules public/main.js *tar +coverage diff --git a/Dockerfile b/Dockerfile index f59b775..c5bfb7a 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,3 +1,3 @@ FROM nginx COPY public /usr/share/nginx/html -COPY default.conf /etc/nginx/conf.d/default.conf +COPY ./config/default.conf /etc/nginx/conf.d/default.conf diff --git a/README.md b/README.md index 9f7951f..0780f38 100644 --- a/README.md +++ b/README.md @@ -4,8 +4,9 @@ [ ] Create welcome / instructions page [ ] Link to repository -[ ] Convert components to use react hooks [ ] Add license +[ ] High score +[ ] Improve banner ## License diff --git a/default.conf b/config/default.conf similarity index 100% rename from default.conf rename to config/default.conf diff --git a/nginx.conf b/config/nginx.conf similarity index 100% rename from nginx.conf rename to config/nginx.conf diff --git a/docker.md b/docker.md new file mode 100644 index 0000000..a8918a7 --- /dev/null +++ b/docker.md @@ -0,0 +1,5 @@ +npm run build +docker build -t briemens/snake . +docker tag briemens/snake briemens/snake +docker push briemens/snake +docker image save briemens/snake:latest -o snake-container.tar diff --git a/jest.config.js b/jest.config.js new file mode 100644 index 0000000..a421390 --- /dev/null +++ b/jest.config.js @@ -0,0 +1,188 @@ +// For a detailed explanation regarding each configuration property, visit: +// https://jestjs.io/docs/en/configuration.html + +module.exports = { + // All imported modules in your tests should be mocked automatically + // automock: false, + + // Stop running tests after `n` failures + // bail: 0, + + // Respect "browser" field in package.json when resolving modules + // browser: false, + + // The directory where Jest should store its cached dependency information + // cacheDirectory: "/private/var/folders/j0/3bkm_b290232jgx7bhffq64w0000gp/T/jest_dy", + + // Automatically clear mock calls and instances between every test + clearMocks: true, + + // Indicates whether the coverage information should be collected while executing the test + // collectCoverage: false, + + // An array of glob patterns indicating a set of files for which coverage information should be collected + // collectCoverageFrom: null, + + // The directory where Jest should output its coverage files + coverageDirectory: "coverage", + + // An array of regexp pattern strings used to skip coverage collection + // coveragePathIgnorePatterns: [ + // "/node_modules/" + // ], + + // A list of reporter names that Jest uses when writing coverage reports + // coverageReporters: [ + // "json", + // "text", + // "lcov", + // "clover" + // ], + + // An object that configures minimum threshold enforcement for coverage results + // coverageThreshold: null, + + // A path to a custom dependency extractor + // dependencyExtractor: null, + + // Make calling deprecated APIs throw helpful error messages + // errorOnDeprecated: false, + + // Force coverage collection from ignored files using an array of glob patterns + // forceCoverageMatch: [], + + // A path to a module which exports an async function that is triggered once before all test suites + // globalSetup: null, + + // A path to a module which exports an async function that is triggered once after all test suites + // globalTeardown: null, + + // A set of global variables that need to be available in all test environments + // globals: {}, + + // The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers. + // maxWorkers: "50%", + + // An array of directory names to be searched recursively up from the requiring module's location + // moduleDirectories: [ + // "node_modules" + // ], + + // An array of file extensions your modules use + // moduleFileExtensions: [ + // "js", + // "json", + // "jsx", + // "ts", + // "tsx", + // "node" + // ], + + // A map from regular expressions to module names that allow to stub out resources with a single module + // moduleNameMapper: {}, + + // An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader + // modulePathIgnorePatterns: [], + + // Activates notifications for test results + // notify: false, + + // An enum that specifies notification mode. Requires { notify: true } + // notifyMode: "failure-change", + + // A preset that is used as a base for Jest's configuration + // preset: null, + + // Run tests from one or more projects + // projects: null, + + // Use this configuration option to add custom reporters to Jest + // reporters: undefined, + + // Automatically reset mock state between every test + // resetMocks: false, + + // Reset the module registry before running each individual test + // resetModules: false, + + // A path to a custom resolver + // resolver: null, + + // Automatically restore mock state between every test + // restoreMocks: false, + + // The root directory that Jest should scan for tests and modules within + // rootDir: null, + + // A list of paths to directories that Jest should use to search for files in + // roots: [ + // "" + // ], + + // Allows you to use a custom runner instead of Jest's default test runner + // runner: "jest-runner", + + // The paths to modules that run some code to configure or set up the testing environment before each test + // setupFiles: [], + + // A list of paths to modules that run some code to configure or set up the testing framework before each test + // setupFilesAfterEnv: [], + + // A list of paths to snapshot serializer modules Jest should use for snapshot testing + // snapshotSerializers: [], + + // The test environment that will be used for testing + testEnvironment: "node", + + // Options that will be passed to the testEnvironment + // testEnvironmentOptions: {}, + + // Adds a location field to test results + // testLocationInResults: false, + + // The glob patterns Jest uses to detect test files + // testMatch: [ + // "**/__tests__/**/*.[jt]s?(x)", + // "**/?(*.)+(spec|test).[tj]s?(x)" + // ], + + // An array of regexp pattern strings that are matched against all test paths, matched tests are skipped + // testPathIgnorePatterns: [ + // "/node_modules/" + // ], + + // The regexp pattern or array of patterns that Jest uses to detect test files + // testRegex: [], + + // This option allows the use of a custom results processor + // testResultsProcessor: null, + + // This option allows use of a custom test runner + // testRunner: "jasmine2", + + // This option sets the URL for the jsdom environment. It is reflected in properties such as location.href + // testURL: "http://localhost", + + // Setting this value to "fake" allows the use of fake timers for functions such as "setTimeout" + // timers: "real", + + // A map from regular expressions to paths to transformers + // transform: null, + + // An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation + // transformIgnorePatterns: [ + // "/node_modules/" + // ], + + // An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them + // unmockedModulePathPatterns: undefined, + + // Indicates whether each individual test should be reported during the run + // verbose: null, + + // An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode + // watchPathIgnorePatterns: [], + + // Whether to use watchman for file crawling + // watchman: true, +}; diff --git a/package.json b/package.json index 8bdaaad..a9fd415 100644 --- a/package.json +++ b/package.json @@ -7,7 +7,7 @@ "dev": "webpack-dev-server --mode development --open", "build": "webpack --optimize-minimize --config webpack.production.config.js", "webpack": "webpack --config webpack.config.js --watch", - "test": "echo \"Error: no test specified\" && exit 1" + "test": "jest" }, "keywords": [], "author": "", @@ -20,6 +20,7 @@ "@babel/preset-react": "^7.0.0", "babel-loader": "^8.0.6", "babel-plugin-styled-components": "^1.10.6", + "jest": "^24.9.0", "react-hot-loader": "^4.12.11", "webpack": "^4.39.2", "webpack-cli": "^3.3.7", diff --git a/src/components/Banner.js b/src/components/Banner.js index e6894f6..a0fd6cb 100644 --- a/src/components/Banner.js +++ b/src/components/Banner.js @@ -1,5 +1,5 @@ import React from "react"; -import styled from "styled-components"; +import styled, { css } from "styled-components"; const StyledBanner = styled.div` border-width: ${({ theme }) => theme.banner.borderWidth}; @@ -15,11 +15,22 @@ const StyledBanner = styled.div` transition: opacity 100ms ease-in; border-radius: 2px; box-shadow: 1px 1px 5px ${({ theme }) => theme.banner.shadowColor}; - &:hover { - opacity: 0.5; - } + ${({ fade = false }) => + fade && + css` + &:hover { + opacity: 0.5; + } + `} `; export const Banner = ({ children }) => {children}; +Banner.Title = styled.h2` + text-align: center; + margin: 0; + padding: 0; + line-height: 1rem; +`; + export default Banner; diff --git a/src/components/Button.js b/src/components/Button.js index 46adaac..b99e6a9 100644 --- a/src/components/Button.js +++ b/src/components/Button.js @@ -1,17 +1,29 @@ import React from "react"; import { NavLink } from "react-router-dom"; -import styled from "styled-components"; +import styled, { css } from "styled-components"; import Tooltip from "./Tooltip.js"; -const SharedStyle = () => ` +const SharedStyle = css` border-width: ${({ theme }) => theme.button.borderWidth}; border-style: solid; - border-color: ${({ theme }) => theme.button.borderColor}; border-radius: ${({ theme }) => theme.button.borderRadius}; - background-color: ${({ theme }) => theme.button.background}; - color: ${({ theme }) => theme.button.color}; + + ${({ inverse = false }) => { + return !inverse + ? css` + border-color: ${({ theme }) => theme.button.borderColor}; + background-color: ${({ theme }) => theme.button.background}; + color: ${({ theme }) => theme.button.color}; + ` + : css` + border-color: ${({ theme }) => theme.button.color}; + background-color: ${({ theme }) => theme.button.color}; + color: ${({ theme }) => theme.button.background}; + `; + }} + text-align: center; - padding: .3125rem; + padding: 0.3125rem; font-size: 1rem; display: inline-block; vertical-align: top; @@ -19,6 +31,11 @@ const SharedStyle = () => ` user-select: none; cursor: pointer; + &:focus, + &:hover { + outline: ${({ disabled }) => (!disabled ? "1px solid silver" : "none")}; + } + &:hover { background-color: ${({ theme }) => theme.button.hover.background}; } @@ -29,6 +46,17 @@ const SharedStyle = () => ` color: ${({ theme }) => theme.button.active.color}; background-color: ${({ theme }) => theme.button.active.background}; } + + &[disabled], + &.disabled { + // background-color: #aaa; + // color: gray; + // border-color: gray; + background-color: ${({ theme }) => theme.button.disabled.background}; + color: ${({ theme }) => theme.button.disabled.color}; + border-color: ${({ theme }) => theme.button.disabled.borderColor}; + cursor: default; + } `; const ButtonWrapper = styled.div.attrs(({ disabled }) => ({ tabIndex: disabled ? null : 0 }))` @@ -85,6 +113,7 @@ export const Button = props => { onMouseLeave={() => setHover(false)} onKeyUp={updatedProps.onKeyUp} onClick={updatedProps.onClick} + className={disabled && "disabled"} disabled={disabled}> theme.button.icon.borderColor}; + } + + &[disabled], + &.disabled { + background-color: ${({ theme }) => theme.button.icon.disabled.background}; + color: ${({ theme }) => theme.button.icon.disabled.color}; + border-color: ${({ theme }) => theme.button.icon.disabled.borderColor}; } `; export const ToggleIconButton = styled(IconButton)` color: ${({ theme, toggle }) => (toggle ? theme.button.toggled.color : null)}; &:before { - text-shadow: 0 0 1px gray, 0 0 1px #d0bfa3; + // text-shadow: 0 0 1px gray, 0 0 1px #d0bfa3; + text-shadow: 0 0 1px + ${({ theme, toggle }) => (toggle ? theme.button.icon.disabled.borderColor : theme.button.icon.borderColor)}; } `; +/* ===== Button Container ============================================================== */ + +export const ButtonContainer = styled.div` + display: flex; + place-content: ${({ alignment = "center" }) => alignment}; + align-content: space-around; + margin: ${({ margin }) => margin}; + ${StyledAnchor}, + ${StyledNavLink}, + ${StyledButton} { + margin-right: 1rem; + &:nth-last-child(1) { + margin-right: 0; + } + } +`; + +ButtonContainer.aligment = { + left: "flex-start", + right: "flex-end", + center: "center" +}; + export default Button; diff --git a/src/components/ControlPanel.js b/src/components/ControlPanel.js index 39e6ca8..8d90619 100644 --- a/src/components/ControlPanel.js +++ b/src/components/ControlPanel.js @@ -76,14 +76,18 @@ export const ControlPanel = ({ - Zoom: {zoom} + + Zoom: {zoom} +
- FPS: {fps} + + FPS: {fps} +
setFps(fps - 1)} /> setFps(fps + 1)} /> diff --git a/src/components/HeaderMenu.js b/src/components/HeaderMenu.js index 12449e1..5ae54d6 100644 --- a/src/components/HeaderMenu.js +++ b/src/components/HeaderMenu.js @@ -35,7 +35,9 @@ const MenuButton = styled(NavLink)` const HeaderMenu = () => ( - Snake + + Snake + diff --git a/src/components/Highscore.js b/src/components/Highscore.js new file mode 100644 index 0000000..d1fc7ab --- /dev/null +++ b/src/components/Highscore.js @@ -0,0 +1,72 @@ +import React from "react"; +import { module, registerHighscore } from "../redux/highscore.js"; +import styled from "styled-components"; +import { connect } from "react-redux"; + +const HighscoreContainer = styled.div` + height: 100%; +`; + +const Title = styled.h1` + margin: 0.5rem 0 1rem; +`; + +const HighscoreEntries = styled.ul` + margin: 0; + padding: 0; + text-indent: 0; +`; + +const Position = styled.div` + font-weight: bold; + min-width: 1rem; + text-align: right; + margin-right: 0.4rem; + font-size: 0.8rem; + color: ${({ theme }) => theme.colors.colorInactive}; +`; +const Username = styled.div` + overflow: hidden; + width: 9rem; + text-overflow: ellipsis; + white-space: nowrap; +`; +const Score = styled.div` + font-weight: bold; + font-size: 1.2rem; + min-width: 1.5rem; + text-align: right; + color: ${({ theme }) => theme.colors.colorAlternate}; +`; + +const HighscoreEntry = styled.li` + list-style: none; + line-height: 1.5rem; + display: flex; + justify-content: space-between; + align-content: center; +`; + +const Highscore = ({ highscores = [] }) => { + console.log("highscores", highscores); + return ( + + Highscore + {!highscores.length &&

No highscores yet

} + + {highscores.map((highscore, index) => ( + + {index + 1} + {highscore.name} + {highscore.score} + + ))} + +
+ ); +}; + +export default connect( + state => ({ ...state[module.name] }), + { registerHighscore } +)(Highscore); diff --git a/src/components/HighscoreInput.js b/src/components/HighscoreInput.js new file mode 100644 index 0000000..98930b6 --- /dev/null +++ b/src/components/HighscoreInput.js @@ -0,0 +1,61 @@ +import React from "react"; +import styled from "styled-components"; + +import Banner from "./Banner.js"; +import Button, { ButtonContainer } from "./Button.js"; +import Input from "./Input.js"; + +const Field = styled.div` + display: flex; + width: 100%; + // align-content: center; + // place-content: center; + // justify-content: center; + align-items: center; + + label { + display: block; + margin-right: 0.5rem; + } + ${Input} { + width: 100%; + } +`; + +const OkButton = styled(Button)` + min-width: 4.6875rem; +`; + +export const HighscoreInput = ({ name, score, gameId, onSubmit }) => { + const [username, setUsername] = React.useState(name || ""); + return ( + + Congratulations! +

+ You have a new highscore of {score} +

+
e.preventDefault() || onSubmit({ name: username, score, gameId })} + onKeyUp={({ which }) => which === 27 && onSubmit(null)}> + + + setUsername(e.target.value)} + /> + + + + OK + + Cancel + +
+
+ ); +}; + +export default HighscoreInput; diff --git a/src/components/Input.js b/src/components/Input.js new file mode 100644 index 0000000..eb587cf --- /dev/null +++ b/src/components/Input.js @@ -0,0 +1,19 @@ +import styled from "styled-components"; + +export const Input = styled.input` + appearance: none; + border-width: ${({ theme }) => theme.input.borderWidth}; + border-style: solid; + border-color: ${({ theme }) => theme.input.borderColor}; + background-color: ${({ theme }) => theme.input.background}; + color: ${({ theme }) => theme.input.color}; + padding: ${({ theme }) => theme.input.padding}; + border-radius: ${({ theme }) => theme.input.borderRadius}; + + &:focus, + &:hover { + outline: ${({ disabled }) => (!disabled ? "1px solid silver" : "none")}; + } +`; + +export default Input; diff --git a/src/containers/App.js b/src/containers/App.js index 106f683..2caffe8 100644 --- a/src/containers/App.js +++ b/src/containers/App.js @@ -24,8 +24,8 @@ const App = ({ theme }) => ( - - + +