소스 검색

03/03/2023 14:40

Volddemar4ik 2 년 전
부모
커밋
bee5b39c58

+ 24 - 29
js/Project/project/src/App.js

@@ -2,20 +2,14 @@ import logo from './logo.svg';
 import './App.css';
 import './App.css';
 import React, { useState, useEffect } from 'react';
 import React, { useState, useEffect } from 'react';
 import { Router, Route, Link, Redirect, Switch, useParams } from 'react-router-dom';
 import { Router, Route, Link, Redirect, Switch, useParams } from 'react-router-dom';
-
 import { createStore, combineRedusers, applyMiddleware } from 'redux';
 import { createStore, combineRedusers, applyMiddleware } from 'redux';
 import thunk from 'redux-thunk';
 import thunk from 'redux-thunk';
 import { Provider, connect, useDispatch, useSelector } from 'react-redux';
 import { Provider, connect, useDispatch, useSelector } from 'react-redux';
-
 import Feed from './components/feed';
 import Feed from './components/feed';
-import Comments from './components/post';
 import User from './components/user';
 import User from './components/user';
 
 
-// import { Provider } from 'react-redux';
-
 import createHistory from "history/createBrowserHistory";
 import createHistory from "history/createBrowserHistory";
 
 
-
 // ==============================================================================
 // ==============================================================================
 // создание promiseReducer
 // создание promiseReducer
 function promiseReducer(state = {}, { type, status, payload, error, nameOfPromise }) {
 function promiseReducer(state = {}, { type, status, payload, error, nameOfPromise }) {
@@ -48,7 +42,6 @@ const actionPromise = (nameOfPromise, promise) =>
         }
         }
     }
     }
 
 
