RomanR 4 роки тому
коміт
c888d3eb64

+ 23 - 0
.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*

+ 68 - 0
README.md

@@ -0,0 +1,68 @@
+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.<br />
+Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
+
+The page will reload if you make edits.<br />
+You will also see any lint errors in the console.
+
+### `npm test`
+
+Launches the test runner in the interactive watch mode.<br />
+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.<br />
+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.<br />
+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
+
+### Analyzing the Bundle Size
+
+This section has moved here: 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
+
+### Advanced Configuration
+
+This section has moved here: 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
+
+### `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

Різницю між файлами не показано, бо вона завелика
+ 14870 - 0
package-lock.json


+ 44 - 0
package.json

@@ -0,0 +1,44 @@
+{
+  "name": "my-project",
+  "version": "0.1.0",
+  "private": true,
+  "proxy": "http://player.asmer.fs.a-level.com.ua/",
+  "dependencies": {
+    "@ant-design/icons": "^4.2.2",
+    "@testing-library/jest-dom": "^4.2.4",
+    "@testing-library/react": "^9.5.0",
+    "@testing-library/user-event": "^7.2.1",
+    "antd": "^4.6.4",
+    "jwt-decode": "^3.0.0-beta.2",
+    "react": "^16.13.1",
+    "react-dom": "^16.13.1",
+    "react-redux": "^7.2.1",
+    "react-router-dom": "^5.2.0",
+    "react-scripts": "3.4.3",
+    "redux": "^4.0.5",
+    "redux-devtools-extension": "^2.13.8",
+    "redux-thunk": "^2.3.0",
+    "vuex": "^3.5.1"
+  },
+  "scripts": {
+    "start": "react-scripts start",
+    "build": "react-scripts build",
+    "test": "react-scripts test",
+    "eject": "react-scripts eject"
+  },
+  "eslintConfig": {
+    "extends": "react-app"
+  },
+  "browserslist": {
+    "production": [
+      ">0.2%",
+      "not dead",
+      "not op_mini all"
+    ],
+    "development": [
+      "last 1 chrome version",
+      "last 1 firefox version",
+      "last 1 safari version"
+    ]
+  }
+}

BIN
public/favicon.ico


+ 43 - 0
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
public/logo192.png


BIN
public/logo512.png


+ 25 - 0
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
public/robots.txt

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

+ 62 - 0
src/App.js

@@ -0,0 +1,62 @@
+import React, { useEffect, useState } from "react";
+import {
+  BrowserRouter as Router,
+  Route,
+  Redirect,
+  Switch,
+} from "react-router-dom";
+import { connect } from "react-redux";
+
+import { Provider } from "react-redux";
+import store from "./store";
+import history from "./utils/history";
+
+import "./styles/Reset.css";
+import "./styles/App.css";
+
+import RegisterForm from "./components/RegisterForm";
+import LoginForm from "./components/LoginForm";
+import Lib from "./components/Library";
+
+const PrivateRoute = (props ) => {
+  console.log(props)
+  const { children, ...rest } = props;
+
+  return (
+    <Route
+      {...rest}
+      render={({ location }) => {
+        return localStorage.authToken ? (
+          children
+        ) : (
+          <Redirect
+            to={{
+              pathname: "/login",
+              state: { from: location },
+            }}
+          />
+        );
+      }}
+    />
+  );
+};
+
+export default () => {
+  return (
+    <Provider store={store}>
+      <div className="App">
+        {/* <div className="wrapper"> */}
+          <Router history={history}>
+            <Switch>
+              <Route exact path="/" component={RegisterForm} />
+              <Route path="/login" component={LoginForm} />
+              <PrivateRoute path="/private">
+                <Lib />
+              </PrivateRoute>
+            </Switch>
+          </Router>
+        {/* </div> */}
+      </div>
+    </Provider>
+  );
+};

+ 58 - 0
src/actions/authActions.js

@@ -0,0 +1,58 @@
+import getGQL from "../utils/getGQL";
+import * as actions from "../constants/actions/index";
+import history from "../utils/history";
+import { clearTrackList } from "../actions/playerActions";
+
+export function actionLogIn(token) {
+  return {
+    type: actions.LOGIN,
+    token,
+  };
+}
+function actionLogOut() {
+  return {
+    type: actions.LOGOUT,
+  };
+}
+
+export const logOut = () => (dispatch) => {
+  dispatch(clearTrackList());
+  dispatch(actionLogOut());
+  history.push("/login");
+};
+
+export const doLogin = (login, password) => async (dispatch) => {
+  // debugger
+  try {
+    await getGQL(
+      "/graphql"
+      // ,{Authorization : "Bearer " + localStorage.authToken}
+    )(
+      `query Login{
+        login(login: "${login}", password: "${password}")
+        }`
+    ).then((data) => {
+      console.log(data);
+      // console.log(data.data.login);
+
+      // localStorage.authToken = data.data.login;
+      // const token = localStorage.authToken;
+      // dispatch(actionLogIn(token));
+
+      dispatch(actionLogIn(data.data.login));
+      // const originalFetch = fetch;
+      // fetch = (url, params = { headers: {} }) => {
+      //   params.headers.Authorization = "Bearer " + localStorage.authToken;
+      //   return originalFetch(url, params);
+      // };
+      // console.log("localStorage.authToken: " + localStorage.authToken);
+    });
+  } catch (error) {
+    console.log(error);
+    if (error.message.includes("Invalid token")) {
+      alert("Invalid credentials!");
+    } else {
+      alert("Something went wrong");
+    }
+  }
+};

