This commit is contained in:
Dawid Wysokiński 2020-11-01 15:19:49 +01:00
commit ebf9698423
38 changed files with 12760 additions and 0 deletions

50
.babelrc Normal file
View File

@ -0,0 +1,50 @@
{
"plugins": [
[
"module-resolver",
{
"@": ["./src"],
"alias": {
"@common": "./src/common",
"@config": "./src/config",
"@features": "./src/features",
"@libs": "./src/libs",
"@utils": "./src/utils"
}
}
],
[
"babel-plugin-transform-imports",
{
"@material-ui/core": {
"transform": "@material-ui/core/${member}",
"preventFullImport": true
},
"@material-ui/core/styles": {
"transform": "@material-ui/core/styles/${member}",
"preventFullImport": true
},
"@material-ui/lab": {
"transform": "@material-ui/lab/${member}",
"preventFullImport": true
},
"@material-ui/icons": {
"transform": "@material-ui/icons/${member}",
"preventFullImport": true
},
"lodash": {
"transform": "lodash/${member}",
"preventFullImport": true
},
"date-fns": {
"transform": "date-fns/${member}",
"preventFullImport": true
},
"validator": {
"transform": "validator/lib/${member}",
"preventFullImport": true
}
}
]
]
}

23
.gitignore vendored Normal file
View File

@ -0,0 +1,23 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# production
/build
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*

4
.prettierignore Normal file
View File

@ -0,0 +1,4 @@
.cache
package.json
package-lock.json
public

5
.prettierrc Normal file
View File

@ -0,0 +1,5 @@
{
"arrowParens": "avoid",
"semi": true,
"singleQuote": true
}

46
README.md Normal file
View File

@ -0,0 +1,46 @@
# Getting Started with Create React App
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
## Available Scripts
In the project directory, you can run:
### `yarn start`
Runs the app in the development mode.\
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
The page will reload if you make edits.\
You will also see any lint errors in the console.
### `yarn test`
Launches the test runner in the interactive watch mode.\
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
### `yarn build`
Builds the app for production to the `build` folder.\
It correctly bundles React in production mode and optimizes the build for the best performance.
The build is minified and the filenames include the hashes.\
Your app is ready to be deployed!
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
### `yarn eject`
**Note: this is a one-way operation. Once you `eject`, you cant go back!**
If you arent satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point youre on your own.
You dont have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldnt feel obligated to use this feature. However we understand that this tool wouldnt be useful if you couldnt customize it when you are ready for it.
## Learn More
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
To learn React, check out the [React documentation](https://reactjs.org/).

3
config-overrides.js Normal file
View File

@ -0,0 +1,3 @@
const { useBabelRc, override } = require('customize-cra');
module.exports = override(useBabelRc());

65
package.json Normal file
View File

@ -0,0 +1,65 @@
{
"name": "lang.tribalwarshelp.com",
"version": "0.1.0",
"private": true,
"dependencies": {
"@apollo/client": "^3.2.5",
"@material-ui/core": "^4.11.0",
"@material-ui/icons": "^4.9.1",
"@material-ui/lab": "^4.0.0-alpha.56",
"@testing-library/jest-dom": "^5.11.4",
"@testing-library/react": "^11.1.0",
"@testing-library/user-event": "^12.1.10",
"@types/jest": "^26.0.15",
"@types/node": "^12.0.0",
"@types/react": "^16.9.53",
"@types/react-dom": "^16.9.8",
"date-fns": "^2.16.1",
"graphql": "^15.4.0",
"i18next": "^19.8.3",
"i18next-browser-languagedetector": "^6.0.1",
"lodash": "^4.17.20",
"query-string": "^6.13.6",
"react": "^17.0.1",
"react-dom": "^17.0.1",
"react-i18next": "^11.7.3",
"react-router-dom": "^5.2.0",
"react-scripts": "4.0.0",
"typescript": "^4.0.3",
"use-debounce": "^5.0.1",
"use-query-params": "^1.1.8",
"web-vitals": "^0.2.4"
},
"scripts": {
"start": "react-app-rewired start",
"build": "react-app-rewired build",
"test": "react-app-rewired test --env=jest-environment-jsdom-sixteen",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"@types/react-router-dom": "^5.1.6",
"babel-plugin-module-resolver": "^4.0.0",
"babel-plugin-transform-imports": "^2.0.0",
"customize-cra": "^1.0.0",
"prettier": "^2.1.2",
"react-app-rewired": "^2.1.6"
}
}

BIN
public/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

43
public/index.html Normal file
View File

@ -0,0 +1,43 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>

BIN
public/logo192.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

BIN
public/logo512.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.4 KiB

25
public/manifest.json Normal file
View File

@ -0,0 +1,25 @@
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
},
{
"src": "logo192.png",
"type": "image/png",
"sizes": "192x192"
},
{
"src": "logo512.png",
"type": "image/png",
"sizes": "512x512"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}

