>;
diff --git a/src/app/utils/localStorage.ts b/src/app/utils/localStorage.ts
new file mode 100644
index 0000000..2a57b65
--- /dev/null
+++ b/src/app/utils/localStorage.ts
@@ -0,0 +1,7 @@
+export const setLocalStorage = (key: string, value: unknown) => {
+ window.localStorage.setItem(key, JSON.stringify(value));
+};
+
+export const getLocalStorage = (key: string): string => {
+ return window.localStorage.getItem(key) || '';
+};
diff --git a/src/features/categories/API/categories.service.ts b/src/features/categories/API/categories.service.ts
new file mode 100644
index 0000000..1eac204
--- /dev/null
+++ b/src/features/categories/API/categories.service.ts
@@ -0,0 +1,10 @@
+import { getLocalStorage } from '../../../app/utils/localStorage';
+import { createAsyncThunk } from '@reduxjs/toolkit';
+
+export const CATEGORIES_KEY = 'categories';
+
+export const fetchCategories = createAsyncThunk('categories/fetchAll', async () => {
+ await new Promise(resolve => setTimeout(resolve, 1500));
+ const response = getLocalStorage(CATEGORIES_KEY);
+ return JSON.parse(response || '');
+});
diff --git a/src/features/categories/Categories.tsx b/src/features/categories/Categories.tsx
new file mode 100644
index 0000000..370d8b9
--- /dev/null
+++ b/src/features/categories/Categories.tsx
@@ -0,0 +1,23 @@
+import React, { FC } from 'react';
+import CategoryItem from './CategoryItem';
+import CategoryAdd from './CategoryAdd';
+import { List, Typography } from '@mui/material';
+import { CategoryModel } from '../../app/models/category.model';
+
+const Categories: FC<{ categories: CategoryModel[] }> = ({ categories }) => {
+ return (
+
+
+ Categories list
+
+
+ {categories.map(category => (
+
+ ))}
+
+
+
+ );
+};
+
+export default Categories;
diff --git a/src/features/categories/CategoryAdd.tsx b/src/features/categories/CategoryAdd.tsx
new file mode 100644
index 0000000..253c29e
--- /dev/null
+++ b/src/features/categories/CategoryAdd.tsx
@@ -0,0 +1,44 @@
+import React, { ChangeEvent, FC, FormEvent, useState } from 'react';
+import { Box, Button, TextField } from '@mui/material';
+import { CategoryModel } from '../../app/models/category.model';
+import { useAppDispatch } from '../../app/hooks/redux';
+import { addCategory } from './categoriesSlice';
+
+const CategoryAdd: FC = () => {
+ const [category, setCategory] = useState({
+ label: '',
+ } as CategoryModel);
+ const dispatch = useAppDispatch();
+ const submit = async (e: FormEvent) => {
+ e.preventDefault();
+ await dispatch(addCategory(category));
+ setCategory({
+ label: '',
+ } as CategoryModel);
+ };
+
+ return (
+
+ ) =>
+ setCategory({
+ ...category,
+ label: e.target.value,
+ })
+ }
+ />
+
+
+ );
+};
+
+export default CategoryAdd;
diff --git a/src/features/categories/CategoryItem.tsx b/src/features/categories/CategoryItem.tsx
new file mode 100644
index 0000000..a78fd5b
--- /dev/null
+++ b/src/features/categories/CategoryItem.tsx
@@ -0,0 +1,17 @@
+import React, { FC } from 'react';
+import { CategoryModel } from '../../app/models/category.model';
+import { Button, ListItem, ListItemText } from '@mui/material';
+import { useAppDispatch } from '../../app/hooks/redux';
+import { removeCategory } from './categoriesSlice';
+
+const CategoryItem: FC<{ category: CategoryModel }> = ({ category }) => {
+ const dispatch = useAppDispatch();
+ return (
+
+
+
+
+ );
+};
+
+export default CategoryItem;
diff --git a/src/features/categories/categoriesSlice.spec.ts b/src/features/categories/categoriesSlice.spec.ts
new file mode 100644
index 0000000..82bcac2
--- /dev/null
+++ b/src/features/categories/categoriesSlice.spec.ts
@@ -0,0 +1,77 @@
+import { configureStore } from '@reduxjs/toolkit';
+import spyOn = jest.spyOn;
+import categoriesReducer, { addCategory, CategoriesState, removeCategory } from './categoriesSlice';
+import { CategoryModel } from '../../app/models/category.model';
+import { fetchCategories } from './API/categories.service';
+import { categories } from '../../app/categories.MOCK';
+
+describe('transactions reducer', () => {
+ const initialState: CategoriesState = {
+ categoriesList: [
+ {
+ label: 'Some name',
+ id: 3,
+ },
+ ],
+ loading: false,
+ };
+
+ it('should handle initial state', () => {
+ expect(categoriesReducer(undefined, { type: 'unknown' })).toEqual({
+ categoriesList: categories,
+ loading: false,
+ });
+ });
+
+ it('should handle add new category', () => {
+ const category: CategoryModel = {
+ label: 'Name',
+ id: 2,
+ };
+ const actual = categoriesReducer(initialState, addCategory(category));
+
+ expect(actual.categoriesList[actual.categoriesList.length - 1]).toMatchObject({
+ id: expect.any(Number),
+ label: 'Name',
+ });
+ });
+
+ it('should handle delete category', () => {
+ const category: CategoryModel = {
+ id: 1,
+ label: 'Salary',
+ };
+ const actual = categoriesReducer(initialState, removeCategory(category));
+
+ expect(actual.categoriesList.find(el => el.id === category.id)).toEqual(undefined);
+ });
+
+ it('should handle loading state on fetch categories', () => {
+ const actual = categoriesReducer(initialState, fetchCategories.pending);
+ expect(actual.loading).toEqual(true);
+ });
+
+ it('should handle success state on fetch categories', async () => {
+ const localStorageData = [{ label: 'Name', id: 22 }];
+ spyOn(Object.getPrototypeOf(window.localStorage), 'getItem').mockImplementation(() => JSON.stringify(localStorageData));
+
+ const store = configureStore({
+ reducer: function (state = [], action) {
+ switch (action.type) {
+ case 'categories/fetchAll/fulfilled':
+ return action.payload;
+ default:
+ return state;
+ }
+ },
+ });
+ await store.dispatch(fetchCategories());
+
+ expect(store.getState()).toEqual(localStorageData);
+ });
+
+ it('should handle error state on fetch categories', () => {
+ const actual = categoriesReducer(initialState, fetchCategories.rejected);
+ expect(actual.loading).toEqual(false);
+ });
+});
diff --git a/src/features/categories/categoriesSlice.ts b/src/features/categories/categoriesSlice.ts
new file mode 100644
index 0000000..0c840c2
--- /dev/null
+++ b/src/features/categories/categoriesSlice.ts
@@ -0,0 +1,54 @@
+import { createSlice, PayloadAction } from '@reduxjs/toolkit';
+import { RootState } from '../../app/store';
+import { CategoryModel } from '../../app/models/category.model';
+import { categories } from '../../app/categories.MOCK';
+import { setLocalStorage } from '../../app/utils/localStorage';
+import { CATEGORIES_KEY, fetchCategories } from './API/categories.service';
+import { fetchTransactions } from '../transactions/transactions-page/API/transactions.service';
+
+export interface CategoriesState {
+ categoriesList: CategoryModel[];
+ loading: boolean;
+}
+
+const initialState: CategoriesState = {
+ categoriesList: categories,
+ loading: false,
+};
+
+export const categoriesSlice = createSlice({
+ name: 'transactions',
+ initialState,
+ reducers: {
+ addCategory: (state, action: PayloadAction) => {
+ const newCategory = { ...action.payload, id: Date.now() };
+ state.categoriesList.push(newCategory);
+ setLocalStorage(CATEGORIES_KEY, state.categoriesList);
+ },
+ removeCategory: (state, action: PayloadAction) => {
+ state.categoriesList = state.categoriesList.filter(category => action.payload.id !== category.id);
+ setLocalStorage(CATEGORIES_KEY, state.categoriesList);
+ },
+ },
+ extraReducers: builder => {
+ builder
+ .addCase(fetchCategories.pending, state => {
+ state.loading = true;
+ })
+ .addCase(fetchCategories.rejected, (state, action: PayloadAction) => {
+ state.loading = false;
+ console.warn(action.payload);
+ })
+ .addCase(fetchCategories.fulfilled, (state, action: PayloadAction) => {
+ state.loading = false;
+ state.categoriesList = action.payload;
+ });
+ },
+});
+
+export const selectCategories = (state: RootState) => state.categories.categoriesList;
+export const selectCategoriesLoading = (state: RootState) => state.categories.loading;
+
+export const { addCategory, removeCategory } = categoriesSlice.actions;
+
+export default categoriesSlice.reducer;
diff --git a/src/features/charts/Charts.tsx b/src/features/charts/Charts.tsx
new file mode 100644
index 0000000..26d405a
--- /dev/null
+++ b/src/features/charts/Charts.tsx
@@ -0,0 +1,47 @@
+import React, { FC, useEffect, useMemo, useState } from 'react';
+import { Chart } from 'react-google-charts';
+import { useAppDispatch, useAppSelector } from '../../app/hooks/redux';
+import { selectTransactions, selectTransactionsLoading } from '../transactions/transactions-page/transactionSlice';
+import { selectCategories, selectCategoriesLoading } from '../categories/categoriesSlice';
+import { fetchTransactions } from '../transactions/transactions-page/API/transactions.service';
+import { fetchCategories } from '../categories/API/categories.service';
+import { maxSumByCategory } from './chart.utils';
+import { CircularProgress, Container, Stack } from '@mui/material';
+
+const Charts: FC = () => {
+ const transactions = useAppSelector(selectTransactions);
+ const categories = useAppSelector(selectCategories);
+ const transactionsLoading = useAppSelector(selectTransactionsLoading);
+ const categoriesLoading = useAppSelector(selectCategoriesLoading);
+ const dispatch = useAppDispatch();
+ const [chartData, setChartData] = useState([] as any[]);
+
+ const convertData = useMemo(() => {
+ return maxSumByCategory(transactions, categories);
+ }, [transactions, categories]);
+
+ useEffect(() => {
+ setChartData(convertData);
+ }, [transactions, categories, convertData]);
+
+ useEffect(() => {
+ if (!categories.length || !transactions.length) {
+ dispatch(fetchTransactions());
+ dispatch(fetchCategories());
+ }
+ }, []);
+
+ return (
+
+ {transactionsLoading || categoriesLoading ? (
+
+
+
+ ) : (
+
+ )}
+
+ );
+};
+
+export default Charts;
diff --git a/src/features/charts/chart.utils.ts b/src/features/charts/chart.utils.ts
new file mode 100644
index 0000000..6123e33
--- /dev/null
+++ b/src/features/charts/chart.utils.ts
@@ -0,0 +1,40 @@
+import { TransactionModel } from '../../app/models/transaction.model';
+import { CategoryModel } from '../../app/models/category.model';
+
+export const maxSumByCategory = (transactions: TransactionModel[], categories: CategoryModel[]): (string | number)[] => {
+ if (!(transactions.length && categories.length)) {
+ return [];
+ }
+
+ const header = ['Category', 'Income', 'Expense'];
+ let result: any[] = [header];
+
+ const categoriesObj = categories.reduce((acc: Record, el) => {
+ if (acc[el.id]) {
+ return acc;
+ }
+ acc[el.id] = el.label;
+ return acc;
+ }, {});
+
+ const dataObj = transactions.reduce((acc: any, val: any) => {
+ const categoryName = categoriesObj[val.categoryId];
+ if (acc[categoryName]) {
+ if (+val.amount >= 0) {
+ acc[categoryName].income += Number(val.amount);
+ }
+ if (+val.amount < 0) {
+ acc[categoryName].expense += Math.abs(Number(val.amount));
+ }
+ }
+ if (!acc[categoryName]) {
+ acc[categoryName] = {
+ income: +val.amount >= 0 ? Number(val.amount) : 0,
+ expense: +val.amount < 0 ? Math.abs(Number(val.amount)) : 0,
+ };
+ }
+ return acc;
+ }, {});
+
+ return Object.keys(dataObj).reduce((acc: any[], key) => [...acc, [key, dataObj[key].income, dataObj[key].expense]], result);
+};
diff --git a/src/features/navbar/Navbar.module.scss b/src/features/navbar/Navbar.module.scss
new file mode 100644
index 0000000..24f7153
--- /dev/null
+++ b/src/features/navbar/Navbar.module.scss
@@ -0,0 +1,13 @@
+.active {
+ color: #1976d2;
+}
+
+.button {
+ a {
+ text-decoration: none;
+ }
+
+ &.active {
+ background: black;
+ }
+}
diff --git a/src/features/navbar/Navbar.tsx b/src/features/navbar/Navbar.tsx
new file mode 100644
index 0000000..873e775
--- /dev/null
+++ b/src/features/navbar/Navbar.tsx
@@ -0,0 +1,34 @@
+import React, { FC } from 'react';
+import { NavLink } from 'react-router-dom';
+import { AppBar, Button, Stack, Toolbar, Typography } from '@mui/material';
+import classes from './Navbar.module.scss';
+
+const Navbar: FC = () => {
+ return (
+
+
+
+ Income/expense app
+
+
+
+
+
+
+
+
+
+ );
+};
+
+export default Navbar;
diff --git a/src/features/transactions/transaction-edit/transactionEdit.tsx b/src/features/transactions/transaction-edit/transactionEdit.tsx
new file mode 100644
index 0000000..d64ba84
--- /dev/null
+++ b/src/features/transactions/transaction-edit/transactionEdit.tsx
@@ -0,0 +1,97 @@
+import React, { Dispatch, FC, FormEvent, SetStateAction, useState } from 'react';
+import { CategoryModel } from '../../../app/models/category.model';
+import { TransactionModel } from '../../../app/models/transaction.model';
+import { useAppDispatch } from '../../../app/hooks/redux';
+import { addTransaction } from '../transactions-page/transactionSlice';
+import { Box, Button, FormControl, InputLabel, MenuItem, Select, TextField, Typography } from '@mui/material';
+
+const TransactionEdit: FC<{ categories: CategoryModel[] }> = ({ categories }) => {
+ const [transaction, setTransaction]: [TransactionModel, Dispatch>] = useState({
+ label: '',
+ amount: '',
+ categoryId: '',
+ } as TransactionModel);
+ const dispatch = useAppDispatch();
+
+ const submit = async (e: FormEvent) => {
+ e.preventDefault();
+ await dispatch(addTransaction(transaction));
+ setTransaction({
+ label: '',
+ amount: '',
+ categoryId: '',
+ } as TransactionModel);
+ };
+
+ return (
+
+
+ New transaction
+
+
+
+ setTransaction({ ...transaction, label: e.target.value })}
+ />
+
+
+ setTransaction({ ...transaction, amount: e.target.value })}
+ />
+
+
+ Category
+
+
+
+
+
+
+ );
+};
+
+export default TransactionEdit;
diff --git a/src/features/transactions/transactions-list/TransactionsList.tsx b/src/features/transactions/transactions-list/TransactionsList.tsx
new file mode 100644
index 0000000..d2f5595
--- /dev/null
+++ b/src/features/transactions/transactions-list/TransactionsList.tsx
@@ -0,0 +1,40 @@
+import React, { FC } from 'react';
+import { TransactionModel } from '../../../app/models/transaction.model';
+import { CategoryModel } from '../../../app/models/category.model';
+import { Paper, Table, TableBody, TableCell, TableContainer, TableHead, TableRow } from '@mui/material';
+
+const TransactionsList: FC<{
+ transactions: TransactionModel[];
+ categories: CategoryModel[];
+}> = ({ transactions, categories }) => {
+ const getCategoryById = (categoryId: number): CategoryModel | undefined => categories?.find(el => el.id === categoryId);
+
+ return (
+
+
+
+
+ Label
+ Amount
+ Date
+ Category
+
+
+
+ {transactions.map(transaction => (
+
+
+ {transaction.label}
+
+ {transaction.amount}
+ {transaction.date}
+ {getCategoryById(+transaction.categoryId)?.label}
+
+ ))}
+
+
+
+ );
+};
+
+export default TransactionsList;
diff --git a/src/features/transactions/transactions-page/API/transactions.service.ts b/src/features/transactions/transactions-page/API/transactions.service.ts
new file mode 100644
index 0000000..811ac70
--- /dev/null
+++ b/src/features/transactions/transactions-page/API/transactions.service.ts
@@ -0,0 +1,10 @@
+import { getLocalStorage } from '../../../../app/utils/localStorage';
+import { createAsyncThunk } from '@reduxjs/toolkit';
+
+export const TRANSACTIONS_KEY = 'transactions';
+
+export const fetchTransactions = createAsyncThunk('transactions/fetchAll', async () => {
+ await new Promise(resolve => setTimeout(resolve, 1000));
+ const response = getLocalStorage(TRANSACTIONS_KEY);
+ return JSON.parse(response || '');
+});
diff --git a/src/features/transactions/transactions-page/TransactionsPage.tsx b/src/features/transactions/transactions-page/TransactionsPage.tsx
new file mode 100644
index 0000000..d4d22b2
--- /dev/null
+++ b/src/features/transactions/transactions-page/TransactionsPage.tsx
@@ -0,0 +1,75 @@
+import React, { FC, useEffect } from 'react';
+import { useAppDispatch, useAppSelector } from '../../../app/hooks/redux';
+
+import { selectTransactions, selectTransactionsLoading } from './transactionSlice';
+import { selectCategories, selectCategoriesLoading } from '../../categories/categoriesSlice';
+import { fetchTransactions } from './API/transactions.service';
+import { CircularProgress, Container, CssBaseline, Grid, Paper, Stack, styled } from '@mui/material';
+import { fetchCategories } from '../../categories/API/categories.service';
+
+const TransactionEdit = React.lazy(() => import('../transaction-edit/transactionEdit'));
+const Categories = React.lazy(() => import('../../categories/Categories'));
+const TransactionsList = React.lazy(() => import('../transactions-list/TransactionsList'));
+
+const TransactionsPage: FC = () => {
+ const transactions = useAppSelector(selectTransactions);
+ const categories = useAppSelector(selectCategories);
+ const transactionsLoading = useAppSelector(selectTransactionsLoading);
+ const categoriesLoading = useAppSelector(selectCategoriesLoading);
+ const dispatch = useAppDispatch();
+
+ const Item = styled(Paper)(({ theme }) => ({
+ ...theme.typography.body2,
+ padding: theme.spacing(1),
+ textAlign: 'center',
+ color: theme.palette.text.secondary,
+ }));
+
+ useEffect(() => {
+ if (!categories.length || !transactions.length) {
+ dispatch(fetchTransactions());
+ dispatch(fetchCategories());
+ }
+ }, []);
+
+ return (
+ <>
+
+
+
+
+
+ -
+ ...>}>
+
+
+
+
+
+ -
+ {categoriesLoading ? (
+
+ ) : (
+ ...>}>
+
+
+ )}
+
+
+
+
+
+ {transactionsLoading ? (
+
+
+
+ ) : (
+ ...>}>
+
+
+ )}
+ >
+ );
+};
+
+export default TransactionsPage;
diff --git a/src/features/transactions/transactions-page/transactionSlice.ts b/src/features/transactions/transactions-page/transactionSlice.ts
new file mode 100644
index 0000000..652939f
--- /dev/null
+++ b/src/features/transactions/transactions-page/transactionSlice.ts
@@ -0,0 +1,54 @@
+import { createSlice, PayloadAction } from '@reduxjs/toolkit';
+import { RootState } from '../../../app/store';
+import { TransactionModel } from '../../../app/models/transaction.model';
+import { fetchTransactions, TRANSACTIONS_KEY } from './API/transactions.service';
+
+export interface TransactionState {
+ transactionsList: TransactionModel[];
+ loading: boolean;
+}
+
+const initialState: TransactionState = {
+ transactionsList: [],
+ loading: false,
+};
+
+export const transactionsSlice = createSlice({
+ name: 'transactions',
+ initialState,
+ reducers: {
+ addTransaction: (state, action: PayloadAction) => {
+ const date = new Date();
+ const newTransaction: TransactionModel = {
+ ...action.payload,
+ id: Date.now(),
+ date: `${date.getDate()} ${date.toLocaleString('default', {
+ month: 'long',
+ })} ${date.getFullYear()}`,
+ };
+ state.transactionsList = [...state.transactionsList, newTransaction];
+ window.localStorage.setItem(TRANSACTIONS_KEY, JSON.stringify(state.transactionsList));
+ },
+ },
+ extraReducers: builder => {
+ builder
+ .addCase(fetchTransactions.pending, state => {
+ state.loading = true;
+ })
+ .addCase(fetchTransactions.rejected, (state, action: PayloadAction) => {
+ state.loading = false;
+ console.warn(action.payload);
+ })
+ .addCase(fetchTransactions.fulfilled, (state, action: PayloadAction) => {
+ state.loading = false;
+ state.transactionsList = action.payload;
+ });
+ },
+});
+
+export const selectTransactions = (state: RootState) => state.transactions.transactionsList;
+export const selectTransactionsLoading = (state: RootState) => state.transactions.loading;
+
+export const { addTransaction } = transactionsSlice.actions;
+
+export default transactionsSlice.reducer;
diff --git a/src/features/transactions/transactions-page/transactionsSlice.spec.ts b/src/features/transactions/transactions-page/transactionsSlice.spec.ts
new file mode 100644
index 0000000..8371cb6
--- /dev/null
+++ b/src/features/transactions/transactions-page/transactionsSlice.spec.ts
@@ -0,0 +1,71 @@
+import transactionsReducer, { addTransaction, TransactionState } from './transactionSlice';
+import { TransactionModel } from '../../../app/models/transaction.model';
+import { fetchTransactions } from './API/transactions.service';
+import { configureStore } from '@reduxjs/toolkit';
+import spyOn = jest.spyOn;
+
+describe('transactions reducer', () => {
+ const initialState: TransactionState = {
+ transactionsList: [
+ {
+ label: 'Some name',
+ amount: 333,
+ categoryId: 3,
+ },
+ ],
+ loading: false,
+ };
+
+ it('should handle initial state', () => {
+ expect(transactionsReducer(undefined, { type: 'unknown' })).toEqual({
+ transactionsList: [],
+ loading: false,
+ });
+ });
+
+ it('should handle add new transaction', () => {
+ const transaction: TransactionModel = {
+ label: 'Name',
+ amount: 100,
+ categoryId: 2,
+ };
+ const actual = transactionsReducer(initialState, addTransaction(transaction));
+
+ expect(actual.transactionsList[actual.transactionsList.length - 1]).toMatchObject({
+ id: expect.any(Number),
+ date: expect.any(String),
+ label: 'Name',
+ amount: 100,
+ categoryId: 2,
+ });
+ });
+
+ it('should handle loading state on fetch transactions', () => {
+ const actual = transactionsReducer(initialState, fetchTransactions.pending);
+ expect(actual.loading).toEqual(true);
+ });
+
+ it('should handle success state on fetch transactions', async () => {
+ const localStorageData = [{ label: 'Name', amount: 222, categoryId: 2 }];
+ spyOn(Object.getPrototypeOf(window.localStorage), 'getItem').mockImplementation(() => JSON.stringify(localStorageData));
+
+ const store = configureStore({
+ reducer: function (state = [], action) {
+ switch (action.type) {
+ case 'transactions/fetchAll/fulfilled':
+ return action.payload;
+ default:
+ return state;
+ }
+ },
+ });
+ await store.dispatch(fetchTransactions());
+
+ expect(store.getState()).toEqual(localStorageData);
+ });
+
+ it('should handle error state on fetch transactions', () => {
+ const actual = transactionsReducer(initialState, fetchTransactions.rejected);
+ expect(actual.loading).toEqual(false);
+ });
+});
diff --git a/src/index.scss b/src/index.scss
new file mode 100644
index 0000000..da0d172
--- /dev/null
+++ b/src/index.scss
@@ -0,0 +1,13 @@
+body {
+ margin: 0;
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen",
+ "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue",
+ sans-serif;
+ -webkit-font-smoothing: antialiased;
+ -moz-osx-font-smoothing: grayscale;
+}
+
+code {
+ font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New",
+ monospace;
+}
diff --git a/src/index.tsx b/src/index.tsx
new file mode 100644
index 0000000..ef73a7e
--- /dev/null
+++ b/src/index.tsx
@@ -0,0 +1,24 @@
+import React from 'react';
+import ReactDOM from 'react-dom';
+import './index.scss';
+import App from './App';
+import { store } from './app/store';
+import { Provider } from 'react-redux';
+import * as serviceWorker from './serviceWorker';
+import { BrowserRouter } from 'react-router-dom';
+
+ReactDOM.render(
+
+
+
+
+
+
+ ,
+ document.getElementById('root'),
+);
+
+// If you want your app to work offline and load faster, you can change
+// unregister() to register() below. Note this comes with some pitfalls.
+// Learn more about service workers: https://bit.ly/CRA-PWA
+serviceWorker.unregister();
diff --git a/src/logo.svg b/src/logo.svg
new file mode 100644
index 0000000..8466738
--- /dev/null
+++ b/src/logo.svg
@@ -0,0 +1 @@
+
diff --git a/src/react-app-env.d.ts b/src/react-app-env.d.ts
new file mode 100644
index 0000000..6431bc5
--- /dev/null
+++ b/src/react-app-env.d.ts
@@ -0,0 +1 @@
+///
diff --git a/src/serviceWorker.ts b/src/serviceWorker.ts
new file mode 100644
index 0000000..e7b8199
--- /dev/null
+++ b/src/serviceWorker.ts
@@ -0,0 +1,146 @@
+// This optional code is used to register a service worker.
+// register() is not called by default.
+
+// This lets the app load faster on subsequent visits in production, and gives
+// it offline capabilities. However, it also means that developers (and users)
+// will only see deployed updates on subsequent visits to a page, after all the
+// existing tabs open on the page have been closed, since previously cached
+// resources are updated in the background.
+
+// To learn more about the benefits of this model and instructions on how to
+// opt-in, read https://bit.ly/CRA-PWA
+
+const isLocalhost = Boolean(
+ window.location.hostname === "localhost" ||
+ // [::1] is the IPv6 localhost address.
+ window.location.hostname === "[::1]" ||
+ // 127.0.0.0/8 are considered localhost for IPv4.
+ window.location.hostname.match(
+ /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
+ )
+);
+
+type Config = {
+ onSuccess?: (registration: ServiceWorkerRegistration) => void;
+ onUpdate?: (registration: ServiceWorkerRegistration) => void;
+};
+
+export function register(config?: Config) {
+ if (process.env.NODE_ENV === "production" && "serviceWorker" in navigator) {
+ // The URL constructor is available in all browsers that support SW.
+ const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
+ if (publicUrl.origin !== window.location.origin) {
+ // Our service worker won't work if PUBLIC_URL is on a different origin
+ // from what our page is served on. This might happen if a CDN is used to
+ // serve assets; see https://github.com/facebook/create-react-app/issues/2374
+ return;
+ }
+
+ window.addEventListener("load", () => {
+ const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
+
+ if (isLocalhost) {
+ // This is running on localhost. Let's check if a service worker still exists or not.
+ checkValidServiceWorker(swUrl, config);
+
+ // Add some additional logging to localhost, pointing developers to the
+ // service worker/PWA documentation.
+ navigator.serviceWorker.ready.then(() => {
+ console.log(
+ "This web app is being served cache-first by a service " +
+ "worker. To learn more, visit https://bit.ly/CRA-PWA"
+ );
+ });
+ } else {
+ // Is not localhost. Just register service worker
+ registerValidSW(swUrl, config);
+ }
+ });
+ }
+}
+
+function registerValidSW(swUrl: string, config?: Config) {
+ navigator.serviceWorker
+ .register(swUrl)
+ .then((registration) => {
+ registration.onupdatefound = () => {
+ const installingWorker = registration.installing;
+ if (installingWorker == null) {
+ return;
+ }
+ installingWorker.onstatechange = () => {
+ if (installingWorker.state === "installed") {
+ if (navigator.serviceWorker.controller) {
+ // At this point, the updated precached content has been fetched,
+ // but the previous service worker will still serve the older
+ // content until all client tabs are closed.
+ console.log(
+ "New content is available and will be used when all " +
+ "tabs for this page are closed. See https://bit.ly/CRA-PWA."
+ );
+
+ // Execute callback
+ if (config && config.onUpdate) {
+ config.onUpdate(registration);
+ }
+ } else {
+ // At this point, everything has been precached.
+ // It's the perfect time to display a
+ // "Content is cached for offline use." message.
+ console.log("Content is cached for offline use.");
+
+ // Execute callback
+ if (config && config.onSuccess) {
+ config.onSuccess(registration);
+ }
+ }
+ }
+ };
+ };
+ })
+ .catch((error) => {
+ console.error("Error during service worker registration:", error);
+ });
+}
+
+function checkValidServiceWorker(swUrl: string, config?: Config) {
+ // Check if the service worker can be found. If it can't reload the page.
+ fetch(swUrl, {
+ headers: { "Service-Worker": "script" },
+ })
+ .then((response) => {
+ // Ensure service worker exists, and that we really are getting a JS file.
+ const contentType = response.headers.get("content-type");
+ if (
+ response.status === 404 ||
+ (contentType != null && contentType.indexOf("javascript") === -1)
+ ) {
+ // No service worker found. Probably a different app. Reload the page.
+ navigator.serviceWorker.ready.then((registration) => {
+ registration.unregister().then(() => {
+ window.location.reload();
+ });
+ });
+ } else {
+ // Service worker found. Proceed as normal.
+ registerValidSW(swUrl, config);
+ }
+ })
+ .catch(() => {
+ console.log(
+ "No internet connection found. App is running in offline mode."
+ );
+ });
+}
+
+export function unregister() {
+ if ("serviceWorker" in navigator) {
+ navigator.serviceWorker.ready
+ .then((registration) => {
+ registration.unregister();
+ })
+ .catch((error) => {
+ console.error(error.message);
+ });
+ }
+}
diff --git a/src/setupTests.ts b/src/setupTests.ts
new file mode 100644
index 0000000..5fdf001
--- /dev/null
+++ b/src/setupTests.ts
@@ -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/extend-expect";
diff --git a/tsconfig.json b/tsconfig.json
new file mode 100644
index 0000000..9d379a3
--- /dev/null
+++ b/tsconfig.json
@@ -0,0 +1,20 @@
+{
+ "compilerOptions": {
+ "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-jsx"
+ },
+ "include": ["src"]
+}