Browse Source

React Hw2 done

Andrey 2 years ago
parent
commit
f33cd9ba09

+ 70 - 0
React Dz/DzReact2/dz-react2/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)

File diff suppressed because it is too large
+ 28700 - 0
React Dz/DzReact2/dz-react2/package-lock.json


+ 38 - 0
React Dz/DzReact2/dz-react2/package.json

@@ -0,0 +1,38 @@
+{
+  "name": "dz-react2",
+  "version": "0.1.0",
+  "private": true,
+  "dependencies": {
+    "@testing-library/jest-dom": "^5.16.5",
+    "@testing-library/react": "^13.3.0",
+    "@testing-library/user-event": "^13.5.0",
+    "react": "^18.2.0",
+    "react-dom": "^18.2.0",
+    "react-scripts": "5.0.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"
+    ]
+  }
+}

BIN
React Dz/DzReact2/dz-react2/public/favicon.ico


+ 43 - 0
React Dz/DzReact2/dz-react2/public/index.html

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

BIN
React Dz/DzReact2/dz-react2/public/logo192.png


BIN
React Dz/DzReact2/dz-react2/public/logo512.png


+ 25 - 0
React Dz/DzReact2/dz-react2/public/manifest.json

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

+ 3 - 0
React Dz/DzReact2/dz-react2/public/robots.txt

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

+ 45 - 0
React Dz/DzReact2/dz-react2/src/App.css

@@ -0,0 +1,45 @@
+.App {
+  text-align: center;
+}
+
+.App-logo {
+  height: 40vmin;
+  pointer-events: none;
+}
+
+@media (prefers-reduced-motion: no-preference) {
+  .App-logo {
+    animation: App-logo-spin infinite 20s linear;
+  }
+}
+
+.App-header {
+  background-color: #282c34;
+  min-height: 100vh;
+  display: flex;
+  flex-direction: column;
+  align-items: center;
+  justify-content: center;
+  font-size: calc(10px + 2vmin);
+  color: white;
+}
+
+.App-link {
+  color: #61dafb;
+}
+
+@keyframes App-logo-spin {
+  from {
+    transform: rotate(0deg);
+  }
+  to {
+    transform: rotate(360deg);
+  }
+}
+input{
+  margin-bottom: 20px;
+}
+.inp{
+  margin-right: 10px;
+  margin-left: 10px;
+}

+ 106 - 0
React Dz/DzReact2/dz-react2/src/App.js

