ソースを参照

HW магазин на react done

Vladimir 2 年 前
コミット
c014d89b15

+ 23 - 0
HW Мой МАГАЗЫН на React/.gitignore

@@ -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*

+ 70 - 0
HW Мой МАГАЗЫН на React/README.md

@@ -0,0 +1,70 @@
+# 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:
+
+### `npm start`
+
+Runs the app in the development mode.\
+Open [http://localhost:3000](http://localhost:3000) to view it in your browser.
+
+The page will reload when you make changes.\
+You may also see any lint errors in the console.
+
+### `npm 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.
+
+### `npm run 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.
+
+### `npm run eject`
+
+**Note: this is a one-way operation. Once you `eject`, you can't go back!**
+
+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.
+
+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.
+
+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.
+
+## 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/).
+
+### Code Splitting
+
+This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting)
+
+### Analyzing the Bundle Size
+
+This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size)
+
+### Making a Progressive Web App
+
+This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app)
+
+### Advanced Configuration
+
+This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration)
+
+### Deployment
+
+This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment)
+
+### `npm run build` fails to minify
+
+This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify)

ファイルの差分が大きいため隠しています
+ 12718 - 0
HW Мой МАГАЗЫН на React/package-lock.json


+ 43 - 0
HW Мой МАГАЗЫН на React/package.json

@@ -0,0 +1,43 @@
+{
+  "name": "react-store",
+  "version": "0.1.0",
+  "private": true,
+  "dependencies": {
+    "@testing-library/jest-dom": "^5.16.1",
+    "@testing-library/react": "^12.1.2",
+    "@testing-library/user-event": "^13.5.0",
+    "node-sass": "^7.0.1",
+    "react": "^17.0.2",
+    "react-dom": "^17.0.2",
+    "react-redux": "^7.2.6",
+    "react-router-dom": "^5.3.0",
+    "react-scripts": "5.0.0",
+    "redux": "^4.1.2",
+    "redux-thunk": "^2.4.1",
+    "web-vitals": "^2.1.4"
+  },
+  "scripts": {
+    "start": "react-scripts start",
+    "build": "react-scripts build",
+    "test": "react-scripts test",
+    "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"
+    ]
+  }
+}

+ 14 - 0
HW Мой МАГАЗЫН на React/public/index.html

@@ -0,0 +1,14 @@
+<!DOCTYPE html>
+<html lang="ru">
+<head>
+  <meta charset="UTF-8">
+  <meta http-equiv="X-UA-Compatible" content="IE=edge">
+  <meta name="viewport" content="width=device-width, initial-scale=1.0">
+  <title>Магазинчик</title>
+</head>
+<body>
+  <div id="root">
+
+  </div>
+</body>
+</html>

+ 533 - 0
HW Мой МАГАЗЫН на React/src/App.js

