Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

lect 5 #423

Open
wants to merge 5 commits into
base: lecture-5
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions src/api/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,10 @@ class APIService {
delete this.defaultHeaders[name];
}
}

setLangHeader(lang) {
this.setHeader('X-lang', lang);
}
}

export default APIService;
43 changes: 30 additions & 13 deletions src/app/article/index.js
Original file line number Diff line number Diff line change
@@ -1,44 +1,53 @@
import { memo, useCallback, useMemo } from 'react';
import { useParams } from 'react-router-dom';
import { memo, useCallback } from 'react';
import { useLocation, useNavigate, useParams } from 'react-router-dom';
import { useDispatch, useSelector } from 'react-redux';
import shallowequal from 'shallowequal';
import useStore from '../../hooks/use-store';
import useTranslate from '../../hooks/use-translate';
import useInit from '../../hooks/use-init';
import useSelectorStore from '../../hooks/use-selector';
import useServices from '../../hooks/use-services';
import PageLayout from '../../components/page-layout';
import Head from '../../components/head';
import Navigation from '../../containers/navigation';
import Spinner from '../../components/spinner';
import ArticleCard from '../../components/article-card';
import LocaleSelect from '../../containers/locale-select';
import TopHead from '../../containers/top-head';
import { useDispatch, useSelector } from 'react-redux';
import shallowequal from 'shallowequal';
import Comments from '../../components/comments';
import articleActions from '../../store-redux/article/actions';
import commentsActions from '../../store-redux/comments/actions';
import { cn as bem } from '@bem-react/classname';
import CommentsContainer from '../../containers/comments';

function Article() {
const store = useStore();

const cn = bem('ArticleCard');
const dispatch = useDispatch();
// Параметры из пути /articles/:id

const params = useParams();

const { t, lang } = useTranslate();

useInit(() => {
//store.actions.article.load(params.id);
dispatch(commentsActions.load(params.id));
dispatch(articleActions.load(params.id));
}, [params.id]);
}, [params.id, lang]);

const select = useSelector(
state => ({
article: state.article.data,
waiting: state.article.waiting,
count: state.comments.count,
list: state.comments.list,
}),
shallowequal,
); // Нужно указать функцию для сравнения свойства объекта, так как хуком вернули объект
);

const { t } = useTranslate();
const selectStore = useSelectorStore(state => ({
exists: state.session.exists,
}));

const callbacks = {
// Добавление в корзину
addToBasket: useCallback(_id => store.actions.basket.addToBasket(_id), [store]),
};

Expand All @@ -50,8 +59,16 @@ function Article() {
</Head>
<Navigation />
<Spinner active={select.waiting}>
<ArticleCard article={select.article} onAdd={callbacks.addToBasket} t={t} />
<ArticleCard
article={select.article}
onAdd={callbacks.addToBasket}
t={t}
count={select.count}
isAuth={selectStore.exists}
list={select.list}
/>
</Spinner>
<CommentsContainer />
</PageLayout>
);
}
Expand Down
9 changes: 0 additions & 9 deletions src/app/login/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,25 +9,16 @@ import Field from '../../components/field';
import SideLayout from '../../components/side-layout';
import TopHead from '../../containers/top-head';
import { useLocation, useNavigate } from 'react-router-dom';
import useStore from '../../hooks/use-store';
import useSelector from '../../hooks/use-selector';
import useInit from '../../hooks/use-init';