@@ -0,0 +1,106 @@
+import React, { useState } from "react";
+import './App.css';
+
+
+const Spoiler = ({header = <button>Жми на меня</button>, open, children}) => {
+  const [openOpen, setOpen] = useState(open)
+  return(
+    <div>
+      <div onClick ={ () => {
+        setOpen(!openOpen)
+      }}>
+        <p>
+        {header}
+        </p>
+          {openOpen && (
+            <div>
+              {children}
+            </div>
+        )}
+      </div>
+    </div>
+  )
+}
+
+const HideSpoiler = () => {
+  return(
+    <div>
+      <Spoiler header={<h1>Заголовок</h1>} open>
+      Контент 1
+        <p>
+          Тут текст который виден всегда!
+        </p>
+      </Spoiler>
+
+      <Spoiler>
+      <h2>Контент 2</h2>
+        <p>
+          Этот текст появляется при нажатии на кнопку!
+        </p>
+      </Spoiler>
+    </div>
+  )
+}
+
+
+const RangeInput = ({min,max}) =>{
+  const [amountSymbol, setAmountSymbol] = useState('')
+  return(
+    <div>
+      <input type = 'text'
+            style ={{ background: amountSymbol.length < min || amountSymbol.length > max ? 'red' : null  }}
+            value = {amountSymbol}
+            onChange={(e) => setAmountSymbol(e.target.value)}
+      />
+            
+      
+    </div>
+  )
+}
+
+const PasswordConfirm = ({min}) => {
+  const [passwordInput1, setPasswordInput1] = useState('')
+  const [passwordInput2, setPasswordInput2] = useState('')
+
+  // const Examination = () => {
+  //   if(passwordInput1 === passwordInput2){
+  //     if(passwordInput1.length > min && passwordInput2.length > min){
+  //       if(passwordInput1.match(/^[A-Za-z]/) && passwordInput2.match(/^[A-Za-z]/)){
+  //           return true
+  //       }
+  //     }
+  //   }
+  //   else{
+  //     return false
+  //   }
+  // }
+  return(
+    <div>
+      <input className='inp' type = "password"
+        style = {{background: (passwordInput1 === passwordInput2) && (passwordInput1.length > min && passwordInput2.length > min) && (passwordInput1.match(/^[A-Za-z]/) && passwordInput2.match(/^[A-Za-z]/)) ? 'green':null}}
+        value = {passwordInput1}
+        onChange = {(e) => setPasswordInput1(e.target.value)}
+        // onInput = {Examination}
+      />
+      <input className= 'inp' type = "password"
+         style = {{background: (passwordInput1 === passwordInput2) && (passwordInput1.length > min && passwordInput2.length > min) && (passwordInput1.match(/^[A-Za-z]/) && passwordInput2.match(/^[A-Za-z]/)) ? 'green':null}}
+        value = {passwordInput2}
+        onChange = {(e) => setPasswordInput2(e.target.value)}
+        // onInput = {Examination}
+      />
+    </div>
+  )
+}
+
+
+function App() {
+  return (
+    <div className="App">
+    <HideSpoiler></HideSpoiler>
+    <RangeInput min={2} max={10} />
+    <PasswordConfirm min={2} />
+    </div>
+  );
+}
+
+export default App;

+ 8 - 0
React Dz/DzReact2/dz-react2/src/App.test.js

@@ -0,0 +1,8 @@
+import { render, screen } from '@testing-library/react';
+import App from './App';
+
+test('renders learn react link', () => {
+  render(<App />);
+  const linkElement = screen.getByText(/learn react/i);
+  expect(linkElement).toBeInTheDocument();
+});

+ 13 - 0
React Dz/DzReact2/dz-react2/src/index.css

@@ -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;
+}

+ 17 - 0
React Dz/DzReact2/dz-react2/src/index.js

@@ -0,0 +1,17 @@
+import React from 'react';
+import ReactDOM from 'react-dom/client';
+import './index.css';
+import App from './App';
+import reportWebVitals from './reportWebVitals';
+
+const root = ReactDOM.createRoot(document.getElementById('root'));
+root.render(
+  <React.StrictMode>
+    <App />
+  </React.StrictMode>
+);
+
+// If you want to start measuring performance in your app, pass a function
+// to log results (for example: reportWebVitals(console.log))
+// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
+reportWebVitals();

File diff suppressed because it is too large
+ 1 - 0
React Dz/DzReact2/dz-react2/src/logo.svg


+ 13 - 0
React Dz/DzReact2/dz-react2/src/reportWebVitals.js

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

+ 5 - 0
React Dz/DzReact2/dz-react2/src/setupTests.js

@@ -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';

+ 134 - 0
React Dz/my-app/package-lock.json

@@ -13,6 +13,7 @@
         "@testing-library/user-event": "^13.5.0",
         "react": "^18.2.0",
         "react-dom": "^18.2.0",
+        "react-redux": "^8.0.2",
         "react-scripts": "5.0.1",
         "web-vitals": "^2.1.4"
       }
@@ -3747,6 +3748,15 @@
         "@types/node": "*"
       }
     },