+ 61 - 0
src/actions/logOutActions.js

@@ -0,0 +1,61 @@
+
+// import getGQL from "../utils/getGQL";
+import * as actions from "../constants/actions/index";
+import getGQL from "../utils/getGQL";
+
+
+function actionLogOut() {
+  // console.log(actions)
+  return {
+    type: actions.LOGOUT,
+  };
+}
+
+// export default actionLogOut;
+// ............................
+  // let p = getGQL('http://player.asmer.fs.a-level.com.ua/graphql')(
+  //   let p = getGQL('/graphql')(
+  //     `query Login(login: String!, password: String!){
+  //     login(login: "${login}", password: "${password}")
+  //     }`
+  //   ).then((data) =>
+  //     console.log(data)
+  // )
+
+  // store.dispatch(actionPending())
+  // p.then(data => store.dispatch(actionResolved(data)))
+
+export const doLogOut = (store, dispatch) => {
+  // debugger
+  try {
+    store.dispatch(actionLogOut());
+
+  } catch (error) {
+    console.log(error)
+    if (error.message.includes("Invalid token")) {
+      alert("Invalid credentials!");
+    } else {
+      alert("Something went wrong");
+    }
+  }
+};
+
+// export default doLogOut, actionLogOut;
+// export default doLogOut, actionLogOut;
+
+// export const doLogOut = ({dispatch, history}) => {
+//     try {
+//         // console.log(login, password, localStorage.authToken);
+//         localStorage.authToken = "";
+//         const token = localStorage.authToken;
+//         dispatch(actionLogOut(token));
+//         console.log("localStorage.authToken: " + localStorage.authToken);
+//         history.push("/login");
+//     } catch (error) {
+//       if (error.message.includes("Invalid token")) {
+//         alert("Invalid credentials!");
+//       } else {
+//         alert("Something went wrong");
+//       }
+//     }
+// };

+ 96 - 0
src/actions/playerActions.js

@@ -0,0 +1,96 @@
+import getGQL from "../utils/getGQL";
+import * as actions from "../constants/actions/index";
+
+const setTracks = (tracks) => ({
+  type: actions.SET_TRACKS,
+  tracks,
+});
+
+export const setCurrentTrack = (trackIndex) => ({
+  type: actions.SET_CURRENT_TRACK,
+  trackIndex,
+});
+
+export const getTracks = () => async (dispatch) => {
+  try {
+    let response = await getGQL("/graphql", {
+      Authorization: `Bearer ${localStorage.authToken}`,
+    })(
+      `query tracksFind($query: String!){
+              TrackFind(query: $query){
+                  _id
+                  url
+                  originalFileName
+              }
+            }`,
+      { query: JSON.stringify([{}]) }
+    );
+    // setTracks(response.data.TrackFind)
+    // console.log(tracks)
+    // console.log('connected')
+    console.log(response);
+
+    dispatch(setTracks(response.data.TrackFind));
+
+    console.log(response.data.TrackFind);
+  } catch (error) {
+    console.log(error);
+  }
+};
+
+export const clearTrackList = () => ({
+  type: actions.CLEAR_TRACK_LIST
+})
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+// export const getTracks = (state) => async (dispatch) => {
+
+// // const List = ({track: {_id, url, originalFileName}}) =>
+// // <li>
+// //     <p>
+// //         <span>{originalFileName}</span>
+// //         {/* <span>{_id}</span>  */}
+// //         {/* <span>{url}</span>  */}
+// //     </p>
+// // </li>
+// const TrackList = () => {
+//   const [tracks, setTracks] = useState([]);
+//   console.log(tracks);
+//   useEffect( async () => {
+//     // {debugger}
+//     let response = await getGQL("/graphql")
+//     (`query tracksFind($query: String!){
+//         TrackFind(query: $query){
+//             _id
+//             url
+//             originalFileName
+//         }
+//       }`,{query: JSON.stringify([{}])})//накой эта строчка нужна?
+//       console.log(response);
+//       (response)? setTracks(response.data.TrackFind) : alert('data is waiting');
+//   },[])//запрос работает, нужно залогиниться, получить токен, и затем перейти во вкладку libraries.
+//   const [list, setList] = useState([]);
+//   (tracks)? setList(tracks) &&  console.log(list) : alert('data is waiting');
+//   return (
+//       <div className="trackList">
+//           <ul>
+//               {/* {(tracks)? tracks.map(track => <List track={track}/>) : alert('data is waiting')} */}
+//           </ul>
+//       </div>
+//   )
+// }
+// }

