Browse Source

03.03.2023 16:00

Volddemar4ik 2 years ago
parent
commit
fb39367929

+ 12 - 26
js/Project/project/src/App.js

@@ -1,4 +1,4 @@
-import logo from './logo.svg';
+// import logo from './logo.svg';
 import './App.css';
 import React, { useState, useEffect } from 'react';
 import { Router, Route, Link, Redirect, Switch, useParams } from 'react-router-dom';
@@ -8,6 +8,15 @@ import { Provider, connect, useDispatch, useSelector } from 'react-redux';
 import Feed from './components/feed';
 import User from './components/user';
 
+// импорт страниц
+import AsideMenu from './components/pages/structure/aside_menu';
+
+
+import { ReduxFeed } from './components/feed';
+
+
+
+
 import createHistory from "history/createBrowserHistory";
 
 // ==============================================================================
@@ -159,11 +168,6 @@ const Registration = () =>
         Регистрация
     </div>
 
-const Direct = () =>
-    <div>
-        Direct
-    </div>
-
 const CreatePost = () =>
     <div>
         Страницв создания поста
@@ -180,9 +184,6 @@ const Page404 = () =>
     </div>
 
 
-// создаем компонент ленты на основе стандартного, который отслеживает все изменения state
-const ReduxFeed = connect(state => ({ posts: state.PostsFind.payload }))(Feed)
-
 // ==================================================
 // страница одного поста
 const CComments = connect(state => ({ post: state?.PostFindOne?.payload }), { loadPost: actionFindPostOne })(Comments)
@@ -217,21 +218,8 @@ function App() {
         <Provider store={store}>
             <Router history={history}>
                 <div className="wrapper" style={{ display: 'flex', minHeight: '100hv' }}>
-                    <aside style={{ width: '15%', minHeight: '100vh', backgroundColor: '#ffdbdb' }}>
-                        <Link to="/">Главная(она же Лента)</Link>
-                        <br />
-                        <Link to="/profile">Профиль</Link>
-                        <br />
-                        <Link to="/createpost">Создание поста</Link>
-                        <br />
-                        <Link to="/direct">Директ</Link>
-                        <br />
-                        <Link to="/about">О нас</Link>
-                        <br />
-                        <Link to="/registration">Регистрация</Link>
-                        <br />
-                        <Link to="/autorization">Авторизация</Link>
-                    </aside>
+
+                    <AsideMenu />
                     <section style={{ width: '50%', margin: '0 auto', minHeight: '100hv', display: 'flex', flexDirection: 'column' }}>
                         <header style={{ backgroundColor: '#dbffe7' }}>
                             Тут будут какие-то заголовки или что-то вроде этого
@@ -242,13 +230,11 @@ function App() {
 
                             <Switch>
                                 <Route path="/autorization" component={Autorization} />
-                                {/* <Route path="/profile" component={User} /> */}
                                 <Route path="/user/:userId" component={CUser} />
 
                                 <Route path="/registration" component={Registration} />
                                 <Route path="/" component={ReduxFeed} exact />
                                 <Route path="/createpost" component={CreatePost} />
-                                <Route path="/direct" component={Direct} />
                                 <Route path="/about" component={PageAbout} />
                                 <Route path="/post/:postId" component={CComments} />
 

+ 24 - 40
js/Project/project/src/App_test.js

@@ -2,20 +2,17 @@ import logo from './logo.svg';
 import './App.css';
 import React, { useState, useEffect } from 'react';
 import { Router, Route, Link, Redirect, Switch, useParams } from 'react-router-dom';
-
 import { createStore, combineRedusers, applyMiddleware } from 'redux';
 import thunk from 'redux-thunk';
 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 AsideMenu from './components/pages/structure/aside_menu';
 
 import createHistory from "history/createBrowserHistory";
 
-
 // ==============================================================================
 // создание promiseReducer
 function promiseReducer(state = {}, { type, status, payload, error, nameOfPromise }) {
@@ -48,7 +45,6 @@ const actionPromise = (nameOfPromise, promise) =>
     }
   }
 
-
 // =============================================================
 // функция getGql
 function getGql(endpoint) {
@@ -83,7 +79,6 @@ function getGql(endpoint) {
 
 const gql = getGql('http://hipstagram.node.ed.asmer.org.ua/graphql')
 
-
 // запрос на все посты (для ленты общей)
 const actionfindPosts = () => actionPromise('PostsFind', gql(`query AllPostsFind ($allPosts: String){
   PostFind(query: $allPosts){
@@ -100,8 +95,6 @@ const actionfindPosts = () => actionPromise('PostsFind', gql(`query AllPostsFind
   allPosts: JSON.stringify([{}])
 }))
 
-
-
 // запрос на конкретный пост
 const actionFindPostOne = _id => actionPromise('PostFindOne', gql(`query OnePostFind ($postOne: String){
   PostFindOne (query: $postOne) {
@@ -131,8 +124,6 @@ const actionFindPostOne = _id => actionPromise('PostFindOne', gql(`query OnePost
   postOne: JSON.stringify([{ _id }])
 }))
 
-
-
 // запрос на конкретного юзера
 const actionFindUserOne = _id => actionPromise('UserFindOne', gql(`query OneUserFind ($userOne: String) {
   UserFindOne(query: $userOne) {
@@ -151,10 +142,6 @@ const actionFindUserOne = _id => actionPromise('UserFindOne', gql(`query OneUser
   userOne: JSON.stringify([{ _id }])
 }))
 
