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

Feature/add-homework-5 #414

Open
wants to merge 12 commits into
base: lecture-5
Choose a base branch
from
51 changes: 37 additions & 14 deletions src/app/article/index.js
Original file line number Diff line number Diff line change
@@ -1,45 +1,57 @@
import { memo, useCallback, useMemo } from 'react';
import { memo, useCallback } from 'react';
import { useDispatch, useSelector as useSelectorRedux } from 'react-redux';
import { useParams } from 'react-router-dom';
import useStore from '../../hooks/use-store';
import useTranslate from '../../hooks/use-translate';
import useInit from '../../hooks/use-init';
import PageLayout from '../../components/page-layout';
import shallowequal from 'shallowequal';
import ArticleCard from '../../components/article-card';
import Head from '../../components/head';
import Navigation from '../../containers/navigation';
import PageLayout from '../../components/page-layout';
import Spinner from '../../components/spinner';
import ArticleCard from '../../components/article-card';
import CommentsZone from '../../containers/comments-zone';
import LocaleSelect from '../../containers/locale-select';
import Navigation from '../../containers/navigation';
import TopHead from '../../containers/top-head';
import { useDispatch, useSelector } from 'react-redux';
import shallowequal from 'shallowequal';
import useInit from '../../hooks/use-init';
import useSelector from '../../hooks/use-selector';
import useStore from '../../hooks/use-store';
import useTranslate from '../../hooks/use-translate';
import articleActions from '../../store-redux/article/actions';
import commentsActions from '../../store-redux/comments/actions';

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

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

const params = useParams();
const { t } = useTranslate();

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

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

const { t } = useTranslate();
const { isAuth, userName } = useSelector(state => ({
isAuth: state.session.exists,
userName: state.session.user?.profile?.name,
}));

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

return (
Expand All @@ -52,6 +64,17 @@ function Article() {
<Spinner active={select.waiting}>
<ArticleCard article={select.article} onAdd={callbacks.addToBasket} t={t} />
</Spinner>
<Spinner active={select.commentsWaiting}>
<CommentsZone
comments={select.comments}
count={select.commentsCount}
articleId={params.id}
onAdd={callbacks.addComment}
isAuth={isAuth}
userName={userName}
t={t}
/>
</Spinner>
</PageLayout>
);
}
Expand Down
54 changes: 54 additions & 0 deletions src/components/comment-form/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { cn as bem } from '@bem-react/classname';
import PropTypes from 'prop-types';
import { memo, useRef, useState } from 'react';
import './style.css';

function CommentForm({ onAdd, onCancel, title, cancelButtonText, t }) {
const cn = bem('CommentForm');
const ref = useRef(null);

const [textInput, setTextInput] = useState('');

const handleSubmit = e => {
e.preventDefault();
if (!textInput.trim()) {
return;
}
const handleSuccess = () => {
setTextInput('');
onCancel();
};
onAdd(textInput, handleSuccess);
};

return (
<form className={cn()} onSubmit={handleSubmit}>
<h3 className={cn('title')}>{title}</h3>
<textarea
value={textInput}
onChange={e => setTextInput(e.target.value)}
className={cn('textarea')}
placeholder={t('comments.placeholder')}
ref={ref}
/>
<div className={cn('actions')}>
<button type="submit">{t('comments.send')}</button>
{cancelButtonText && (
<button type="button" onClick={onCancel}>
{cancelButtonText}
</button>
)}
</div>
</form>
);
}

CommentForm.propTypes = {
onAdd: PropTypes.func,
onCancel: PropTypes.func,
title: PropTypes.string.isRequired,
cancelButtonText: PropTypes.string,
t: PropTypes.func,
};

export default memo(CommentForm);
24 changes: 24 additions & 0 deletions src/components/comment-form/style.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
.CommentForm {
width: 100%;
margin-bottom: 30px;
}

.CommentForm-title {
margin: 0 0 10px;
font-size: 12px;
}

.CommentForm-textarea {
width: 100%;
min-height: 76px;
padding: 4px;
margin-bottom: 10px;
resize: vertical;
font-family: Arial, Helvetica, sans-serif;
box-sizing: border-box;
}

.CommentForm-actions {
display: flex;
gap: 10px;
}
56 changes: 56 additions & 0 deletions src/components/comment-list/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import { cn as bem } from '@bem-react/classname';
import PropTypes from 'prop-types';
import { memo } from 'react';
import Comment from '../comment';
import './style.css';

function CommentList({
comments,
onAdd,
isOpenComment,
onCancel,
onOpen,
t,
isChildList,
isAuth,
maxDepth,
userName,
children,
}) {
const cn = bem('CommentList');

return (
<ul className={cn({ child: isChildList, depth: maxDepth <= 4 && maxDepth >= 2 })}>
{comments?.map(commentItem => (
<li key={commentItem._id}>
<Comment
isOpenComment={isOpenComment}
comment={commentItem}
onAdd={onAdd}
onCancel={onCancel}
onOpen={onOpen}
isAuth={isAuth}
userName={userName}
maxDepth={maxDepth}
t={t}
/>
</li>
))}
{children}
</ul>
);
}