+ 6 - 0
src/components/Footer.js

@@ -0,0 +1,6 @@
+import React from 'react'
+
+
+export default () => {
+    return <div className="footer">Copiryght &copy; 2020 Romanenko Roman</div>;
+  };

+ 56 - 0
src/components/Header.js

@@ -0,0 +1,56 @@
+import React, { useState, useEffect } from "react";
+// import  {doLogOut} from "../actions/logOutActions";
+
+import { Link } from "react-router-dom";
+import { connect } from "react-redux";
+import history from "../utils/history";
+import { logOut } from "../actions/authActions";
+// const mapStateToProps = (state) => ({
+//   doLogOut: !!state.auth.token,
+// });
+
+// const mapDispatchToProps = (dispatch) => ({
+//   doLoginOut: (login, password) => dispatch(doLogOut()),
+// });
+
+const Header = ({ login, logOut }) => {
+  console.log(login);
+
+  function onLogOut() {
+    logOut();
+  }
+
+  return (
+    <div className="header">
+      <ul className="mainMenu">
+        <li>
+          <h2>gRomkoPlayer</h2>
+        </li>
+        <li>
+          <h2>Library</h2>
+        </li>
+        <li>
+          <h2>Playlist</h2>
+        </li>
+        <li>
+          <h2>Search</h2>
+        </li>
+        <li className="userMenu">
+          <h2>User: {login}</h2>
+          <ul className="userMenu-child">
+            <li onClick={onLogOut}>
+              {/* <li onClick={doLogOut}> */}
+              {/* <Link to="/login">Log out</Link> */}
+              {/* <a href="#">Log out</a> */}
+              Log out
+            </li>
+          </ul>
+        </li>
+      </ul>
+    </div>
+  );
+};
+
+// export default Header;
+export default connect(null, { logOut })(Header);
+// export default connect(null, {doLogOut})(Header);

+ 91 - 0
src/components/Library.js

@@ -0,0 +1,91 @@
+import React, { useState, useEffect, Component } from "react";
+import { Link } from "react-router-dom";
+import { Provider, connect } from "react-redux";
+import { createStore, combineReducers, applyMiddleware } from "redux";
+import { render } from "react-dom";
+import { Spin } from "antd";
+import Header from "./Header";
+import Footer from "./Footer";
+
+import App from "../App";
+import Player from "./Player";
+import getGQL from "../utils/getGQL";
+import { getTracks, setCurrentTrack } from "../actions/playerActions";
+
+import "../styles/library.css";
+
+const Lib = ({
+  tracks,
+  history,
+  getTracks,
+  login,
+  setCurrentTrack,
+  currentTrack,
+}) => {
+  useEffect(() => {
+    getTracks && getTracks();
+  }, []);
+
+  const Track = ({ track, highlighted }) => {
+    const { originalFileName, url, _id, trackIndex } = track;
+    return (
+      <li
+        className={highlighted ? "highlighted" : null}
+        onClick={(e) => setCurrentTrack(trackIndex)}
+      >
+        <p>
+          <span>{originalFileName}</span>
+          <span onClick={() => console.log("TODO action")}>+</span>
+        </p>
+      </li>
+    );
+  };
+
+  const TrackList = ({ playlist, currentTrack }) => {
+    console.log(playlist);
+    return (
+      <div className="main">
+        <div className="trackList">
+          <ul>
+            {playlist.map((track, trackIndex) => (
+              <Track
+                key={trackIndex}
+                track={{ ...track, trackIndex }}
+                highlighted={trackIndex === currentTrack}
+              />
+              // console.log(track)
+            ))}
+          </ul>
+          <Player playlist={tracks} />
+        </div>
+      </div>
+    );
+  };
+
+  return (
+    <>
+      <Header login={login} />
+      {!tracks.length && (
+        <div className="container">
+          <Spin size="large" />
+        </div>
+      )}
+      <TrackList playlist={tracks} currentTrack={currentTrack} />
+      <Footer />
+    </>
+  );
+};
+
+const mapStateToProps = (state) => ({
+  tracks: state.player.tracks,
+  currentTrack: state.player.currentTrack,
+  login: (state.auth.data.data && state.auth.data.data.sub.login) || "",
+});
+
+const mapDispatchToProps = (dispatch) => ({
+  getTracks: () => dispatch(getTracks()),
+  setCurrentTrack: (trackIndex) => dispatch(setCurrentTrack(trackIndex)),
+});
+
+// export default connect(mapStateToProps, mapDispatchToProps)(Main);
+export default connect(mapStateToProps, mapDispatchToProps)(Lib);

+ 166 - 0
src/components/LoginForm.js