3
public/robots.txt Normal file
View File

@ -0,0 +1,3 @@
# https://www.robotstxt.org/robotstxt.html
User-agent: *
Disallow:

View File

@ -0,0 +1,20 @@
import React from 'react';
import {
Pagination as MaterialUIPagination,
PaginationProps,
} from '@material-ui/lab';
export type Props = PaginationProps & {
total?: number;
perPage?: number;
};
function Pagination({ total, perPage, ...rest }: Props) {
if (total && perPage) {
rest.count = total > 0 ? Math.ceil(total / perPage) : 1;
}
return <MaterialUIPagination {...rest} />;
}
export default Pagination;

2
src/config/api.ts Normal file
View File

@ -0,0 +1,2 @@
export const URI =
process.env.REACT_APP_API_URI ?? 'https://api.tribalwarshelp.com/graphql';

6
src/config/app.ts Normal file
View File

@ -0,0 +1,6 @@
export const DEFAULT_LANGUAGE = 'en';
export const SERVER_STATUS = {
CLOSED: 'closed',
OPEN: 'open',
};

1
src/config/routes.ts Normal file
View File

@ -0,0 +1 @@
export const INDEX_PAGE = '/';

22
src/features/App.tsx Normal file
View File

@ -0,0 +1,22 @@
import React, { Fragment } from 'react';
import * as ROUTES from '@config/routes';
import { Switch, Route } from 'react-router-dom';
import { CssBaseline } from '@material-ui/core';
import IndexPage from './IndexPage/IndexPage';
function App() {
return (
<Fragment>
<Switch>
<Route path={ROUTES.INDEX_PAGE} exact>
<IndexPage />
</Route>
</Switch>
<CssBaseline />
</Fragment>
);
}
export default App;

View File

@ -0,0 +1,23 @@
import React from 'react';
import useStyles from './styles';
import { Container, Toolbar } from '@material-ui/core';
import Header from './components/Header/Header';
import ServerSelection from './components/ServerSelection/ServerSelection';
export default function IndexPage() {
const classes = useStyles();
return (
<div>
<Header />
<Toolbar />
<main className={classes.main}>
<Container>
<ServerSelection />
</Container>
</main>
</div>
);
}

View File

@ -0,0 +1,60 @@
import React from 'react';
import { useQueryParams, StringParam, withDefault } from 'use-query-params';
import { useDebouncedCallback } from 'use-debounce';
import useLanguage from '@libs/i18n/useLanguage';
import {
AppBar,
Toolbar,
TextField,
InputAdornment,
Container,
Button,
} from '@material-ui/core';
import {
Search as SearchIcon,
Language as LanguageIcon,
} from '@material-ui/icons';
export default function Header() {
const [query, setQuery] = useQueryParams({
q: withDefault(StringParam, ''),
});
const debouncedSetQuery = useDebouncedCallback(
value => setQuery({ q: value }),
1000
);
const language = useLanguage();
return (
<AppBar position="fixed">
<Container>
<Toolbar style={{ justifyContent: 'space-between' }}>
<div></div>
<div style={{ width: '40%' }}>
<TextField
fullWidth
variant="outlined"
placeholder="Search"
defaultValue={query.q}
onChange={e => {
debouncedSetQuery.callback(e.target.value);
}}
style={{ backgroundColor: 'rgba(0, 0, 0, 0.1)' }}
InputProps={{
startAdornment: (
<InputAdornment position="start">
<SearchIcon />
</InputAdornment>
),
}}
/>
</div>
<div>
<Button startIcon={<LanguageIcon />}>{language}</Button>
</div>
</Toolbar>
</Container>
</AppBar>
);
}

View File