+    "node_modules/@types/hoist-non-react-statics": {
+      "version": "3.3.1",
+      "resolved": "https://registry.npmjs.org/@types/hoist-non-react-statics/-/hoist-non-react-statics-3.3.1.tgz",
+      "integrity": "sha512-iMIqiko6ooLrTh1joXodJK5X9xeEALT1kM5G3ZLhD3hszxBdIEd5C75U834D9mLcINgD4OyZf5uQXjkuYydWvA==",
+      "dependencies": {
+        "@types/react": "*",
+        "hoist-non-react-statics": "^3.3.0"
+      }
+    },
     "node_modules/@types/html-minifier-terser": {
       "version": "6.1.0",
       "resolved": "https://registry.npmjs.org/@types/html-minifier-terser/-/html-minifier-terser-6.1.0.tgz",
@@ -4131,6 +4141,11 @@
       "resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.2.tgz",
       "integrity": "sha512-F5DIZ36YVLE+PN+Zwws4kJogq47hNgX3Nx6WyDJ3kcplxyke3XIzB8uK5n/Lpm1HBsbGzd6nmGehL8cPekP+Tg=="
     },
+    "node_modules/@types/use-sync-external-store": {
+      "version": "0.0.3",
+      "resolved": "https://registry.npmjs.org/@types/use-sync-external-store/-/use-sync-external-store-0.0.3.tgz",
+      "integrity": "sha512-EwmlvuaxPNej9+T4v5AuBPJa2x2UOJVdjCtDHgcDqitUeOtjnJKJ+apYjVcAoBEMjKW1VVFGZLUb5+qqa09XFA=="
+    },
     "node_modules/@types/ws": {
       "version": "8.5.3",
       "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.5.3.tgz",
@@ -8484,6 +8499,19 @@
         "he": "bin/he"
       }
     },
+    "node_modules/hoist-non-react-statics": {
+      "version": "3.3.2",
+      "resolved": "https://registry.npmjs.org/hoist-non-react-statics/-/hoist-non-react-statics-3.3.2.tgz",
+      "integrity": "sha512-/gGivxi8JPKWNm/W0jSmzcMPpfpPLc3dY/6GxhX2hQ9iGj3aDfklV4ET7NjKpSinLpJ5vafa9iiGIEZg10SfBw==",
+      "dependencies": {
+        "react-is": "^16.7.0"
+      }
+    },
+    "node_modules/hoist-non-react-statics/node_modules/react-is": {
+      "version": "16.13.1",
+      "resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz",
+      "integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ=="
+    },
     "node_modules/hoopy": {
       "version": "0.1.4",
       "resolved": "https://registry.npmjs.org/hoopy/-/hoopy-0.1.4.tgz",
@@ -13971,6 +13999,49 @@
       "resolved": "https://registry.npmjs.org/react-is/-/react-is-17.0.2.tgz",
       "integrity": "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w=="
     },
+    "node_modules/react-redux": {
+      "version": "8.0.2",
+      "resolved": "https://registry.npmjs.org/react-redux/-/react-redux-8.0.2.tgz",
+      "integrity": "sha512-nBwiscMw3NoP59NFCXFf02f8xdo+vSHT/uZ1ldDwF7XaTpzm+Phk97VT4urYBl5TYAPNVaFm12UHAEyzkpNzRA==",
+      "dependencies": {
+        "@babel/runtime": "^7.12.1",
+        "@types/hoist-non-react-statics": "^3.3.1",
+        "@types/use-sync-external-store": "^0.0.3",
+        "hoist-non-react-statics": "^3.3.2",
+        "react-is": "^18.0.0",
+        "use-sync-external-store": "^1.0.0"
+      },
+      "peerDependencies": {
+        "@types/react": "^16.8 || ^17.0 || ^18.0",
+        "@types/react-dom": "^16.8 || ^17.0 || ^18.0",
+        "react": "^16.8 || ^17.0 || ^18.0",
+        "react-dom": "^16.8 || ^17.0 || ^18.0",
+        "react-native": ">=0.59",
+        "redux": "^4"
+      },
+      "peerDependenciesMeta": {
+        "@types/react": {
+          "optional": true
+        },
+        "@types/react-dom": {
+          "optional": true
+        },
+        "react-dom": {
+          "optional": true
+        },
+        "react-native": {
+          "optional": true
+        },
+        "redux": {
+          "optional": true
+        }
+      }
+    },
+    "node_modules/react-redux/node_modules/react-is": {
+      "version": "18.2.0",
+      "resolved": "https://registry.npmjs.org/react-is/-/react-is-18.2.0.tgz",
+      "integrity": "sha512-xWGDIW6x921xtzPkhiULtthJHoJvBbF3q26fzloPCK0hsvxtPVelvftw3zjbHWSkR2km9Z+4uxbDDK/6Zw9B8w=="
+    },
     "node_modules/react-refresh": {
       "version": "0.11.0",
       "resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.11.0.tgz",
@@ -15784,6 +15855,14 @@
         "punycode": "^2.1.0"
       }
     },