CommentList.propTypes = {
isOpenComment: PropTypes.string,
comments: PropTypes.array,
onAdd: PropTypes.func,
onCancel: PropTypes.func,
onOpen: PropTypes.func,
isChildList: PropTypes.bool,
isAuth: PropTypes.bool,
userName: PropTypes.string,
t: PropTypes.func,
};

export default memo(CommentList);
9 changes: 9 additions & 0 deletions src/components/comment-list/style.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
.CommentList {
list-style: none;
padding: 0;
margin: 0;
}

.CommentList_depth {
padding-left: 30px;
}
123 changes: 123 additions & 0 deletions src/components/comment/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
import { cn as bem } from '@bem-react/classname';
import PropTypes from 'prop-types';
import { memo, useEffect, useRef } from 'react';
import { dateParser } from '../../utils/date-parser';
import CommentForm from '../comment-form';
import CommentList from '../comment-list';
import GuestComment from '../guest-comment';
import './style.css';

function Comment({
comment,
isOpenComment,
onCancel,
onAdd,
onOpen,
isAuth,
maxDepth,
t,
userName,
}) {
const cn = bem('Comment');

const { author, text, dateCreate, isDeleted, children, _id } = comment;

const handleAddAnswer = (text, onSuccess) => {
onAdd({ parent: { _id, _type: 'comment' }, text }, onSuccess);
};

const hasChildren = Boolean(children?.length);
const isUsersComment = Boolean(author?.profile?.name === userName);

const isFormShow = isAuth && isOpenComment === _id;

const formItem = useRef(null);

useEffect(() => {
if (isFormShow && formItem.current) {
formItem.current.scrollIntoView({ behavior: 'smooth', block: 'center' });
}
}, [isFormShow]);

return (
<div className={cn()}>
<div className={cn('user-date')}>
<div className={cn('user', { currentUser: isUsersComment })}>{author.profile.name}</div>
<div className={cn('date')}>{dateParser(dateCreate)}</div>
</div>
<p className={cn('text')}>{isDeleted ? t('comments.deleteComment') : text}</p>
<button className={cn('answer-btn')} onClick={() => onOpen(_id)}>
{t('comments.answer')}
</button>
{isAuth && isOpenComment === _id ? (
<CommentForm
onAdd={handleAddAnswer}
onCancel={onCancel}
title={t('comments.newAnswer')}
cancelButtonText={t('comments.cancel')}
t={t}
/>
) : null}
{!isAuth && isOpenComment === _id && (
<GuestComment
onCancel={onCancel}
buttonText={t('comments.cancel')}
text={t('comments.noAuthText')}
t={t}
/>
)}
{hasChildren && (
<CommentList
comments={children}
onAdd={onAdd}
isOpenComment={isOpenComment}
onCancel={onCancel}
onOpen={onOpen}
isAuth={isAuth}
isChildList
maxDepth={maxDepth + 1}
t={t}
>
{isFormShow && (
<li ref={formItem}>
<CommentForm
onAdd={handleAddAnswer}
onCancel={onCancel}
title={t('comments.newAnswer')}
cancelButtonText={t('comments.cancel')}
t={t}
/>
</li>
)}
</CommentList>
)}
</div>
);
}

Comment.propTypes = {
comment: PropTypes.shape({
children: PropTypes.array,
_id: PropTypes.string.isRequired,
parent: PropTypes.shape({
_id: PropTypes.string,
_type: PropTypes.oneOf(['article', 'comment']),
}),
text: PropTypes.string.isRequired,
dateCreate: PropTypes.string.isRequired,
isDeleted: PropTypes.bool,
author: PropTypes.shape({
profile: PropTypes.shape({
name: PropTypes.string.isRequired,
}).isRequired,
}).isRequired,
}),
onCancel: PropTypes.func,
onAdd: PropTypes.func,
onOpen: PropTypes.func,
isAuth: PropTypes.bool,
userName: PropTypes.string,
t: PropTypes.func,
};

export default memo(Comment);
35 changes: 35 additions & 0 deletions src/components/comment/style.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
.Comment-user-date {
display: flex;
font-size: 12px;
gap: 10px;
}

.Comment-user {
font-weight: bold;
}

.Comment-user_currentUser {
color: #666666;
}

.Comment-date {
color: #666666;
font-size: 12px;
}

.Comment-text {
margin: 10px 0;
padding-right: 20px;
font-size: 14px;
word-break: break-all;
}

.Comment-answer-btn {
cursor: pointer;
color: #0087e9;
padding: 0;
margin-bottom: 26px;
background-color: transparent;
border: none;
font-size: 12px;
}
Loading
Loading