@ -0,0 +1,118 @@
import React from 'react';
import { useQuery } from '@apollo/client';
import {
useQueryParams,
StringParam,
NumberParam,
withDefault,
} from 'use-query-params';
import { SERVER_STATUS } from '@config/app';
import { ServerList } from './types';
import { SERVERS } from './queries';
import extractLangTagFromHostname from '@utils/extractLangTagFromHostname';
import { Grid, Card, CardHeader, Box } from '@material-ui/core';
import { Skeleton } from '@material-ui/lab';
import Pagination, {
Props as PaginationProps,
} from '@common/Pagination/Pagination';
const PER_PAGE = 30;
export default function ServerSelection() {
const [query, setQuery] = useQueryParams({
page: withDefault(NumberParam, 1),
q: withDefault(StringParam, ''),
});
const { data, loading: loadingServers } = useQuery<ServerList>(SERVERS, {
fetchPolicy: 'cache-and-network',
variables: {
filter: {
sort: 'key ASC',
offset: (query.page - 1) * PER_PAGE,
keyIEQ: '%' + query.q + '%',
limit: PER_PAGE,
langVersionTag: [extractLangTagFromHostname(window.location.hostname)],
},
},
});
const servers = data?.servers?.items ?? [];
const total = data?.servers?.total ?? 0;
const loading = servers.length === 0 && loadingServers;
const handlePageChange = (_: React.ChangeEvent<unknown>, page: number) => {
setQuery({ page });
};
const renderPagination = (top: boolean): JSX.Element => {
const paginationProps: PaginationProps = {
total,
perPage: PER_PAGE,
size: 'large',
page: query.page,
onChange: handlePageChange,
};
return (
<Box
mb={top ? 3 : 0}
mt={top ? 0 : 3}
display="flex"
justifyContent="center"
>
{loading ? (
<Skeleton variant="rect" width={414} height={40} />
) : (
<Pagination {...paginationProps} />
)}
</Box>
);
};
return (
<div>
{renderPagination(true)}
<Grid container spacing={3}>
{loading
? new Array(PER_PAGE).fill(0).map((_, index) => {
return (
<Grid key={index} item xs={12} sm={6} md={4}>
<Card>
<CardHeader
title={<Skeleton variant="text" />}
subheader={<Skeleton variant="text" />}
/>
</Card>
</Grid>
);
})
: servers.map(server => {
return (
<Grid key={server.key} item xs={12} sm={6} md={4}>
<Card>
<CardHeader
title={`${server.key}${
SERVER_STATUS.CLOSED === server.status
? ' (closed)'
: ''
}`}
subheader={
<span>
Number of players:{' '}
{server.numberOfPlayers.toLocaleString()}
<br />
Number of tribes:{' '}
{server.numberOfTribes.toLocaleString()}
<br />
Number of villages:{' '}
{server.numberOfVillages.toLocaleString()}
</span>
}
/>
</Card>
</Grid>
);
})}
</Grid>
{renderPagination(false)}
</div>
);
}

View File

@ -0,0 +1,16 @@
import { gql } from '@apollo/client';
export const SERVERS = gql`
query servers($filter: ServerFilter) {
servers(filter: $filter) {
items {
key
status
numberOfPlayers
numberOfTribes
numberOfVillages
}
total
}
}
`;

View File

@ -0,0 +1,13 @@
import { List } from '@libs/graphql/types';
export type Server = {
key: string;
status: string;
numberOfPlayers: number;
numberOfTribes: number;
numberOfVillages: number;
};
export type ServerList = {
servers?: List<Server[]>;
};

View File

@ -0,0 +1,11 @@
import { makeStyles } from '@material-ui/core/styles';
const useStyles = makeStyles(theme => {
return {
main: {
padding: theme.spacing(3, 0),
},
};
});
export default useStyles;

34
src/index.tsx Normal file
View File

@ -0,0 +1,34 @@
import React from 'react';
import ReactDOM from 'react-dom';
import { ThemeProvider } from '@material-ui/styles';
import { ApolloProvider } from '@apollo/client';
import { BrowserRouter, Route } from 'react-router-dom';
import { I18nextProvider } from 'react-i18next';
import { QueryParamProvider } from 'use-query-params';
import App from './features/App';
import createTheme from './theme/createTheme';
import createGraphQLClient from './libs/graphql/createClient';
import initI18N from './libs/i18n/init';
import { URI as API_URI } from './config/api';
import reportWebVitals from './reportWebVitals';
const jsx = (
<BrowserRouter>
<ThemeProvider theme={createTheme()}>
<I18nextProvider i18n={initI18N()}>
<ApolloProvider client={createGraphQLClient(API_URI)}>
<QueryParamProvider ReactRouterRoute={Route}>
<App />
</QueryParamProvider>
</ApolloProvider>
</I18nextProvider>
</ThemeProvider>
</BrowserRouter>
);
ReactDOM.render(jsx, document.getElementById('root'));
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

