Skip to content
Open

Hw 4 #44

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
9 changes: 8 additions & 1 deletion src/AC/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {INCREMENT, DELETE_ARTICLE, CHANGE_DATE_RANGE, CHANGE_SELECTION} from '../constants'
import {INCREMENT, DELETE_ARTICLE, CHANGE_DATE_RANGE, CHANGE_SELECTION, ADD_COMMENT} from '../constants'

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

export function addComment(data) {
return {
type: ADD_COMMENT,
payload: {data}
}
}
2 changes: 1 addition & 1 deletion src/components/article-list/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export class ArticleList extends Component {
render() {
const { articles, openItemId, toggleItem } = this.props
console.log('---', 'rendering ArticlList')
const articleElements = articles.map(article =>
const articleElements = Object.values(articles).map(article =>
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Лучше селектор, который достанет их в виде массива

<li key = {article.id} className = "test__article-list--item">
<Article
article = {article}
Expand Down
3 changes: 3 additions & 0 deletions src/components/article/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import PropTypes from 'prop-types'
import CSSTransition from 'react-addons-css-transition-group'
import { connect } from 'react-redux'
import CommentList from '../comment-list'
import CommentForm from '../comment-form'
import { deleteArticle } from '../../AC'
import './style.css'

Expand Down Expand Up @@ -34,6 +35,8 @@ class Article extends PureComponent {
delete me
</button>
</h2>

<CommentForm rel={article.id}/>
<CSSTransition
transitionName = "article"
transitionAppear
Expand Down
60 changes: 60 additions & 0 deletions src/components/comment-form.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import React, { Component } from 'react'
import { connect } from 'react-redux'
import { addComment } from '../AC'
import toggleOpen from '../decorators/toggleOpen'

class CommentForm extends Component {
state = {
authorname: "",
commenttext: ""
}

render() {

const {rel, isOpen, toggleOpen} = this.props

return (
<div>
<button onClick = {toggleOpen}>comment me</button>
<form method="post" style={{display: isOpen ? "block": "none"}}>

<label htmlFor={"authorname-" + rel}>name: </label>
<input type="text"
name="authorname"
id={"authorname-" + rel}
value={this.state.authorname}
onChange={this.handleInput}
/><br/>

<label htmlFor={"newcommenttext-" + rel}>text: </label>
<textarea name="text" id={"newcommenttext-" + rel} onChange={this.handleTextChange}
value={this.state.commenttext}></textarea> <br/>
<input type="button" onClick={this.handleAddcommentClick} value="Add"/>
</form>
</div>
)
}

handleInput = ev => {
this.setState({
authorname: ev.target.value
})
}

handleTextChange = ev => {
this.setState({
commenttext: ev.target.value
})
}

handleAddcommentClick = () => {
const {addComment, rel, toggleOpen} = this.props
if (this.state.authorname.length && this.state.commenttext.length ) {
toggleOpen()
addComment({articleid: rel, user: this.state.authorname, text: this.state.commenttext})
this.setState({authorname: '', commenttext:''})
}
}
}

export default connect(null, { addComment })(toggleOpen(CommentForm))
4 changes: 2 additions & 2 deletions src/components/filters/select.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,14 @@ import 'react-select/dist/react-select.css'

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

handleChange = selected => this.props.changeSelection(selected.map(option => option.value))

render() {
const { articles, selected } = this.props
const options = articles.map(article => ({
const options = Object.values(articles).map(article => ({
label: article.title,
value: article.id
}))
Expand Down
4 changes: 3 additions & 1 deletion src/constants/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,6 @@ export const INCREMENT = 'INCREMENT'
export const DELETE_ARTICLE = 'DELETE_ARTICLE'

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

export const ADD_COMMENT = 'ADD_COMMENT'
22 changes: 22 additions & 0 deletions src/middlewares/randomid.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { ADD_COMMENT } from '../constants'
/**
* Shuffles array in place. ES6 version
* @param {Array} a items An array containing the items.
*/
function shuffle(a) {
for (let i = a.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[a[i], a[j]] = [a[j], a[i]];
}
return a;
}

export default store => next => action => {
if (action.type === ADD_COMMENT) {
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

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

const randomId = shuffle((new Date()).toLocaleString('en-US').split('').filter((symbol)=> {
return symbol !== ' '
})).join('')
action.payload.data['id'] = randomId
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

лучше не мутировать payload, мало-ли что там станут передавать

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

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

export default (articlesState = defaultArticles, action) => {

const { type, payload } = action

switch (type) {
case DELETE_ARTICLE:
return articlesState.filter(article => article.id !== payload.id)
let articles = Object.assign({}, articlesState);
delete articles[payload.id]
return articles

case ADD_COMMENT:
let comments = articlesState[payload.data.articleid].comments
typeof comments !== 'undefined' ? comments.push(payload.data.id) : articlesState[payload.data.articleid].comments = new Array(payload.data.id)
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

здесь ты мутируешь стейт и ничего не возвращаешь

//break

default:
return articlesState
Expand Down
9 changes: 6 additions & 3 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((acc, comment) => ({
Expand All @@ -8,10 +8,13 @@ const defaultComments = normalizedComments.reduce((acc, comment) => ({
, {})

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

switch (type) {

case ADD_COMMENT:
const {id, user, text} = payload.data
commentsState[id] = {id: id, user: user, text: text}
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

не мутируй стейт!

//break
default:
return commentsState
}
Expand Down
4 changes: 2 additions & 2 deletions src/selectors/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ const idSelector = (_, props) => props.id
export const filtratedArticles = createSelector(articleListSelector, filtersSelector, (articles, filters) => {
const {selected, dateRange: {from, to}} = filters
console.log('---', 'recomputing filtration')

return articles.filter(article => {
return Object.values(articles).filter(article => {
const published = Date.parse(article.date)
return (!selected.length || selected.includes(article.id)) &&
(!from || !to || (published > from && published < to))
Expand Down
5 changes: 4 additions & 1 deletion src/store/index.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
import { createStore, applyMiddleware } from 'redux'
import reducer from '../reducer'
import logger from '../middlewares/logger'
import randomstringid from '../middlewares/randomid'

const enhancer = applyMiddleware(logger)

const store = createStore(reducer, enhancer)
const saidtodo = applyMiddleware(randomstringid)

const store = createStore(reducer, enhancer, saidtodo)

//dev only, no need in prod
window.store = store
Expand Down