@@ -0,0 +1,166 @@
+import React, { useState, useEffect } from "react";
+import { Form, Input, Button, Checkbox } from "antd";
+import { UserOutlined, LockOutlined } from "@ant-design/icons";
+import { useHistory, Link } from "react-router-dom";
+//////////////////////////////////
+import jwt_decode from "jwt-decode";
+// import store from './vuex/store';
+import thunk from "redux-thunk";
+import { createStore, combineReducers, applyMiddleware } from "redux";
+import { connect } from "react-redux";
+/////////////////////////////////
+
+import getGQL from "../utils/getGQL";
+import "../styles/RegisterForm.css";
+import { doLogin } from "../actions/authActions";
+
+// import { BrowserRouter as Router, Route } from 'react-router-dom';
+// import createHistory from 'history/createBrowserHistory';
+
+// const history = createHistory()
+
+//////////////////////////////////////////////////////////////
+// const store = createStore(applyMiddleware(thunk)) //вторым параметром идет миддлварь
+
+const LoginForm = ({ store, history, doLogin, isLoggedIn }) => {
+  // const history = useHistory();
+  const [form] = Form.useForm();
+  const [login, setLogin] = useState("");
+  const [password, setPassword] = useState("");
+
+  useEffect(() => {
+    isLoggedIn && history.push("/private");
+  }, [isLoggedIn]);
+
+  const onFinish = (values) => {
+    console.log("Success:", values);
+  };
+
+  const onFinishFailed = (errorInfo) => {
+    console.log("Failed:", errorInfo);
+  };
+
+  // let p = getGQL('http://player.asmer.fs.a-level.com.ua/graphql')(
+  //   let p = getGQL('/graphql')(
+  //     `query Login{
+  //     login(login: "${login}", password: "${password}")
+  //     }`
+  //   ).then((data) =>
+  //     console.log(data)
+  // )
+
+  // store.dispatch(actionPending())
+  // p.then(data => store.dispatch(actionResolved(data)))
+
+  /////////////////////////////////////////////////////////////////////////
+
+  function onLogin() {
+    doLogin && doLogin(login, password);
+    console.log(login);
+  }
+
+  return (
+    <div className="registerForm">
+      {/* <div className="wrapperRegisterForm"> */}
+      <div>
+        <Form
+          name="basic"
+          form={form}
+          // initialValues={{
+          //   remember: true,
+          // }}
+          onFinish={onFinish}
+          onFinishFailed={onFinishFailed}
+        >
+          <Form.Item
+            label="Username"
+            name="username"
+            value={onLogin}
+            onChange={(e) => setLogin(e.target.value)}
+            rules={[
+              {
+                required: true,
+                message: "Please input your username!",
+              },
+            ]}
+          >
+            <Input
+              prefix={<UserOutlined className="site-form-item-icon" />}
+              onChange={(e) => {
+                console.log(e.target.value);
+                form.setFieldsValue({ username: e.target.value });
+              }}
+            />
+          </Form.Item>
+
+          <Form.Item
+            label="Password"
+            name="password"
+            value={password}
+            onChange={(e) => setPassword(e.target.value)}
+            rules={[
+              {
+                required: true,
+                message: "Please input your password!",
+              },
+            ]}
+          >
+            <Input.Password
+              prefix={<LockOutlined className="site-form-item-icon" />}
+            />
+          </Form.Item>
+          {/* 
+        <Form.Item name="remember" valuePropName="checked">
+          <Checkbox>Remember me</Checkbox>
+        </Form.Item> */}
+
+          <Form.Item>
+            <Button 
+            type="primary" 
+            htmlType="submit" 
+            // disabled = {!onLogin ? true : false}
+            onClick={onLogin}
+            >
+              Submit
+            </Button>
+            {/* <Button
+              onClick={() => {
+                history.push("/library");
+              }}
+            >
+              Library
+            </Button> */}
+            <Link to="/" className="link-approval">Registration</Link>
+          </Form.Item>
+        </Form>
+      </div>
+    </div>
+  );
+};
+
+const mapStateToProps = (state) => ({
+  isLoggedIn: !!state.auth.token,
+});
+
+const mapDispatchToProps = (dispatch) => ({
+  doLogin: (login, password) => dispatch(doLogin(login, password)),
+});
+
+export default connect(mapStateToProps, mapDispatchToProps)(LoginForm);
+
+// if(type == 'PROMISE') {
+//   {
+//     status PENDING ||
+//           FULFILED ||
+//           REJECTED
+//   }
+// }
+// action PENDING = () => (
+//   {type: 'promise', status: 'PENDING', payload: 'null', error: 'null'}
+// )
+// action FULFILED =() => (
+//   {type: 'SET_STATUS', status: 'RESOLVED', payload, error: null }
+// )
+// action REJECTED =() => (
+//   {type: 'SET_STATUS', status: 'REJECTED', payload: null, error}
+// )

+ 44 - 0
src/components/Player.js