@@ -0,0 +1,533 @@
+import "./App.scss";
+import {createStore, combineReducers, applyMiddleware} from "redux";
+import {Provider, connect}                             from "react-redux";
+import thunk                                           from "redux-thunk";
+import React, {useState, useEffect}                    from "react";
+import {Router, Route, Link, Redirect, Switch}         from 'react-router-dom';
+import createHistory                                   from "history/createBrowserHistory";
+
+const promiseReducer = function(state={}, {type, name, status, payload, error}) {
+  if (type == 'PROMISE'){
+      return {
+          ...state,
+          [name]:{status, payload, error}
+      }
+  }
+
+  return state;
+};
+
+const actionPending             = name => ({type: "PROMISE", name, status: 'PENDING'});
+const actionFulfilled = (name,payload) => ({type: "PROMISE", name, status: 'FULFILLED', payload});
+const actionRejected  = (name,error)   => ({type: "PROMISE", name, status: 'REJECTED', error});
+const actionPromise = function(name, promise) {
+  return async dispatch => {
+      dispatch(actionPending(name));
+      try {
+          let payload = await promise
+          dispatch(actionFulfilled(name, payload))
+          return payload
+      }
+      catch(error){
+          dispatch(actionRejected(name, error))
+      };
+  };
+};
+
+let jwtDecode = function(token) {
+  let payloadInBase64;
+  let payloadInJson;
+  let payload;
+
+  try {
+      payloadInBase64 = token.split(".")[1];
+      payloadInJson = atob(payloadInBase64);
+      payload = JSON.parse(payloadInJson);
+
+      return payload;
+  }
+  catch(err) {
+
+  }
+};
+
+const authReducer = function(state, {type, token}) {
+  let payload;
+
+  if (state == undefined) {
+      if(localStorage.authToken) {
+          type = "AUTH_LOGIN";
+          token = localStorage.authToken;
+      } else {
+          type = "AUTH_LOGOUT";
+      };
+  };
+  if (type == "AUTH_LOGIN") {
+      payload = jwtDecode(token);
+
+      if(payload) {
+          localStorage.authToken = token;
+          return {
+              token: token,
+              payload: payload
+          }
+      }
+
+  };
+  if (type == "AUTH_LOGOUT") {
+      localStorage.removeItem("authToken");
+
+      return {};
+  };
+
+  return state || {};
+};
+
+const actionAuthLogin  = token => ({type: "AUTH_LOGIN", token});
+const actionAuthLogout = () => ({type: "AUTH_LOGOUT"});
+const actionFullLogin = function(login, password) {
+  return async dispatch => {
+    let token = await gql("query userLogin($login: String, $password: String) {login(login: $login, password: $password)}", {"login": login, "password": password});
+    dispatch(actionAuthLogin(token));
+  };
+};
+
+let actionFullRegister = function(login, password, nick) {
+  return async dispatch => {
+    dispatch(actionPromise("userRegister", gql(`mutation userRegister($login:String, $password:String, $nick:String) {
+      UserUpsert(user: {login:$login, password:$password, nick:$nick}) {
+        _id login nick
+      }
+    }`,
+    {
+      "login": login,
+      "password": password,
+      "nick": nick
+    })));
+    dispatch(actionFullLogin(login, password));
+  };
+};
+
+let cartReducer = function(state={}, {type, good, count=1}) {
+  if(type == "CART_ADD") {
+      let newState = {...state};
+
+      if(good["_id"] in state) {
+          newState[good._id] = {count: newState[good._id].count + count, good}
+      }
+      else {
+          newState = {
+              ...state,
+              [good._id]: {count, good} 
+          };
+      };
+
+      return newState;
+  };
+  if(type == "CART_CHANGE") {
+      let newState = {...state,
+          [good._id]: {count, good}
+      };
+
+      return newState;
+  };
+  if(type == "CART_DELETE") {
+      let newState = {...state};
+
+      delete newState[good._id];
+
+      return newState;
+  };
+  if(type == "CART_CLEAR") {
+      return {};
+  };
+
+  return state;
+};
+
+const actionCartAdd    = (good, count=1) => ({type: 'CART_ADD', good, count: +count})
+const actionCartChange = (good, count=1) => ({type: 'CART_CHANGE', good, count: +count})
+const actionCartDelete = (good)          => ({type: 'CART_DELETE', good})
+const actionCartClear  = ()              => ({type: 'CART_CLEAR'})
+
+const getGQL = function(url) {
+  return async function(query, variables) {
+    const res = await fetch(url, {
+        method: "POST",
+        headers: {
+            "Content-Type": "application/json",
+            ...(localStorage.authToken ? { "Authorization": "Bearer " + localStorage.authToken } : {})
+        },
+        body: JSON.stringify({ query, variables })
+    });
+    const data = await res.json();
+    if (data.data) {
+        return Object.values(data.data)[0];
+    }
+    else {
+        throw new Error(JSON.stringify(data.errors));
+    };
+  };
+};
+
+const backendURL = 'http://shop-roles.asmer.fs.a-level.com.ua';
+
+const gql = getGQL(backendURL + '/graphql');
+
+let actionRootCats = function() {
+  return actionPromise("rootCats", gql(`query {
+      CategoryFind(query: "[{\\"parent\\":null}]"){
+          _id name
+    }
+  }`));
+};
+
+let actionCatById = function(_id) {
+  return actionPromise("catById", gql(`query catById($q: String){
+      CategoryFindOne(query: $q){
+          _id name goods {
+              _id name price images {
+                  url
+              }
+          }
+      }
+  }`,
+  {q: JSON.stringify([{_id}])}
+  ));
+};
+
+let actionGoodById = function(_id) {
+  return actionPromise("goodById", gql(`query findGood($goodQuery: String) {
+      GoodFindOne(query:$goodQuery) {
+          _id name price images {
+              url
+          }
+      }
+  }`,
+  {goodQuery: JSON.stringify([{"_id": _id}])}
+  ));
+};
+
+let actionOrders = async function() {
+  let order = await gql(`mutation makeOrder($order:OrderInput){
+      OrderUpsert(order: $order){
+        _id
+      }
+    }`, {
+        "order": {
+            orderGoods: Object.entries(store.getState().cart).map(([_id, count]) =>({"count": count.count, "good": {_id}}))
+          }
+    });
+
+  store.dispatch(actionCartClear());
+}
+
+let actionOrdersFind = function() {
+  return actionPromise("ordersFind", gql(`query ordersFind($query:String) {
+    OrderFind(query: $query) {
+      createdAt orderGoods {
+        count good {
+          name price images {
+            url
+          }
+        }
+      }
+    }
+  }`,
+    {
+    "query": JSON.stringify([{}])
+    }));
+}
+
+const store = createStore(combineReducers({promise: promiseReducer,
+                                           auth: authReducer,
+                                           cart: cartReducer}), applyMiddleware(thunk));
+
+store.subscribe(() => console.log(store.getState()));
+store.dispatch(actionRootCats());
+
+
+let Nav = function({auth}) {
+  return (
+    <ul className="nav">
+      <li>
+        <Link to="/login">Логин</Link>
+      </li>
+      <li>
+        <Link to="/registration">Регистрация</Link>
+      </li>
+      <li>
+        <Link to="/cart">Корзина</Link>
+      </li>
+      <li>
+        <Link to="/dashboard">История покупок</Link>
+      </li>
+    </ul>
+  );
+};
+
+const CNav = connect(state => ({auth: state.auth}))(Nav);
+
+let Header = function() {
+  return (
+    <header className="header">
+      <div className="header__logo">Типо логотип</div>
+      <CNav />
+    </header>
+  );
+};
+
+let RootCategories = function({rootCats}) {
+  return (
+    <aside className="rootCats">
+      <ul className="rootCats__list">
+        {rootCats.map(rootCat => <li><Link to={`/category/${rootCat._id}`}>{rootCat.name}</Link></li>)}
+      </ul>
+    </aside>
+  );
+};
+
+const CRootCategories = connect(state => ({rootCats: state.promise?.rootCats?.payload || []}))(RootCategories);
+
+let MainPage = function() {
+  return (
+    <h1>Главная страничка</h1>
+  );
+};
+
+let GoodCard = function({good}) {
+  return (
+    <li className="goods__item">
+      <img src={`${backendURL}/${good.images[0].url}`} />
+      <b>{good.name}</b><br />
+      <span>Цена: {good.price}</span><br />
+      <Link to={`/good/${good._id}`}>Перейти на страничку товара</Link>
+    </li>
+  );
+};
+
+let Goods = function({goods}) {
+  return (
+    <section className="goods">
+      <ul className="goods__list">
+        {goods.map(good => <GoodCard good={good} />)}
+      </ul>
+    </section>
+  );
+};
+
+const CGoods = connect(state => ({goods: state.promise?.catById?.payload?.goods || []}))(Goods);
+
+let Categories = function({match: {params: {_id}}, catById}) {
+  catById(_id);
+  return (
+    <CGoods />
+  );
+};
+
+const CCategories = connect(null, {catById: actionCatById})(Categories);
+
+let GoodPageCard = function({good, cartAdd}) {
+  return (
+    <section className="good">
+      <img src={`${backendURL}/${good?.images[0]?.url}`} />
+      <div>
+        <b>{good?.name}</b><br />
+        <span>Цена: {good?.price}</span><br />
+        <button onClick={() => cartAdd(good)}>Добавить в корзину</button>
+      </div>
+    </section>
+  );
+};
+
+const CGoodPageCard = connect(state => ({good: state.promise?.goodById?.payload}),
+                                        {cartAdd: actionCartAdd})(GoodPageCard)
+
+let GoodPage = function({match: {params: {_id}}, goodById}) {
+  goodById(_id);
+  return (
+    <CGoodPageCard />
+  );
+};
+
+const CGoodPage = connect(null, {goodById: actionGoodById})(GoodPage);
+
+let Login = function({fullLogin}) {
+  const [login, setLogin]       = useState("");
+  const [password, setPassword] = useState("");
+
+  return (
+    <section className="login">
+      <h2>Логин</h2>
+      <input type="text"
+             placeholder="Введите ваш логин"
+             onChange={evt => setLogin(evt.target.value)} /><br />
+      <input type="password"
+             placeholder="Введите ваш пароль"
+             onChange={evt => setPassword(evt.target.value)} /><br />
+      <button onClick={() => fullLogin(login, password)}>Залогинится</button>
+    </section>
+  );
+};
+
+const CLogin = connect(null, {fullLogin: actionFullLogin})(Login);
+
+let Registration = function({fullRegister}) {
+  const [login, setLogin]       = useState("");
+  const [nick, setNick]         = useState("");
+  const [password, setPassword] = useState("");
+
+  return (
+    <section className="registration">
+      <h2>Регистрация</h2>
+      <input type="text"
+             placeholder="Введите ваш логин"
+             onChange={evt => setLogin(evt.target.value)} /><br/>
+      <input type="text"
+             placeholder="Введите ваш никнейм"
+             onChange={evt => setNick(evt.target.value)} /><br/>
+      <input type="password"
+             placeholder="Введите ваш пароль"
+             onChange={evt => setPassword(evt.target.value)} /><br/>
+      <button onClick={() => fullRegister(login, password, nick)}>Зарегистрироваться</button>
+    </section>
+  );
+};
+
+const CRegistration = connect(null, {fullRegister: actionFullRegister})(Registration)
+
+let CardGood = function({good: {count, good}, cartChange, cartDelete}) {
+  const [value, setValue] = useState(count);
+
+  return (
+    <tr>
+      <td>
+        <img className="cart__img"
+             src={`${backendURL}/${good?.images[0]?.url}`} />
+      </td>
+      <td>{good?.name}</td>
+      <td>Цена: {good?.price}</td>
+      <td>Количество:
+        <input type="number" 
+               value={value} 
+               onChange={evt => {
+                setValue(evt.target.value);
+                cartChange(good, evt.target.value);
+               }}/>
+      </td>
+      <td>
+        <button onClick={() => cartDelete(good)}>Удоли</button>
+      </td>
+    </tr>
+  );
+};
+
+const CCardGood = connect(null, {cartChange: actionCartChange,
+                                cartDelete: actionCartDelete})(CardGood);
+
+let Cart = function({cart, makeOrder}) {
+  return (
+    <section className="cart">
+      <h2>Корзина</h2>
+      <table>
+        {cart.map(good => <CCardGood good={good} />)}
+      </table>
+      <button onClick={() => makeOrder()}>Сделать заказ</button>
+    </section>
+  );
+};
+
+const CCart = connect(state => ({cart: Object.values(state.cart) || []}), 
+                                {makeOrder: actionOrders})(Cart);
+
+let OrderGood = function({good: {count, good}}) {
+  return (
+    <li>
+      <ul className="dashboard__good-list">
+        <li>
+          <img className="dashboard__img"
+               src={`${backendURL}/${good?.images[0]?.url}`} />
+        </li>
+        <li>{good?.name}</li>
+        <li>Цена: {good?.price}</li>
+        <li>Количество: {count}</li>
+      </ul>
+    </li>
+  );
+};
+
+let Order = function({order: {createdAt, orderGoods}}) {
+  return (
+    <tr>
+      <td className="dashboard__date">{(new Date(+createdAt)).toLocaleString()}</td>
+      <td>
+        <ul className="dashboard__list">
+          {orderGoods.map(orderGood => <OrderGood good={orderGood} />)}
+        </ul>
+      </td>
+    </tr>
+  );
+}
+
+let Dashboard = function({orders}) {
+  return (
+    <table>
+      {orders.map(order => <Order order={order} />)}
+    </table>
+  );
+};
+
+const CDashboardTable = connect(state => ({orders: state.promise?.ordersFind?.payload || []}))(Dashboard)
+
+let PreDashboard = function({orderFind}) {
+  orderFind();
+
+  return (
+    <section className="dashboard">
+      <h2>История заказов</h2>
+      <CDashboardTable />
+    </section>
+  );
+};
+
+const CDashboard = connect(null, {orderFind: actionOrdersFind})(PreDashboard);
+
+let Content = function() {
+  return (
+      <Switch>
+        <Route path="/" exact component={MainPage} />
+        <Route path="/category/:_id" exact component={CCategories} />
+        <Route path="/good/:_id" exact component={CGoodPage} />
+        <Route path="/login" exact component={CLogin} />
+        <Route path="/registration" exact component={CRegistration} />
+        <Route path="/cart" exact component={CCart} />
+        <Route path="/dashboard" exact component={CDashboard} />
+      </Switch>
+  );
+};
+
+let Main = function() {
+  return (
+    <main className="main">
+      <CRootCategories />
+      <Content />
+    </main>
+  );
+};
+
+const history = createHistory()
+
+function App() {
+  return (
+    <Router history={history}>
+      <Provider store={store}>
+        <div className="App">
+          <Header />
+          <Main />
+        </div>
+      </Provider>
+    </Router>
+  );
+}
+
+export default App;

