├── .eslintrc.js
├── .github
└── workflows
│ ├── linter.yml
│ └── nodejs.yml
├── .gitignore
├── .prettierrc
├── .vscode
└── settings.json
├── README.md
├── internals
└── generators
│ ├── component
│ ├── Component.spec.tsx.hbs
│ ├── Component.tsx.hbs
│ ├── index.js
│ ├── index.ts.hbs
│ └── types.ts.hbs
│ ├── container
│ ├── Container.spec.tsx.hbs
│ ├── Container.tsx.hbs
│ ├── ContainerContext.ts.hbs
│ ├── Loadable.tsx.hbs
│ ├── index.js
│ ├── index.ts.hbs
│ └── types.ts.hbs
│ ├── index.js
│ └── utils
│ └── componentExists.js
├── package-lock.json
├── package.json
├── public
├── favicon.ico
├── index.html
└── manifest.json
├── src
├── components
│ └── README.md
├── containers
│ ├── App
│ │ ├── App.spec.tsx
│ │ ├── App.tsx
│ │ ├── AppContext.ts
│ │ ├── index.ts
│ │ └── types.ts
│ ├── HomePage
│ │ ├── HomePage.spec.tsx
│ │ ├── HomePage.tsx
│ │ ├── HomePageContext.ts
│ │ ├── Loadable.tsx
│ │ ├── index.ts
│ │ └── types.ts
│ ├── Language
│ │ ├── Language.spec.tsx
│ │ ├── Language.tsx
│ │ ├── LanguageContext.ts
│ │ ├── i18n.ts
│ │ ├── index.ts
│ │ └── types.ts
│ ├── NotFoundPage
│ │ ├── Loadable.tsx
│ │ ├── NotFoundPage.spec.tsx
│ │ ├── NotFoundPage.tsx
│ │ └── index.ts
│ └── README.md
├── index.tsx
├── react-app-env.d.ts
├── serviceWorker.js
├── setupTests.ts
├── translations
│ ├── en.json
│ └── fil.json
└── utils
│ ├── loadable.tsx
│ ├── request.spec.ts
│ └── request.ts
└── tsconfig.json
/.eslintrc.js:
--------------------------------------------------------------------------------
1 | const fs = require('fs');
2 | const path = require('path');
3 |
4 | const prettierOptions = JSON.parse(
5 | fs.readFileSync(path.resolve(__dirname, '.prettierrc'), 'utf8'),
6 | );
7 |
8 | module.exports = {
9 | parser: '@typescript-eslint/parser',
10 | extends: ['airbnb', 'prettier', 'prettier/react', 'plugin:@typescript-eslint/recommended'],
11 | plugins: ['prettier', 'react', 'react-hooks', 'jsx-a11y'],
12 | env: {
13 | jest: true,
14 | browser: true,
15 | node: true,
16 | es6: true,
17 | },
18 | parserOptions: {
19 | ecmaVersion: 6,
20 | sourceType: 'module',
21 | ecmaFeatures: {
22 | jsx: true,
23 | },
24 | },
25 | rules: {
26 | 'prettier/prettier': ['error', prettierOptions],
27 | 'arrow-body-style': [2, 'as-needed'],
28 | 'class-methods-use-this': 0,
29 | 'import/imports-first': 0,
30 | 'import/newline-after-import': 0,
31 | 'import/no-dynamic-require': 0,
32 | 'import/no-extraneous-dependencies': 0,
33 | 'import/no-named-as-default': 0,
34 | 'import/no-unresolved': 2,
35 | 'import/no-webpack-loader-syntax': 0,
36 | 'import/prefer-default-export': 0,
37 | 'import/extensions': 0,
38 | indent: [
39 | 2,
40 | 2,
41 | {
42 | SwitchCase: 1,
43 | },
44 | ],
45 | 'jsx-a11y/aria-props': 2,
46 | 'jsx-a11y/heading-has-content': 0,
47 | 'jsx-a11y/label-has-associated-control': [
48 | 2,
49 | {
50 | // NOTE: If this error triggers, either disable it or add
51 | // your custom components, labels and attributes via these options
52 | // See https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/label-has-associated-control.md
53 | controlComponents: ['Input'],
54 | },
55 | ],
56 | 'jsx-a11y/label-has-for': 0,
57 | 'jsx-a11y/mouse-events-have-key-events': 2,
58 | 'jsx-a11y/role-has-required-aria-props': 2,
59 | 'jsx-a11y/role-supports-aria-props': 2,
60 | 'max-len': 0,
61 | 'newline-per-chained-call': 0,
62 | 'no-confusing-arrow': 0,
63 | 'no-console': 1,
64 | 'no-unused-vars': 2,
65 | 'no-use-before-define': 0,
66 | 'prefer-template': 2,
67 | 'react/destructuring-assignment': 0,
68 | 'react-hooks/rules-of-hooks': 'error',
69 | 'react/jsx-closing-tag-location': 0,
70 | 'react/forbid-prop-types': 0,
71 | 'react/jsx-first-prop-new-line': [2, 'multiline'],
72 | 'react/jsx-filename-extension': 0,
73 | 'react/jsx-no-target-blank': 0,
74 | 'react/jsx-uses-vars': 2,
75 | 'react/prop-types': 0,
76 | 'react/require-default-props': 0,
77 | 'react/require-extension': 0,
78 | 'react/self-closing-comp': 0,
79 | 'react/sort-comp': 0,
80 | 'require-yield': 0,
81 | '@typescript-eslint/no-use-before-define': 0,
82 | },
83 | settings: {
84 | 'import/resolver': {
85 | 'node': {
86 | "extensions": ['.js', '.jsx', '.ts', '.tsx']
87 | }
88 | }
89 | },
90 | };
91 |
--------------------------------------------------------------------------------
/.github/workflows/linter.yml:
--------------------------------------------------------------------------------
1 | on: [pull_request]
2 |
3 | jobs:
4 | build:
5 |
6 | runs-on: ubuntu-latest
7 |
8 | strategy:
9 | matrix:
10 | node-version: [8.x]
11 |
12 | steps:
13 | - uses: actions/checkout@v1
14 | - name: Use Node.js ${{ matrix.node-version }}
15 | uses: actions/setup-node@v1
16 | with:
17 | node-version: ${{ matrix.node-version }}
18 | - name: npm lint
19 | run: |
20 | npm install
21 | npm run lint
22 | env:
23 | CI: true
24 |
--------------------------------------------------------------------------------
/.github/workflows/nodejs.yml:
--------------------------------------------------------------------------------
1 | on:
2 | pull_request:
3 | branches:
4 | - '*'
5 | push:
6 | branches:
7 | - master
8 |
9 | jobs:
10 | build:
11 |
12 | runs-on: ubuntu-latest
13 |
14 | strategy:
15 | matrix:
16 | node-version: [8.x, 10.x, 12.x]
17 |
18 | steps:
19 | - uses: actions/checkout@v1
20 | - name: Use Node.js ${{ matrix.node-version }}
21 | uses: actions/setup-node@v1
22 | with:
23 | node-version: ${{ matrix.node-version }}
24 | - name: npm install, build, and test
25 | run: |
26 | npm install
27 | npm run build --if-present
28 | npm test
29 | env:
30 | CI: true
31 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
2 |
3 | # dependencies
4 | /node_modules
5 | /.pnp
6 | .pnp.js
7 |
8 | # testing
9 | /coverage
10 |
11 | # production
12 | /build
13 |
14 | # misc
15 | .DS_Store
16 | .env.local
17 | .env.development.local
18 | .env.test.local
19 | .env.production.local
20 |
21 | npm-debug.log*
22 | yarn-debug.log*
23 | yarn-error.log*
24 |
--------------------------------------------------------------------------------
/.prettierrc:
--------------------------------------------------------------------------------
1 | {
2 | "printWidth": 80,
3 | "tabWidth": 2,
4 | "useTabs": false,
5 | "semi": true,
6 | "singleQuote": true,
7 | "trailingComma": "all",
8 | "jsxBracketSameLine": false,
9 | "bracketSpacing": true
10 | }
11 |
--------------------------------------------------------------------------------
/.vscode/settings.json:
--------------------------------------------------------------------------------
1 | {
2 | "eslint.validate": [
3 | "javascript",
4 | "javascriptreact",
5 | { "language": "typescript", "autoFix": true },
6 | { "language": "typescriptreact", "autoFix": true }
7 | ]
8 | }
9 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | Based on Create React App with Typescript, bootstrapped with the latest packages of [react](https://github.com/facebook/react), [react-router-dom](https://github.com/ReactTraining/react-router), [react-helmet-async](https://github.com/staylor/react-helmet-async), [react-intl](https://github.com/formatjs/react-intl), [styled-components](https://github.com/styled-components/styled-components), and [@testing-library/react](https://github.com/testing-library/react-testing-library). A redux-less boilerplate inspired by [@kentcdodds](https://twitter.com/kentcdodds) and [@ryanflorence](https://twitter.com/ryanflorence).
2 |
3 | ## Library Selections
4 |
5 | ### State Management
6 | React Context
7 |
8 | ### CSS Styling
9 | styled-components
10 |
11 | ### Routing
12 | react-router-dom
13 |
14 | ### Head Document
15 | react-helmet-async
16 |
17 | ### Internationalization
18 | react-intl
19 |
20 | ### Component Lazy Loading
21 | React lazy, Suspense
22 |
23 | ### Unit Testing
24 | @testing-library/react
25 |
26 | ## Available Scripts
27 |
28 | In the project directory, you can run:
29 |
30 | ### `npm start`
31 |
32 | Runs the app in the development mode.
33 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
34 |
35 | The page will reload if you make edits.
36 | You will also see any lint errors in the console.
37 |
38 | ### `npm test`
39 |
40 | Launches the test runner in the interactive watch mode.
41 | See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
42 |
43 | ### `npm run build`
44 |
45 | Builds the app for production to the `build` folder.
46 | It correctly bundles React in production mode and optimizes the build for the best performance.
47 |
48 | The build is minified and the filenames include the hashes.
49 | Your app is ready to be deployed!
50 |
51 | See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
52 |
53 | ### `npm run eject`
54 |
55 | **Note: this is a one-way operation. Once you `eject`, you can’t go back!**
56 |
57 | If you aren’t 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.
58 |
59 | 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 you’re on your own.
60 |
61 | You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.
62 |
63 | ### `npm run generate`
64 |
65 | Creates template files either for `component` or `container`.
66 |
--------------------------------------------------------------------------------
/internals/generators/component/Component.spec.tsx.hbs:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { render } from '@testing-library/react';
3 | import {{name}} from './{{name}}';
4 |
5 | describe('<{{name}} />', () => {
6 | it('should get the text', () => {
7 | const { getByText } = render(<{{name}} />);
8 |
9 | expect(getByText('Hello World')).toBeInTheDocument();
10 | });
11 | });
12 |
--------------------------------------------------------------------------------
/internals/generators/component/Component.tsx.hbs:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { {{name}}Props } from './types';
3 |
4 | const {{name}}: React.FC<{{name}}Props> = (): React.ReactElement => (<>>);
5 |
6 | export default {{name}};
7 |
--------------------------------------------------------------------------------
/internals/generators/component/index.js:
--------------------------------------------------------------------------------
1 | const componentDir = '../../src/components/{{name}}';
2 | const componentExists = require('../utils/componentExists');
3 |
4 | module.exports = {
5 | description: 'Generate a component',
6 | prompts: [
7 | {
8 | type: 'input',
9 | name: 'name',
10 | message: 'Name of component:',
11 | default: 'Button',
12 | validate: value => {
13 | if (/.+/.test(value)) {
14 | return componentExists(value)
15 | ? `Component (${value}) already exists.`
16 | : true;
17 | }
18 |
19 | return 'Component name is required.';
20 | },
21 | },
22 | {
23 | type: 'confirm',
24 | name: 'wantUnitTests',
25 | default: true,
26 | message: 'Do you want to add unit test(s)?',
27 | },
28 | ],
29 | actions: data => {
30 | const actions = [
31 | {
32 | type: 'add',
33 | path: `${componentDir}/index.ts`,
34 | templateFile: './component/index.ts.hbs',
35 | },
36 | {
37 | type: 'add',
38 | path: `${componentDir}/{{name}}.tsx`,
39 | templateFile: './component/Component.tsx.hbs',
40 | },
41 | {
42 | type: 'add',
43 | path: `${componentDir}/types.ts`,
44 | templateFile: './component/types.ts.hbs',
45 | },
46 | ];
47 |
48 | if (data.wantUnitTests) {
49 | actions.push({
50 | type: 'add',
51 | path: `${componentDir}/{{name}}.spec.tsx`,
52 | templateFile: './component/Component.spec.tsx.hbs',
53 | });
54 | }
55 |
56 | return actions;
57 | },
58 | };
59 |
--------------------------------------------------------------------------------
/internals/generators/component/index.ts.hbs:
--------------------------------------------------------------------------------
1 | import {{name}} from './{{name}}';
2 |
3 | export default {{name}};
4 |
--------------------------------------------------------------------------------
/internals/generators/component/types.ts.hbs:
--------------------------------------------------------------------------------
1 | export type {{name}}Props = {
2 |
3 | };
4 |
--------------------------------------------------------------------------------
/internals/generators/container/Container.spec.tsx.hbs:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { render } from '@testing-library/react';
3 | import {{name}} from './{{name}}';
4 |
5 | describe('<{{name}} />', () => {
6 | it('should have {{name}} text', () => {
7 | const { getByText } = render(<{{name}} />);
8 |
9 | expect(getByText('{{name}}')).toBeInTheDocument();
10 | });
11 | });
12 |
--------------------------------------------------------------------------------
/internals/generators/container/Container.tsx.hbs:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { Helmet } from 'react-helmet-async';
3 | import {{name}}Context from './{{name}}Context';
4 |
5 | const {{name}} = (): React.ReactElement => (
6 | <{{name}}Context.Provider value=\{{}}>
7 |
8 | {{name}}
9 |
10 |
11 |
{{name}}
12 | {{name}}Context.Provider>
13 | );
14 |
15 | export default {{name}};
16 |
--------------------------------------------------------------------------------
/internals/generators/container/ContainerContext.ts.hbs:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { T{{name}}Context } from './types';
3 |
4 | const {{name}}Context = React.createContext(undefined);
5 |
6 | {{name}}Context.displayName = '{{name}}Context';
7 |
8 | export const use{{name}}Context = (): T{{name}}Context => {
9 | const context = React.useContext({{name}}Context);
10 | if (context === undefined) {
11 | throw new Error('use{{name}}Context must be used within a {{name}}Provider.');
12 | }
13 | return context;
14 | };
15 |
16 | export default {{name}}Context;
17 |
--------------------------------------------------------------------------------
/internals/generators/container/Loadable.tsx.hbs:
--------------------------------------------------------------------------------
1 | import loadable from '../../utils/loadable';
2 |
3 | export default loadable(() => import('./index'));
4 |
--------------------------------------------------------------------------------
/internals/generators/container/index.js:
--------------------------------------------------------------------------------
1 | const containerDir = '../../src/containers/{{name}}';
2 | const componentExists = require('../utils/componentExists');
3 |
4 | module.exports = {
5 | description: 'Generate a container',
6 | prompts: [
7 | {
8 | type: 'input',
9 | name: 'name',
10 | message: 'Name of container:',
11 | default: 'Form',
12 | validate: value => {
13 | if (/.+/.test(value)) {
14 | return componentExists(value)
15 | ? `Container (${value}) already exists.`
16 | : true;
17 | }
18 |
19 | return 'Container name is required.';
20 | },
21 | },
22 | {
23 | type: 'confirm',
24 | name: 'wantUnitTests',
25 | default: true,
26 | message: 'Do you want to add unit test(s)?',
27 | },
28 | ],
29 | actions: data => {
30 | const actions = [
31 | {
32 | type: 'add',
33 | path: `${containerDir}/index.ts`,
34 | templateFile: './container/index.ts.hbs',
35 | },
36 | {
37 | type: 'add',
38 | path: `${containerDir}/{{name}}.tsx`,
39 | templateFile: './container/Container.tsx.hbs',
40 | },
41 | {
42 | type: 'add',
43 | path: `${containerDir}/types.ts`,
44 | templateFile: './container/types.ts.hbs',
45 | },
46 | {
47 | type: 'add',
48 | path: `${containerDir}/{{name}}Context.ts`,
49 | templateFile: './container/ContainerContext.ts.hbs',
50 | },
51 | {
52 | type: 'add',
53 | path: `${containerDir}/Loadable.tsx`,
54 | templateFile: './container/Loadable.tsx.hbs',
55 | },
56 | ];
57 |
58 | if (data.wantUnitTests) {
59 | actions.push({
60 | type: 'add',
61 | path: `${containerDir}/{{name}}.spec.tsx`,
62 | templateFile: './container/Container.spec.tsx.hbs',
63 | });
64 | }
65 |
66 | return actions;
67 | },
68 | };
69 |
--------------------------------------------------------------------------------
/internals/generators/container/index.ts.hbs:
--------------------------------------------------------------------------------
1 | import {{name}} from './{{name}}';
2 |
3 | export default {{name}};
4 |
--------------------------------------------------------------------------------
/internals/generators/container/types.ts.hbs:
--------------------------------------------------------------------------------
1 | export type T{{name}}Context = {};
2 |
--------------------------------------------------------------------------------
/internals/generators/index.js:
--------------------------------------------------------------------------------
1 | const componentGenerator = require('./component');
2 | const containerGenerator = require('./container');
3 |
4 | module.exports = function generator(plop) {
5 | plop.setGenerator('component', componentGenerator);
6 | plop.setGenerator('container', containerGenerator);
7 | };
8 |
--------------------------------------------------------------------------------
/internals/generators/utils/componentExists.js:
--------------------------------------------------------------------------------
1 | const fs = require('fs');
2 | const path = require('path');
3 |
4 | const components = fs.readdirSync(
5 | path.join(__dirname, '../../../src/components'),
6 | );
7 | const containers = fs.readdirSync(
8 | path.join(__dirname, '../../../src/containers'),
9 | );
10 |
11 | function componentExists(comp) {
12 | return [...components, ...containers].indexOf(comp) >= 0;
13 | }
14 |
15 | module.exports = componentExists;
16 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "react-jump-start",
3 | "version": "1.2.0",
4 | "private": false,
5 | "dependencies": {
6 | "react": "16.12.0",
7 | "react-dom": "16.12.0",
8 | "react-helmet-async": "1.0.4",
9 | "react-intl": "4.3.1",
10 | "react-router-dom": "5.1.2",
11 | "react-scripts": "3.4.1",
12 | "styled-components": "5.0.1",
13 | "typescript": "3.8.3"
14 | },
15 | "scripts": {
16 | "start": "react-scripts start",
17 | "build": "react-scripts build",
18 | "test": "react-scripts test",
19 | "eject": "react-scripts eject",
20 | "generate": "plop --plopfile ./internals/generators/index.js",
21 | "lint": "eslint src/**/*.{ts,tsx}"
22 | },
23 | "eslintConfig": {
24 | "extends": "react-app"
25 | },
26 | "browserslist": [
27 | ">0.2%",
28 | "not dead",
29 | "not ie <= 11",
30 | "not op_mini all"
31 | ],
32 | "devDependencies": {
33 | "@testing-library/jest-dom": "5.3.0",
34 | "@testing-library/react": "9.4.0",
35 | "@types/jest": "25.1.4",
36 | "@types/node": "13.7.0",
37 | "@types/react": "16.9.19",
38 | "@types/react-dom": "16.9.5",
39 | "@types/react-router-dom": "5.1.3",
40 | "@types/styled-components": "4.4.2",
41 | "@typescript-eslint/parser": "2.19.0",
42 | "eslint": "6.8.0",
43 | "eslint-config-airbnb": "18.0.1",
44 | "eslint-config-prettier": "6.10.1",
45 | "eslint-plugin-import": "2.20.1",
46 | "eslint-plugin-jsx-a11y": "6.2.3",
47 | "eslint-plugin-prettier": "3.1.2",
48 | "eslint-plugin-react": "7.18.3",
49 | "husky": "4.2.3",
50 | "lint-staged": "10.0.7",
51 | "plop": "2.5.3",
52 | "prettier": "1.19.1"
53 | },
54 | "jest": {
55 | "collectCoverageFrom": [
56 | "src/**/*.{js,jsx,ts,tsx}",
57 | "!/coverage/",
58 | "!/node_modules/",
59 | "!/src/index.tsx",
60 | "!/src/serviceWorker.js",
61 | "!src/**/*{L,l}oadable.tsx",
62 | "!src/**/*Context.ts"
63 | ],
64 | "coverageThreshold": {
65 | "global": {
66 | "branches": 98,
67 | "functions": 98,
68 | "lines": 98,
69 | "statements": 98
70 | }
71 | }
72 | },
73 | "husky": {
74 | "hooks": {
75 | "pre-commit": "lint-staged"
76 | }
77 | },
78 | "lint-staged": {
79 | "*.{ts,tsx}": [
80 | "eslint --fix",
81 | "git add"
82 | ]
83 | }
84 | }
85 |
--------------------------------------------------------------------------------
/public/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kmhigashioka/react-jump-start/9f1be968570d2bbb781793046fc6e6b1f1db9265/public/favicon.ico
--------------------------------------------------------------------------------
/public/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
10 |
11 |
15 |
16 |
25 | React App
26 |
27 |
28 |
29 |
30 |
40 |
41 |
42 |
--------------------------------------------------------------------------------
/public/manifest.json:
--------------------------------------------------------------------------------
1 | {
2 | "short_name": "React App",
3 | "name": "Create React App Sample",
4 | "icons": [
5 | {
6 | "src": "favicon.ico",
7 | "sizes": "64x64 32x32 24x24 16x16",
8 | "type": "image/x-icon"
9 | }
10 | ],
11 | "start_url": ".",
12 | "display": "standalone",
13 | "theme_color": "#000000",
14 | "background_color": "#ffffff"
15 | }
16 |
--------------------------------------------------------------------------------
/src/components/README.md:
--------------------------------------------------------------------------------
1 | Libraries for components.
2 |
--------------------------------------------------------------------------------
/src/containers/App/App.spec.tsx:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { render } from '@testing-library/react';
3 | import { MemoryRouter } from 'react-router-dom';
4 | import App from './App';
5 |
6 | jest.mock('../HomePage/Loadable', () => (): string => 'MockHomePage');
7 |
8 | jest.mock('../NotFoundPage/Loadable', () => (): string => 'MockNotFoundPage');
9 |
10 | describe('', () => {
11 | it('should able to navigate to /', () => {
12 | const { getByText } = render();
13 |
14 | expect(getByText('MockHomePage')).toBeInTheDocument();
15 | });
16 |
17 | it('should redirect to Not Found when access an unable route', () => {
18 | const { getByText } = render();
19 |
20 | expect(getByText('MockNotFoundPage')).toBeInTheDocument();
21 | });
22 | });
23 |
24 | type ComponentProps = {
25 | initialEntries: string[] | undefined;
26 | };
27 |
28 | function Component({ initialEntries }: ComponentProps): React.ReactElement {
29 | return (
30 |
31 |
32 |
33 | );
34 | }
35 |
--------------------------------------------------------------------------------
/src/containers/App/App.tsx:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { Route, Switch } from 'react-router-dom';
3 | import { Helmet } from 'react-helmet-async';
4 | import { AppProps } from './types';
5 | import AppContext from './AppContext';
6 |
7 | import HomePage from '../HomePage/Loadable';
8 | import NotFoundPage from '../NotFoundPage/Loadable';
9 |
10 | const App: React.FC = () => (
11 |
12 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 | );
24 |
25 | export default App;
26 |
--------------------------------------------------------------------------------
/src/containers/App/AppContext.ts:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { TAppContext } from './types';
3 |
4 | const AppContext = React.createContext(undefined);
5 |
6 | AppContext.displayName = 'AppContext';
7 |
8 | export const useAppContext = (): TAppContext => {
9 | const context = React.useContext(AppContext);
10 | if (context === undefined) {
11 | throw new Error('useAppContext must be used within a AppContextProvider.');
12 | }
13 | return context;
14 | };
15 |
16 | export default AppContext;
17 |
--------------------------------------------------------------------------------
/src/containers/App/index.ts:
--------------------------------------------------------------------------------
1 | import App from './App';
2 |
3 | export default App;
4 |
--------------------------------------------------------------------------------
/src/containers/App/types.ts:
--------------------------------------------------------------------------------
1 | export type AppProps = {};
2 | export type TAppContext = {};
3 |
--------------------------------------------------------------------------------
/src/containers/HomePage/HomePage.spec.tsx:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { render } from '@testing-library/react';
3 | import HomePage from './HomePage';
4 |
5 | describe('', () => {
6 | it('should have HomePage text', () => {
7 | const { getByText } = render();
8 |
9 | expect(getByText('HomePage')).toBeInTheDocument();
10 | });
11 | });
12 |
--------------------------------------------------------------------------------
/src/containers/HomePage/HomePage.tsx:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { Helmet } from 'react-helmet-async';
3 | import HomePageContext from './HomePageContext';
4 |
5 | const HomePage = (): React.ReactElement => (
6 |
7 |
8 | Home
9 |
10 |
11 | HomePage
12 |
13 | );
14 |
15 | export default HomePage;
16 |
--------------------------------------------------------------------------------
/src/containers/HomePage/HomePageContext.ts:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { THomePageContext } from './types';
3 |
4 | const HomePageContext = React.createContext(
5 | undefined,
6 | );
7 |
8 | HomePageContext.displayName = 'HomePageContext';
9 |
10 | export const useHomePageContext = (): THomePageContext => {
11 | const context = React.useContext(HomePageContext);
12 | if (context === undefined) {
13 | throw new Error(
14 | 'useHomePageContext must be used within a HomePageContextProvider.',
15 | );
16 | }
17 | return context;
18 | };
19 |
20 | export default HomePageContext;
21 |
--------------------------------------------------------------------------------
/src/containers/HomePage/Loadable.tsx:
--------------------------------------------------------------------------------
1 | import loadable from '../../utils/loadable';
2 |
3 | export default loadable(() => import('./index'));
4 |
--------------------------------------------------------------------------------
/src/containers/HomePage/index.ts:
--------------------------------------------------------------------------------
1 | import HomePage from './HomePage';
2 |
3 | export default HomePage;
4 |
--------------------------------------------------------------------------------
/src/containers/HomePage/types.ts:
--------------------------------------------------------------------------------
1 | export type THomePageContext = {};
2 |
--------------------------------------------------------------------------------
/src/containers/Language/Language.spec.tsx:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { render, fireEvent } from '@testing-library/react';
3 | import Language, { LanguageContext, useIntl } from './index';
4 | import { translationMessages } from './i18n';
5 |
6 | describe('', () => {
7 | it('should able to change locale', () => {
8 | const { getByText } = render(
9 |
10 |
11 | ,
12 | );
13 |
14 | const filRadio = getByText('fil');
15 | fireEvent.click(filRadio);
16 |
17 | const homePageTranslatedText = getByText('PahinangTahanan');
18 | expect(homePageTranslatedText).toBeInTheDocument();
19 | });
20 | });
21 |
22 | function Component(): React.ReactElement {
23 | const languageState = React.useContext(LanguageContext);
24 | const { formatMessage: f } = useIntl();
25 |
26 | return (
27 | <>
28 | {f({ id: 'containers.HomePage.title' })}
29 | languageState.setLocale('en')}
34 | />
35 |
36 | languageState.setLocale('fil')}
41 | />
42 |
43 | >
44 | );
45 | }
46 |
--------------------------------------------------------------------------------
/src/containers/Language/Language.tsx:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { IntlProvider } from 'react-intl';
3 | import LanguageContext from './LanguageContext';
4 | import { LanguageProps } from './types';
5 |
6 | const Language: React.FC = ({ children, messages }) => {
7 | const localeLanguage = navigator.language.split('-')[0];
8 | const [locale, setLocale] = React.useState(localeLanguage);
9 | const languageState = { setLocale };
10 |
11 | return (
12 |
13 |
14 | {children}
15 |
16 |
17 | );
18 | };
19 |
20 | export default Language;
21 |
--------------------------------------------------------------------------------
/src/containers/Language/LanguageContext.ts:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { TLanguageContext } from './types';
3 |
4 | const LanguageContext = React.createContext(
5 | undefined,
6 | );
7 |
8 | LanguageContext.displayName = 'LanguageContext';
9 |
10 | export const useLanguageContext = (): TLanguageContext => {
11 | const context = React.useContext(LanguageContext);
12 | if (context === undefined) {
13 | throw new Error(
14 | 'useLanguageContext must be used within a LanguageContextProvider.',
15 | );
16 | }
17 | return context;
18 | };
19 |
20 | export default LanguageContext;
21 |
--------------------------------------------------------------------------------
/src/containers/Language/i18n.ts:
--------------------------------------------------------------------------------
1 | import en from '../../translations/en.json';
2 | import fil from '../../translations/fil.json';
3 | import { TTranslationMessages } from './types';
4 |
5 | export const translationMessages: TTranslationMessages = {
6 | en,
7 | fil,
8 | };
9 |
--------------------------------------------------------------------------------
/src/containers/Language/index.ts:
--------------------------------------------------------------------------------
1 | import Language from './Language';
2 | import Context from './LanguageContext';
3 |
4 | export { useIntl } from 'react-intl';
5 | export default Language;
6 | export const LanguageContext = Context;
7 |
--------------------------------------------------------------------------------
/src/containers/Language/types.ts:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 |
3 | export interface LanguageProps {
4 | children: React.ReactNode;
5 | messages: TTranslationMessages;
6 | }
7 |
8 | export type TLanguageContext = {
9 | setLocale: (locale: string) => void;
10 | };
11 |
12 | export type TTranslationMessages = { [language: string]: {} };
13 |
--------------------------------------------------------------------------------
/src/containers/NotFoundPage/Loadable.tsx:
--------------------------------------------------------------------------------
1 | import loadable from '../../utils/loadable';
2 |
3 | export default loadable(() => import('./index'));
4 |
--------------------------------------------------------------------------------
/src/containers/NotFoundPage/NotFoundPage.spec.tsx:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { render } from '@testing-library/react';
3 | import NotFoundPage from './NotFoundPage';
4 |
5 | describe('', () => {
6 | it('should have Not Found text', () => {
7 | const { getByText } = render();
8 |
9 | expect(getByText('Not Found.')).toBeInTheDocument();
10 | });
11 | });
12 |
--------------------------------------------------------------------------------
/src/containers/NotFoundPage/NotFoundPage.tsx:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { Helmet } from 'react-helmet-async';
3 |
4 | const NotFoundPage = (): React.ReactElement => (
5 | <>
6 |
7 | Not Found
8 |
9 |
10 | Not Found.
11 | >
12 | );
13 |
14 | export default NotFoundPage;
15 |
--------------------------------------------------------------------------------
/src/containers/NotFoundPage/index.ts:
--------------------------------------------------------------------------------
1 | import NotFoundPage from './NotFoundPage';
2 |
3 | export default NotFoundPage;
4 |
--------------------------------------------------------------------------------
/src/containers/README.md:
--------------------------------------------------------------------------------
1 | Libraries for containers.
2 |
--------------------------------------------------------------------------------
/src/index.tsx:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import ReactDOM from 'react-dom';
3 | import { BrowserRouter as Router } from 'react-router-dom';
4 | import { HelmetProvider, Helmet } from 'react-helmet-async';
5 | import App from './containers/App';
6 | import Language from './containers/Language';
7 | import * as serviceWorker from './serviceWorker';
8 | import { translationMessages } from './containers/Language/i18n';
9 |
10 | ReactDOM.render(
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 | ,
21 | document.getElementById('root'),
22 | );
23 |
24 | // If you want your app to work offline and load faster, you can change
25 | // unregister() to register() below. Note this comes with some pitfalls.
26 | // Learn more about service workers: http://bit.ly/CRA-PWA
27 | serviceWorker.unregister();
28 |
--------------------------------------------------------------------------------
/src/react-app-env.d.ts:
--------------------------------------------------------------------------------
1 | // eslint-disable-next-line spaced-comment
2 | ///
3 |
--------------------------------------------------------------------------------
/src/serviceWorker.js:
--------------------------------------------------------------------------------
1 | // This optional code is used to register a service worker.
2 | // register() is not called by default.
3 |
4 | // This lets the app load faster on subsequent visits in production, and gives
5 | // it offline capabilities. However, it also means that developers (and users)
6 | // will only see deployed updates on subsequent visits to a page, after all the
7 | // existing tabs open on the page have been closed, since previously cached
8 | // resources are updated in the background.
9 |
10 | // To learn more about the benefits of this model and instructions on how to
11 | // opt-in, read http://bit.ly/CRA-PWA
12 |
13 | const isLocalhost = Boolean(
14 | window.location.hostname === 'localhost' ||
15 | // [::1] is the IPv6 localhost address.
16 | window.location.hostname === '[::1]' ||
17 | // 127.0.0.1/8 is considered localhost for IPv4.
18 | window.location.hostname.match(
19 | /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
20 | )
21 | );
22 |
23 | export function register(config) {
24 | if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
25 | // The URL constructor is available in all browsers that support SW.
26 | const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
27 | if (publicUrl.origin !== window.location.origin) {
28 | // Our service worker won't work if PUBLIC_URL is on a different origin
29 | // from what our page is served on. This might happen if a CDN is used to
30 | // serve assets; see https://github.com/facebook/create-react-app/issues/2374
31 | return;
32 | }
33 |
34 | window.addEventListener('load', () => {
35 | const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
36 |
37 | if (isLocalhost) {
38 | // This is running on localhost. Let's check if a service worker still exists or not.
39 | checkValidServiceWorker(swUrl, config);
40 |
41 | // Add some additional logging to localhost, pointing developers to the
42 | // service worker/PWA documentation.
43 | navigator.serviceWorker.ready.then(() => {
44 | console.log(
45 | 'This web app is being served cache-first by a service ' +
46 | 'worker. To learn more, visit http://bit.ly/CRA-PWA'
47 | );
48 | });
49 | } else {
50 | // Is not localhost. Just register service worker
51 | registerValidSW(swUrl, config);
52 | }
53 | });
54 | }
55 | }
56 |
57 | function registerValidSW(swUrl, config) {
58 | navigator.serviceWorker
59 | .register(swUrl)
60 | .then(registration => {
61 | registration.onupdatefound = () => {
62 | const installingWorker = registration.installing;
63 | if (installingWorker == null) {
64 | return;
65 | }
66 | installingWorker.onstatechange = () => {
67 | if (installingWorker.state === 'installed') {
68 | if (navigator.serviceWorker.controller) {
69 | // At this point, the updated precached content has been fetched,
70 | // but the previous service worker will still serve the older
71 | // content until all client tabs are closed.
72 | console.log(
73 | 'New content is available and will be used when all ' +
74 | 'tabs for this page are closed. See http://bit.ly/CRA-PWA.'
75 | );
76 |
77 | // Execute callback
78 | if (config && config.onUpdate) {
79 | config.onUpdate(registration);
80 | }
81 | } else {
82 | // At this point, everything has been precached.
83 | // It's the perfect time to display a
84 | // "Content is cached for offline use." message.
85 | console.log('Content is cached for offline use.');
86 |
87 | // Execute callback
88 | if (config && config.onSuccess) {
89 | config.onSuccess(registration);
90 | }
91 | }
92 | }
93 | };
94 | };
95 | })
96 | .catch(error => {
97 | console.error('Error during service worker registration:', error);
98 | });
99 | }
100 |
101 | function checkValidServiceWorker(swUrl, config) {
102 | // Check if the service worker can be found. If it can't reload the page.
103 | fetch(swUrl)
104 | .then(response => {
105 | // Ensure service worker exists, and that we really are getting a JS file.
106 | const contentType = response.headers.get('content-type');
107 | if (
108 | response.status === 404 ||
109 | (contentType != null && contentType.indexOf('javascript') === -1)
110 | ) {
111 | // No service worker found. Probably a different app. Reload the page.
112 | navigator.serviceWorker.ready.then(registration => {
113 | registration.unregister().then(() => {
114 | window.location.reload();
115 | });
116 | });
117 | } else {
118 | // Service worker found. Proceed as normal.
119 | registerValidSW(swUrl, config);
120 | }
121 | })
122 | .catch(() => {
123 | console.log(
124 | 'No internet connection found. App is running in offline mode.'
125 | );
126 | });
127 | }
128 |
129 | export function unregister() {
130 | if ('serviceWorker' in navigator) {
131 | navigator.serviceWorker.ready.then(registration => {
132 | registration.unregister();
133 | });
134 | }
135 | }
136 |
--------------------------------------------------------------------------------
/src/setupTests.ts:
--------------------------------------------------------------------------------
1 | import '@testing-library/jest-dom/extend-expect';
2 | jest.mock('react-helmet-async', () => ({
3 | Helmet: (): null => null,
4 | }));
5 |
--------------------------------------------------------------------------------
/src/translations/en.json:
--------------------------------------------------------------------------------
1 | {
2 | "containers.HomePage.title": "HomePage"
3 | }
4 |
--------------------------------------------------------------------------------
/src/translations/fil.json:
--------------------------------------------------------------------------------
1 | {
2 | "containers.HomePage.title": "PahinangTahanan"
3 | }
4 |
--------------------------------------------------------------------------------
/src/utils/loadable.tsx:
--------------------------------------------------------------------------------
1 | /* eslint-disable @typescript-eslint/no-explicit-any */
2 | /* eslint-disable react/jsx-props-no-spreading */
3 | import React, { lazy, Suspense } from 'react';
4 | import { RouteComponentProps, StaticContext } from 'react-router';
5 |
6 | const loadable = (
7 | importFunc: () => Promise<{ default: React.ComponentType }>,
8 | { fallback = null } = { fallback: null },
9 | ):
10 | | React.ComponentClass
11 | | React.FunctionComponent
12 | | React.ComponentClass, any>
13 | | React.FunctionComponent>
14 | | undefined => {
15 | const LazyComponent = lazy(importFunc);
16 |
17 | return (props: {}): React.ReactElement => (
18 |
19 |
20 |
21 | );
22 | };
23 |
24 | export default loadable;
25 |
--------------------------------------------------------------------------------
/src/utils/request.spec.ts:
--------------------------------------------------------------------------------
1 | import request, { ResponseError } from './request';
2 |
3 | describe('request', () => {
4 | const mockFetch = jest.fn();
5 |
6 | beforeEach(() => {
7 | window.fetch = mockFetch;
8 | });
9 |
10 | it('should get json', async () => {
11 | type Res = { hello: string };
12 | const res = new Response('{"hello":"world"}', {
13 | status: 200,
14 | headers: {
15 | 'Content-type': 'application/json',
16 | },
17 | });
18 | mockFetch.mockReturnValue(Promise.resolve(res));
19 |
20 | const data = await request('http://example.com/api/examples');
21 |
22 | expect(data.hello).toBe('world');
23 | });
24 |
25 | it('should get null when status code is 204', async () => {
26 | const res = new Response('', {
27 | status: 204,
28 | headers: {
29 | 'Content-type': 'application/json',
30 | },
31 | });
32 | mockFetch.mockReturnValue(Promise.resolve(res));
33 |
34 | const data = await request('http://example.com/api/examples');
35 |
36 | expect(data).toBeNull();
37 | });
38 |
39 | it('should get null when status code is 205', async () => {
40 | const res = new Response('', {
41 | status: 205,
42 | headers: {
43 | 'Content-type': 'application/json',
44 | },
45 | });
46 | mockFetch.mockReturnValue(Promise.resolve(res));
47 |
48 | const data = await request('http://example.com/api/examples');
49 |
50 | expect(data).toBeNull();
51 | });
52 |
53 | it('should throw an ErrorResponse', async () => {
54 | const res = new Response('', {
55 | status: 400,
56 | headers: {
57 | 'Content-type': 'application/json',
58 | },
59 | });
60 | mockFetch.mockReturnValue(Promise.resolve(res));
61 |
62 | await request('http://example.com/api/examples').catch(
63 | (err: ResponseError) => {
64 | expect(err.response.status).toBe(400);
65 | },
66 | );
67 | });
68 | });
69 |
--------------------------------------------------------------------------------
/src/utils/request.ts:
--------------------------------------------------------------------------------
1 | /* eslint-disable @typescript-eslint/no-explicit-any */
2 | export default function request(
3 | url: string,
4 | options?: {} | undefined,
5 | ): Promise {
6 | return fetch(url, options)
7 | .then(checkStatus)
8 | .then(parseJSON);
9 | }
10 |
11 | function checkStatus(response: Response): Response {
12 | if (response.status >= 200 && response.status < 300) {
13 | return response;
14 | }
15 |
16 | const error = new ResponseError(response.statusText);
17 | error.response = response;
18 | throw error;
19 | }
20 |
21 | export class ResponseError extends Error {
22 | response: Response;
23 |
24 | constructor(message: string) {
25 | super(message);
26 |
27 | this.response = new Response();
28 | }
29 | }
30 |
31 | function parseJSON(response: Response): Promise | null {
32 | if (response.status === 204 || response.status === 205) {
33 | return null;
34 | }
35 | return response.json();
36 | }
37 |
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "target": "es5",
4 | "lib": [
5 | "dom",
6 | "dom.iterable",
7 | "esnext"
8 | ],
9 | "allowJs": true,
10 | "skipLibCheck": true,
11 | "esModuleInterop": true,
12 | "allowSyntheticDefaultImports": true,
13 | "strict": true,
14 | "forceConsistentCasingInFileNames": true,
15 | "module": "esnext",
16 | "moduleResolution": "node",
17 | "resolveJsonModule": true,
18 | "isolatedModules": true,
19 | "noEmit": true,
20 | "jsx": "react"
21 | },
22 | "include": [
23 | "src"
24 | ]
25 | }
26 |
--------------------------------------------------------------------------------