-
-
-
-
 const store = createStore(promiseReducer, applyMiddleware(thunk))
 store.subscribe(() => console.log(store.getState()))
 
@@ -163,8 +150,6 @@ store.dispatch(actionfindPosts())
 // store.dispatch(actionFindUserOne())
 
 
-
-
 const history = createHistory()
 
 const Autorization = () =>
@@ -187,12 +172,6 @@ const CreatePost = () =>
     Страницв создания поста
   </div>
 
-// const User = () =>
-//     // <div>
-//     //     Страница юзера
-//     // </div>
-//     <SimpleContainer />
-
 const PageAbout = () =>
   <div>
     Страница "О нас"
@@ -210,11 +189,30 @@ const ReduxFeed = connect(state => ({ posts: state.PostsFind.payload }))(Feed)
 // ==================================================
 // страница одного поста
 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)
+
 // ====================================================
 
 function App() {
@@ -222,21 +220,8 @@ function App() {
     <Provider store={store}>
       <Router history={history}>
         <div className="wrapper" style={{ display: 'flex', minHeight: '100hv' }}>
-          <aside style={{ width: '15%', minHeight: '100vh', backgroundColor: '#ffdbdb' }}>
-            <Link to="/">Главная(она же Лента)</Link>
-            <br />
-            <Link to="/profile">Профиль</Link>
-            <br />
-            <Link to="/createpost">Создание поста</Link>
-            <br />
-            <Link to="/direct">Директ</Link>
-            <br />
-            <Link to="/about">О нас</Link>
-            <br />
-            <Link to="/registration">Регистрация</Link>
-            <br />
-            <Link to="/autorization">Авторизация</Link>
-          </aside>
+
+          <AsideMenu />
           <section style={{ width: '50%', margin: '0 auto', minHeight: '100hv', display: 'flex', flexDirection: 'column' }}>
             <header style={{ backgroundColor: '#dbffe7' }}>
               Тут будут какие-то заголовки или что-то вроде этого
@@ -247,7 +232,6 @@ function App() {
 
               <Switch>
                 <Route path="/autorization" component={Autorization} />
-                {/* <Route path="/profile" component={User} /> */}
                 <Route path="/user/:userId" component={CUser} />
 
                 <Route path="/registration" component={Registration} />

+ 119 - 0
js/Project/project/src/components/feed/card.js

@@ -0,0 +1,119 @@
+import Card from '@mui/material/Card';
+import CardHeader from '@mui/material/CardHeader';
+import CardMedia from '@mui/material/CardMedia';
+import CardContent from '@mui/material/CardContent';
+import CardActions from '@mui/material/CardActions';
+import Avatar from '@mui/material/Avatar';
+import IconButton from '@mui/material/IconButton';
+import Typography from '@mui/material/Typography';
+import MoreVertIcon from '@mui/icons-material/MoreVert';
+import FavoriteBorderRoundedIcon from '@mui/icons-material/FavoriteBorderRounded';
+import SendIcon from '@mui/icons-material/Send';
+import ChatBubbleOutlineIcon from '@mui/icons-material/ChatBubbleOutline';
+import { Link } from 'react-router-dom';
+import TurnedInNotIcon from '@mui/icons-material/TurnedInNot';
+import Grid from '@mui/material/Unstable_Grid2';
+import { MyCarousel } from './carousel';
+import Box from '@mui/material/Box';
+
+// урл бека
+const url = 'http://hipstagram.node.ed.asmer.org.ua/'
+
+
+
+export function RecipeReviewCard({ postData }) {
+    // формируем дату поста
+    const dateofPost = new Date(+postData.createdAt)
+    const months = ['января', 'февраля', 'марта', 'апреля', 'мая', 'июня', 'июля', 'августа', 'сентября', 'октября', 'ноября', 'декабря']
+    const dateofPostParse = `${dateofPost.getDate() < 10 ? '0' + dateofPost.getDate() : dateofPost.getDate()} ${months[dateofPost.getMonth()]} ${dateofPost.getFullYear()}  ${dateofPost.getHours()}:${dateofPost.getMinutes() < 10 ? '0' + dateofPost.getMinutes() : dateofPost.getMinutes()}`
+
+    // рисуем картинки на постах
+    let imgOfPost
+    if ((postData.images != null) && ((postData.images).length != 0)) {
+        imgOfPost = url + postData.images[0].url
+    }
+
+    return (
+        <Card sx={{ maxWidth: 500 }}>
+            <CardHeader
+                avatar={
+                    <Avatar
+                        alt=""
+                        src="/images/avatar.jpeg"
+                        sx={{ width: 50, height: 50 }}
+                        style={{ margin: '5px', border: '3px solid black', borderRadius: '50%', flexShrink: '0', overflow: 'hidden' }}
+                    />
+                }
+                action={   // троеточие в хедере
+                    <IconButton aria-label="settings">
+                        <MoreVertIcon />
+                    </IconButton>
+                }
+                title={
+                    <Link to={`/user/${postData._id}`}>
+                        {postData.owner.login}
+                    </Link>
+                }
+
+                subheader={dateofPostParse} // дата создания поста
+            />
+            <CardMedia>
+                <MyCarousel />
+            </CardMedia>
+            <CardActions disableSpacing>
+                <Box sx={{ flexGrow: 1 }}>
+                    <Grid container spacing={2}>
+                        <Grid
+                            xs={12}
+                            container
+                            justifyContent="space-between"
+                            alignItems="center"
+                            flexDirection={{ xs: 'column', sm: 'row' }}
+                            sx={{ fontSize: '12px' }}
+                        >
+                            <Grid container columnSpacing={1} sx={{ order: { xs: 2, sm: 1 } }}>
+                                <Grid>
+                                    <IconButton aria-label="add to favorites">
+                                        <FavoriteBorderRoundedIcon />
+                                    </IconButton>
+                                </Grid>
+                                <Grid>
+                                    <IconButton>
+                                        <ChatBubbleOutlineIcon />
+                                    </IconButton>
+                                </Grid>
+                                <Grid>
+                                    <IconButton aria-label="share">
+                                        <SendIcon />
+                                    </IconButton>
+                                </Grid>
+                            </Grid>
+                            <Grid sx={{ order: { xs: 1, sm: 2 } }}>
+                                <IconButton>
+                                    <TurnedInNotIcon />
+                                </IconButton>
+                            </Grid>
+                        </Grid>
+                    </Grid>
+                </Box>
+            </CardActions>
+            <CardActions>
+                Нравится: {postData.likesCount ? postData.likesCount : '0'}
+                {/* Нравится: {postData.likesCount || '0'} // сработает или нет - проверить */}
+            </CardActions>
+            <CardContent>
+                <Typography variant="subtitle2" color="text.secondary">
+                    {postData.title}
+                </Typography>
+                <Typography variant="body2" color="text.secondary">
+                    {postData.text}
+                </Typography>
+            </CardContent>
+            <CardActions>
+                <Link to={`/post/${postData._id}`}>Посмотреть все комментарии (44)</Link>
+            </CardActions>
+        </Card >
+    )
+}
+
+// export default RecipeReviewCard

+ 8 - 117
js/Project/project/src/components/feed/index.js

@@ -1,24 +1,10 @@
 import * as React from 'react';
-import Card from '@mui/material/Card';
-import CardHeader from '@mui/material/CardHeader';
-import CardMedia from '@mui/material/CardMedia';
-import CardContent from '@mui/material/CardContent';
-import CardActions from '@mui/material/CardActions';
-import Avatar from '@mui/material/Avatar';
-import IconButton from '@mui/material/IconButton';
-import Typography from '@mui/material/Typography';
-import MoreVertIcon from '@mui/icons-material/MoreVert';
-import FavoriteBorderRoundedIcon from '@mui/icons-material/FavoriteBorderRounded';
-import SendIcon from '@mui/icons-material/Send';
-import ChatBubbleOutlineIcon from '@mui/icons-material/ChatBubbleOutline';
-import { Link } from 'react-router-dom';
-import TurnedInNotIcon from '@mui/icons-material/TurnedInNot';
-import Grid from '@mui/material/Unstable_Grid2';
 import Box from '@mui/material/Box';
-import { MyCarousel } from './carousel';
 import Stack from '@mui/material/Stack';
 import Paper from '@mui/material/Paper';
 import { styled } from '@mui/material/styles';
+import { connect } from 'react-redux';
+import { RecipeReviewCard as Card } from './card';
 
 // урл бека
 const url = 'http://hipstagram.node.ed.asmer.org.ua/'
@@ -29,104 +15,7 @@ const Item = styled(Paper)(({ theme }) => ({
     width: 500
 }))
 
-
-function RecipeReviewCard({ postData }) {
-    // формируем дату поста
-    const dateofPost = new Date(+postData.createdAt)
-    const months = ['января', 'февраля', 'марта', 'апреля', 'мая', 'июня', 'июля', 'августа', 'сентября', 'октября', 'ноября', 'декабря']
-    const dateofPostParse = `${dateofPost.getDate() < 10 ? '0' + dateofPost.getDate() : dateofPost.getDate()} ${months[dateofPost.getMonth()]} ${dateofPost.getFullYear()}  ${dateofPost.getHours()}:${dateofPost.getMinutes() < 10 ? '0' + dateofPost.getMinutes() : dateofPost.getMinutes()}`
-
-    // рисуем картинки на постах
-    let imgOfPost
-    if ((postData.images != null) && ((postData.images).length != 0)) {
-        imgOfPost = url + postData.images[0].url
-    }
-
-    return (
-        <Card sx={{ maxWidth: 500 }}>
-            <CardHeader
-                avatar={
-                    <Avatar
-                        alt=""
-                        src="/images/avatar.jpeg"
-                        sx={{ width: 50, height: 50 }}
-                        style={{ margin: '5px', border: '3px solid black', borderRadius: '50%', flexShrink: '0', overflow: 'hidden' }}
-                    />
-                }
-                action={   // троеточие в хедере
-                    <IconButton aria-label="settings">
-                        <MoreVertIcon />
-                    </IconButton>
-                }
-                title={
-                    <Link to={`/user/${postData._id}`}>
-                        {postData.owner.login}
-                    </Link>
-                }
-
-                subheader={dateofPostParse} // дата создания поста
-            />
-            <CardMedia>
-                <MyCarousel />
-            </CardMedia>
-            <CardActions disableSpacing>
-                <Box sx={{ flexGrow: 1 }}>
-                    <Grid container spacing={2}>
-                        <Grid
-                            xs={12}
-                            container
-                            justifyContent="space-between"
-                            alignItems="center"
-                            flexDirection={{ xs: 'column', sm: 'row' }}
-                            sx={{ fontSize: '12px' }}
-                        >
-                            <Grid container columnSpacing={1} sx={{ order: { xs: 2, sm: 1 } }}>
-                                <Grid>
-                                    <IconButton aria-label="add to favorites">
-                                        <FavoriteBorderRoundedIcon />
-                                    </IconButton>
-                                </Grid>
-                                <Grid>
-                                    <IconButton>
-                                        <ChatBubbleOutlineIcon />
-                                    </IconButton>
-                                </Grid>
-                                <Grid>
-                                    <IconButton aria-label="share">
-                                        <SendIcon />
-                                    </IconButton>
-                                </Grid>
-                            </Grid>
-                            <Grid sx={{ order: { xs: 1, sm: 2 } }}>
-                                <IconButton>
-                                    <TurnedInNotIcon />
-                                </IconButton>
-                            </Grid>
-                        </Grid>
-                    </Grid>
-                </Box>
-            </CardActions>
-            <CardActions>
-                Нравится: {postData.likesCount ? postData.likesCount : '0'}
-                {/* Нравится: {postData.likesCount || '0'} // сработает или нет - проверить */}
-            </CardActions>
-            <CardContent>
-                <Typography variant="subtitle2" color="text.secondary">
-                    {postData.title}
-                </Typography>
-                <Typography variant="body2" color="text.secondary">
-                    {postData.text}
-                </Typography>
-            </CardContent>
-            <CardActions>
-                <Link to={`/post/${postData._id}`}>Посмотреть все комментарии (44)</Link>
-            </CardActions>
-        </Card >
-    )
-}
-
-
-export default function Feed({ posts = [] }) {
+function Feed({ posts = [] }) {
     return (
         <Box sx={{
             width: '500',
@@ -135,8 +24,10 @@ export default function Feed({ posts = [] }) {
         }}>
             {/* spacing - это отступ между карточками в ленте */}
             <Stack spacing={1}>
-                {posts.map(post => <Item key={post._id}><RecipeReviewCard postData={post} /></Item>)}
+                {posts.map(post => <Item key={post._id}><Card postData={post} /></Item>)}
             </Stack>
         </Box >
-    );
-}
+    )
+}
+
+export const ReduxFeed = connect(state => ({ posts: state.PostsFind.payload }))(Feed)

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


+ 11 - 0
js/Project/project/src/components/pages/index.js

@@ -0,0 +1,11 @@
+import AsideMenu from "./aside_menu";
+import Main from "./structure/main";
+
+const Page = () =>
+    <div className="wrapper" style={{ display: 'flex', minHeight: '100hv' }}>
+        <AsideMenu />
+        <Main />
+    </div>
+
+
+export default Page

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

@@ -0,0 +1,20 @@
+import { Link } from "react-router-dom"
+
+const AsideMenu = () =>
+    <aside style={{ width: '15%', minHeight: '100vh', backgroundColor: '#ffdbdb' }}>
+        <Link to="/">Главная(она же Лента)</Link>
+        <br />
+        <Link to="/profile">Профиль</Link>
+        <br />
+        <Link to="/createpost">Создание поста</Link>
+        <br />
+        <Link to="/direct">Директ</Link>
+        <br />
+        <Link to="/about">О нас</Link>
+        <br />
+        <Link to="/registration">Регистрация</Link>
+        <br />
+        <Link to="/autorization">Авторизация</Link>
+    </aside>
+
+export default AsideMenu

+ 19 - 0
js/Project/project/src/components/pages/structure/main.js

@@ -0,0 +1,19 @@
+import { Route, Switch } from "react-router"
+
+
+const Main = () =>
+    <section style={{ width: '50%', margin: '0 auto', minHeight: '100hv', display: 'flex', flexDirection: 'column' }}>
+        <header style={{ backgroundColor: '#dbffe7' }}>
+            Тут будут какие-то заголовки или что-то вроде этого
+        </header>
+        <main style={{ backgroundColor: '#dcdbff', flex: '1 1 auto' }}>
+            {/* прописывание редиректа */}
+            {/* <Redirect from='/direct' to='/profile' /> */}
+
+
+        </main>
+        <footer style={{ backgroundColor: '#dbffe7' }}>Hipstagram from Volddemar4ik</footer>
+    </section>
+
+
+export default Main