+ 99 - 0
HW Мой МАГАЗЫН на React/src/App.scss

@@ -0,0 +1,99 @@
+.App {
+    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
+}
+
+.header {
+    display: flex;
+    flex-wrap: nowrap;
+    justify-content: space-between;
+    &__logo {
+        font-size: 40px;
+        font-weight: 600;
+    }
+}
+
+.nav {
+    list-style: none;
+    margin: 0;
+    padding: 0;
+}
+
+.main {
+    display: flex;
+    flex-wrap: nowrap;
+}
+
+.rootCats {
+    flex-shrink: 0;
+    background-color: aquamarine;
+    &__list {
+        list-style: none;
+        margin: 0;
+        padding: 0;
+    }
+}
+
+.goods {
+    &__list {
+        display: flex;
+        flex-wrap: wrap;
+        justify-content: space-around;
+        text-align: center;
+        list-style: none;
+        margin: 0;
+        padding: 0;
+    }
+    &__item {
+        width: 300px;
+        margin-bottom: 30px;
+        & img {
+            width: 100%;
+        }
+    }
+}
+
+.good {
+    display: flex;
+    flex-wrap: wrap;
+    align-self: flex-start;
+    & img {
+        width: 500px;
+    }
+}
+
+.login {
+    text-align: center;
+    margin: 0 auto;
+}
+
+.registration {
+    text-align: center;
+    margin: 0 auto;
+}
+
+.cart {
+    &__img {
+        width: 200px;
+    }
+}
+
+.dashboard {
+    &__date {
+        vertical-align: top;
+    }
+    &__list {
+        list-style: none;
+        margin: 0;
+        padding: 0;
+    }
+    &__good-list {
+        display: flex;
+        flex-wrap: nowrap;
+        list-style: none;
+        margin: 0;
+        padding: 0;
+    }
+    &__img {
+        width: 100px;
+    }
+}

+ 10 - 0
HW Мой МАГАЗЫН на React/src/index.js

@@ -0,0 +1,10 @@
+import React from 'react';
+import ReactDOM from 'react-dom';
+import App from './App';
+
+ReactDOM.render(
+  <React.StrictMode>
+    <App />
+  </React.StrictMode>,
+  document.getElementById('root')
+);