-
 // =============================================================
 // =============================================================
 // функция getGql
 // функция getGql
 function getGql(endpoint) {
 function getGql(endpoint) {
@@ -83,7 +76,6 @@ function getGql(endpoint) {
 
 
 const gql = getGql('http://hipstagram.node.ed.asmer.org.ua/graphql')
 const gql = getGql('http://hipstagram.node.ed.asmer.org.ua/graphql')
 
 
-
 // запрос на все посты (для ленты общей)
 // запрос на все посты (для ленты общей)
 const actionfindPosts = () => actionPromise('PostsFind', gql(`query AllPostsFind ($allPosts: String){
 const actionfindPosts = () => actionPromise('PostsFind', gql(`query AllPostsFind ($allPosts: String){
   PostFind(query: $allPosts){
   PostFind(query: $allPosts){
@@ -100,8 +92,6 @@ const actionfindPosts = () => actionPromise('PostsFind', gql(`query AllPostsFind
     allPosts: JSON.stringify([{}])
     allPosts: JSON.stringify([{}])
 }))
 }))
 
 
-
-
 // запрос на конкретный пост
 // запрос на конкретный пост
 const actionFindPostOne = _id => actionPromise('PostFindOne', gql(`query OnePostFind ($postOne: String){
 const actionFindPostOne = _id => actionPromise('PostFindOne', gql(`query OnePostFind ($postOne: String){
   PostFindOne (query: $postOne) {
   PostFindOne (query: $postOne) {
@@ -131,12 +121,10 @@ const actionFindPostOne = _id => actionPromise('PostFindOne', gql(`query OnePost
     postOne: JSON.stringify([{ _id }])
     postOne: JSON.stringify([{ _id }])
 }))
 }))
 
 
-
-
 // запрос на конкретного юзера
 // запрос на конкретного юзера
 const actionFindUserOne = _id => actionPromise('UserFindOne', gql(`query OneUserFind ($userOne: String) {
 const actionFindUserOne = _id => actionPromise('UserFindOne', gql(`query OneUserFind ($userOne: String) {
   UserFindOne(query: $userOne) {
   UserFindOne(query: $userOne) {
-    createdAt login nick 
+    _id createdAt login nick 
     avatar {
     avatar {
       _id url
       _id url
     } 
     } 
@@ -151,18 +139,12 @@ const actionFindUserOne = _id => actionPromise('UserFindOne', gql(`query OneUser
     userOne: JSON.stringify([{ _id }])
     userOne: JSON.stringify([{ _id }])
 }))
 }))
 
 
-
-
-
-
 const store = createStore(promiseReducer, applyMiddleware(thunk))
 const store = createStore(promiseReducer, applyMiddleware(thunk))
 store.subscribe(() => console.log(store.getState()))
 store.subscribe(() => console.log(store.getState()))
 
 
 store.dispatch(actionfindPosts())
 store.dispatch(actionfindPosts())
 // store.dispatch(actionCategoryFind())
 // store.dispatch(actionCategoryFind())
-store.dispatch(actionFindUserOne())
-
-
+// store.dispatch(actionFindUserOne())
 
 
 
 
 const history = createHistory()
 const history = createHistory()
@@ -187,12 +169,6 @@ const CreatePost = () =>
         Страницв создания поста
         Страницв создания поста
     </div>
     </div>
 
 
-// const User = () =>
-//     // <div>
-//     //     Страница юзера
-//     // </div>
-//     <SimpleContainer />
-
 const PageAbout = () =>
 const PageAbout = () =>
     <div>
     <div>
         Страница "О нас"
         Страница "О нас"
@@ -210,11 +186,30 @@ const ReduxFeed = connect(state => ({ posts: state.PostsFind.payload }))(Feed)
 // ==================================================
 // ==================================================
 // страница одного поста
 // страница одного поста
 const CComments = connect(state => ({ post: state?.PostFindOne?.payload }), { loadPost: actionFindPostOne })(Comments)
 const CComments = connect(state => ({ post: state?.PostFindOne?.payload }), { loadPost: actionFindPostOne })(Comments)
-// ====================================================
+
+function Comments({ post = {}, loadPost }) {
+
+    const { postId } = useParams() // отслеживаем изменения в урле
+    // const post2 = useSelector(state => state?.CategoryGoodsAndSubCategoryGoods?.payload)
+    console.log(66, postId)
+
+    useEffect(() => { loadPost(postId) }, [postId]) // перезапускаем loadPost, если произошло изменение в урле
+
+    // console.log(post)
+
+    return (
+        <div>
+            {/* <div>{user} and {postId}</div> */}
+            тут будут отображаться все комментарии под постом
+            <h2>{post.createdAt}</h2>
+        </div>
+    )
+}
 
 
 // ==================================================
 // ==================================================
 // страница юзера
 // страница юзера
 const CUser = connect(state => ({ user: state?.UserFindOne?.payload }), { loadUser: actionFindUserOne })(User)
 const CUser = connect(state => ({ user: state?.UserFindOne?.payload }), { loadUser: actionFindUserOne })(User)
+
 // ====================================================
 // ====================================================
 
 
 function App() {
 function App() {
@@ -248,14 +243,14 @@ function App() {
                             <Switch>
                             <Switch>
                                 <Route path="/autorization" component={Autorization} />
                                 <Route path="/autorization" component={Autorization} />
                                 {/* <Route path="/profile" component={User} /> */}
                                 {/* <Route path="/profile" component={User} /> */}
-                                <Route path="/profile" component={CUser} />
+                                <Route path="/user/:userId" component={CUser} />
 
 
                                 <Route path="/registration" component={Registration} />
                                 <Route path="/registration" component={Registration} />
                                 <Route path="/" component={ReduxFeed} exact />
                                 <Route path="/" component={ReduxFeed} exact />
                                 <Route path="/createpost" component={CreatePost} />
                                 <Route path="/createpost" component={CreatePost} />
                                 <Route path="/direct" component={Direct} />
                                 <Route path="/direct" component={Direct} />
                                 <Route path="/about" component={PageAbout} />
                                 <Route path="/about" component={PageAbout} />
-                                <Route path="/:postId" component={CComments} />
+                                <Route path="/post/:postId" component={CComments} />
 
 
 
 
                                 <Route path="*" component={Page404} />
                                 <Route path="*" component={Page404} />

+ 80 - 67
js/Project/project/src/App_test.js

@@ -2,17 +2,15 @@ import logo from './logo.svg';
 import './App.css';
 import './App.css';
 import React, { useState, useEffect } from 'react';
 import React, { useState, useEffect } from 'react';
 import { Router, Route, Link, Redirect, Switch, useParams } from 'react-router-dom';
 import { Router, Route, Link, Redirect, Switch, useParams } from 'react-router-dom';
-import RecipeReviewCard from './components/Feed' // импортируем карточку поста в лентеы
-import Box from '@mui/material/Box';
-import Stack from '@mui/material/Stack';
-import Paper from '@mui/material/Paper';
-import { styled } from '@mui/material/styles';
-
 
 
 import { createStore, combineRedusers, applyMiddleware } from 'redux';
 import { createStore, combineRedusers, applyMiddleware } from 'redux';
 import thunk from 'redux-thunk';
 import thunk from 'redux-thunk';
 import { Provider, connect, useDispatch, useSelector } from 'react-redux';
 import { Provider, connect, useDispatch, useSelector } from 'react-redux';
 
 
+import Feed from './components/feed';
+import Comments from './components/post';
+import User from './components/user';
+
 // import { Provider } from 'react-redux';
 // import { Provider } from 'react-redux';
 
 
 import createHistory from "history/createBrowserHistory";
 import createHistory from "history/createBrowserHistory";
@@ -87,33 +85,84 @@ const gql = getGql('http://hipstagram.node.ed.asmer.org.ua/graphql')
 
 
 
 
 // запрос на все посты (для ленты общей)
 // запрос на все посты (для ленты общей)
-const actionfindPosts = () => actionPromise('PostsFind', gql(`query findPosts($allPosts: String){
-    PostFind(query: $allPosts){
-    _id createdAt title text likesCount images {url} owner{_id login nick} comments{
-        _id
+const actionfindPosts = () => actionPromise('PostsFind', gql(`query AllPostsFind ($allPosts: String){
+  PostFind(query: $allPosts){
+    _id createdAt title text likesCount
+    images {
+      url
+    }
+    owner {
+      _id login nick
     }
     }
-  }}`, {
+    
+  }
+}`, {
   allPosts: JSON.stringify([{}])
   allPosts: JSON.stringify([{}])
 }))
 }))
 
 
 
 
 
 
 // запрос на конкретный пост
 // запрос на конкретный пост
-const actionFindPostOne = _id => actionPromise('PostFindOne', gql(`
-query PostFindOne ($postOne: String){
+const actionFindPostOne = _id => actionPromise('PostFindOne', gql(`query OnePostFind ($postOne: String){
   PostFindOne (query: $postOne) {
   PostFindOne (query: $postOne) {
-    _id createdAt title text likesCount images {url} owner{_id login nick}
+    _id createdAt title text likesCount
+    images {
+      url
+    }
+    comments {
+      _id createdAt text answers {
+        _id createdAt text likes {
+          _id
+        }
+        likesCount owner {
+          _id login nick  avatar {
+            _id url
+          }
+        }
+      }
+      likesCount
+    }
+    owner {
+      _id login nick
+    }
+    
   }
   }
 }`, {
 }`, {
   postOne: JSON.stringify([{ _id }])
   postOne: JSON.stringify([{ _id }])
 }))
 }))
 
 
 
 
+
+// запрос на конкретного юзера
+const actionFindUserOne = _id => actionPromise('UserFindOne', gql(`query OneUserFind ($userOne: String) {
+  UserFindOne(query: $userOne) {
+    _id createdAt login nick 
+    avatar {
+      _id url
+    } 
+     followers {
+      _id login nick avatar {_id url}
+    }
+    following {
+       _id login nick avatar {_id url}
+    }
+  }
+}`, {
+  userOne: JSON.stringify([{ _id }])
+}))
+
+
+
+
+
 const store = createStore(promiseReducer, applyMiddleware(thunk))
 const store = createStore(promiseReducer, applyMiddleware(thunk))
 store.subscribe(() => console.log(store.getState()))
 store.subscribe(() => console.log(store.getState()))
 
 
 store.dispatch(actionfindPosts())
 store.dispatch(actionfindPosts())
 // store.dispatch(actionCategoryFind())
 // store.dispatch(actionCategoryFind())
+// store.dispatch(actionFindUserOne())
+
+
 
 
 
 
 const history = createHistory()
 const history = createHistory()
@@ -133,42 +182,16 @@ const Direct = () =>
     Direct
     Direct
   </div>
   </div>
 
 
-// ===================================================
-// сам item для поста
-const Item = styled(Paper)(({ theme }) => ({
-  backgroundColor: theme.palette.mode === 'dark' ? '#1A2027' : '#fff',
-  width: 500
-}));
-
-// const Feed = ({ posts = arrPosts }) => {
-const Feed = ({ posts = [] }) => {
-  return (
-    <Box sx={{
-      width: '500',
-      height: '600',
-      margin: '10, 20'
-    }}>
-      {/* spacing - это отступ между карточками в ленте */}
-      <Stack spacing={1}>
-        {/* {posts.map(post => <Item key={post._id}><RecipeReviewCard date={post.createdAt} title={post.title} text={post.text} likesCount={post.likesCount} nickName={post.owner.nick} login={post.owner.login} /></Item>)} */}
-        {posts.map(post => <Item key={post._id}><RecipeReviewCard postData={post} /></Item>)}
-      </Stack>
-    </Box >
-  );
-}
-
-const ReduxFeed = connect(state => ({ posts: state.PostsFind.payload }))(Feed)
-
-// ================================================
 const CreatePost = () =>
 const CreatePost = () =>
   <div>
   <div>
     Страницв создания поста
     Страницв создания поста
   </div>
   </div>
 
 
-const User = () =>
-  <div>
-    Страница юзера
-  </div>
+// const User = () =>
+//     // <div>
+//     //     Страница юзера
+//     // </div>
+//     <SimpleContainer />
 
 
 const PageAbout = () =>
 const PageAbout = () =>
   <div>
   <div>
@@ -181,31 +204,19 @@ const Page404 = () =>
   </div>
   </div>
 
 
 
 
+// создаем компонент ленты на основе стандартного, который отслеживает все изменения state
+const ReduxFeed = connect(state => ({ posts: state.PostsFind.payload }))(Feed)
+
 // ==================================================
 // ==================================================
 // страница одного поста
 // страница одного поста
-
-const Comments = ({ post = {}, loadPost }) => {
-
-
-  const { postId } = useParams()
-  // const post2 = useSelector(state => state?.CategoryGoodsAndSubCategoryGoods?.payload)
-
-  useEffect(() => { loadPost(postId) }, [postId])
-
-  return (
-    <div>
-      {/* <div>{user} and {postId}</div> */}
-      тут будут отображаться все комментарии под постом
-      <h2>{post.createdAt}</h2>
-    </div>
-  )
-}
-
-// store.dispatch(actionFindPostOne())
-
 const CComments = connect(state => ({ post: state?.PostFindOne?.payload }), { loadPost: actionFindPostOne })(Comments)
 const CComments = connect(state => ({ post: state?.PostFindOne?.payload }), { loadPost: actionFindPostOne })(Comments)
 // ====================================================
 // ====================================================
 
 
+// ==================================================
+// страница юзера
+const CUser = connect(state => ({ user: state?.UserFindOne?.payload }), { loadUser: actionFindUserOne })(User)
+// ====================================================
+
 function App() {
 function App() {
   return (
   return (
     <Provider store={store}>
     <Provider store={store}>
@@ -236,13 +247,15 @@ function App() {
 
 
               <Switch>
               <Switch>
                 <Route path="/autorization" component={Autorization} />
                 <Route path="/autorization" component={Autorization} />
-                <Route path="/profile" component={User} />
+                {/* <Route path="/profile" component={User} /> */}
+                <Route path="/user/:userId" component={CUser} />
+
                 <Route path="/registration" component={Registration} />
                 <Route path="/registration" component={Registration} />
                 <Route path="/" component={ReduxFeed} exact />
                 <Route path="/" component={ReduxFeed} exact />
                 <Route path="/createpost" component={CreatePost} />
                 <Route path="/createpost" component={CreatePost} />
                 <Route path="/direct" component={Direct} />
                 <Route path="/direct" component={Direct} />
                 <Route path="/about" component={PageAbout} />
                 <Route path="/about" component={PageAbout} />
-                <Route path="/:postId" component={CComments} />
+                <Route path="/post/:postId" component={CComments} />
 
 
 
 
                 <Route path="*" component={Page404} />
                 <Route path="*" component={Page404} />

+ 0 - 2
js/Project/project/src/components/feed/carousel.js

@@ -1,8 +1,6 @@
 // import React from 'react';
 // import React from 'react';
 import Carousel from 'react-material-ui-carousel'
 import Carousel from 'react-material-ui-carousel'
 
 
-
-
 // сама карусель - ее нужно вынеси в отдельный контенйре
 // сама карусель - ее нужно вынеси в отдельный контенйре
 export const MyCarousel = function Example(props) {
 export const MyCarousel = function Example(props) {
     let items = [
     let items = [

+ 7 - 7
js/Project/project/src/components/feed/index.js

@@ -20,8 +20,6 @@ import Stack from '@mui/material/Stack';
 import Paper from '@mui/material/Paper';
 import Paper from '@mui/material/Paper';
 import { styled } from '@mui/material/styles';
 import { styled } from '@mui/material/styles';
 
 
-// import BasicModal from '../PostOne';
-
 // урл бека
 // урл бека
 const url = 'http://hipstagram.node.ed.asmer.org.ua/'
 const url = 'http://hipstagram.node.ed.asmer.org.ua/'
 
 
@@ -42,7 +40,6 @@ function RecipeReviewCard({ postData }) {
     let imgOfPost
     let imgOfPost
     if ((postData.images != null) && ((postData.images).length != 0)) {
     if ((postData.images != null) && ((postData.images).length != 0)) {
         imgOfPost = url + postData.images[0].url
         imgOfPost = url + postData.images[0].url
-        // console.log(imgOfPost)
     }
     }
 
 
     return (
     return (
@@ -61,8 +58,11 @@ function RecipeReviewCard({ postData }) {
                         <MoreVertIcon />
                         <MoreVertIcon />
                     </IconButton>
                     </IconButton>
                 }
                 }
-
-                title={<a href={postData.owner._id}>{postData.owner.nick ? postData.owner.nick : postData.owner.login}</a>} // автор поста
+                title={
+                    <Link to={`/user/${postData._id}`}>
+                        {postData.owner.login}
+                    </Link>
+                }
 
 
                 subheader={dateofPostParse} // дата создания поста
                 subheader={dateofPostParse} // дата создания поста
             />
             />
@@ -119,9 +119,9 @@ function RecipeReviewCard({ postData }) {
                 </Typography>
                 </Typography>
             </CardContent>
             </CardContent>
             <CardActions>
             <CardActions>
-                <Link to={postData._id}>Посмотреть все комментарии (44)</Link>
+                <Link to={`/post/${postData._id}`}>Посмотреть все комментарии (44)</Link>
             </CardActions>
             </CardActions>
-        </Card>
+        </Card >
     )
     )
 }
 }
 
 

+ 0 - 0
js/Project/project/src/components/pages/aside_menu.js


+ 0 - 1
js/Project/project/src/components/post/index.js

@@ -23,4 +23,3 @@ export default function Comments({ post = {}, loadPost }) {
 
 
 
 
 // store.dispatch(actionFindPostOne())
 // store.dispatch(actionFindPostOne())
-

+ 14 - 0
js/Project/project/src/components/user/avatar.js

@@ -0,0 +1,14 @@
+import * as React from 'react';
+import Avatar from '@mui/material/Avatar';
+import Stack from '@mui/material/Stack';
+
+export default function ImageAvatars({ userData }) {
+    return (
+        <Stack direction="row" spacing={2}>
+            <Avatar alt={userData.login} src={userData.avatar?.url} sx={{ width: 100, height: 100 }} />
+        </Stack>
+    );
+}
+
+
+

+ 21 - 17
js/Project/project/src/components/user/index.js

@@ -5,31 +5,40 @@ import Container from '@mui/material/Container';
 import StandardImageList from './gallery';
 import StandardImageList from './gallery';
 import Divider from '@mui/material/Divider';
 import Divider from '@mui/material/Divider';
 import Grid from '@mui/material/Unstable_Grid2';
 import Grid from '@mui/material/Unstable_Grid2';
+import ImageAvatars from './avatar';
+import BasicCard from './user_data';
 
 
+import { useEffect, useState } from 'react';
+import { useParams } from 'react-router';
 
 
-// import { useEffect, useState } from 'react';
-// import { useParams } from 'react-router';
 
 
-export default function User() {
-    // console.log(111, user)
-    // const { userId } = useParams()
-    // useEffect(() => { loadUser(userId) }, [userId])
+
+export default function User({ user = {}, loadUser }) {
+
+    const { userId } = useParams()
+    useEffect(() => { loadUser(userId) }, [userId])
+
+    console.log(22, userId)
 
 
     return (
     return (
         <React.Fragment>
         <React.Fragment>
             <CssBaseline />
             <CssBaseline />
-            <Container sx={{ minHeight: '100vh' }} maxWidth="100%">
-                <Box>
+            <Container sx={{ minHeight: '100vh' }} maxWidth="100%" >
+                <Box sx={{ margin: "30px 10px" }}>
                     <Grid container spacing={2}>
                     <Grid container spacing={2}>
-                        <Grid xs={3} style={{ backgroundColor: "red" }}>
-                            текст
+                        <Grid xs={3}>
+                            <Container>
+                                <ImageAvatars userData={user} />
+                            </Container>
                         </Grid>
                         </Grid>
-                        <Grid xs={9} style={{ backgroundColor: "green" }}>
-                            текст
+                        <Grid xs={9}>
+                            <BasicCard userData={user} />
                         </Grid>
                         </Grid>
                     </Grid>
                     </Grid>
                 </Box>
                 </Box>
+
                 <Divider />
                 <Divider />
+
                 <Box >
                 <Box >
                     <StandardImageList />
                     <StandardImageList />
                 </Box>
                 </Box>
@@ -38,8 +47,3 @@ export default function User() {
     );
     );
 }
 }
 
 
-
-
-
-
-

+ 61 - 0
js/Project/project/src/components/user/user_data.js

@@ -0,0 +1,61 @@
+import * as React from 'react';
+import Box from '@mui/material/Box';
+import Card from '@mui/material/Card';
+import CardContent from '@mui/material/CardContent';
+import Typography from '@mui/material/Typography';
+
+import Button from '@mui/material/Button';
+import DeleteIcon from '@mui/icons-material/Delete';
+import SendIcon from '@mui/icons-material/Send';
+import Stack from '@mui/material/Stack';
+
+import ManageAccountsOutlinedIcon from '@mui/icons-material/ManageAccountsOutlined';
+
+function UptadeProfile() {
+    return (
+        // < Stack direction="row" spacing={2} >
+        <Button variant="outlined" startIcon={<ManageAccountsOutlinedIcon />} disableRipple>Редактировать аккаунт</Button>
+        // </Stack >
+    )
+}
+
+export default function BasicCard({ userData }) {
+
+    return (
+        <Card sx={{ width: '100%' }}>
+            <CardContent>
+                <Stack direction="row" spacing={5}>
+                    <Typography variant="h5" component="div">
+                        {userData.login}
+                    </Typography>
+                    <UptadeProfile />
+                </Stack>
+                <Stack direction="row" spacing={5}>
+                    <Typography color="text.secondary">
+                        NaN Публикаций
+                    </Typography>
+                    <Typography color="text.secondary">
+                        {userData.followers?.length} подписчиков
+                    </Typography>
+                    <Typography color="text.secondary">
+                        {userData.following?.length || '0'} подписок
+                    </Typography>
+                </Stack>
+
+                <Typography sx={{ fontSize: 14 }} color="text.secondary" gutterBottom>
+                    hhhhhh
+                </Typography>
+
+                <Typography sx={{ mb: 1.5 }} color="text.secondary">
+                    adjective
+                </Typography>
+                <Typography variant="body2">
+                    well meaning and kindly.
+                    <br />
+                    {'"a benevolent smile"'}
+                </Typography>
+            </CardContent>
+
+        </Card>
+    );
+}

+ 3 - 2
js/Project/project/src/index.js

@@ -9,8 +9,9 @@ const root = ReactDOM.createRoot(document.getElementById('root'));
 root.render(
 root.render(
   // <React.StrictMode>
   // <React.StrictMode>
   // <Provider>
   // <Provider>
-    <App />
-  // </Provider>  // </React.StrictMode>
+  <App />
+  // </Provider>  
+  // </React.StrictMode>
 );
 );
 
 
 // If you want to start measuring performance in your app, pass a function
 // If you want to start measuring performance in your app, pass a function