+    "node_modules/use-sync-external-store": {
+      "version": "1.2.0",
+      "resolved": "https://registry.npmjs.org/use-sync-external-store/-/use-sync-external-store-1.2.0.tgz",
+      "integrity": "sha512-eEgnFxGQ1Ife9bzYs6VLi8/4X6CObHMw9Qr9tPY43iKwsPw8xE8+EFsf/2cFZ5S3esXgpWgtSCtLNS41F+sKPA==",
+      "peerDependencies": {
+        "react": "^16.8.0 || ^17.0.0 || ^18.0.0"
+      }
+    },
     "node_modules/util-deprecate": {
       "version": "1.0.2",
       "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",
@@ -19299,6 +19378,15 @@
         "@types/node": "*"
       }
     },
+    "@types/hoist-non-react-statics": {
+      "version": "3.3.1",
+      "resolved": "https://registry.npmjs.org/@types/hoist-non-react-statics/-/hoist-non-react-statics-3.3.1.tgz",
+      "integrity": "sha512-iMIqiko6ooLrTh1joXodJK5X9xeEALT1kM5G3ZLhD3hszxBdIEd5C75U834D9mLcINgD4OyZf5uQXjkuYydWvA==",
+      "requires": {
+        "@types/react": "*",
+        "hoist-non-react-statics": "^3.3.0"
+      }
+    },
     "@types/html-minifier-terser": {
       "version": "6.1.0",
       "resolved": "https://registry.npmjs.org/@types/html-minifier-terser/-/html-minifier-terser-6.1.0.tgz",
@@ -19633,6 +19721,11 @@
       "resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.2.tgz",
       "integrity": "sha512-F5DIZ36YVLE+PN+Zwws4kJogq47hNgX3Nx6WyDJ3kcplxyke3XIzB8uK5n/Lpm1HBsbGzd6nmGehL8cPekP+Tg=="
     },
+    "@types/use-sync-external-store": {
+      "version": "0.0.3",
+      "resolved": "https://registry.npmjs.org/@types/use-sync-external-store/-/use-sync-external-store-0.0.3.tgz",
+      "integrity": "sha512-EwmlvuaxPNej9+T4v5AuBPJa2x2UOJVdjCtDHgcDqitUeOtjnJKJ+apYjVcAoBEMjKW1VVFGZLUb5+qqa09XFA=="
+    },
     "@types/ws": {
       "version": "8.5.3",
       "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.5.3.tgz",
@@ -22781,6 +22874,21 @@
       "resolved": "https://registry.npmjs.org/he/-/he-1.2.0.tgz",
       "integrity": "sha512-F/1DnUGPopORZi0ni+CvrCgHQ5FyEAHRLSApuYWMmrbSwoN2Mn/7k+Gl38gJnR7yyDZk6WLXwiGod1JOWNDKGw=="
     },