@@ -0,0 +1,44 @@
+import React, { useState, useEffect } from "react";
+import Library from "./Library";
+import { connect } from "react-redux";
+
+import "../styles/player.css";
+import { setCurrentTrack } from "../actions/playerActions";
+
+// this.props.playlist
+const Player = ({ playlist, currentTrack, setCurrentTrack }) => {
+  const [isAutoplayed, setIsAutoplayed] = useState(true);
+
+  function goPrevTrack() {
+    setIsAutoplayed(true);
+    currentTrack > 0 && setCurrentTrack(currentTrack - 1);
+  }
+  function goNextTrack() {
+    setIsAutoplayed(true);
+    currentTrack < playlist.length && setCurrentTrack(currentTrack + 1);
+  }
+
+  return (
+    <div className="player">
+      <button className="prevTrack" onClick={goPrevTrack}></button>
+      {!!playlist.length && (
+        <audio
+          controls
+          src={playlist[currentTrack] && playlist[currentTrack].url}
+          autoPlay={isAutoplayed}
+        />
+      )}
+      <button className="nextTrack" onClick={goNextTrack}></button>
+    </div>
+  );
+};
+
+const mapStateToProps = (state) => ({
+  currentTrack: state.player.currentTrack,
+});
+
+const mapDispatchToProps = (dispatch) => ({
+  setCurrentTrack: (trackIndex) => dispatch(setCurrentTrack(trackIndex)),
+});
+
+export default connect(mapStateToProps, mapDispatchToProps)(Player);

+ 131 - 0
src/components/RegisterForm.js

@@ -0,0 +1,131 @@
+import React, { useState } from "react";
+import { Form, Input, Button, Checkbox } from "antd";
+import { UserOutlined, LockOutlined } from "@ant-design/icons";
+import { Link } from 'react-router-dom';
+
+// import { BrowserRouter as Router, Route } from 'react-router-dom';
+// import createHistory from 'history/createBrowserHistory';
+import getGQL from "../utils/getGQL";
+
+import "../styles/RegisterForm.css";
+
+// const history = createHistory()
+
+
+export default ({store, history}) => {
+  const [form] = Form.useForm();
+  const [login, setLogin] = useState("");
+  const [password, setPassword] = useState("");
+  const [confPassword, setConfPassword] = useState("");
+
+  const onFinish = (values) => {
+    console.log("Success:", values);
+  };
+
+  const onFinishFailed = (errorInfo) => {
+    console.log("Failed:", errorInfo);
+  };
+
+
+  return (
+    <div className="registerForm">
+      {/* <div className="wrapperRegisterForm"> */}
+      <div>
+        <Form
+          name="basic"
+          form={form}
+          // initialValues={{
+          //   remember: true,
+          // }}
+          onFinish={onFinish}
+          onFinishFailed={onFinishFailed}
+        >
+          <Form.Item onChange={(e)=> setLogin(e.target.value)}
+            label="Username"
+            name="username"
+            value={login}
+            rules={[
+              {
+                required: true,
+                message: "Please input your username!",
+              },
+            ]}
+          >
+            <Input
+              prefix={<UserOutlined className="site-form-item-icon" />}
+              onChange={(e) => {
+                // console.log(e.target.value);
+                form.setFieldsValue({ username: e.target.value });
+              }}
+            />
+          </Form.Item>
+
+          <Form.Item onChange={(e)=> setPassword(e.target.value)}
+            label="Password"
+            name="password"
+            value={password}
+            rules={[
+              {
+                required: true,
+                message: "Please input your password!",
+              },
+            ]}
+          >
+            <Input.Password
+              prefix={<LockOutlined className="site-form-item-icon" />}
+            />
+          </Form.Item>
+          <Form.Item onChange={(e)=> setConfPassword(e.target.value)}
+            label="Confirm password"
+            name="Confirm password"
+            value={confPassword}
+            rules={[
+              {
+                required: true,
+                message: "Please input your password!",
+                // validator: 
+                // value: 
+              },
+            ]}
+          >
+            <Input.Password
+              prefix={<LockOutlined className="site-form-item-icon" />}
+            />
+          </Form.Item>
+          {/* 
+        <Form.Item name="remember" valuePropName="checked">
+          <Checkbox>Remember me</Checkbox>
+        </Form.Item> */}
+
+          <Form.Item>
+            <Button type="primary" htmlType="submit"
+            disabled = {password !== confPassword ? true : false}
+            onClick={async () => {
+              await getGQL("/graphql")(
+                `mutation User{
+                createUser (login: "${login}", password: "${password}"){
+                _id login
+                  }
+              }`
+              ).then((data) => {
+                console.log(data);
+                if (!data.errors && login && password) {
+                  history.push("/login");
+                  // window.location.assign("http://localhost:3000/login");
+                } else {
+                //   setError(() => true);// если поле не заполнено, то формируем ошибку
+                }
+              });
+            }
+          }
+            type="primary"
+            >         
+              Submit
+            </Button>
+        <Link to="/login" className="link-approval">Sign_in</Link>
+          </Form.Item>
+        </Form>
+      </div>
+    </div>
+  );
+};

+ 8 - 0
src/constants/actions/index.js

@@ -0,0 +1,8 @@
+export const LOGIN = "LOGIN";
+export const LOGOUT = "LOGOUT";
+
+export const SET_TRACKS = "SET_TRACKS";
+
+export const SET_CURRENT_TRACK = "SET_CURRENT_TRACK";
+
+export const CLEAR_TRACK_LIST = "CLEAR_TRACK_LIST";