View File

@ -0,0 +1,14 @@
import {
ApolloClient,
InMemoryCache,
NormalizedCacheObject,
} from '@apollo/client';
const createClient = (uri: string): ApolloClient<NormalizedCacheObject> => {
return new ApolloClient({
uri: uri,
cache: new InMemoryCache(),
});
};
export default createClient;

View File

@ -0,0 +1,4 @@
export type List<T> = {
total: number;
items: T;
};

View File

@ -0,0 +1 @@
export default {};

34
src/libs/i18n/init.ts Normal file
View File

@ -0,0 +1,34 @@
import i18n, { i18n as i18nT } from 'i18next';
import { initReactI18next } from 'react-i18next';
import LanguageDetector from 'i18next-browser-languagedetector';
import pl from './pl';
import en from './en';
import { DEFAULT_LANGUAGE } from '@config/app';
const init = (): i18nT => {
i18n
.use(LanguageDetector)
.use(initReactI18next)
.init({
fallbackLng: DEFAULT_LANGUAGE,
debug: false,
load: 'languageOnly',
detection: {
order: ['subdomain'],
},
resources: {
en,
pl,
},
defaultNS: 'common',
react: {
useSuspense: false,
},
interpolation: {
escapeValue: false,
},
});
return i18n;
};
export default init;

View File

@ -0,0 +1 @@
export default {};

View File

@ -0,0 +1,7 @@
import { useTranslation } from 'react-i18next';
import { DEFAULT_LANGUAGE } from '@config/app';
export default function useLanguage() {
const { i18n } = useTranslation();
return i18n.language || DEFAULT_LANGUAGE;
}

1
src/react-app-env.d.ts vendored Normal file
View File

@ -0,0 +1 @@
/// <reference types="react-scripts" />

15
src/reportWebVitals.ts Normal file
View File

@ -0,0 +1,15 @@
import { ReportHandler } from 'web-vitals';
const reportWebVitals = (onPerfEntry?: ReportHandler) => {
if (onPerfEntry && onPerfEntry instanceof Function) {
import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
getCLS(onPerfEntry);
getFID(onPerfEntry);
getFCP(onPerfEntry);
getLCP(onPerfEntry);
getTTFB(onPerfEntry);
});
}
}
export default reportWebVitals;

5
src/setupTests.ts Normal file
View File

@ -0,0 +1,5 @@
// jest-dom adds custom jest matchers for asserting on DOM nodes.
// allows you to do things like:
// expect(element).toHaveTextContent(/react/i)
// learn more: https://github.com/testing-library/jest-dom
import '@testing-library/jest-dom';

30
src/theme/createTheme.ts Normal file
View File

@ -0,0 +1,30 @@
import {
createMuiTheme,
responsiveFontSizes,
Theme,
} from '@material-ui/core/styles';
const createTheme = (): Theme => {
return responsiveFontSizes(
createMuiTheme({
palette: {
type: 'dark',
},
typography: {
h2: {
fontWeight: 400,
},
},
props: {
MuiTextField: {
variant: 'outlined',
},
MuiAppBar: {
color: 'default',
},
},
})
);
};
export default createTheme;

View File

@ -0,0 +1,7 @@
import { DEFAULT_LANGUAGE } from '@config/app';
const extractLangTagFromHostname = (hostname = '') => {
return hostname.substring(0, hostname.lastIndexOf('.')) || DEFAULT_LANGUAGE;
};
export default extractLangTagFromHostname;

50
tsconfig.json Normal file
View File

@ -0,0 +1,50 @@
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": [
"src/*"
],
"@common/*": [
"src/common/*"
],
"@config/*": [
"src/config/*"
],
"@features/*": [
"src/features/*"
],
"@libs/*": [
"src/libs/*"
],
"@utils/*": [
"src/utils/*"
]
},
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react"
},
"exclude": [
"node_modules"
],
"include": [
"src"
]
}

11998
yarn.lock Normal file

File diff suppressed because it is too large Load Diff