+    "hoist-non-react-statics": {
+      "version": "3.3.2",
+      "resolved": "https://registry.npmjs.org/hoist-non-react-statics/-/hoist-non-react-statics-3.3.2.tgz",
+      "integrity": "sha512-/gGivxi8JPKWNm/W0jSmzcMPpfpPLc3dY/6GxhX2hQ9iGj3aDfklV4ET7NjKpSinLpJ5vafa9iiGIEZg10SfBw==",
+      "requires": {
+        "react-is": "^16.7.0"
+      },
+      "dependencies": {
+        "react-is": {
+          "version": "16.13.1",
+          "resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz",
+          "integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ=="
+        }
+      }
+    },
     "hoopy": {
       "version": "0.1.4",
       "resolved": "https://registry.npmjs.org/hoopy/-/hoopy-0.1.4.tgz",
@@ -26565,6 +26673,26 @@
       "resolved": "https://registry.npmjs.org/react-is/-/react-is-17.0.2.tgz",
       "integrity": "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w=="
     },
+    "react-redux": {
+      "version": "8.0.2",
+      "resolved": "https://registry.npmjs.org/react-redux/-/react-redux-8.0.2.tgz",
+      "integrity": "sha512-nBwiscMw3NoP59NFCXFf02f8xdo+vSHT/uZ1ldDwF7XaTpzm+Phk97VT4urYBl5TYAPNVaFm12UHAEyzkpNzRA==",
+      "requires": {
+        "@babel/runtime": "^7.12.1",
+        "@types/hoist-non-react-statics": "^3.3.1",
+        "@types/use-sync-external-store": "^0.0.3",
+        "hoist-non-react-statics": "^3.3.2",
+        "react-is": "^18.0.0",
+        "use-sync-external-store": "^1.0.0"
+      },
+      "dependencies": {
+        "react-is": {
+          "version": "18.2.0",
+          "resolved": "https://registry.npmjs.org/react-is/-/react-is-18.2.0.tgz",
+          "integrity": "sha512-xWGDIW6x921xtzPkhiULtthJHoJvBbF3q26fzloPCK0hsvxtPVelvftw3zjbHWSkR2km9Z+4uxbDDK/6Zw9B8w=="
+        }
+      }
+    },
     "react-refresh": {
       "version": "0.11.0",
       "resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.11.0.tgz",
@@ -27897,6 +28025,12 @@
         "punycode": "^2.1.0"
       }
     },
+    "use-sync-external-store": {
+      "version": "1.2.0",
+      "resolved": "https://registry.npmjs.org/use-sync-external-store/-/use-sync-external-store-1.2.0.tgz",
+      "integrity": "sha512-eEgnFxGQ1Ife9bzYs6VLi8/4X6CObHMw9Qr9tPY43iKwsPw8xE8+EFsf/2cFZ5S3esXgpWgtSCtLNS41F+sKPA==",
+      "requires": {}
+    },
     "util-deprecate": {
       "version": "1.0.2",
       "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",

+ 1 - 0
React Dz/my-app/package.json

@@ -8,6 +8,7 @@
     "@testing-library/user-event": "^13.5.0",
     "react": "^18.2.0",
     "react-dom": "^18.2.0",
+    "react-redux": "^8.0.2",
     "react-scripts": "5.0.1",
     "web-vitals": "^2.1.4"
   },

+ 442 - 6
React Dz/my-app/src/App.js

@@ -1,13 +1,447 @@
 import { useState } from 'react';
 import './App.css';
 