BIN
src/images/girl.jpg


BIN
src/images/headfphones.jpg


+ 13 - 0
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
src/index.js

@@ -0,0 +1,17 @@
+import React from 'react';
+import ReactDOM from 'react-dom';
+import './index.css';
+import App from './App';
+import * as serviceWorker from './serviceWorker';
+
+ReactDOM.render(
+  <React.StrictMode>
+    <App />
+  </React.StrictMode>,
+  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();

+ 32 - 0
src/reducers/authReducer.js

@@ -0,0 +1,32 @@
+import jwt_decode from "jwt-decode";
+import * as actions from "../constants/actions/index";
+
+const initialState = {
+  data: {},
+  token: "",
+};
+
+let authReducer = (state = initialState, action) => {
+  // debugger
+  switch (action.type) {
+    case actions.LOGIN:
+      var data = jwt_decode(action.token);
+      console.log(data);
+
+      // localStorage.authToken = data.data.login;
+      const token = localStorage.authToken;
+
+      localStorage.authToken = action.token;
+      console.log({ data: { data }, token: action.token });
+      return { ...state, data: { data }, token: action.token };
+
+    case actions.LOGOUT:
+      localStorage.authToken = "";
+      return { ...state, data: initialState.data };
+
+    default:
+      return { ...state };
+  }
+};
+
+export default authReducer;

+ 91 - 0
src/reducers/mainReducer.js

@@ -0,0 +1,91 @@
+import { combineReducers } from "redux";
+import authReducer from "./authReducer"
+import playerReducer from "./playerReducer"
+
+// ДЗ:
+// написать authReducer, который будет возвращать
+// пустой объект {} или {data: {.....}, token: "ey...."}, в зависимости от action.
+// Предусмотреть два action с типами LOGIN и LOGOUT.
+
+// в action LOGIN, кроме типа должен быть ключ с токеном. Редьюсер должен раскодировать токен, положить результат в data, токен в token, сохранить token в localStorage. Для раскодирования поставьте jwt-decode (npm i jwt-decode)
+
+// по action LOGOUT - стираем ключ из localStorage, возвращаем пустой объект
+
+// напишите два actionCreator для этих действий.
+// поэкспериментируйте с токенами, который вы получали от graphql
+
+// в коде, ниже запуска createStore проверьте наличие токена в localStorage и при наличии задиспатчите actionLogin, для синхронизации localStorage и состояния redux в момент загрузки страницы. Так же вы можете сделать эту проверку внутри редьюсера при его первом запуске (со state === undefined)
+
+// Сделайте компонент, который будет писать логин в заголовке сайта, или же писать anon если вы не залогинены. Используйте connect и mapStateToProps для получения логина из redux
+
+// Сделайте кнопку -компонент`logout`, которая по нажатию запускает внешний колбэк, переданный пропсами. Используя connect и mapDispatchToProps научите её экшену LOGOUT
+
+// Попробуйте сделать компонент логина, который:
+// 1) отображает login и password
+// 2) по кнопке делает query login
+// 3) в then при получении токена запускает внешний колбэк, переданный пропсами.
+// 4) используя connect и mapDispatchToProps подвяжите actionLogin к этому пропсу.
+
+// const initialState = {
+//     token: null,
+//     userName: null,
+//     id:null
+//   };
+
+//   export default function authReducer(state=initialState, action){
+//       if (state === undefined) {
+//         return Object.assign({}, state)
+//       }
+//       if (action.type === 'LOGIN') {
+//         var decoded = jwt_decode(action.token)
+//         localStorage.authToken = action.token
+//         console.log(action.token,'++')
+//         return Object.assign({}, state, {
+//           'token': action.token,
+//           'userName': decoded.sub.login,
+//           'id': decoded.sub.id
+//         })
+//       }
+//       // if ( action.type === 'FAILURE'){
+//       //   return Object.assign({}, state, {
+//       //     'token': null,
+//       //     'userName': null,
+//       //     'id': null,
+//       //   })
+//       // }
+//       if (action.type === 'LOGOUT') {
+//           localStorage.authToken = ''
+//           return Object.assign({}, state, {
+//             'token': null,
+//             'userName': null,
+//             'id': null,
+//         })
+//       }
+//       return state
+
+
+
+// store.dispatch(actionPending())
+// p.then(data => store.dispatch(actionResolved(data)))
+
+// const promiseReducer = (state, action) => {
+//   if (state === undefined) {
+//     return {};
+//   }
+//   if (action.type === "PROMISE") {
+//     return {
+//       ...state,
+//       [action.name]: {
+//         status: action.status,
+//         payload: action.payload,
+//         error: action.error,
+//       },
+//     };
+//   }
+// };
+
+export default combineReducers({
+  auth: authReducer,
+  // promise: promiseReducer,
+  player: playerReducer
+});

+ 29 - 0
src/reducers/playerReducer.js

@@ -0,0 +1,29 @@
+import * as actions from "../constants/actions/index";
+
+const initialState = { tracks: [], currentTrack: {} };
+
+export default (state = initialState, { type, tracks, trackIndex }) => {
+  switch (type) {
+    case actions.SET_TRACKS:
+      return {
+        ...state,
+        tracks,
+      };
+
+    case actions.SET_CURRENT_TRACK:
+      return {
+        ...state,
+        currentTrack: trackIndex,
+      };
+
+    case actions.CLEAR_TRACK_LIST:
+      return {
+        ...state,
+        currentTrack: {},
+        tracks: [],
+      };
+
+    default:
+      return { ...state };
+  }
+};

+ 141 - 0
src/serviceWorker.js

@@ -0,0 +1,141 @@
+// 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}$/
+    )
+);
+
+export function register(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, 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, 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);
+      });
+  }
+}

