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

Hm4 kazmin #40

Open
wants to merge 2 commits into
base: master
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
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
"version": "0.1.0",
"private": true,
"dependencies": {
"node-uuid": "^1.4.8",
"prop-types": "^15.6.1",
"react": "^16.3.2",
"react-addons-css-transition-group": "^15.6.2",
Expand Down
10 changes: 9 additions & 1 deletion src/ac/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ import {
INCREMENT,
DELETE_ARTICLE,
CHANGE_DATE_RANGE,
CHANGE_SELECTION
CHANGE_SELECTION,
ADD_COMMENT
} from '../constants'

export function increment() {
Expand Down Expand Up @@ -31,3 +32,10 @@ export function changeSelection(selected) {
payload: { selected }
}
}

export function addComment(holder, comment) {
return {
type: ADD_COMMENT,
payload: { holder, comment }
}
}
76 changes: 76 additions & 0 deletions src/components/add-comment-form.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import CommentHolder from '../entities/CommentHolder'
import { addComment } from '../ac'

class AddCommentForm extends Component {
state = {
user: '',
text: ''
}

static propTypes = {
commentHolder: PropTypes.instanceOf(CommentHolder).isRequired,
addComment: PropTypes.func.isRequired
}

render() {
return (
<form>
<label>
User name:
<input
placeholder="User name"
name="user"
onChange={this.handleUserChange}
value={this.state.user}
/>
</label>
<label>
Comment :
<textarea
placeholder="Comment text"
name="comment"
onChange={this.handleCommentChange}
value={this.state.text}
/>
</label>
<button type="button" onClick={this.handleAddClick}>
add
</button>
</form>
)
}

handleUserChange = (e) => {
e.preventDefault()
e.stopPropagation()

this.setState({ user: e.target.value })
}

handleCommentChange = (e) => {
e.preventDefault()
e.stopPropagation()

this.setState({ text: e.target.value })
}

handleAddClick = (e) => {
e.preventDefault()
e.stopPropagation()

this.props.addComment(this.props.commentHolder, {
...this.state
})

this.setState({
text: ''
})
}
}

export default connect(null, {
addComment
})(AddCommentForm)
22 changes: 12 additions & 10 deletions src/components/article-list.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { filtratedArticlesSelector } from '../selectors'

export class ArticleList extends Component {
static propTypes = {
articles: PropTypes.array.isRequired,
articles: PropTypes.object.isRequired,

//from accordion decorator
openItemId: PropTypes.string,
Expand All @@ -20,15 +20,17 @@ export class ArticleList extends Component {

render() {
console.log('---', 'rerendering')
const articleElements = this.props.articles.map((article) => (
<li key={article.id} className="test__article-list_item">
<Article
article={article}
isOpen={article.id === this.props.openItemId}
toggleOpen={this.props.toggleOpenItem}
/>
</li>
))
const articleElements = Object.values(this.props.articles).map(
(article) => (
<li key={article.id} className="test__article-list_item">
<Article
article={article}
isOpen={article.id === this.props.openItemId}
toggleOpen={this.props.toggleOpenItem}
/>
</li>
)
)

return <ul>{articleElements}</ul>
}
Expand Down
12 changes: 11 additions & 1 deletion src/components/article/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { connect } from 'react-redux'
import CommentList from '../comment-list'
import { deleteArticle } from '../../ac'
import './article.css'
import CommentHolder from '../../entities/CommentHolder'

class Article extends PureComponent {
static propTypes = {
Expand All @@ -19,6 +20,12 @@ class Article extends PureComponent {
deleteArticle: PropTypes.func
}

constructor(props) {
super(props)

this.commentHolder = new CommentHolder(props.article.id)
}

state = {
hasError: false
}
Expand Down Expand Up @@ -59,7 +66,10 @@ class Article extends PureComponent {
return (
<section className="test__article_body">
{article.text}
<CommentList comments={article.comments} />
<CommentList
comments={article.comments}
commentHolder={this.commentHolder}
/>
</section>
)
}
Expand Down
5 changes: 4 additions & 1 deletion src/components/comment-list/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import CSSTransition from 'react-addons-css-transition-group'
import Comment from '../comment'
import toggleOpen from '../../decorators/toggleOpen'
import './style.css'
import AddComment from '../add-comment-form'

class CommentList extends Component {
static defaultProps = {
Expand All @@ -14,7 +15,8 @@ class CommentList extends Component {
comments: PropTypes.array.isRequired,
//from toggleOpen decorator
isOpen: PropTypes.bool,
toggleOpen: PropTypes.func
toggleOpen: PropTypes.func,
commentHolder: PropTypes.object.isRequired
}

render() {
Expand Down Expand Up @@ -47,6 +49,7 @@ class CommentList extends Component {
) : (
<h3 className="test__comment-list--empty">No comments yet</h3>
)}
<AddComment commentHolder={this.props.commentHolder} />
</div>
)
}
Expand Down
4 changes: 2 additions & 2 deletions src/components/filters/select.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,15 @@ import { changeSelection } from '../../ac'

class SelectFilter extends Component {
static propTypes = {
articles: PropTypes.array.isRequired
articles: PropTypes.object.isRequired
}

handleChange = (selected) => {
this.props.changeSelection(selected)
}

get options() {
return this.props.articles.map((article) => ({
return Object.values(this.props.articles).map((article) => ({
label: article.title,
value: article.id
}))
Expand Down
2 changes: 2 additions & 0 deletions src/constants/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,5 @@ export const DELETE_ARTICLE = 'DELETE_ARTICLE'

export const CHANGE_SELECTION = 'CHANGE_SELECTION'
export const CHANGE_DATE_RANGE = 'CHANGE_DATE_RANGE'

export const ADD_COMMENT = 'ADD_COMMENT'
28 changes: 28 additions & 0 deletions src/entities/CommentHolder.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
const TYPE_ARTICLE = Symbol('TYPE_ARTICLE')

export default class CommentHolder {
static get TYPE_ARTICLE() {
return TYPE_ARTICLE
}

constructor(id, type = CommentHolder.TYPE_ARTICLE) {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Как по мне - перемудрил с этим. Тем более ты пользуешься тем, что у нас key={id}, но ты не можешь быть в этом уверен в самом компоненте.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

тогда можно просто передавать entityId + entityOwner (entityHolder, etc.)

потому что если мы не будем делать абстракцию и потом компонент коментариев будет использоватся например списком новостей, прийдется компонент коментариев рефакторить

if (typeof id !== 'string' || id.length === 0) {
throw new TypeError('id should be a not empty string')
}

if (type !== CommentHolder.TYPE_ARTICLE) {
throw new TypeError('type should be equal TYPE_ARTICLE')
}

this._id = id
this._type = type
}

getId() {
return this._id
}

getType() {
return this._type
}
}
15 changes: 15 additions & 0 deletions src/middlewares/generateAndMixId.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { ADD_COMMENT } from '../constants'
import generateId from 'uuid/v1'

export default (store) => (next) => (action) => {
const { type, payload } = action

if (type === ADD_COMMENT) {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

через мидлвары будет проходить каждый экшин, они должны быть максимально общими, завязывать на конкретные экшины - не лучшее решение

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

тогда просто подмешивать в каждый екшене в payload generatedId ?

payload.comment = {
...payload.comment,
id: generateId()
}
}

next(action)
}
37 changes: 34 additions & 3 deletions src/reducer/articles.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,43 @@
import { DELETE_ARTICLE } from '../constants'
import { normalizedArticles as defaultArticles } from '../fixtures'
import { DELETE_ARTICLE, ADD_COMMENT } from '../constants'
import { normalizedArticles } from '../fixtures'
import CommentHolder from '../entities/CommentHolder'

const defaultArticles = normalizedArticles.reduce(
(acc, article) => ({
...acc,
[article.id]: article
}),
{}
)

export default (articleState = defaultArticles, action) => {
const { type, payload } = action

switch (type) {
case DELETE_ARTICLE:
return articleState.filter((article) => article.id !== payload.id)
delete articleState[payload.id]

return {
...articleState
}

case ADD_COMMENT:
if (payload.holder.getType() === CommentHolder.TYPE_ARTICLE) {
const articleId = payload.holder.getId()
const article = articleState[articleId]

article.comments = [].concat(article.comments)
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

article тоже по ссылке не меняй

Copy link
Author

@kazminigor1988 kazminigor1988 May 31, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

лучшее решение думаю deepClone (lodash), и в коменты подмешивать новый commentId

ну и если говорить о разбиении, comments - не лучшний нейминг, скорее commentIds

article.comments.push(payload.comment.id)

return {
...articleState,
[articleId]: {
...article
}
}
} else {
return articleState
}

default:
return articleState
Expand Down
11 changes: 9 additions & 2 deletions src/reducer/comments.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {} from '../constants'
import { ADD_COMMENT } from '../constants'
import { normalizedComments } from '../fixtures'

const defaultComments = normalizedComments.reduce(
Expand All @@ -10,9 +10,16 @@ const defaultComments = normalizedComments.reduce(
)

export default (commentsState = defaultComments, action) => {
const { type } = action
const { type, payload } = action

switch (type) {
case ADD_COMMENT:
return {
...commentsState,
[payload.comment.id]: {
...payload.comment
}
}
default:
return commentsState
}
Expand Down
13 changes: 9 additions & 4 deletions src/selectors/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,19 @@ export const filtratedArticlesSelector = createSelector(
} = filters
console.log('---', 'calculating filters')

return articles.filter((article) => {
return Object.values(articles).reduce((acc, article) => {
const published = Date.parse(article.date)
return (

if (
(!selected.length ||
selected.find((selected) => selected.value === article.id)) &&
(!from || !to || (published > from && published < to))
)
})
) {
acc[article.id] = article
}

return acc
}, {})
}
)

Expand Down
3 changes: 2 additions & 1 deletion src/store/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { createStore, applyMiddleware, compose } from 'redux'
import reducer from '../reducer'
import logger from '../middlewares/logger'
import generateAndMixId from '../middlewares/generateAndMixId'

const composeEnhancers =
typeof window === 'object' && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
Expand All @@ -9,7 +10,7 @@ const composeEnhancers =
})
: compose

const enhancer = composeEnhancers(applyMiddleware(logger))
const enhancer = composeEnhancers(applyMiddleware(logger, generateAndMixId))

const store = createStore(reducer, enhancer)

Expand Down