-const LoginForm = () => {
+import thunk from 'redux-thunk';
+import {createStore, combineReducers, applyMiddleware} from 'redux';
+import { Provider, connect } from 'react-redux';
+
+const store = createStore(combineReducers({ 
+  auth: authReducer, 
+  promise: promiseReducer, 
+  cart: localStoreReducer(cartReducer, "cart") 
+}), applyMiddleware(thunk))
+
+
+function jwtDecode(token) {
+    try {
+        return JSON.parse(atob(token.split('.')[1]))
+    }
+    catch (e) {
+    }
+}
+
+function authReducer(state = {}, { type, token }) {
+    //{
+    //  token, payload
+    //}
+
+    if (type === 'AUTH_LOGIN') {
+        //пытаемся токен раскодировать
+        const payload = jwtDecode(token)
+        if (payload) { //и если получилось
+            return {
+                token, payload //payload - раскодированный токен;
+            }
+        }
+    }
+    if (type === 'AUTH_LOGOUT') {
+        return {}
+    }
+    return state;
+}
+
+function countReducer(state = { count: 0 }, { type }) {
+    if (type === "COUNT_INC") {
+        return {
+            count: state.count + 1
+        }
+    }
+    if (type === "COUNT_DEC") {
+        return {
+            count: state.count - 1
+        }
+    }
+    return state
+}
+
+function localStoreReducer(reducer, localStorageKey) {
+    function localStoredReducer(state, action) {
+        // Если state === undefined, то достать старый state из local storage
+        if (state === undefined) {
+            try {
+                return JSON.parse(localStorage[localStorageKey])
+            } catch (e) { }
+
+        }
+        const newState = reducer(state, action)
+        // Сохранить newState в local storage
+        localStorage[localStorageKey] = JSON.stringify(newState)
+        return newState
+
+    }
+    return localStoredReducer
+}
+
+function promiseReducer(state = {}, { type, name, status, payload, error }) {
+    ////?????
+    //ОДИН ПРОМИС:
+    //состояние: PENDING/FULFILLED/REJECTED
+    //результат
+    //ошибка:
+    //{status, payload, error}
+    //{
+    //       name1:{status, payload, error}   
+    //       name2:{status, payload, error}   
+    //       name3:{status, payload, error}   
+    //}
+    if (type === 'PROMISE') {
+        return {
+            ...state,
+            [name]: { status, payload, error }
+        }
+    }
+    return state
+}
+
+
+
+const actionPending = (name) => ({
+  type: 'PROMISE',
+  status: 'PENDING',
+  name
+})
+const actionFulfilled = (name, payload) => ({
+  type: 'PROMISE',
+  status: 'FULFILLED',
+  name,
+  payload
+})
+const actionRejected = (name, error) => ({
+  type: 'PROMISE',
+  status: 'REJECTED',
+  name,
+  error
+})
+
+const actionPromise = (name, promise) =>
+  async dispatch => {
+      try {
+          dispatch(actionPending(name))
+          let payload = await promise
+          dispatch(actionFulfilled(name, payload))
+          return payload
+      }
+      catch (e) {
+          dispatch(actionRejected(name, e))
+      }
+  }
+
+// const delay = ms => new Promise(ok => setTimeout(() => ok(ms), ms))
+
+
+// function combineReducers(reducers) { //пачку редьюсеров как объект {auth: authReducer, promise: promiseReducer}
+//   function combinedReducer(combinedState = {}, action) { //combinedState - типа {auth: {...}, promise: {....}}
+//       const newCombinedState = {}
+//       for (const [reducerName, reducer] of Object.entries(reducers)) {
+//           const newSubState = reducer(combinedState[reducerName], action)
+//           if (newSubState !== combinedState[reducerName]) {
+//               newCombinedState[reducerName] = newSubState
+//           }
+//       }
+//       if (Object.keys(newCombinedState).length === 0) {
+//           return combinedState
+//       }
+//       return { ...combinedState, ...newCombinedState }
+//   }
+
+//   return combinedReducer //нам возвращают один редьюсер, который имеет стейт вида {auth: {...стейт authReducer-а}, promise: {...стейт promiseReducer-а}}
+// }
+
+function cartReducer(state = {}, { type, count = 1, good }) {
+  // type CART_ADD CART_REMOVE CART_CLEAR CART_DEL
+  // {
+  //  id1: {count: 1, good: {name, price, images, id}}
+  // }
+  if (type === "CART_ADD") {
+      return {
+          ...state,
+          [good._id]: { count: count + (state[good._id]?.count || 0), good },
+      };
+  }
+
+  if (type === "CART_DELETE") {
+      if (state[good._id].count > 1) {
+          return {
+              ...state,
+              [good._id]: {
+                  count: -count + (state[good._id]?.count || 0),
+                  good,
+              },
+          };
+      }
+
+      if (state[good._id].count === 1) {
+          let { [good._id]: id1, ...newState } = state; //o4en strashnoe koldunstvo
+          //delete newState[good._id]
+          return newState;
+      }
+  }
+
+  if (type === "CART_CLEAR") {
+      return {};
+  }
+  if (type === "CART_REMOVE") {
+      // let newState = {...state}
+      let { [good._id]: id1, ...newState } = state; //o4en strashnoe koldunstvo
+      //delete newState[good._id]
+      return newState;
+  }
+
+  return state;
+}
+
+const backendURL = 'http://shop-roles.node.ed.asmer.org.ua/'
+
+
+
+
+const getGQL = (url) => (query, variables) =>
+    fetch(url, {
+        method: "POST",
+        headers: {
+            "Content-Type": "application/json",
+            ...(localStorage.authToken
+                ? { Authorization: "Bearer " + localStorage.authToken }
+                : {}),
+        },
+        body: JSON.stringify({ query, variables }),
+    })
+        .then((res) => res.json())
+        .then((data) => {
+            if (data.data) {
+                return Object.values(data.data)[0];
+            } else throw new Error(JSON.stringify(data.errors));
+        });
+
+const gql = getGQL(backendURL + "graphql");
+
+// const gql = (url, query, variables) => fetch(url, {
+//     method: 'POST',
+//     headers: {
+//         "Content-Type": "application/json",
+//         Accept: "application/json",
+//     },
+//     body: JSON.stringify({ query, variables })
+// }).then(res => res.json())
+
+// const backendURL = 'http://shop-roles.node.ed.asmer.org.ua/graphql'
+
+
+const actionRootCats = () =>
+    actionPromise(
+        'rootCats',
+        gql(
+
+            `query {
+                CategoryFind(query: "[{\\"parent\\":null}]"){
+                _id name
+        }
+    }`
+        )
+    )
+
+const actionCatById = (_id) =>  //добавить подкатегории
+    actionPromise(
+        'catById',
+        gql(
+
+            `query catById($q: String){
+                CategoryFindOne(query: $q){
+                    _id name goods {
+                        _id name price images {
+                            url
+                }
+            }
+        }
+    }`,
+            { q: JSON.stringify([{ _id }]) }
+        )
+    )
+
+const actionGoodById = (_id) =>
+    actionPromise(
+        'goodByID',
+        gql(
+
+            `query goodByID($q:String){
+                GoodFindOne(query: $q){
+                    _id
+                    name
+  	                description
+                    price
+                    categories{
+                        _id
+                        name
+                    }
+                    images{
+                        url
+                    }
+                }
+            }`,
+            { q: JSON.stringify([{ _id }]) }
+        )
+    )
+
+const actionRegistr = (login, password) =>
+    actionPromise(
+        'registr',
+        gql(
+
+            `mutation register($login:String, $password:String){
+                UserUpsert(user: {login:$login, password:$password}){
+                  _id login 
+                }
+              }`,
+            { login: login, password: password }
+        )
+    )
+
+const actionLogin = (login, password) =>
+    actionPromise(
+        'login',
+        gql(
+
+            `query log($login:String, $password:String){
+                login(login:$login, password:$password)
+            }`,
+            { login: login, password: password }
+        )
+    )
+
+    const actionOrder = () => async (dispatch, getState) => {
+        let { cart } = getState();
+        const orderGoods = Object.entries(cart).map(([_id, { count }]) => ({
+            good: { _id },
+            count,
+        }));
+    
+        let result = await dispatch(
+            actionPromise(
+                "order",
+                gql(
+                    `
+                        mutation newOrder($order:OrderInput){
+                        OrderUpsert(order:$order)
+                            { _id total  }
+                        }
+                `,
+                    { order: { orderGoods } }
+                )
+            )
+        );
+        if (result?._id) {
+            dispatch(actionCartClear());
+            document.location.hash = "#/cart/";
+            alert("Покупка успішна")
+        }
+    
+    };
+
+    const orderHistory = () =>
+    actionPromise(
+        "history",
+        gql(` query OrderFind{
+        OrderFind(query:"[{}]"){
+            _id total createdAt orderGoods{
+                count good{
+                    _id name price images{
+                        url
+                    }
+                }
+                owner{
+                    _id login 
+                }
+            }
+        }
+    }
+    `)
+    );
+
+const actionAuthLogin = (token) =>
+    (dispatch, getState) => {
+        const oldState = getState()
+        dispatch({ type: 'AUTH_LOGIN', token })
+        const newState = getState()
+        if (oldState !== newState)
+            localStorage.authToken = token
+    }
+
+const actionAuthLogout = () =>
+    dispatch => {
+        dispatch({ type: 'AUTH_LOGOUT' })
+        localStorage.removeItem('authToken')
+    }
+
+const actionCartAdd = (good, count = 1) => ({
+    type: "CART_ADD",
+    good,
+    count
+});
+const actionCartChange = (good, count = 1) => ({
+    type: "CART_CHANGE",
+    good,
+    count,
+}); ///oninput меняяем полностью
+const actionCartDelete = (good) => ({
+    type: "CART_DELETE",
+    good
+});
+const actionCartClear = () => ({
+    type: "CART_CLEAR"
+});
+const actionCartRemove = (good) =>({
+    type: "CART_REMOVE",
+    good
+})
+
+const actionFullLogin = (login, password) => async (dispatch) => {
+    let token = await dispatch(actionLogin(login, password))
+    if (token) {
+        dispatch(actionAuthLogin(token))
+    }
+}
+
+const actionFullRegistr = (login, password) => async (dispatch) => {
+    try {
+        await dispatch(actionRegistr(login, password))
+    }
+    catch (e) {
+        return console.log(e)
+    }
+    await dispatch(actionFullLogin(login, password))
+}
+
+
+   //не забудьте combineReducers если он у вас уже есть
+if (localStorage.authToken) {
+    store.dispatch(actionAuthLogin(localStorage.authToken))
+}
+//const store = createStore(combineReducers({promise: promiseReducer, auth: authReducer, cart: cartReducer}))
+store.subscribe(() => console.log(store.getState()))
+
+store.dispatch(actionRootCats())
+// store.dispatch(actionLogin('test456', '123123'))
+
+
+
+
+
+
+
+
+
+
+
+const LoginForm = ({onLogin}) => {
   const [login, setLogin] = useState('')
   const [password, setPassword] =  useState('')
-      const onLogin = () => {
+      const disableButton = () => {
         return !(login !== '' && password !== '')
       }
-        const Vhod = () => alert('Конгратюлатион')
+       
+        const Vhod = () => {
+            onLogin(login,password)
+        }
 
       return(
 
@@ -23,7 +457,7 @@ const LoginForm = () => {
                       onChange = { (e) => setPassword(e.target.value) }
             />
             
-            <button disabled = {onLogin()} onClick = {Vhod}
+            <button disabled = {disableButton()} onClick = {Vhod}
 
             >Вход</button>
         </div>
@@ -105,17 +539,19 @@ const Category  = () =>
 
 
 
-
+const CLoginForm = connect(null, {onLogin: actionFullLogin})(LoginForm) 
 function App() {
   return (
+    <Provider store = {store}>
     <div className="App">
-        <LoginForm />
+        <CLoginForm />
           <div className ='shop'>
             <CategoryMenu />
             <Category />
           </div>
         
     </div>
+    </Provider>
   );
 }