+ 9 - 0
src/store.js

@@ -0,0 +1,9 @@
+import { createStore, combineReducers, applyMiddleware, compose } from "redux";
+import mainReducer from "./reducers/mainReducer";
+import thunk from "redux-thunk";
+
+const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
+
+const enhancer = composeEnhancers(applyMiddleware(thunk));
+
+export default createStore(mainReducer, enhancer); //вторым параметром идет

+ 28 - 0
src/styles/App.css

@@ -0,0 +1,28 @@
+@import '~antd/dist/antd.css';
+
+#root {
+    display: flex;
+    justify-content: center;
+    align-items: center;
+    width: 100%;
+}
+.App {
+    display: flex;
+    align-items: center;
+    justify-content: center;
+    width: 100%;
+    height: 100%;
+    background: url("../images/headfphones.jpg");
+}
+h2 {
+    margin-bottom: 0em;
+    font-size: 25px;
+    line-height: 1.5;
+    font-weight: 700;
+}
+ul{
+    margin-bottom: 0em; 
+}
+li{
+    list-style-type: none;
+}

+ 27 - 0
src/styles/RegisterForm.css

@@ -0,0 +1,27 @@
+.registerForm {
+    display: flex;
+    justify-content: center;
+    padding: 24px;
+    border-radius: 5px;
+    border: 2px solid #666666;
+    margin: auto;
+    /* background-color: #94e0e0; */
+    /* background-color: #fefdf9a8; */
+    background-color:#e0f8fcd4;
+}  
+/* .link-approval{
+    color: white;
+} */
+.ant-form-item-control-input-content{
+    display: flex;
+    justify-content: space-between;
+}
+/* .registerForm div{
+    margin:0 auto; 
+    display: flex;
+    justify-content: center;
+    align-items: center;
+    padding: 24px;
+    border-radius: 5px;
+    border: 2px solid #666666;
+} */

+ 62 - 0
src/styles/Reset.css

@@ -0,0 +1,62 @@
+/* http://meyerweb.com/eric/tools/css/reset/ 
+   v2.0 | 20110126
+   License: none (public domain)
+*/
+
+html, body, div, span, applet, object, iframe,
+h1, h2, h3, h4, h5, h6, p, blockquote, pre,
+a, abbr, acronym, address, big, cite, code,
+del, dfn, em, img, ins, kbd, q, s, samp,
+small, strike, strong, sub, sup, tt, var,
+b, u, i, center,
+dl, dt, dd, ol, ul, li,
+fieldset, form, label, legend,
+table, caption, tbody, tfoot, thead, tr, th, td,
+article, aside, canvas, details, embed, 
+figure, figcaption, footer, header, hgroup, 
+menu, nav, output, ruby, section, summary,
+time, mark, audio, video {
+	margin: 0;
+	padding: 0;
+	border: 0;
+	font-size: 100%;
+	font: inherit;
+	vertical-align: baseline;
+	margin: 0;
+	padding-inline-start: 0;
+}
+/* HTML5 display-role reset for older browsers */
+article, aside, details, figcaption, figure, 
+footer, header, hgroup, menu, nav, section {
+	display: block;
+}
+body {
+	display: flex;
+	box-sizing: border-box;
+    /* justify-content: center; */
+	/* align-items: center; */
+	/* margin: 0 0 100 0 px; */
+	line-height: 1;
+	/* background: url("../images/headfphones.jpg"); */
+	/* width: 100%;
+    background-position-x: 50%; */
+}
+ol, ul {
+	list-style: none;
+}
+blockquote, q {
+	quotes: none;
+}
+blockquote:before, blockquote:after,
+q:before, q:after {
+	content: '';
+	content: none;
+}
+table {
+	border-collapse: collapse;
+	border-spacing: 0;
+}
+img {
+    max-width: 100%;
+    height: auto;
+}

+ 198 - 0
src/styles/library.css