function Login() {
const { t } = useTranslate();
const location = useLocation();
const navigate = useNavigate();
const store = useStore();

useInit(() => {
store.actions.session.resetErrors();
});

const select = useSelector(state => ({
waiting: state.session.waiting,
errors: state.session.errors,
}));

const [data, setData] = useState({
login: '',
password: '',
Expand Down
5 changes: 2 additions & 3 deletions src/app/main/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,17 +12,16 @@ import TopHead from '../../containers/top-head';

function Main() {
const store = useStore();
const { t, lang } = useTranslate();

useInit(
async () => {
await Promise.all([store.actions.catalog.initParams(), store.actions.categories.load()]);
},
[],
[lang],
true,
);

const { t } = useTranslate();

return (
<PageLayout>
<TopHead />
Expand Down
119 changes: 119 additions & 0 deletions src/components/comment-area/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
import React, { memo, useEffect, useState, useRef } from 'react';
import PropTypes from 'prop-types';
import { cn as bem } from '@bem-react/classname';
import './style.css';

const CommentArea = ({
setIsMainAreaVisible,
setActiveReplyId,
authorName,
title,
cancel,
createFirstComment,
createAnswerComment,
isAuth,
parent,
margin,
mainClass,
loginNavigate,
}) => {
const [area, setArea] = useState('');
const cn = bem('CommentArea');
const textareaRef = useRef(null);

useEffect(() => {
if (mainClass) {
setArea('Текст');
} else {
setArea(`Мой ответ для ${authorName}`);
}
}, []);

useEffect(() => {
if (textareaRef.current && !mainClass) {
textareaRef.current.scrollIntoView({ behavior: 'smooth', block: 'center' });
}
}, [isAuth]);

const onSend = e => {
e.preventDefault();
if (area.trim()) {
if (parent && !mainClass) {
createAnswerComment(parent, area, 'comment');
} else {
createFirstComment(area, 'article');
}
setArea('');
}
};

const cancleHandler = () => {
setActiveReplyId(null);
setIsMainAreaVisible(true);
};

return (
<div
className={`${cn()} ${mainClass}`}
id="comment_area"
data-id={parent}
style={{ marginLeft: !mainClass && `${margin + 15}px`, marginBottom: !mainClass && `30px` }}
>
{isAuth ? (
<>
<div className={cn('title')}>{title}</div>
<textarea
ref={textareaRef}
className={cn('area')}
onChange={e => setArea(e.target.value)}
value={area}
/>
<button className={cn('send-btn')} onClick={onSend} disabled={!area}>
Отправить
</button>
{cancel && (
<button onClick={cancleHandler} className={cn('cancel-btn')}>
Отмена
</button>
)}
</>
) : (
<div className={cn('not-logged-in')}>
<a href="#" onClick={loginNavigate}>
Войдите
</a>
, чтобы иметь возможность комментировать{' '}
{cancel && <span className={cn('cancel-btn')}>Отмена</span>}
</div>
)}
</div>
);
};

CommentArea.propTypes = {
setIsMainAreaVisible: PropTypes.func,
setActiveReplyId: PropTypes.func,
authorName: PropTypes.string,
title: PropTypes.string,
cancel: PropTypes.bool,
createFirstComment: PropTypes.func.isRequired,
createAnswerComment: PropTypes.func.isRequired,
isAuth: PropTypes.bool,
parent: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
margin: PropTypes.number,
mainClass: PropTypes.string,
loginNavigate: PropTypes.func.isRequired,
};

CommentArea.defaultProps = {
setIsMainAreaVisible: () => {},
authorName: '',
title: 'Новый комментарий',
cancel: false,
isAuth: false,
parent: 0,
margin: 0,
mainClass: '',
};

export default memo(CommentArea);
40 changes: 40 additions & 0 deletions src/components/comment-area/style.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
.CommentArea {
/* display: none; */
}

.CommentArea.Main {
display: block;
}

.CommentArea.CommentArea--active {
display: block;
margin-top: 30px;
}

.CommentArea--margin {
margin-bottom: 30px;
}

.CommentArea-area {
width: 100%;
min-height: 76px;
resize: none;
margin-bottom: 10px;
padding: 5px;
}

.CommentArea-title {
font-size: 12px;
font-weight: 700;
margin-bottom: 10px;
}

.CommentArea-send-btn {
margin-right: 10px;
}

.CommentArea-not-logged-in span {
color: rgb(102, 102, 102);
text-decoration: underline;
cursor: pointer;
}
Loading
Loading