@@ -0,0 +1,198 @@
+.header {
+    display: flex;
+    /* border: 1px solid black; */
+    justify-content: center;
+    /* align-items: center; */
+    width: 100%;
+    top: 0;
+    /* left: 0;
+    right: 0; */
+    position: fixed;
+    z-index:1;
+}
+
+/* .header ul {
+    display: flex;
+    justify-content: center;
+    align-items: center;
+} */
+
+/* .header ul>li{
+    list-style-type: none;
+    width: 300px; 
+} */
+
+.mainMenu {
+    display: flex;
+    justify-content: center;
+    align-items: center;
+    width: 100%;
+    text-align: center;
+}
+
+.mainMenu li {
+    display: flex;
+    align-items: center;
+    justify-content: center;
+    width: 100%;
+    padding: 10px;
+    border: 1px solid black;
+    background-color: rgb(241, 214, 182);
+}
+
+.mainMenu li:hover {
+    background-color: orange;
+    cursor: pointer;
+    /* color: white; */
+}
+
+.userMenu{
+    position: relative;  
+}
+
+.userMenu-child{
+    position: absolute;
+    background: orange;
+    /* width: 100px;
+    height: 100px; */
+    position: fixed;
+    top: 0px;
+    z-index: -1;
+    transition: 0.3s ease-in-out;
+}
+
+.userMenu:hover
+.userMenu-child {
+    top: 50px;
+}
+
+.main{
+    display: flex;
+    /* position:relative; */
+    flex-grow: 1;
+    width: 100%;
+    background: url("../images/girl.jpg");
+    background-attachment: fixed;
+}
+/* .main:after {
+    content: '';
+    display: flex;
+    position: absolute;
+    top: 0;
+    left: 0;
+    right: 0;
+    bottom: 0;
+    width: 100%;
+    height: 100%;
+    background-color: #5d6cdd;
+    opacity: 0.8;
+    margin: 0;
+    z-index: 3;
+} */
+
+.trackList {
+    /* padding-top: 90px; */
+    flex-grow: 1;
+    padding: 155px 0px 100px;
+    /* background: url("../images/girl.jpg"); */
+    width: 100%;
+    display: flex;
+    justify-content: center;
+    font-weight: bold;
+    font-size: 20px;
+}
+
+.trackList ul>li {
+    padding: 5px;
+}
+
+.trackList ul>li:hover {
+    background-color: #85C0FF;
+    cursor: pointer;
+    display: flex;
+    justify-content: center;
+    transition-duration: 0.2s
+}
+
+.highlighted {
+    background-color: #335C81;
+}
+
+/* .mainMenu h2 {
+    margin-bottom: 0em;
+} */
+
+.footer {
+    display: flex;
+    border: 1px solid black;
+    /* text-align: center;
+    align-items: center; */
+    justify-content: center;
+    padding: 5px;
+    background-color: rgb(241, 214, 182);
+    left: 0;
+    right: 0;
+    bottom: 0;
+    position: fixed;
+}
+
+.container {
+    position: absolute;
+    display: flex;
+    justify-content: center;
+    align-items: center;
+    top: 0;
+    left: 0;
+    right: 0;
+    bottom: 0;
+    z-index: 99;
+    text-align: center;
+    background: rgba(0, 0, 0, 0.692);
+}
+
+
+/* .userMenu:hover {
+    top: 0;
+} */
+/*     position: absolute;
+    color: #fff;
+    background-color: grey;
+    border: none;
+    transform-origin: 0% 100%;
+    transform: rotate(90deg);
+    margin-top: 120px;
+    margin-left: 179px;
+    font-size: 16px;
+    line-height: 17px;
+    font-family: 'Times New Roman', Times, serif; */
+/* ///////////////////////// */
+/* .mainmenubtn {
+    background-color: red;
+    color: white;
+    border: none;
+    cursor: pointer;
+    padding:5px;
+}
+
+.mainmenubtn:hover {
+    background-color: red;
+    }
+    
+.dropdown {
+    position: relative;
+    display: inline-block;
+}
+.dropdown-child {
+    display: none;
+    background-color: black;
+    min-width: 10px;
+}
+.dropdown-child a {
+    color: white;
+    padding: 5px;
+    text-decoration: none;
+    display: block;
+}
+.dropdown:hover .dropdown-child {
+    display: block;
+} */

+ 19 - 0
src/styles/player.css

@@ -0,0 +1,19 @@
+.player{
+    display: flex;
+    justify-content: center;
+    bottom: 50px;
+    position: fixed;
+    right: 0px;
+    left: 0px;
+}
+.player audio {
+    display: flex;
+    border: 1px solid grey;
+    border-radius: 25px;
+}
+.prevTrack,
+.nextTrack {
+    height: 50px;
+    width: 50px;
+    border-radius: 50px;
+}

+ 10 - 0
src/utils/getGQL.js

@@ -0,0 +1,10 @@
+export default (url, headers = {}) => (query = "", variables = {}) =>
+  fetch(url, {
+    method: "POST",
+    headers: {
+      Accept: "application/json",
+      "Content-Type": "application/json",
+      ...headers,
+    },
+    body: JSON.stringify({ query, variables }),
+  }).then((res) => res.json());

+ 3 - 0
src/utils/history.js

@@ -0,0 +1,3 @@
+import createHistory from "history/createBrowserHistory";
+
+export default createHistory()